github.com/cuiweixie/go-ethereum@v1.8.2-0.20180303084001-66cd41af1e38/p2p/rlpx_test.go (about)

     1  // Copyright 2015 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 p2p
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/rand"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  	"io/ioutil"
    26  	"net"
    27  	"reflect"
    28  	"strings"
    29  	"sync"
    30  	"testing"
    31  	"time"
    32  
    33  	"github.com/davecgh/go-spew/spew"
    34  	"github.com/ethereum/go-ethereum/crypto"
    35  	"github.com/ethereum/go-ethereum/crypto/ecies"
    36  	"github.com/ethereum/go-ethereum/crypto/sha3"
    37  	"github.com/ethereum/go-ethereum/p2p/discover"
    38  	"github.com/ethereum/go-ethereum/rlp"
    39  )
    40  
    41  func TestSharedSecret(t *testing.T) {
    42  	prv0, _ := crypto.GenerateKey() // = ecdsa.GenerateKey(crypto.S256(), rand.Reader)
    43  	pub0 := &prv0.PublicKey
    44  	prv1, _ := crypto.GenerateKey()
    45  	pub1 := &prv1.PublicKey
    46  
    47  	ss0, err := ecies.ImportECDSA(prv0).GenerateShared(ecies.ImportECDSAPublic(pub1), sskLen, sskLen)
    48  	if err != nil {
    49  		return
    50  	}
    51  	ss1, err := ecies.ImportECDSA(prv1).GenerateShared(ecies.ImportECDSAPublic(pub0), sskLen, sskLen)
    52  	if err != nil {
    53  		return
    54  	}
    55  	t.Logf("Secret:\n%v %x\n%v %x", len(ss0), ss0, len(ss0), ss1)
    56  	if !bytes.Equal(ss0, ss1) {
    57  		t.Errorf("dont match :(")
    58  	}
    59  }
    60  
    61  func TestEncHandshake(t *testing.T) {
    62  	for i := 0; i < 10; i++ {
    63  		start := time.Now()
    64  		if err := testEncHandshake(nil); err != nil {
    65  			t.Fatalf("i=%d %v", i, err)
    66  		}
    67  		t.Logf("(without token) %d %v\n", i+1, time.Since(start))
    68  	}
    69  	for i := 0; i < 10; i++ {
    70  		tok := make([]byte, shaLen)
    71  		rand.Reader.Read(tok)
    72  		start := time.Now()
    73  		if err := testEncHandshake(tok); err != nil {
    74  			t.Fatalf("i=%d %v", i, err)
    75  		}
    76  		t.Logf("(with token) %d %v\n", i+1, time.Since(start))
    77  	}
    78  }
    79  
    80  func testEncHandshake(token []byte) error {
    81  	type result struct {
    82  		side string
    83  		id   discover.NodeID
    84  		err  error
    85  	}
    86  	var (
    87  		prv0, _  = crypto.GenerateKey()
    88  		prv1, _  = crypto.GenerateKey()
    89  		fd0, fd1 = net.Pipe()
    90  		c0, c1   = newRLPX(fd0).(*rlpx), newRLPX(fd1).(*rlpx)
    91  		output   = make(chan result)
    92  	)
    93  
    94  	go func() {
    95  		r := result{side: "initiator"}
    96  		defer func() { output <- r }()
    97  		defer fd0.Close()
    98  
    99  		dest := &discover.Node{ID: discover.PubkeyID(&prv1.PublicKey)}
   100  		r.id, r.err = c0.doEncHandshake(prv0, dest)
   101  		if r.err != nil {
   102  			return
   103  		}
   104  		id1 := discover.PubkeyID(&prv1.PublicKey)
   105  		if r.id != id1 {
   106  			r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.id, id1)
   107  		}
   108  	}()
   109  	go func() {
   110  		r := result{side: "receiver"}
   111  		defer func() { output <- r }()
   112  		defer fd1.Close()
   113  
   114  		r.id, r.err = c1.doEncHandshake(prv1, nil)
   115  		if r.err != nil {
   116  			return
   117  		}
   118  		id0 := discover.PubkeyID(&prv0.PublicKey)
   119  		if r.id != id0 {
   120  			r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.id, id0)
   121  		}
   122  	}()
   123  
   124  	// wait for results from both sides
   125  	r1, r2 := <-output, <-output
   126  	if r1.err != nil {
   127  		return fmt.Errorf("%s side error: %v", r1.side, r1.err)
   128  	}
   129  	if r2.err != nil {
   130  		return fmt.Errorf("%s side error: %v", r2.side, r2.err)
   131  	}
   132  
   133  	// compare derived secrets
   134  	if !reflect.DeepEqual(c0.rw.egressMAC, c1.rw.ingressMAC) {
   135  		return fmt.Errorf("egress mac mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.egressMAC, c1.rw.ingressMAC)
   136  	}
   137  	if !reflect.DeepEqual(c0.rw.ingressMAC, c1.rw.egressMAC) {
   138  		return fmt.Errorf("ingress mac mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.ingressMAC, c1.rw.egressMAC)
   139  	}
   140  	if !reflect.DeepEqual(c0.rw.enc, c1.rw.enc) {
   141  		return fmt.Errorf("enc cipher mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.enc, c1.rw.enc)
   142  	}
   143  	if !reflect.DeepEqual(c0.rw.dec, c1.rw.dec) {
   144  		return fmt.Errorf("dec cipher mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.dec, c1.rw.dec)
   145  	}
   146  	return nil
   147  }
   148  
   149  func TestProtocolHandshake(t *testing.T) {
   150  	var (
   151  		prv0, _ = crypto.GenerateKey()
   152  		node0   = &discover.Node{ID: discover.PubkeyID(&prv0.PublicKey), IP: net.IP{1, 2, 3, 4}, TCP: 33}
   153  		hs0     = &protoHandshake{Version: 3, ID: node0.ID, Caps: []Cap{{"a", 0}, {"b", 2}}}
   154  
   155  		prv1, _ = crypto.GenerateKey()
   156  		node1   = &discover.Node{ID: discover.PubkeyID(&prv1.PublicKey), IP: net.IP{5, 6, 7, 8}, TCP: 44}
   157  		hs1     = &protoHandshake{Version: 3, ID: node1.ID, Caps: []Cap{{"c", 1}, {"d", 3}}}
   158  
   159  		wg sync.WaitGroup
   160  	)
   161  
   162  	fd0, fd1, err := tcpPipe()
   163  	if err != nil {
   164  		t.Fatal(err)
   165  	}
   166  
   167  	wg.Add(2)
   168  	go func() {
   169  		defer wg.Done()
   170  		defer fd0.Close()
   171  		rlpx := newRLPX(fd0)
   172  		remid, err := rlpx.doEncHandshake(prv0, node1)
   173  		if err != nil {
   174  			t.Errorf("dial side enc handshake failed: %v", err)
   175  			return
   176  		}
   177  		if remid != node1.ID {
   178  			t.Errorf("dial side remote id mismatch: got %v, want %v", remid, node1.ID)
   179  			return
   180  		}
   181  
   182  		phs, err := rlpx.doProtoHandshake(hs0)
   183  		if err != nil {
   184  			t.Errorf("dial side proto handshake error: %v", err)
   185  			return
   186  		}
   187  		phs.Rest = nil
   188  		if !reflect.DeepEqual(phs, hs1) {
   189  			t.Errorf("dial side proto handshake mismatch:\ngot: %s\nwant: %s\n", spew.Sdump(phs), spew.Sdump(hs1))
   190  			return
   191  		}
   192  		rlpx.close(DiscQuitting)
   193  	}()
   194  	go func() {
   195  		defer wg.Done()
   196  		defer fd1.Close()
   197  		rlpx := newRLPX(fd1)
   198  		remid, err := rlpx.doEncHandshake(prv1, nil)
   199  		if err != nil {
   200  			t.Errorf("listen side enc handshake failed: %v", err)
   201  			return
   202  		}
   203  		if remid != node0.ID {
   204  			t.Errorf("listen side remote id mismatch: got %v, want %v", remid, node0.ID)
   205  			return
   206  		}
   207  
   208  		phs, err := rlpx.doProtoHandshake(hs1)
   209  		if err != nil {
   210  			t.Errorf("listen side proto handshake error: %v", err)
   211  			return
   212  		}
   213  		phs.Rest = nil
   214  		if !reflect.DeepEqual(phs, hs0) {
   215  			t.Errorf("listen side proto handshake mismatch:\ngot: %s\nwant: %s\n", spew.Sdump(phs), spew.Sdump(hs0))
   216  			return
   217  		}
   218  
   219  		if err := ExpectMsg(rlpx, discMsg, []DiscReason{DiscQuitting}); err != nil {
   220  			t.Errorf("error receiving disconnect: %v", err)
   221  		}
   222  	}()
   223  	wg.Wait()
   224  }
   225  
   226  func TestProtocolHandshakeErrors(t *testing.T) {
   227  	our := &protoHandshake{Version: 3, Caps: []Cap{{"foo", 2}, {"bar", 3}}, Name: "quux"}
   228  	tests := []struct {
   229  		code uint64
   230  		msg  interface{}
   231  		err  error
   232  	}{
   233  		{
   234  			code: discMsg,
   235  			msg:  []DiscReason{DiscQuitting},
   236  			err:  DiscQuitting,
   237  		},
   238  		{
   239  			code: 0x989898,
   240  			msg:  []byte{1},
   241  			err:  errors.New("expected handshake, got 989898"),
   242  		},
   243  		{
   244  			code: handshakeMsg,
   245  			msg:  make([]byte, baseProtocolMaxMsgSize+2),
   246  			err:  errors.New("message too big"),
   247  		},
   248  		{
   249  			code: handshakeMsg,
   250  			msg:  []byte{1, 2, 3},
   251  			err:  newPeerError(errInvalidMsg, "(code 0) (size 4) rlp: expected input list for p2p.protoHandshake"),
   252  		},
   253  		{
   254  			code: handshakeMsg,
   255  			msg:  &protoHandshake{Version: 3},
   256  			err:  DiscInvalidIdentity,
   257  		},
   258  	}
   259  
   260  	for i, test := range tests {
   261  		p1, p2 := MsgPipe()
   262  		go Send(p1, test.code, test.msg)
   263  		_, err := readProtocolHandshake(p2, our)
   264  		if !reflect.DeepEqual(err, test.err) {
   265  			t.Errorf("test %d: error mismatch: got %q, want %q", i, err, test.err)
   266  		}
   267  	}
   268  }
   269  
   270  func TestRLPXFrameFake(t *testing.T) {
   271  	buf := new(bytes.Buffer)
   272  	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})
   273  	rw := newRLPXFrameRW(buf, secrets{
   274  		AES:        crypto.Keccak256(),
   275  		MAC:        crypto.Keccak256(),
   276  		IngressMAC: hash,
   277  		EgressMAC:  hash,
   278  	})
   279  
   280  	golden := unhex(`
   281  00828ddae471818bb0bfa6b551d1cb42
   282  01010101010101010101010101010101
   283  ba628a4ba590cb43f7848f41c4382885
   284  01010101010101010101010101010101
   285  `)
   286  
   287  	// Check WriteMsg. This puts a message into the buffer.
   288  	if err := Send(rw, 8, []uint{1, 2, 3, 4}); err != nil {
   289  		t.Fatalf("WriteMsg error: %v", err)
   290  	}
   291  	written := buf.Bytes()
   292  	if !bytes.Equal(written, golden) {
   293  		t.Fatalf("output mismatch:\n  got:  %x\n  want: %x", written, golden)
   294  	}
   295  
   296  	// Check ReadMsg. It reads the message encoded by WriteMsg, which
   297  	// is equivalent to the golden message above.
   298  	msg, err := rw.ReadMsg()
   299  	if err != nil {
   300  		t.Fatalf("ReadMsg error: %v", err)
   301  	}
   302  	if msg.Size != 5 {
   303  		t.Errorf("msg size mismatch: got %d, want %d", msg.Size, 5)
   304  	}
   305  	if msg.Code != 8 {
   306  		t.Errorf("msg code mismatch: got %d, want %d", msg.Code, 8)
   307  	}
   308  	payload, _ := ioutil.ReadAll(msg.Payload)
   309  	wantPayload := unhex("C401020304")
   310  	if !bytes.Equal(payload, wantPayload) {
   311  		t.Errorf("msg payload mismatch:\ngot  %x\nwant %x", payload, wantPayload)
   312  	}
   313  }
   314  
   315  type fakeHash []byte
   316  
   317  func (fakeHash) Write(p []byte) (int, error) { return len(p), nil }
   318  func (fakeHash) Reset()                      {}
   319  func (fakeHash) BlockSize() int              { return 0 }
   320  
   321  func (h fakeHash) Size() int           { return len(h) }
   322  func (h fakeHash) Sum(b []byte) []byte { return append(b, h...) }
   323  
   324  func TestRLPXFrameRW(t *testing.T) {
   325  	var (
   326  		aesSecret      = make([]byte, 16)
   327  		macSecret      = make([]byte, 16)
   328  		egressMACinit  = make([]byte, 32)
   329  		ingressMACinit = make([]byte, 32)
   330  	)
   331  	for _, s := range [][]byte{aesSecret, macSecret, egressMACinit, ingressMACinit} {
   332  		rand.Read(s)
   333  	}
   334  	conn := new(bytes.Buffer)
   335  
   336  	s1 := secrets{
   337  		AES:        aesSecret,
   338  		MAC:        macSecret,
   339  		EgressMAC:  sha3.NewKeccak256(),
   340  		IngressMAC: sha3.NewKeccak256(),
   341  	}
   342  	s1.EgressMAC.Write(egressMACinit)
   343  	s1.IngressMAC.Write(ingressMACinit)
   344  	rw1 := newRLPXFrameRW(conn, s1)
   345  
   346  	s2 := secrets{
   347  		AES:        aesSecret,
   348  		MAC:        macSecret,
   349  		EgressMAC:  sha3.NewKeccak256(),
   350  		IngressMAC: sha3.NewKeccak256(),
   351  	}
   352  	s2.EgressMAC.Write(ingressMACinit)
   353  	s2.IngressMAC.Write(egressMACinit)
   354  	rw2 := newRLPXFrameRW(conn, s2)
   355  
   356  	// send some messages
   357  	for i := 0; i < 10; i++ {
   358  		// write message into conn buffer
   359  		wmsg := []interface{}{"foo", "bar", strings.Repeat("test", i)}
   360  		err := Send(rw1, uint64(i), wmsg)
   361  		if err != nil {
   362  			t.Fatalf("WriteMsg error (i=%d): %v", i, err)
   363  		}
   364  
   365  		// read message that rw1 just wrote
   366  		msg, err := rw2.ReadMsg()
   367  		if err != nil {
   368  			t.Fatalf("ReadMsg error (i=%d): %v", i, err)
   369  		}
   370  		if msg.Code != uint64(i) {
   371  			t.Fatalf("msg code mismatch: got %d, want %d", msg.Code, i)
   372  		}
   373  		payload, _ := ioutil.ReadAll(msg.Payload)
   374  		wantPayload, _ := rlp.EncodeToBytes(wmsg)
   375  		if !bytes.Equal(payload, wantPayload) {
   376  			t.Fatalf("msg payload mismatch:\ngot  %x\nwant %x", payload, wantPayload)
   377  		}
   378  	}
   379  }
   380  
   381  type handshakeAuthTest struct {
   382  	input       string
   383  	isPlain     bool
   384  	wantVersion uint
   385  	wantRest    []rlp.RawValue
   386  }
   387  
   388  var eip8HandshakeAuthTests = []handshakeAuthTest{
   389  	// (Auth₁) RLPx v4 plain encoding
   390  	{
   391  		input: `
   392  			048ca79ad18e4b0659fab4853fe5bc58eb83992980f4c9cc147d2aa31532efd29a3d3dc6a3d89eaf
   393  			913150cfc777ce0ce4af2758bf4810235f6e6ceccfee1acc6b22c005e9e3a49d6448610a58e98744
   394  			ba3ac0399e82692d67c1f58849050b3024e21a52c9d3b01d871ff5f210817912773e610443a9ef14
   395  			2e91cdba0bd77b5fdf0769b05671fc35f83d83e4d3b0b000c6b2a1b1bba89e0fc51bf4e460df3105
   396  			c444f14be226458940d6061c296350937ffd5e3acaceeaaefd3c6f74be8e23e0f45163cc7ebd7622
   397  			0f0128410fd05250273156d548a414444ae2f7dea4dfca2d43c057adb701a715bf59f6fb66b2d1d2
   398  			0f2c703f851cbf5ac47396d9ca65b6260bd141ac4d53e2de585a73d1750780db4c9ee4cd4d225173
   399  			a4592ee77e2bd94d0be3691f3b406f9bba9b591fc63facc016bfa8
   400  		`,
   401  		isPlain:     true,
   402  		wantVersion: 4,
   403  	},
   404  	// (Auth₂) EIP-8 encoding
   405  	{
   406  		input: `
   407  			01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b
   408  			0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84
   409  			9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c
   410  			da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc
   411  			147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6
   412  			d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee
   413  			70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09
   414  			c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3
   415  			6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e
   416  			2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c
   417  			3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c
   418  		`,
   419  		wantVersion: 4,
   420  		wantRest:    []rlp.RawValue{},
   421  	},
   422  	// (Auth₃) RLPx v4 EIP-8 encoding with version 56, additional list elements
   423  	{
   424  		input: `
   425  			01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7
   426  			2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf
   427  			280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb
   428  			f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b
   429  			cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352
   430  			bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19
   431  			6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757
   432  			1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15
   433  			116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740
   434  			7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2
   435  			f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6
   436  			d490
   437  		`,
   438  		wantVersion: 56,
   439  		wantRest:    []rlp.RawValue{{0x01}, {0x02}, {0xC2, 0x04, 0x05}},
   440  	},
   441  }
   442  
   443  type handshakeAckTest struct {
   444  	input       string
   445  	wantVersion uint
   446  	wantRest    []rlp.RawValue
   447  }
   448  
   449  var eip8HandshakeRespTests = []handshakeAckTest{
   450  	// (Ack₁) RLPx v4 plain encoding
   451  	{
   452  		input: `
   453  			049f8abcfa9c0dc65b982e98af921bc0ba6e4243169348a236abe9df5f93aa69d99cadddaa387662
   454  			b0ff2c08e9006d5a11a278b1b3331e5aaabf0a32f01281b6f4ede0e09a2d5f585b26513cb794d963
   455  			5a57563921c04a9090b4f14ee42be1a5461049af4ea7a7f49bf4c97a352d39c8d02ee4acc416388c
   456  			1c66cec761d2bc1c72da6ba143477f049c9d2dde846c252c111b904f630ac98e51609b3b1f58168d
   457  			dca6505b7196532e5f85b259a20c45e1979491683fee108e9660edbf38f3add489ae73e3dda2c71b
   458  			d1497113d5c755e942d1
   459  		`,
   460  		wantVersion: 4,
   461  	},
   462  	// (Ack₂) EIP-8 encoding
   463  	{
   464  		input: `
   465  			01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470
   466  			b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de
   467  			05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814
   468  			c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171
   469  			ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f
   470  			6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb
   471  			e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d
   472  			3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b
   473  			201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8
   474  			797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac
   475  			8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7
   476  			1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7
   477  			5833c2464c805246155289f4
   478  		`,
   479  		wantVersion: 4,
   480  		wantRest:    []rlp.RawValue{},
   481  	},
   482  	// (Ack₃) EIP-8 encoding with version 57, additional list elements
   483  	{
   484  		input: `
   485  			01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7
   486  			ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0
   487  			3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d
   488  			dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20
   489  			2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3
   490  			d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8
   491  			590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1
   492  			c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115
   493  			8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c
   494  			436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59
   495  			3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f
   496  			39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0
   497  			35b9593b48b9d3ca4c13d245d5f04169b0b1
   498  		`,
   499  		wantVersion: 57,
   500  		wantRest:    []rlp.RawValue{{0x06}, {0xC2, 0x07, 0x08}, {0x81, 0xFA}},
   501  	},
   502  }
   503  
   504  func TestHandshakeForwardCompatibility(t *testing.T) {
   505  	var (
   506  		keyA, _       = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
   507  		keyB, _       = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   508  		pubA          = crypto.FromECDSAPub(&keyA.PublicKey)[1:]
   509  		pubB          = crypto.FromECDSAPub(&keyB.PublicKey)[1:]
   510  		ephA, _       = crypto.HexToECDSA("869d6ecf5211f1cc60418a13b9d870b22959d0c16f02bec714c960dd2298a32d")
   511  		ephB, _       = crypto.HexToECDSA("e238eb8e04fee6511ab04c6dd3c89ce097b11f25d584863ac2b6d5b35b1847e4")
   512  		ephPubA       = crypto.FromECDSAPub(&ephA.PublicKey)[1:]
   513  		ephPubB       = crypto.FromECDSAPub(&ephB.PublicKey)[1:]
   514  		nonceA        = unhex("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6")
   515  		nonceB        = unhex("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd")
   516  		_, _, _, _    = pubA, pubB, ephPubA, ephPubB
   517  		authSignature = unhex("299ca6acfd35e3d72d8ba3d1e2b60b5561d5af5218eb5bc182045769eb4226910a301acae3b369fffc4a4899d6b02531e89fd4fe36a2cf0d93607ba470b50f7800")
   518  		_             = authSignature
   519  	)
   520  	makeAuth := func(test handshakeAuthTest) *authMsgV4 {
   521  		msg := &authMsgV4{Version: test.wantVersion, Rest: test.wantRest, gotPlain: test.isPlain}
   522  		copy(msg.Signature[:], authSignature)
   523  		copy(msg.InitiatorPubkey[:], pubA)
   524  		copy(msg.Nonce[:], nonceA)
   525  		return msg
   526  	}
   527  	makeAck := func(test handshakeAckTest) *authRespV4 {
   528  		msg := &authRespV4{Version: test.wantVersion, Rest: test.wantRest}
   529  		copy(msg.RandomPubkey[:], ephPubB)
   530  		copy(msg.Nonce[:], nonceB)
   531  		return msg
   532  	}
   533  
   534  	// check auth msg parsing
   535  	for _, test := range eip8HandshakeAuthTests {
   536  		r := bytes.NewReader(unhex(test.input))
   537  		msg := new(authMsgV4)
   538  		ciphertext, err := readHandshakeMsg(msg, encAuthMsgLen, keyB, r)
   539  		if err != nil {
   540  			t.Errorf("error for input %x:\n  %v", unhex(test.input), err)
   541  			continue
   542  		}
   543  		if !bytes.Equal(ciphertext, unhex(test.input)) {
   544  			t.Errorf("wrong ciphertext for input %x:\n  %x", unhex(test.input), ciphertext)
   545  		}
   546  		want := makeAuth(test)
   547  		if !reflect.DeepEqual(msg, want) {
   548  			t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", unhex(test.input), spew.Sdump(msg), spew.Sdump(want))
   549  		}
   550  	}
   551  
   552  	// check auth resp parsing
   553  	for _, test := range eip8HandshakeRespTests {
   554  		input := unhex(test.input)
   555  		r := bytes.NewReader(input)
   556  		msg := new(authRespV4)
   557  		ciphertext, err := readHandshakeMsg(msg, encAuthRespLen, keyA, r)
   558  		if err != nil {
   559  			t.Errorf("error for input %x:\n  %v", input, err)
   560  			continue
   561  		}
   562  		if !bytes.Equal(ciphertext, input) {
   563  			t.Errorf("wrong ciphertext for input %x:\n  %x", input, err)
   564  		}
   565  		want := makeAck(test)
   566  		if !reflect.DeepEqual(msg, want) {
   567  			t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", input, spew.Sdump(msg), spew.Sdump(want))
   568  		}
   569  	}
   570  
   571  	// check derivation for (Auth₂, Ack₂) on recipient side
   572  	var (
   573  		hs = &encHandshake{
   574  			initiator:     false,
   575  			respNonce:     nonceB,
   576  			randomPrivKey: ecies.ImportECDSA(ephB),
   577  		}
   578  		authCiphertext     = unhex(eip8HandshakeAuthTests[1].input)
   579  		authRespCiphertext = unhex(eip8HandshakeRespTests[1].input)
   580  		authMsg            = makeAuth(eip8HandshakeAuthTests[1])
   581  		wantAES            = unhex("80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487")
   582  		wantMAC            = unhex("2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98")
   583  		wantFooIngressHash = unhex("0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5")
   584  	)
   585  	if err := hs.handleAuthMsg(authMsg, keyB); err != nil {
   586  		t.Fatalf("handleAuthMsg: %v", err)
   587  	}
   588  	derived, err := hs.secrets(authCiphertext, authRespCiphertext)
   589  	if err != nil {
   590  		t.Fatalf("secrets: %v", err)
   591  	}
   592  	if !bytes.Equal(derived.AES, wantAES) {
   593  		t.Errorf("aes-secret mismatch:\ngot %x\nwant %x", derived.AES, wantAES)
   594  	}
   595  	if !bytes.Equal(derived.MAC, wantMAC) {
   596  		t.Errorf("mac-secret mismatch:\ngot %x\nwant %x", derived.MAC, wantMAC)
   597  	}
   598  	io.WriteString(derived.IngressMAC, "foo")
   599  	fooIngressHash := derived.IngressMAC.Sum(nil)
   600  	if !bytes.Equal(fooIngressHash, wantFooIngressHash) {
   601  		t.Errorf("ingress-mac('foo') mismatch:\ngot %x\nwant %x", fooIngressHash, wantFooIngressHash)
   602  	}
   603  }
   604  
   605  // tcpPipe creates an in process full duplex pipe based on a localhost TCP socket
   606  func tcpPipe() (net.Conn, net.Conn, error) {
   607  	l, err := net.Listen("tcp", "127.0.0.1:0")
   608  	if err != nil {
   609  		return nil, nil, err
   610  	}
   611  	defer l.Close()
   612  
   613  	var aconn net.Conn
   614  	aerr := make(chan error, 1)
   615  	go func() {
   616  		var err error
   617  		aconn, err = l.Accept()
   618  		aerr <- err
   619  	}()
   620  
   621  	dconn, err := net.Dial("tcp", l.Addr().String())
   622  	if err != nil {
   623  		<-aerr
   624  		return nil, nil, err
   625  	}
   626  	if err := <-aerr; err != nil {
   627  		dconn.Close()
   628  		return nil, nil, err
   629  	}
   630  	return aconn, dconn, nil
   631  }