github.com/klaytn/klaytn@v1.12.1/networks/p2p/rlpx/rlpx_test.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from p2p/rlpx/rlpx_test.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package rlpx
    22  
    23  import (
    24  	"bytes"
    25  	"crypto/ecdsa"
    26  	"encoding/hex"
    27  	"fmt"
    28  	"io"
    29  	"math/rand"
    30  	"net"
    31  	"reflect"
    32  	"strings"
    33  	"testing"
    34  
    35  	"github.com/davecgh/go-spew/spew"
    36  	"github.com/klaytn/klaytn/crypto"
    37  	"github.com/klaytn/klaytn/crypto/ecies"
    38  	"github.com/klaytn/klaytn/networks/p2p/simulations/pipes"
    39  	"github.com/klaytn/klaytn/rlp"
    40  	"github.com/stretchr/testify/assert"
    41  )
    42  
    43  type message struct {
    44  	code uint64
    45  	data []byte
    46  	err  error
    47  }
    48  
    49  func TestHandshake(t *testing.T) {
    50  	p1, p2 := createPeers(t)
    51  	p1.Close()
    52  	p2.Close()
    53  }
    54  
    55  // This test checks that messages can be sent and received through WriteMsg/ReadMsg.
    56  func TestReadWriteMsg(t *testing.T) {
    57  	peer1, peer2 := createPeers(t)
    58  	defer peer1.Close()
    59  	defer peer2.Close()
    60  
    61  	testCode := uint64(23)
    62  	testData := []byte("test")
    63  	checkMsgReadWrite(t, peer1, peer2, testCode, testData)
    64  
    65  	t.Log("enabling snappy")
    66  	peer1.SetSnappy(true)
    67  	peer2.SetSnappy(true)
    68  	checkMsgReadWrite(t, peer1, peer2, testCode, testData)
    69  }
    70  
    71  func checkMsgReadWrite(t *testing.T, p1, p2 *Conn, msgCode uint64, msgData []byte) {
    72  	// Set up the reader.
    73  	ch := make(chan message, 1)
    74  	go func() {
    75  		var msg message
    76  		msg.code, msg.data, msg.err = p1.Read()
    77  		ch <- msg
    78  	}()
    79  
    80  	// Write the message.
    81  	if err := p2.Write(msgCode, msgData); err != nil {
    82  		t.Fatal(err)
    83  	}
    84  
    85  	// Check it was received correctly.
    86  	msg := <-ch
    87  	assert.Equal(t, msgCode, msg.code, "wrong message code returned from ReadMsg")
    88  	assert.Equal(t, msgData, msg.data, "wrong message data returned from ReadMsg")
    89  }
    90  
    91  func createPeers(t *testing.T) (peer1, peer2 *Conn) {
    92  	conn1, conn2 := net.Pipe()
    93  	key1, key2 := newkey(), newkey()
    94  	peer1 = NewConn(conn1, &key2.PublicKey) // dialer
    95  	peer2 = NewConn(conn2, nil)             // listener
    96  	doHandshake(t, peer1, peer2, key1, key2)
    97  	return peer1, peer2
    98  }
    99  
   100  func doHandshake(t *testing.T, peer1, peer2 *Conn, key1, key2 *ecdsa.PrivateKey) {
   101  	keyChan := make(chan *ecdsa.PublicKey, 1)
   102  	go func() {
   103  		pubKey, err := peer2.Handshake(key2)
   104  		if err != nil {
   105  			t.Errorf("peer2 could not do handshake: %v", err)
   106  		}
   107  		keyChan <- pubKey
   108  	}()
   109  
   110  	pubKey2, err := peer1.Handshake(key1)
   111  	if err != nil {
   112  		t.Errorf("peer1 could not do handshake: %v", err)
   113  	}
   114  	pubKey1 := <-keyChan
   115  
   116  	// Confirm the handshake was successful.
   117  	if !reflect.DeepEqual(pubKey1, &key1.PublicKey) || !reflect.DeepEqual(pubKey2, &key2.PublicKey) {
   118  		t.Fatal("unsuccessful handshake")
   119  	}
   120  }
   121  
   122  // This test checks the frame data of written messages.
   123  func TestFrameReadWrite(t *testing.T) {
   124  	conn := NewConn(nil, nil)
   125  	hash := fakeHash([]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})
   126  	conn.InitWithSecrets(Secrets{
   127  		AES:        crypto.Keccak256(),
   128  		MAC:        crypto.Keccak256(),
   129  		IngressMAC: hash,
   130  		EgressMAC:  hash,
   131  	})
   132  	h := conn.session
   133  
   134  	golden := unhex(`
   135  		00828ddae471818bb0bfa6b551d1cb42
   136  		01010101010101010101010101010101
   137  		ba628a4ba590cb43f7848f41c4382885
   138  		01010101010101010101010101010101
   139  	`)
   140  	msgCode := uint64(8)
   141  	msg := []uint{1, 2, 3, 4}
   142  	msgEnc, _ := rlp.EncodeToBytes(msg)
   143  
   144  	// Check writeFrame. The frame that's written should be equal to the test vector.
   145  	buf := new(bytes.Buffer)
   146  	if err := h.writeFrame(buf, msgCode, msgEnc); err != nil {
   147  		t.Fatalf("WriteMsg error: %v", err)
   148  	}
   149  	if !bytes.Equal(buf.Bytes(), golden) {
   150  		t.Fatalf("output mismatch:\n  got:  %x\n  want: %x", buf.Bytes(), golden)
   151  	}
   152  
   153  	// Check readFrame on the test vector.
   154  	content, err := h.readFrame(bytes.NewReader(golden))
   155  	if err != nil {
   156  		t.Fatalf("ReadMsg error: %v", err)
   157  	}
   158  	wantContent := unhex("08C401020304")
   159  	if !bytes.Equal(content, wantContent) {
   160  		t.Errorf("frame content mismatch:\ngot  %x\nwant %x", content, wantContent)
   161  	}
   162  }
   163  
   164  type fakeHash []byte
   165  
   166  func (fakeHash) Write(p []byte) (int, error) { return len(p), nil }
   167  func (fakeHash) Reset()                      {}
   168  func (fakeHash) BlockSize() int              { return 0 }
   169  func (h fakeHash) Size() int                 { return len(h) }
   170  func (h fakeHash) Sum(b []byte) []byte       { return append(b, h...) }
   171  
   172  type handshakeAuthTest struct {
   173  	input       string
   174  	wantVersion uint
   175  	wantRest    []rlp.RawValue
   176  }
   177  
   178  var eip8HandshakeAuthTests = []handshakeAuthTest{
   179  	// (Auth₂) EIP-8 encoding
   180  	{
   181  		input: `
   182  			01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b
   183  			0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84
   184  			9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c
   185  			da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc
   186  			147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6
   187  			d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee
   188  			70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09
   189  			c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3
   190  			6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e
   191  			2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c
   192  			3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c
   193  		`,
   194  		wantVersion: 4,
   195  		wantRest:    []rlp.RawValue{},
   196  	},
   197  	// (Auth₃) RLPx v4 EIP-8 encoding with version 56, additional list elements
   198  	{
   199  		input: `
   200  			01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7
   201  			2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf
   202  			280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb
   203  			f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b
   204  			cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352
   205  			bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19
   206  			6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757
   207  			1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15
   208  			116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740
   209  			7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2
   210  			f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6
   211  			d490
   212  		`,
   213  		wantVersion: 56,
   214  		wantRest:    []rlp.RawValue{{0x01}, {0x02}, {0xC2, 0x04, 0x05}},
   215  	},
   216  }
   217  
   218  type handshakeAckTest struct {
   219  	input       string
   220  	wantVersion uint
   221  	wantRest    []rlp.RawValue
   222  }
   223  
   224  var eip8HandshakeRespTests = []handshakeAckTest{
   225  	// (Ack₂) EIP-8 encoding
   226  	{
   227  		input: `
   228  			01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470
   229  			b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de
   230  			05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814
   231  			c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171
   232  			ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f
   233  			6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb
   234  			e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d
   235  			3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b
   236  			201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8
   237  			797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac
   238  			8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7
   239  			1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7
   240  			5833c2464c805246155289f4
   241  		`,
   242  		wantVersion: 4,
   243  		wantRest:    []rlp.RawValue{},
   244  	},
   245  	// (Ack₃) EIP-8 encoding with version 57, additional list elements
   246  	{
   247  		input: `
   248  			01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7
   249  			ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0
   250  			3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d
   251  			dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20
   252  			2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3
   253  			d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8
   254  			590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1
   255  			c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115
   256  			8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c
   257  			436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59
   258  			3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f
   259  			39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0
   260  			35b9593b48b9d3ca4c13d245d5f04169b0b1
   261  		`,
   262  		wantVersion: 57,
   263  		wantRest:    []rlp.RawValue{{0x06}, {0xC2, 0x07, 0x08}, {0x81, 0xFA}},
   264  	},
   265  }
   266  
   267  var (
   268  	keyA, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
   269  	keyB, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   270  )
   271  
   272  func TestHandshakeForwardCompatibility(t *testing.T) {
   273  	var (
   274  		pubA          = crypto.FromECDSAPub(&keyA.PublicKey)[1:]
   275  		pubB          = crypto.FromECDSAPub(&keyB.PublicKey)[1:]
   276  		ephA, _       = crypto.HexToECDSA("869d6ecf5211f1cc60418a13b9d870b22959d0c16f02bec714c960dd2298a32d")
   277  		ephB, _       = crypto.HexToECDSA("e238eb8e04fee6511ab04c6dd3c89ce097b11f25d584863ac2b6d5b35b1847e4")
   278  		ephPubA       = crypto.FromECDSAPub(&ephA.PublicKey)[1:]
   279  		ephPubB       = crypto.FromECDSAPub(&ephB.PublicKey)[1:]
   280  		nonceA        = unhex("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6")
   281  		nonceB        = unhex("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd")
   282  		_, _, _, _    = pubA, pubB, ephPubA, ephPubB
   283  		authSignature = unhex("299ca6acfd35e3d72d8ba3d1e2b60b5561d5af5218eb5bc182045769eb4226910a301acae3b369fffc4a4899d6b02531e89fd4fe36a2cf0d93607ba470b50f7800")
   284  		_             = authSignature
   285  	)
   286  	makeAuth := func(test handshakeAuthTest) *authMsgV4 {
   287  		msg := &authMsgV4{Version: test.wantVersion, Rest: test.wantRest}
   288  		copy(msg.Signature[:], authSignature)
   289  		copy(msg.InitiatorPubkey[:], pubA)
   290  		copy(msg.Nonce[:], nonceA)
   291  		return msg
   292  	}
   293  	makeAck := func(test handshakeAckTest) *authRespV4 {
   294  		msg := &authRespV4{Version: test.wantVersion, Rest: test.wantRest}
   295  		copy(msg.RandomPubkey[:], ephPubB)
   296  		copy(msg.Nonce[:], nonceB)
   297  		return msg
   298  	}
   299  
   300  	// check auth msg parsing
   301  	for _, test := range eip8HandshakeAuthTests {
   302  		var h handshakeState
   303  		r := bytes.NewReader(unhex(test.input))
   304  		msg := new(authMsgV4)
   305  		ciphertext, err := h.readMsg(msg, keyB, r)
   306  		if err != nil {
   307  			t.Errorf("error for input %x:\n  %v", unhex(test.input), err)
   308  			continue
   309  		}
   310  		if !bytes.Equal(ciphertext, unhex(test.input)) {
   311  			t.Errorf("wrong ciphertext for input %x:\n  %x", unhex(test.input), ciphertext)
   312  		}
   313  		want := makeAuth(test)
   314  		if !reflect.DeepEqual(msg, want) {
   315  			t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", unhex(test.input), spew.Sdump(msg), spew.Sdump(want))
   316  		}
   317  	}
   318  
   319  	// check auth resp parsing
   320  	for _, test := range eip8HandshakeRespTests {
   321  		var h handshakeState
   322  		input := unhex(test.input)
   323  		r := bytes.NewReader(input)
   324  		msg := new(authRespV4)
   325  		ciphertext, err := h.readMsg(msg, keyA, r)
   326  		if err != nil {
   327  			t.Errorf("error for input %x:\n  %v", input, err)
   328  			continue
   329  		}
   330  		if !bytes.Equal(ciphertext, input) {
   331  			t.Errorf("wrong ciphertext for input %x:\n  %x", input, err)
   332  		}
   333  		want := makeAck(test)
   334  		if !reflect.DeepEqual(msg, want) {
   335  			t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", input, spew.Sdump(msg), spew.Sdump(want))
   336  		}
   337  	}
   338  
   339  	// check derivation for (Auth₂, Ack₂) on recipient side
   340  	var (
   341  		hs = &handshakeState{
   342  			initiator:     false,
   343  			respNonce:     nonceB,
   344  			randomPrivKey: ecies.ImportECDSA(ephB),
   345  		}
   346  		authCiphertext     = unhex(eip8HandshakeAuthTests[0].input)
   347  		authRespCiphertext = unhex(eip8HandshakeRespTests[0].input)
   348  		authMsg            = makeAuth(eip8HandshakeAuthTests[0])
   349  		wantAES            = unhex("80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487")
   350  		wantMAC            = unhex("2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98")
   351  		wantFooIngressHash = unhex("0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5")
   352  	)
   353  	if err := hs.handleAuthMsg(authMsg, keyB); err != nil {
   354  		t.Fatalf("handleAuthMsg: %v", err)
   355  	}
   356  	derived, err := hs.secrets(authCiphertext, authRespCiphertext)
   357  	if err != nil {
   358  		t.Fatalf("secrets: %v", err)
   359  	}
   360  	if !bytes.Equal(derived.AES, wantAES) {
   361  		t.Errorf("aes-secret mismatch:\ngot %x\nwant %x", derived.AES, wantAES)
   362  	}
   363  	if !bytes.Equal(derived.MAC, wantMAC) {
   364  		t.Errorf("mac-secret mismatch:\ngot %x\nwant %x", derived.MAC, wantMAC)
   365  	}
   366  	io.WriteString(derived.IngressMAC, "foo")
   367  	fooIngressHash := derived.IngressMAC.Sum(nil)
   368  	if !bytes.Equal(fooIngressHash, wantFooIngressHash) {
   369  		t.Errorf("ingress-mac('foo') mismatch:\ngot %x\nwant %x", fooIngressHash, wantFooIngressHash)
   370  	}
   371  }
   372  
   373  func BenchmarkHandshakeRead(b *testing.B) {
   374  	input := unhex(eip8HandshakeAuthTests[0].input)
   375  
   376  	for i := 0; i < b.N; i++ {
   377  		var (
   378  			h   handshakeState
   379  			r   = bytes.NewReader(input)
   380  			msg = new(authMsgV4)
   381  		)
   382  		if _, err := h.readMsg(msg, keyB, r); err != nil {
   383  			b.Fatal(err)
   384  		}
   385  	}
   386  }
   387  
   388  func BenchmarkThroughput(b *testing.B) {
   389  	pipe1, pipe2, err := pipes.TCPPipe()
   390  	if err != nil {
   391  		b.Fatal(err)
   392  	}
   393  
   394  	var (
   395  		conn1, conn2  = NewConn(pipe1, nil), NewConn(pipe2, &keyA.PublicKey)
   396  		handshakeDone = make(chan error, 1)
   397  		msgdata       = make([]byte, 1024)
   398  		rand          = rand.New(rand.NewSource(1337))
   399  	)
   400  	rand.Read(msgdata)
   401  
   402  	// Server side.
   403  	go func() {
   404  		defer conn1.Close()
   405  		// Perform handshake.
   406  		_, err := conn1.Handshake(keyA)
   407  		handshakeDone <- err
   408  		if err != nil {
   409  			return
   410  		}
   411  		conn1.SetSnappy(true)
   412  		// Keep sending messages until connection closed.
   413  		for {
   414  			if conn1.Write(0, msgdata) != nil {
   415  				return
   416  			}
   417  		}
   418  	}()
   419  
   420  	// Set up client side.
   421  	defer conn2.Close()
   422  	if _, err := conn2.Handshake(keyB); err != nil {
   423  		b.Fatal("client handshake error:", err)
   424  	}
   425  	conn2.SetSnappy(true)
   426  	if err := <-handshakeDone; err != nil {
   427  		b.Fatal("server hanshake error:", err)
   428  	}
   429  
   430  	// Read N messages.
   431  	b.SetBytes(int64(len(msgdata)))
   432  	b.ReportAllocs()
   433  	for i := 0; i < b.N; i++ {
   434  		_, _, err := conn2.Read()
   435  		if err != nil {
   436  			b.Fatal("read error:", err)
   437  		}
   438  	}
   439  }
   440  
   441  func unhex(str string) []byte {
   442  	r := strings.NewReplacer("\t", "", " ", "", "\n", "")
   443  	b, err := hex.DecodeString(r.Replace(str))
   444  	if err != nil {
   445  		panic(fmt.Sprintf("invalid hex string: %q", str))
   446  	}
   447  	return b
   448  }
   449  
   450  func newkey() *ecdsa.PrivateKey {
   451  	key, err := crypto.GenerateKey()
   452  	if err != nil {
   453  		panic("couldn't generate key: " + err.Error())
   454  	}
   455  	return key
   456  }