encoding_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. // Copyright 2019 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. package v5wire
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "flag"
  22. "fmt"
  23. "io/ioutil"
  24. "net"
  25. "os"
  26. "path/filepath"
  27. "reflect"
  28. "strings"
  29. "testing"
  30. "github.com/davecgh/go-spew/spew"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/common/mclock"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/p2p/enode"
  35. )
  36. // To regenerate discv5 test vectors, run
  37. //
  38. // go test -run TestVectors -write-test-vectors
  39. //
  40. var writeTestVectorsFlag = flag.Bool("write-test-vectors", false, "Overwrite discv5 test vectors in testdata/")
  41. var (
  42. testKeyA, _ = crypto.HexToECDSA("eef77acb6c6a6eebc5b363a475ac583ec7eccdb42b6481424c60f59aa326547f")
  43. testKeyB, _ = crypto.HexToECDSA("66fb62bfbd66b9177a138c1e5cddbe4f7c30c343e94e68df8769459cb1cde628")
  44. testEphKey, _ = crypto.HexToECDSA("0288ef00023598499cb6c940146d050d2b1fb914198c327f76aad590bead68b6")
  45. testIDnonce = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
  46. )
  47. // This test checks that the minPacketSize and randomPacketMsgSize constants are well-defined.
  48. func TestMinSizes(t *testing.T) {
  49. var (
  50. gcmTagSize = 16
  51. emptyMsg = sizeofMessageAuthData + gcmTagSize
  52. )
  53. t.Log("static header size", sizeofStaticPacketData)
  54. t.Log("whoareyou size", sizeofStaticPacketData+sizeofWhoareyouAuthData)
  55. t.Log("empty msg size", sizeofStaticPacketData+emptyMsg)
  56. if want := emptyMsg; minMessageSize != want {
  57. t.Fatalf("wrong minMessageSize %d, want %d", minMessageSize, want)
  58. }
  59. if sizeofMessageAuthData+randomPacketMsgSize < minMessageSize {
  60. t.Fatalf("randomPacketMsgSize %d too small", randomPacketMsgSize)
  61. }
  62. }
  63. // This test checks the basic handshake flow where A talks to B and A has no secrets.
  64. func TestHandshake(t *testing.T) {
  65. t.Parallel()
  66. net := newHandshakeTest()
  67. defer net.close()
  68. // A -> B RANDOM PACKET
  69. packet, _ := net.nodeA.encode(t, net.nodeB, &Findnode{})
  70. resp := net.nodeB.expectDecode(t, UnknownPacket, packet)
  71. // A <- B WHOAREYOU
  72. challenge := &Whoareyou{
  73. Nonce: resp.(*Unknown).Nonce,
  74. IDNonce: testIDnonce,
  75. RecordSeq: 0,
  76. }
  77. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  78. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  79. // A -> B FINDNODE (handshake packet)
  80. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  81. net.nodeB.expectDecode(t, FindnodeMsg, findnode)
  82. if len(net.nodeB.c.sc.handshakes) > 0 {
  83. t.Fatalf("node B didn't remove handshake from challenge map")
  84. }
  85. // A <- B NODES
  86. nodes, _ := net.nodeB.encode(t, net.nodeA, &Nodes{Total: 1})
  87. net.nodeA.expectDecode(t, NodesMsg, nodes)
  88. }
  89. // This test checks that handshake attempts are removed within the timeout.
  90. func TestHandshake_timeout(t *testing.T) {
  91. t.Parallel()
  92. net := newHandshakeTest()
  93. defer net.close()
  94. // A -> B RANDOM PACKET
  95. packet, _ := net.nodeA.encode(t, net.nodeB, &Findnode{})
  96. resp := net.nodeB.expectDecode(t, UnknownPacket, packet)
  97. // A <- B WHOAREYOU
  98. challenge := &Whoareyou{
  99. Nonce: resp.(*Unknown).Nonce,
  100. IDNonce: testIDnonce,
  101. RecordSeq: 0,
  102. }
  103. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  104. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  105. // A -> B FINDNODE (handshake packet) after timeout
  106. net.clock.Run(handshakeTimeout + 1)
  107. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  108. net.nodeB.expectDecodeErr(t, errUnexpectedHandshake, findnode)
  109. }
  110. // This test checks handshake behavior when no record is sent in the auth response.
  111. func TestHandshake_norecord(t *testing.T) {
  112. t.Parallel()
  113. net := newHandshakeTest()
  114. defer net.close()
  115. // A -> B RANDOM PACKET
  116. packet, _ := net.nodeA.encode(t, net.nodeB, &Findnode{})
  117. resp := net.nodeB.expectDecode(t, UnknownPacket, packet)
  118. // A <- B WHOAREYOU
  119. nodeA := net.nodeA.n()
  120. if nodeA.Seq() == 0 {
  121. t.Fatal("need non-zero sequence number")
  122. }
  123. challenge := &Whoareyou{
  124. Nonce: resp.(*Unknown).Nonce,
  125. IDNonce: testIDnonce,
  126. RecordSeq: nodeA.Seq(),
  127. Node: nodeA,
  128. }
  129. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  130. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  131. // A -> B FINDNODE
  132. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  133. net.nodeB.expectDecode(t, FindnodeMsg, findnode)
  134. // A <- B NODES
  135. nodes, _ := net.nodeB.encode(t, net.nodeA, &Nodes{Total: 1})
  136. net.nodeA.expectDecode(t, NodesMsg, nodes)
  137. }
  138. // In this test, A tries to send FINDNODE with existing secrets but B doesn't know
  139. // anything about A.
  140. func TestHandshake_rekey(t *testing.T) {
  141. t.Parallel()
  142. net := newHandshakeTest()
  143. defer net.close()
  144. session := &session{
  145. readKey: []byte("BBBBBBBBBBBBBBBB"),
  146. writeKey: []byte("AAAAAAAAAAAAAAAA"),
  147. }
  148. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session)
  149. // A -> B FINDNODE (encrypted with zero keys)
  150. findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{})
  151. net.nodeB.expectDecode(t, UnknownPacket, findnode)
  152. // A <- B WHOAREYOU
  153. challenge := &Whoareyou{Nonce: authTag, IDNonce: testIDnonce}
  154. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  155. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  156. // Check that new keys haven't been stored yet.
  157. sa := net.nodeA.c.sc.session(net.nodeB.id(), net.nodeB.addr())
  158. if !bytes.Equal(sa.writeKey, session.writeKey) || !bytes.Equal(sa.readKey, session.readKey) {
  159. t.Fatal("node A stored keys too early")
  160. }
  161. if s := net.nodeB.c.sc.session(net.nodeA.id(), net.nodeA.addr()); s != nil {
  162. t.Fatal("node B stored keys too early")
  163. }
  164. // A -> B FINDNODE encrypted with new keys
  165. findnode, _ = net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  166. net.nodeB.expectDecode(t, FindnodeMsg, findnode)
  167. // A <- B NODES
  168. nodes, _ := net.nodeB.encode(t, net.nodeA, &Nodes{Total: 1})
  169. net.nodeA.expectDecode(t, NodesMsg, nodes)
  170. }
  171. // In this test A and B have different keys before the handshake.
  172. func TestHandshake_rekey2(t *testing.T) {
  173. t.Parallel()
  174. net := newHandshakeTest()
  175. defer net.close()
  176. initKeysA := &session{
  177. readKey: []byte("BBBBBBBBBBBBBBBB"),
  178. writeKey: []byte("AAAAAAAAAAAAAAAA"),
  179. }
  180. initKeysB := &session{
  181. readKey: []byte("CCCCCCCCCCCCCCCC"),
  182. writeKey: []byte("DDDDDDDDDDDDDDDD"),
  183. }
  184. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), initKeysA)
  185. net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), initKeysB)
  186. // A -> B FINDNODE encrypted with initKeysA
  187. findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{Distances: []uint{3}})
  188. net.nodeB.expectDecode(t, UnknownPacket, findnode)
  189. // A <- B WHOAREYOU
  190. challenge := &Whoareyou{Nonce: authTag, IDNonce: testIDnonce}
  191. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  192. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  193. // A -> B FINDNODE (handshake packet)
  194. findnode, _ = net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  195. net.nodeB.expectDecode(t, FindnodeMsg, findnode)
  196. // A <- B NODES
  197. nodes, _ := net.nodeB.encode(t, net.nodeA, &Nodes{Total: 1})
  198. net.nodeA.expectDecode(t, NodesMsg, nodes)
  199. }
  200. func TestHandshake_BadHandshakeAttack(t *testing.T) {
  201. t.Parallel()
  202. net := newHandshakeTest()
  203. defer net.close()
  204. // A -> B RANDOM PACKET
  205. packet, _ := net.nodeA.encode(t, net.nodeB, &Findnode{})
  206. resp := net.nodeB.expectDecode(t, UnknownPacket, packet)
  207. // A <- B WHOAREYOU
  208. challenge := &Whoareyou{
  209. Nonce: resp.(*Unknown).Nonce,
  210. IDNonce: testIDnonce,
  211. RecordSeq: 0,
  212. }
  213. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  214. net.nodeA.expectDecode(t, WhoareyouPacket, whoareyou)
  215. // A -> B FINDNODE
  216. incorrect_challenge := &Whoareyou{
  217. IDNonce: [16]byte{5, 6, 7, 8, 9, 6, 11, 12},
  218. RecordSeq: challenge.RecordSeq,
  219. Node: challenge.Node,
  220. sent: challenge.sent,
  221. }
  222. incorrect_findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, incorrect_challenge, &Findnode{})
  223. incorrect_findnode2 := make([]byte, len(incorrect_findnode))
  224. copy(incorrect_findnode2, incorrect_findnode)
  225. net.nodeB.expectDecodeErr(t, errInvalidNonceSig, incorrect_findnode)
  226. // Reject new findnode as previous handshake is now deleted.
  227. net.nodeB.expectDecodeErr(t, errUnexpectedHandshake, incorrect_findnode2)
  228. // The findnode packet is again rejected even with a valid challenge this time.
  229. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &Findnode{})
  230. net.nodeB.expectDecodeErr(t, errUnexpectedHandshake, findnode)
  231. }
  232. // This test checks some malformed packets.
  233. func TestDecodeErrorsV5(t *testing.T) {
  234. t.Parallel()
  235. net := newHandshakeTest()
  236. defer net.close()
  237. net.nodeA.expectDecodeErr(t, errTooShort, []byte{})
  238. // TODO some more tests would be nice :)
  239. // - check invalid authdata sizes
  240. // - check invalid handshake data sizes
  241. }
  242. // This test checks that all test vectors can be decoded.
  243. func TestTestVectorsV5(t *testing.T) {
  244. var (
  245. idA = enode.PubkeyToIDV4(&testKeyA.PublicKey)
  246. idB = enode.PubkeyToIDV4(&testKeyB.PublicKey)
  247. addr = "127.0.0.1"
  248. session = &session{
  249. writeKey: hexutil.MustDecode("0x00000000000000000000000000000000"),
  250. readKey: hexutil.MustDecode("0x01010101010101010101010101010101"),
  251. }
  252. challenge0A, challenge1A, challenge0B Whoareyou
  253. )
  254. // Create challenge packets.
  255. c := Whoareyou{
  256. Nonce: Nonce{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
  257. IDNonce: testIDnonce,
  258. }
  259. challenge0A, challenge1A, challenge0B = c, c, c
  260. challenge1A.RecordSeq = 1
  261. net := newHandshakeTest()
  262. challenge0A.Node = net.nodeA.n()
  263. challenge0B.Node = net.nodeB.n()
  264. challenge1A.Node = net.nodeA.n()
  265. net.close()
  266. type testVectorTest struct {
  267. name string // test vector name
  268. packet Packet // the packet to be encoded
  269. challenge *Whoareyou // handshake challenge passed to encoder
  270. prep func(*handshakeTest) // called before encode/decode
  271. }
  272. tests := []testVectorTest{
  273. {
  274. name: "v5.1-whoareyou",
  275. packet: &challenge0B,
  276. },
  277. {
  278. name: "v5.1-ping-message",
  279. packet: &Ping{
  280. ReqID: []byte{0, 0, 0, 1},
  281. ENRSeq: 2,
  282. },
  283. prep: func(net *handshakeTest) {
  284. net.nodeA.c.sc.storeNewSession(idB, addr, session)
  285. net.nodeB.c.sc.storeNewSession(idA, addr, session.keysFlipped())
  286. },
  287. },
  288. {
  289. name: "v5.1-ping-handshake-enr",
  290. packet: &Ping{
  291. ReqID: []byte{0, 0, 0, 1},
  292. ENRSeq: 1,
  293. },
  294. challenge: &challenge0A,
  295. prep: func(net *handshakeTest) {
  296. // Update challenge.Header.AuthData.
  297. net.nodeA.c.Encode(idB, "", &challenge0A, nil)
  298. net.nodeB.c.sc.storeSentHandshake(idA, addr, &challenge0A)
  299. },
  300. },
  301. {
  302. name: "v5.1-ping-handshake",
  303. packet: &Ping{
  304. ReqID: []byte{0, 0, 0, 1},
  305. ENRSeq: 1,
  306. },
  307. challenge: &challenge1A,
  308. prep: func(net *handshakeTest) {
  309. // Update challenge data.
  310. net.nodeA.c.Encode(idB, "", &challenge1A, nil)
  311. net.nodeB.c.sc.storeSentHandshake(idA, addr, &challenge1A)
  312. },
  313. },
  314. }
  315. for _, test := range tests {
  316. test := test
  317. t.Run(test.name, func(t *testing.T) {
  318. net := newHandshakeTest()
  319. defer net.close()
  320. // Override all random inputs.
  321. net.nodeA.c.sc.nonceGen = func(counter uint32) (Nonce, error) {
  322. return Nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, nil
  323. }
  324. net.nodeA.c.sc.maskingIVGen = func(buf []byte) error {
  325. return nil // all zero
  326. }
  327. net.nodeA.c.sc.ephemeralKeyGen = func() (*ecdsa.PrivateKey, error) {
  328. return testEphKey, nil
  329. }
  330. // Prime the codec for encoding/decoding.
  331. if test.prep != nil {
  332. test.prep(net)
  333. }
  334. file := filepath.Join("testdata", test.name+".txt")
  335. if *writeTestVectorsFlag {
  336. // Encode the packet.
  337. d, nonce := net.nodeA.encodeWithChallenge(t, net.nodeB, test.challenge, test.packet)
  338. comment := testVectorComment(net, test.packet, test.challenge, nonce)
  339. writeTestVector(file, comment, d)
  340. }
  341. enc := hexFile(file)
  342. net.nodeB.expectDecode(t, test.packet.Kind(), enc)
  343. })
  344. }
  345. }
  346. // testVectorComment creates the commentary for discv5 test vector files.
  347. func testVectorComment(net *handshakeTest, p Packet, challenge *Whoareyou, nonce Nonce) string {
  348. o := new(strings.Builder)
  349. printWhoareyou := func(p *Whoareyou) {
  350. fmt.Fprintf(o, "whoareyou.challenge-data = %#x\n", p.ChallengeData)
  351. fmt.Fprintf(o, "whoareyou.request-nonce = %#x\n", p.Nonce[:])
  352. fmt.Fprintf(o, "whoareyou.id-nonce = %#x\n", p.IDNonce[:])
  353. fmt.Fprintf(o, "whoareyou.enr-seq = %d\n", p.RecordSeq)
  354. }
  355. fmt.Fprintf(o, "src-node-id = %#x\n", net.nodeA.id().Bytes())
  356. fmt.Fprintf(o, "dest-node-id = %#x\n", net.nodeB.id().Bytes())
  357. switch p := p.(type) {
  358. case *Whoareyou:
  359. // WHOAREYOU packet.
  360. printWhoareyou(p)
  361. case *Ping:
  362. fmt.Fprintf(o, "nonce = %#x\n", nonce[:])
  363. fmt.Fprintf(o, "read-key = %#x\n", net.nodeA.c.sc.session(net.nodeB.id(), net.nodeB.addr()).writeKey)
  364. fmt.Fprintf(o, "ping.req-id = %#x\n", p.ReqID)
  365. fmt.Fprintf(o, "ping.enr-seq = %d\n", p.ENRSeq)
  366. if challenge != nil {
  367. // Handshake message packet.
  368. fmt.Fprint(o, "\nhandshake inputs:\n\n")
  369. printWhoareyou(challenge)
  370. fmt.Fprintf(o, "ephemeral-key = %#x\n", testEphKey.D.Bytes())
  371. fmt.Fprintf(o, "ephemeral-pubkey = %#x\n", crypto.CompressPubkey(&testEphKey.PublicKey))
  372. }
  373. default:
  374. panic(fmt.Errorf("unhandled packet type %T", p))
  375. }
  376. return o.String()
  377. }
  378. // This benchmark checks performance of handshake packet decoding.
  379. func BenchmarkV5_DecodeHandshakePingSecp256k1(b *testing.B) {
  380. net := newHandshakeTest()
  381. defer net.close()
  382. var (
  383. idA = net.nodeA.id()
  384. challenge = &Whoareyou{Node: net.nodeB.n()}
  385. message = &Ping{ReqID: []byte("reqid")}
  386. )
  387. enc, _, err := net.nodeA.c.Encode(net.nodeB.id(), "", message, challenge)
  388. if err != nil {
  389. b.Fatal("can't encode handshake packet")
  390. }
  391. challenge.Node = nil // force ENR signature verification in decoder
  392. b.ResetTimer()
  393. input := make([]byte, len(enc))
  394. for i := 0; i < b.N; i++ {
  395. copy(input, enc)
  396. net.nodeB.c.sc.storeSentHandshake(idA, "", challenge)
  397. _, _, _, err := net.nodeB.c.Decode(input, "")
  398. if err != nil {
  399. b.Fatal(err)
  400. }
  401. }
  402. }
  403. // This benchmark checks how long it takes to decode an encrypted ping packet.
  404. func BenchmarkV5_DecodePing(b *testing.B) {
  405. net := newHandshakeTest()
  406. defer net.close()
  407. session := &session{
  408. readKey: []byte{233, 203, 93, 195, 86, 47, 177, 186, 227, 43, 2, 141, 244, 230, 120, 17},
  409. writeKey: []byte{79, 145, 252, 171, 167, 216, 252, 161, 208, 190, 176, 106, 214, 39, 178, 134},
  410. }
  411. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session)
  412. net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), session.keysFlipped())
  413. addrB := net.nodeA.addr()
  414. ping := &Ping{ReqID: []byte("reqid"), ENRSeq: 5}
  415. enc, _, err := net.nodeA.c.Encode(net.nodeB.id(), addrB, ping, nil)
  416. if err != nil {
  417. b.Fatalf("can't encode: %v", err)
  418. }
  419. b.ResetTimer()
  420. input := make([]byte, len(enc))
  421. for i := 0; i < b.N; i++ {
  422. copy(input, enc)
  423. _, _, packet, _ := net.nodeB.c.Decode(input, addrB)
  424. if _, ok := packet.(*Ping); !ok {
  425. b.Fatalf("wrong packet type %T", packet)
  426. }
  427. }
  428. }
  429. var pp = spew.NewDefaultConfig()
  430. type handshakeTest struct {
  431. nodeA, nodeB handshakeTestNode
  432. clock mclock.Simulated
  433. }
  434. type handshakeTestNode struct {
  435. ln *enode.LocalNode
  436. c *Codec
  437. }
  438. func newHandshakeTest() *handshakeTest {
  439. t := new(handshakeTest)
  440. t.nodeA.init(testKeyA, net.IP{127, 0, 0, 1}, &t.clock)
  441. t.nodeB.init(testKeyB, net.IP{127, 0, 0, 1}, &t.clock)
  442. return t
  443. }
  444. func (t *handshakeTest) close() {
  445. t.nodeA.ln.Database().Close()
  446. t.nodeB.ln.Database().Close()
  447. }
  448. func (n *handshakeTestNode) init(key *ecdsa.PrivateKey, ip net.IP, clock mclock.Clock) {
  449. db, _ := enode.OpenDB("")
  450. n.ln = enode.NewLocalNode(db, key)
  451. n.ln.SetStaticIP(ip)
  452. if n.ln.Node().Seq() != 1 {
  453. panic(fmt.Errorf("unexpected seq %d", n.ln.Node().Seq()))
  454. }
  455. n.c = NewCodec(n.ln, key, clock)
  456. }
  457. func (n *handshakeTestNode) encode(t testing.TB, to handshakeTestNode, p Packet) ([]byte, Nonce) {
  458. t.Helper()
  459. return n.encodeWithChallenge(t, to, nil, p)
  460. }
  461. func (n *handshakeTestNode) encodeWithChallenge(t testing.TB, to handshakeTestNode, c *Whoareyou, p Packet) ([]byte, Nonce) {
  462. t.Helper()
  463. // Copy challenge and add destination node. This avoids sharing 'c' among the two codecs.
  464. var challenge *Whoareyou
  465. if c != nil {
  466. challengeCopy := *c
  467. challenge = &challengeCopy
  468. challenge.Node = to.n()
  469. }
  470. // Encode to destination.
  471. enc, nonce, err := n.c.Encode(to.id(), to.addr(), p, challenge)
  472. if err != nil {
  473. t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err))
  474. }
  475. t.Logf("(%s) -> (%s) %s\n%s", n.ln.ID().TerminalString(), to.id().TerminalString(), p.Name(), hex.Dump(enc))
  476. return enc, nonce
  477. }
  478. func (n *handshakeTestNode) expectDecode(t *testing.T, ptype byte, p []byte) Packet {
  479. t.Helper()
  480. dec, err := n.decode(p)
  481. if err != nil {
  482. t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err))
  483. }
  484. t.Logf("(%s) %#v", n.ln.ID().TerminalString(), pp.NewFormatter(dec))
  485. if dec.Kind() != ptype {
  486. t.Fatalf("expected packet type %d, got %d", ptype, dec.Kind())
  487. }
  488. return dec
  489. }
  490. func (n *handshakeTestNode) expectDecodeErr(t *testing.T, wantErr error, p []byte) {
  491. t.Helper()
  492. if _, err := n.decode(p); !reflect.DeepEqual(err, wantErr) {
  493. t.Fatal(fmt.Errorf("(%s) got err %q, want %q", n.ln.ID().TerminalString(), err, wantErr))
  494. }
  495. }
  496. func (n *handshakeTestNode) decode(input []byte) (Packet, error) {
  497. _, _, p, err := n.c.Decode(input, "127.0.0.1")
  498. return p, err
  499. }
  500. func (n *handshakeTestNode) n() *enode.Node {
  501. return n.ln.Node()
  502. }
  503. func (n *handshakeTestNode) addr() string {
  504. return n.ln.Node().IP().String()
  505. }
  506. func (n *handshakeTestNode) id() enode.ID {
  507. return n.ln.ID()
  508. }
  509. // hexFile reads the given file and decodes the hex data contained in it.
  510. // Whitespace and any lines beginning with the # character are ignored.
  511. func hexFile(file string) []byte {
  512. fileContent, err := ioutil.ReadFile(file)
  513. if err != nil {
  514. panic(err)
  515. }
  516. // Gather hex data, ignore comments.
  517. var text []byte
  518. for _, line := range bytes.Split(fileContent, []byte("\n")) {
  519. line = bytes.TrimSpace(line)
  520. if len(line) > 0 && line[0] == '#' {
  521. continue
  522. }
  523. text = append(text, line...)
  524. }
  525. // Parse the hex.
  526. if bytes.HasPrefix(text, []byte("0x")) {
  527. text = text[2:]
  528. }
  529. data := make([]byte, hex.DecodedLen(len(text)))
  530. if _, err := hex.Decode(data, text); err != nil {
  531. panic("invalid hex in " + file)
  532. }
  533. return data
  534. }
  535. // writeTestVector writes a test vector file with the given commentary and binary data.
  536. func writeTestVector(file, comment string, data []byte) {
  537. fd, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  538. if err != nil {
  539. panic(err)
  540. }
  541. defer fd.Close()
  542. if len(comment) > 0 {
  543. for _, line := range strings.Split(strings.TrimSpace(comment), "\n") {
  544. fmt.Fprintf(fd, "# %s\n", line)
  545. }
  546. fmt.Fprintln(fd)
  547. }
  548. for len(data) > 0 {
  549. var chunk []byte
  550. if len(data) < 32 {
  551. chunk = data
  552. } else {
  553. chunk = data[:32]
  554. }
  555. data = data[len(chunk):]
  556. fmt.Fprintf(fd, "%x\n", chunk)
  557. }
  558. }