github.com/FUSIONFoundation/efsn@v3.6.2-0.20200916075423-dbb5dd5d2cc7+incompatible/swarm/storage/mru/request_test.go (about)

     1  package mru
     2  
     3  import (
     4  	"encoding/binary"
     5  	"encoding/json"
     6  	"fmt"
     7  	"reflect"
     8  	"testing"
     9  )
    10  
    11  func areEqualJSON(s1, s2 string) (bool, error) {
    12  	//credit for the trick: turtlemonvh https://gist.github.com/turtlemonvh/e4f7404e28387fadb8ad275a99596f67
    13  	var o1 interface{}
    14  	var o2 interface{}
    15  
    16  	err := json.Unmarshal([]byte(s1), &o1)
    17  	if err != nil {
    18  		return false, fmt.Errorf("Error mashalling string 1 :: %s", err.Error())
    19  	}
    20  	err = json.Unmarshal([]byte(s2), &o2)
    21  	if err != nil {
    22  		return false, fmt.Errorf("Error mashalling string 2 :: %s", err.Error())
    23  	}
    24  
    25  	return reflect.DeepEqual(o1, o2), nil
    26  }
    27  
    28  // TestEncodingDecodingUpdateRequests ensures that requests are serialized properly
    29  // while also checking cryptographically that only the owner of a resource can update it.
    30  func TestEncodingDecodingUpdateRequests(t *testing.T) {
    31  
    32  	signer := newCharlieSigner()  //Charlie, our good guy
    33  	falseSigner := newBobSigner() //Bob will play the bad guy again
    34  
    35  	// Create a resource to our good guy Charlie's name
    36  	createRequest, err := NewCreateRequest(&ResourceMetadata{
    37  		Name:      "a good resource name",
    38  		Frequency: 300,
    39  		StartTime: Timestamp{Time: 1528900000},
    40  		Owner:     signer.Address()})
    41  
    42  	if err != nil {
    43  		t.Fatalf("Error creating resource name: %s", err)
    44  	}
    45  
    46  	// We now encode the create message to simulate we send it over the wire
    47  	messageRawData, err := createRequest.MarshalJSON()
    48  	if err != nil {
    49  		t.Fatalf("Error encoding create resource request: %s", err)
    50  	}
    51  
    52  	// ... the message arrives and is decoded...
    53  	var recoveredCreateRequest Request
    54  	if err := recoveredCreateRequest.UnmarshalJSON(messageRawData); err != nil {
    55  		t.Fatalf("Error decoding create resource request: %s", err)
    56  	}
    57  
    58  	// ... but verification should fail because it is not signed!
    59  	if err := recoveredCreateRequest.Verify(); err == nil {
    60  		t.Fatal("Expected Verify to fail since the message is not signed")
    61  	}
    62  
    63  	// We now assume that the resource was created and propagated. With rootAddr we can retrieve the resource metadata
    64  	// and recover the information above. To sign an update, we need the rootAddr and the metaHash to construct
    65  	// proof of ownership
    66  
    67  	metaHash := createRequest.metaHash
    68  	rootAddr := createRequest.rootAddr
    69  	const expectedSignature = "0x1c2bab66dc4ed63783d62934e3a628e517888d6949aef0349f3bd677121db9aa09bbfb865904e6c50360e209e0fe6fe757f8a2474cf1b34169c99b95e3fd5a5101"
    70  	const expectedJSON = `{"rootAddr":"0x6e744a730f7ea0881528576f0354b6268b98e35a6981ef703153ff1b8d32bbef","metaHash":"0x0c0d5c18b89da503af92302a1a64fab6acb60f78e288eb9c3d541655cd359b60","version":1,"period":7,"data":"0x5468697320686f75722773207570646174653a20537761726d2039392e3020686173206265656e2072656c656173656421","multiHash":false}`
    71  
    72  	//Put together an unsigned update request that we will serialize to send it to the signer.
    73  	data := []byte("This hour's update: Swarm 99.0 has been released!")
    74  	request := &Request{
    75  		SignedResourceUpdate: SignedResourceUpdate{
    76  			resourceUpdate: resourceUpdate{
    77  				updateHeader: updateHeader{
    78  					UpdateLookup: UpdateLookup{
    79  						period:   7,
    80  						version:  1,
    81  						rootAddr: rootAddr,
    82  					},
    83  					multihash: false,
    84  					metaHash:  metaHash,
    85  				},
    86  				data: data,
    87  			},
    88  		},
    89  	}
    90  
    91  	messageRawData, err = request.MarshalJSON()
    92  	if err != nil {
    93  		t.Fatalf("Error encoding update request: %s", err)
    94  	}
    95  
    96  	equalJSON, err := areEqualJSON(string(messageRawData), expectedJSON)
    97  	if err != nil {
    98  		t.Fatalf("Error decoding update request JSON: %s", err)
    99  	}
   100  	if !equalJSON {
   101  		t.Fatalf("Received a different JSON message. Expected %s, got %s", expectedJSON, string(messageRawData))
   102  	}
   103  
   104  	// now the encoded message messageRawData is sent over the wire and arrives to the signer
   105  
   106  	//Attempt to extract an UpdateRequest out of the encoded message
   107  	var recoveredRequest Request
   108  	if err := recoveredRequest.UnmarshalJSON(messageRawData); err != nil {
   109  		t.Fatalf("Error decoding update request: %s", err)
   110  	}
   111  
   112  	//sign the request and see if it matches our predefined signature above.
   113  	if err := recoveredRequest.Sign(signer); err != nil {
   114  		t.Fatalf("Error signing request: %s", err)
   115  	}
   116  
   117  	compareByteSliceToExpectedHex(t, "signature", recoveredRequest.signature[:], expectedSignature)
   118  
   119  	// mess with the signature and see what happens. To alter the signature, we briefly decode it as JSON
   120  	// to alter the signature field.
   121  	var j updateRequestJSON
   122  	if err := json.Unmarshal([]byte(expectedJSON), &j); err != nil {
   123  		t.Fatal("Error unmarshalling test json, check expectedJSON constant")
   124  	}
   125  	j.Signature = "Certainly not a signature"
   126  	corruptMessage, _ := json.Marshal(j) // encode the message with the bad signature
   127  	var corruptRequest Request
   128  	if err = corruptRequest.UnmarshalJSON(corruptMessage); err == nil {
   129  		t.Fatal("Expected DecodeUpdateRequest to fail when trying to interpret a corrupt message with an invalid signature")
   130  	}
   131  
   132  	// Now imagine Evil Bob (why always Bob, poor Bob) attempts to update Charlie's resource,
   133  	// signing a message with his private key
   134  	if err := request.Sign(falseSigner); err != nil {
   135  		t.Fatalf("Error signing: %s", err)
   136  	}
   137  
   138  	// Now Bob encodes the message to send it over the wire...
   139  	messageRawData, err = request.MarshalJSON()
   140  	if err != nil {
   141  		t.Fatalf("Error encoding message:%s", err)
   142  	}
   143  
   144  	// ... the message arrives to our Swarm node and it is decoded.
   145  	recoveredRequest = Request{}
   146  	if err := recoveredRequest.UnmarshalJSON(messageRawData); err != nil {
   147  		t.Fatalf("Error decoding message:%s", err)
   148  	}
   149  
   150  	// Before discovering Bob's misdemeanor, let's see what would happen if we mess
   151  	// with the signature big time to see if Verify catches it
   152  	savedSignature := *recoveredRequest.signature                               // save the signature for later
   153  	binary.LittleEndian.PutUint64(recoveredRequest.signature[5:], 556845463424) // write some random data to break the signature
   154  	if err = recoveredRequest.Verify(); err == nil {
   155  		t.Fatal("Expected Verify to fail on corrupt signature")
   156  	}
   157  
   158  	// restore the Evil Bob's signature from corruption
   159  	*recoveredRequest.signature = savedSignature
   160  
   161  	// Now the signature is not corrupt, however Verify should now fail because Bob doesn't own the resource
   162  	if err = recoveredRequest.Verify(); err == nil {
   163  		t.Fatalf("Expected Verify to fail because this resource belongs to Charlie, not Bob the attacker:%s", err)
   164  	}
   165  
   166  	// Sign with our friend Charlie's private key
   167  	if err := recoveredRequest.Sign(signer); err != nil {
   168  		t.Fatalf("Error signing with the correct private key: %s", err)
   169  	}
   170  
   171  	// And now, Verify should work since this resource belongs to Charlie
   172  	if err = recoveredRequest.Verify(); err != nil {
   173  		t.Fatalf("Error verifying that Charlie, the good guy, can sign his resource:%s", err)
   174  	}
   175  }