github.com/codingfuture/orig-energi3@v0.8.4/swarm/storage/feed/request_test.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package feed
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  	"encoding/json"
    23  	"fmt"
    24  	"reflect"
    25  	"testing"
    26  
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/swarm/storage"
    29  	"github.com/ethereum/go-ethereum/swarm/storage/feed/lookup"
    30  )
    31  
    32  func areEqualJSON(s1, s2 string) (bool, error) {
    33  	//credit for the trick: turtlemonvh https://gist.github.com/turtlemonvh/e4f7404e28387fadb8ad275a99596f67
    34  	var o1 interface{}
    35  	var o2 interface{}
    36  
    37  	err := json.Unmarshal([]byte(s1), &o1)
    38  	if err != nil {
    39  		return false, fmt.Errorf("Error mashalling string 1 :: %s", err.Error())
    40  	}
    41  	err = json.Unmarshal([]byte(s2), &o2)
    42  	if err != nil {
    43  		return false, fmt.Errorf("Error mashalling string 2 :: %s", err.Error())
    44  	}
    45  
    46  	return reflect.DeepEqual(o1, o2), nil
    47  }
    48  
    49  // TestEncodingDecodingUpdateRequests ensures that requests are serialized properly
    50  // while also checking cryptographically that only the owner of a feed can update it.
    51  func TestEncodingDecodingUpdateRequests(t *testing.T) {
    52  
    53  	charlie := newCharlieSigner() //Charlie
    54  	bob := newBobSigner()         //Bob
    55  
    56  	// Create a feed to our good guy Charlie's name
    57  	topic, _ := NewTopic("a good topic name", nil)
    58  	firstRequest := NewFirstRequest(topic)
    59  	firstRequest.User = charlie.Address()
    60  
    61  	// We now encode the create message to simulate we send it over the wire
    62  	messageRawData, err := firstRequest.MarshalJSON()
    63  	if err != nil {
    64  		t.Fatalf("Error encoding first feed update request: %s", err)
    65  	}
    66  
    67  	// ... the message arrives and is decoded...
    68  	var recoveredFirstRequest Request
    69  	if err := recoveredFirstRequest.UnmarshalJSON(messageRawData); err != nil {
    70  		t.Fatalf("Error decoding first feed update request: %s", err)
    71  	}
    72  
    73  	// ... but verification should fail because it is not signed!
    74  	if err := recoveredFirstRequest.Verify(); err == nil {
    75  		t.Fatal("Expected Verify to fail since the message is not signed")
    76  	}
    77  
    78  	// We now assume that the feed ypdate was created and propagated.
    79  
    80  	const expectedSignature = "0x7235b27a68372ddebcf78eba48543fa460864b0b0e99cb533fcd3664820e603312d29426dd00fb39628f5299480a69bf6e462838d78de49ce0704c754c9deb2601"
    81  	const expectedJSON = `{"feed":{"topic":"0x6120676f6f6420746f706963206e616d65000000000000000000000000000000","user":"0x876a8936a7cd0b79ef0735ad0896c1afe278781c"},"epoch":{"time":1000,"level":1},"protocolVersion":0,"data":"0x5468697320686f75722773207570646174653a20537761726d2039392e3020686173206265656e2072656c656173656421"}`
    82  
    83  	//Put together an unsigned update request that we will serialize to send it to the signer.
    84  	data := []byte("This hour's update: Swarm 99.0 has been released!")
    85  	request := &Request{
    86  		Update: Update{
    87  			ID: ID{
    88  				Epoch: lookup.Epoch{
    89  					Time:  1000,
    90  					Level: 1,
    91  				},
    92  				Feed: firstRequest.Update.Feed,
    93  			},
    94  			data: data,
    95  		},
    96  	}
    97  
    98  	messageRawData, err = request.MarshalJSON()
    99  	if err != nil {
   100  		t.Fatalf("Error encoding update request: %s", err)
   101  	}
   102  
   103  	equalJSON, err := areEqualJSON(string(messageRawData), expectedJSON)
   104  	if err != nil {
   105  		t.Fatalf("Error decoding update request JSON: %s", err)
   106  	}
   107  	if !equalJSON {
   108  		t.Fatalf("Received a different JSON message. Expected %s, got %s", expectedJSON, string(messageRawData))
   109  	}
   110  
   111  	// now the encoded message messageRawData is sent over the wire and arrives to the signer
   112  
   113  	//Attempt to extract an UpdateRequest out of the encoded message
   114  	var recoveredRequest Request
   115  	if err := recoveredRequest.UnmarshalJSON(messageRawData); err != nil {
   116  		t.Fatalf("Error decoding update request: %s", err)
   117  	}
   118  
   119  	//sign the request and see if it matches our predefined signature above.
   120  	if err := recoveredRequest.Sign(charlie); err != nil {
   121  		t.Fatalf("Error signing request: %s", err)
   122  	}
   123  
   124  	compareByteSliceToExpectedHex(t, "signature", recoveredRequest.Signature[:], expectedSignature)
   125  
   126  	// mess with the signature and see what happens. To alter the signature, we briefly decode it as JSON
   127  	// to alter the signature field.
   128  	var j updateRequestJSON
   129  	if err := json.Unmarshal([]byte(expectedJSON), &j); err != nil {
   130  		t.Fatal("Error unmarshalling test json, check expectedJSON constant")
   131  	}
   132  	j.Signature = "Certainly not a signature"
   133  	corruptMessage, _ := json.Marshal(j) // encode the message with the bad signature
   134  	var corruptRequest Request
   135  	if err = corruptRequest.UnmarshalJSON(corruptMessage); err == nil {
   136  		t.Fatal("Expected DecodeUpdateRequest to fail when trying to interpret a corrupt message with an invalid signature")
   137  	}
   138  
   139  	// Now imagine Bob wants to create an update of his own about the same feed,
   140  	// signing a message with his private key
   141  	if err := request.Sign(bob); err != nil {
   142  		t.Fatalf("Error signing: %s", err)
   143  	}
   144  
   145  	// Now Bob encodes the message to send it over the wire...
   146  	messageRawData, err = request.MarshalJSON()
   147  	if err != nil {
   148  		t.Fatalf("Error encoding message:%s", err)
   149  	}
   150  
   151  	// ... the message arrives to our Swarm node and it is decoded.
   152  	recoveredRequest = Request{}
   153  	if err := recoveredRequest.UnmarshalJSON(messageRawData); err != nil {
   154  		t.Fatalf("Error decoding message:%s", err)
   155  	}
   156  
   157  	// Before checking what happened with Bob's update, let's see what would happen if we mess
   158  	// with the signature big time to see if Verify catches it
   159  	savedSignature := *recoveredRequest.Signature                               // save the signature for later
   160  	binary.LittleEndian.PutUint64(recoveredRequest.Signature[5:], 556845463424) // write some random data to break the signature
   161  	if err = recoveredRequest.Verify(); err == nil {
   162  		t.Fatal("Expected Verify to fail on corrupt signature")
   163  	}
   164  
   165  	// restore the Bob's signature from corruption
   166  	*recoveredRequest.Signature = savedSignature
   167  
   168  	// Now the signature is not corrupt
   169  	if err = recoveredRequest.Verify(); err != nil {
   170  		t.Fatal(err)
   171  	}
   172  
   173  	// Reuse object and sign with our friend Charlie's private key
   174  	if err := recoveredRequest.Sign(charlie); err != nil {
   175  		t.Fatalf("Error signing with the correct private key: %s", err)
   176  	}
   177  
   178  	// And now, Verify should work since this update now belongs to Charlie
   179  	if err = recoveredRequest.Verify(); err != nil {
   180  		t.Fatalf("Error verifying that Charlie, can sign a reused request object:%s", err)
   181  	}
   182  
   183  	// mess with the lookup key to make sure Verify fails:
   184  	recoveredRequest.Time = 77999 // this will alter the lookup key
   185  	if err = recoveredRequest.Verify(); err == nil {
   186  		t.Fatalf("Expected Verify to fail since the lookup key has been altered")
   187  	}
   188  }
   189  
   190  func getTestRequest() *Request {
   191  	return &Request{
   192  		Update: *getTestFeedUpdate(),
   193  	}
   194  }
   195  
   196  func TestUpdateChunkSerializationErrorChecking(t *testing.T) {
   197  
   198  	// Test that parseUpdate fails if the chunk is too small
   199  	var r Request
   200  	if err := r.fromChunk(storage.NewChunk(storage.ZeroAddr, make([]byte, minimumUpdateDataLength-1+signatureLength))); err == nil {
   201  		t.Fatalf("Expected request.fromChunk to fail when chunkData contains less than %d bytes", minimumUpdateDataLength)
   202  	}
   203  
   204  	r = *getTestRequest()
   205  
   206  	_, err := r.toChunk()
   207  	if err == nil {
   208  		t.Fatal("Expected request.toChunk to fail when there is no data")
   209  	}
   210  	r.data = []byte("Al bien hacer jamás le falta premio") // put some arbitrary length data
   211  	_, err = r.toChunk()
   212  	if err == nil {
   213  		t.Fatal("expected request.toChunk to fail when there is no signature")
   214  	}
   215  
   216  	charlie := newCharlieSigner()
   217  	if err := r.Sign(charlie); err != nil {
   218  		t.Fatalf("error signing:%s", err)
   219  	}
   220  
   221  	chunk, err := r.toChunk()
   222  	if err != nil {
   223  		t.Fatalf("error creating update chunk:%s", err)
   224  	}
   225  
   226  	compareByteSliceToExpectedHex(t, "chunk", chunk.Data(), "0x0000000000000000776f726c64206e657773207265706f72742c20657665727920686f7572000000876a8936a7cd0b79ef0735ad0896c1afe278781ce803000000000019416c206269656e206861636572206a616dc3a173206c652066616c7461207072656d696f5a0ffe0bc27f207cd5b00944c8b9cee93e08b89b5ada777f123ac535189333f174a6a4ca2f43a92c4a477a49d774813c36ce8288552c58e6205b0ac35d0507eb00")
   227  
   228  	var recovered Request
   229  	recovered.fromChunk(chunk)
   230  	if !reflect.DeepEqual(recovered, r) {
   231  		t.Fatal("Expected recovered feed update request to equal the original one")
   232  	}
   233  }
   234  
   235  // check that signature address matches update signer address
   236  func TestReverse(t *testing.T) {
   237  
   238  	epoch := lookup.Epoch{
   239  		Time:  7888,
   240  		Level: 6,
   241  	}
   242  
   243  	// make fake timeProvider
   244  	timeProvider := &fakeTimeProvider{
   245  		currentTime: startTime.Time,
   246  	}
   247  
   248  	// signer containing private key
   249  	signer := newAliceSigner()
   250  
   251  	// set up rpc and create feeds handler
   252  	_, _, teardownTest, err := setupTest(timeProvider, signer)
   253  	if err != nil {
   254  		t.Fatal(err)
   255  	}
   256  	defer teardownTest()
   257  
   258  	topic, _ := NewTopic("Cervantes quotes", nil)
   259  	fd := Feed{
   260  		Topic: topic,
   261  		User:  signer.Address(),
   262  	}
   263  
   264  	data := []byte("Donde una puerta se cierra, otra se abre")
   265  
   266  	request := new(Request)
   267  	request.Feed = fd
   268  	request.Epoch = epoch
   269  	request.data = data
   270  
   271  	// generate a chunk key for this request
   272  	key := request.Addr()
   273  
   274  	if err = request.Sign(signer); err != nil {
   275  		t.Fatal(err)
   276  	}
   277  
   278  	chunk, err := request.toChunk()
   279  	if err != nil {
   280  		t.Fatal(err)
   281  	}
   282  
   283  	// check that we can recover the owner account from the update chunk's signature
   284  	var checkUpdate Request
   285  	if err := checkUpdate.fromChunk(chunk); err != nil {
   286  		t.Fatal(err)
   287  	}
   288  	checkdigest, err := checkUpdate.GetDigest()
   289  	if err != nil {
   290  		t.Fatal(err)
   291  	}
   292  	recoveredAddr, err := getUserAddr(checkdigest, *checkUpdate.Signature)
   293  	if err != nil {
   294  		t.Fatalf("Retrieve address from signature fail: %v", err)
   295  	}
   296  	originalAddr := crypto.PubkeyToAddress(signer.PrivKey.PublicKey)
   297  
   298  	// check that the metadata retrieved from the chunk matches what we gave it
   299  	if recoveredAddr != originalAddr {
   300  		t.Fatalf("addresses dont match: %x != %x", originalAddr, recoveredAddr)
   301  	}
   302  
   303  	if !bytes.Equal(key[:], chunk.Address()[:]) {
   304  		t.Fatalf("Expected chunk key '%x', was '%x'", key, chunk.Address())
   305  	}
   306  	if epoch != checkUpdate.Epoch {
   307  		t.Fatalf("Expected epoch to be '%s', was '%s'", epoch.String(), checkUpdate.Epoch.String())
   308  	}
   309  	if !bytes.Equal(data, checkUpdate.data) {
   310  		t.Fatalf("Expected data '%x', was '%x'", data, checkUpdate.data)
   311  	}
   312  }