github.com/inphi/go-ethereum@v1.9.7/p2p/discover/v4_udp_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 discover 18 19 import ( 20 "bytes" 21 "crypto/ecdsa" 22 crand "crypto/rand" 23 "encoding/binary" 24 "encoding/hex" 25 "errors" 26 "io" 27 "math/rand" 28 "net" 29 "reflect" 30 "sync" 31 "testing" 32 "time" 33 34 "github.com/davecgh/go-spew/spew" 35 "github.com/ethereum/go-ethereum/common" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/internal/testlog" 38 "github.com/ethereum/go-ethereum/log" 39 "github.com/ethereum/go-ethereum/p2p/enode" 40 "github.com/ethereum/go-ethereum/p2p/enr" 41 "github.com/ethereum/go-ethereum/rlp" 42 ) 43 44 func init() { 45 spew.Config.DisableMethods = true 46 } 47 48 // shared test variables 49 var ( 50 futureExp = uint64(time.Now().Add(10 * time.Hour).Unix()) 51 testTarget = encPubkey{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} 52 testRemote = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2} 53 testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4} 54 testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6} 55 ) 56 57 type udpTest struct { 58 t *testing.T 59 pipe *dgramPipe 60 table *Table 61 db *enode.DB 62 udp *UDPv4 63 sent [][]byte 64 localkey, remotekey *ecdsa.PrivateKey 65 remoteaddr *net.UDPAddr 66 } 67 68 func newUDPTest(t *testing.T) *udpTest { 69 test := &udpTest{ 70 t: t, 71 pipe: newpipe(), 72 localkey: newkey(), 73 remotekey: newkey(), 74 remoteaddr: &net.UDPAddr{IP: net.IP{10, 0, 1, 99}, Port: 30303}, 75 } 76 77 test.db, _ = enode.OpenDB("") 78 ln := enode.NewLocalNode(test.db, test.localkey) 79 test.udp, _ = ListenV4(test.pipe, ln, Config{ 80 PrivateKey: test.localkey, 81 Log: testlog.Logger(t, log.LvlTrace), 82 }) 83 test.table = test.udp.tab 84 // Wait for initial refresh so the table doesn't send unexpected findnode. 85 <-test.table.initDone 86 return test 87 } 88 89 func (test *udpTest) close() { 90 test.udp.Close() 91 test.db.Close() 92 } 93 94 // handles a packet as if it had been sent to the transport. 95 func (test *udpTest) packetIn(wantError error, data packetV4) { 96 test.t.Helper() 97 98 test.packetInFrom(wantError, test.remotekey, test.remoteaddr, data) 99 } 100 101 // handles a packet as if it had been sent to the transport by the key/endpoint. 102 func (test *udpTest) packetInFrom(wantError error, key *ecdsa.PrivateKey, addr *net.UDPAddr, data packetV4) { 103 test.t.Helper() 104 105 enc, _, err := test.udp.encode(key, data) 106 if err != nil { 107 test.t.Errorf("%s encode error: %v", data.name(), err) 108 } 109 test.sent = append(test.sent, enc) 110 if err = test.udp.handlePacket(addr, enc); err != wantError { 111 test.t.Errorf("error mismatch: got %q, want %q", err, wantError) 112 } 113 } 114 115 // waits for a packet to be sent by the transport. 116 // validate should have type func(X, *net.UDPAddr, []byte), where X is a packet type. 117 func (test *udpTest) waitPacketOut(validate interface{}) (closed bool) { 118 test.t.Helper() 119 120 dgram, ok := test.pipe.receive() 121 if !ok { 122 return true 123 } 124 p, _, hash, err := decodeV4(dgram.data) 125 if err != nil { 126 test.t.Errorf("sent packet decode error: %v", err) 127 return false 128 } 129 fn := reflect.ValueOf(validate) 130 exptype := fn.Type().In(0) 131 if !reflect.TypeOf(p).AssignableTo(exptype) { 132 test.t.Errorf("sent packet type mismatch, got: %v, want: %v", reflect.TypeOf(p), exptype) 133 return false 134 } 135 fn.Call([]reflect.Value{reflect.ValueOf(p), reflect.ValueOf(&dgram.to), reflect.ValueOf(hash)}) 136 return false 137 } 138 139 func TestUDPv4_packetErrors(t *testing.T) { 140 test := newUDPTest(t) 141 defer test.close() 142 143 test.packetIn(errExpired, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4}) 144 test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: []byte{}, Expiration: futureExp}) 145 test.packetIn(errUnknownNode, &findnodeV4{Expiration: futureExp}) 146 test.packetIn(errUnsolicitedReply, &neighborsV4{Expiration: futureExp}) 147 } 148 149 func TestUDPv4_pingTimeout(t *testing.T) { 150 t.Parallel() 151 test := newUDPTest(t) 152 defer test.close() 153 154 key := newkey() 155 toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222} 156 node := enode.NewV4(&key.PublicKey, toaddr.IP, 0, toaddr.Port) 157 if _, err := test.udp.ping(node); err != errTimeout { 158 t.Error("expected timeout error, got", err) 159 } 160 } 161 162 type testPacket byte 163 164 func (req testPacket) kind() byte { return byte(req) } 165 func (req testPacket) name() string { return "" } 166 func (req testPacket) preverify(*UDPv4, *net.UDPAddr, enode.ID, encPubkey) error { 167 return nil 168 } 169 func (req testPacket) handle(*UDPv4, *net.UDPAddr, enode.ID, []byte) { 170 } 171 172 func TestUDPv4_responseTimeouts(t *testing.T) { 173 t.Parallel() 174 test := newUDPTest(t) 175 defer test.close() 176 177 rand.Seed(time.Now().UnixNano()) 178 randomDuration := func(max time.Duration) time.Duration { 179 return time.Duration(rand.Int63n(int64(max))) 180 } 181 182 var ( 183 nReqs = 200 184 nTimeouts = 0 // number of requests with ptype > 128 185 nilErr = make(chan error, nReqs) // for requests that get a reply 186 timeoutErr = make(chan error, nReqs) // for requests that time out 187 ) 188 for i := 0; i < nReqs; i++ { 189 // Create a matcher for a random request in udp.loop. Requests 190 // with ptype <= 128 will not get a reply and should time out. 191 // For all other requests, a reply is scheduled to arrive 192 // within the timeout window. 193 p := &replyMatcher{ 194 ptype: byte(rand.Intn(255)), 195 callback: func(interface{}) (bool, bool) { return true, true }, 196 } 197 binary.BigEndian.PutUint64(p.from[:], uint64(i)) 198 if p.ptype <= 128 { 199 p.errc = timeoutErr 200 test.udp.addReplyMatcher <- p 201 nTimeouts++ 202 } else { 203 p.errc = nilErr 204 test.udp.addReplyMatcher <- p 205 time.AfterFunc(randomDuration(60*time.Millisecond), func() { 206 if !test.udp.handleReply(p.from, p.ip, testPacket(p.ptype)) { 207 t.Logf("not matched: %v", p) 208 } 209 }) 210 } 211 time.Sleep(randomDuration(30 * time.Millisecond)) 212 } 213 214 // Check that all timeouts were delivered and that the rest got nil errors. 215 // The replies must be delivered. 216 var ( 217 recvDeadline = time.After(20 * time.Second) 218 nTimeoutsRecv, nNil = 0, 0 219 ) 220 for i := 0; i < nReqs; i++ { 221 select { 222 case err := <-timeoutErr: 223 if err != errTimeout { 224 t.Fatalf("got non-timeout error on timeoutErr %d: %v", i, err) 225 } 226 nTimeoutsRecv++ 227 case err := <-nilErr: 228 if err != nil { 229 t.Fatalf("got non-nil error on nilErr %d: %v", i, err) 230 } 231 nNil++ 232 case <-recvDeadline: 233 t.Fatalf("exceeded recv deadline") 234 } 235 } 236 if nTimeoutsRecv != nTimeouts { 237 t.Errorf("wrong number of timeout errors received: got %d, want %d", nTimeoutsRecv, nTimeouts) 238 } 239 if nNil != nReqs-nTimeouts { 240 t.Errorf("wrong number of successful replies: got %d, want %d", nNil, nReqs-nTimeouts) 241 } 242 } 243 244 func TestUDPv4_findnodeTimeout(t *testing.T) { 245 t.Parallel() 246 test := newUDPTest(t) 247 defer test.close() 248 249 toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222} 250 toid := enode.ID{1, 2, 3, 4} 251 target := encPubkey{4, 5, 6, 7} 252 result, err := test.udp.findnode(toid, toaddr, target) 253 if err != errTimeout { 254 t.Error("expected timeout error, got", err) 255 } 256 if len(result) > 0 { 257 t.Error("expected empty result, got", result) 258 } 259 } 260 261 func TestUDPv4_findnode(t *testing.T) { 262 test := newUDPTest(t) 263 defer test.close() 264 265 // put a few nodes into the table. their exact 266 // distribution shouldn't matter much, although we need to 267 // take care not to overflow any bucket. 268 nodes := &nodesByDistance{target: testTarget.id()} 269 live := make(map[enode.ID]bool) 270 numCandidates := 2 * bucketSize 271 for i := 0; i < numCandidates; i++ { 272 key := newkey() 273 ip := net.IP{10, 13, 0, byte(i)} 274 n := wrapNode(enode.NewV4(&key.PublicKey, ip, 0, 2000)) 275 // Ensure half of table content isn't verified live yet. 276 if i > numCandidates/2 { 277 n.livenessChecks = 1 278 live[n.ID()] = true 279 } 280 nodes.push(n, numCandidates) 281 } 282 fillTable(test.table, nodes.entries) 283 284 // ensure there's a bond with the test node, 285 // findnode won't be accepted otherwise. 286 remoteID := encodePubkey(&test.remotekey.PublicKey).id() 287 test.table.db.UpdateLastPongReceived(remoteID, test.remoteaddr.IP, time.Now()) 288 289 // check that closest neighbors are returned. 290 expected := test.table.closest(testTarget.id(), bucketSize, true) 291 test.packetIn(nil, &findnodeV4{Target: testTarget, Expiration: futureExp}) 292 waitNeighbors := func(want []*node) { 293 test.waitPacketOut(func(p *neighborsV4, to *net.UDPAddr, hash []byte) { 294 if len(p.Nodes) != len(want) { 295 t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize) 296 } 297 for i, n := range p.Nodes { 298 if n.ID.id() != want[i].ID() { 299 t.Errorf("result mismatch at %d:\n got: %v\n want: %v", i, n, expected.entries[i]) 300 } 301 if !live[n.ID.id()] { 302 t.Errorf("result includes dead node %v", n.ID.id()) 303 } 304 } 305 }) 306 } 307 // Receive replies. 308 want := expected.entries 309 if len(want) > maxNeighbors { 310 waitNeighbors(want[:maxNeighbors]) 311 want = want[maxNeighbors:] 312 } 313 waitNeighbors(want) 314 } 315 316 func TestUDPv4_findnodeMultiReply(t *testing.T) { 317 test := newUDPTest(t) 318 defer test.close() 319 320 rid := enode.PubkeyToIDV4(&test.remotekey.PublicKey) 321 test.table.db.UpdateLastPingReceived(rid, test.remoteaddr.IP, time.Now()) 322 323 // queue a pending findnode request 324 resultc, errc := make(chan []*node), make(chan error) 325 go func() { 326 rid := encodePubkey(&test.remotekey.PublicKey).id() 327 ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget) 328 if err != nil && len(ns) == 0 { 329 errc <- err 330 } else { 331 resultc <- ns 332 } 333 }() 334 335 // wait for the findnode to be sent. 336 // after it is sent, the transport is waiting for a reply 337 test.waitPacketOut(func(p *findnodeV4, to *net.UDPAddr, hash []byte) { 338 if p.Target != testTarget { 339 t.Errorf("wrong target: got %v, want %v", p.Target, testTarget) 340 } 341 }) 342 343 // send the reply as two packets. 344 list := []*node{ 345 wrapNode(enode.MustParse("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304")), 346 wrapNode(enode.MustParse("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303")), 347 wrapNode(enode.MustParse("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17")), 348 wrapNode(enode.MustParse("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303")), 349 } 350 rpclist := make([]rpcNode, len(list)) 351 for i := range list { 352 rpclist[i] = nodeToRPC(list[i]) 353 } 354 test.packetIn(nil, &neighborsV4{Expiration: futureExp, Nodes: rpclist[:2]}) 355 test.packetIn(nil, &neighborsV4{Expiration: futureExp, Nodes: rpclist[2:]}) 356 357 // check that the sent neighbors are all returned by findnode 358 select { 359 case result := <-resultc: 360 want := append(list[:2], list[3:]...) 361 if !reflect.DeepEqual(result, want) { 362 t.Errorf("neighbors mismatch:\n got: %v\n want: %v", result, want) 363 } 364 case err := <-errc: 365 t.Errorf("findnode error: %v", err) 366 case <-time.After(5 * time.Second): 367 t.Error("findnode did not return within 5 seconds") 368 } 369 } 370 371 // This test checks that reply matching of pong verifies the ping hash. 372 func TestUDPv4_pingMatch(t *testing.T) { 373 test := newUDPTest(t) 374 defer test.close() 375 376 randToken := make([]byte, 32) 377 crand.Read(randToken) 378 379 test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp}) 380 test.waitPacketOut(func(*pongV4, *net.UDPAddr, []byte) {}) 381 test.waitPacketOut(func(*pingV4, *net.UDPAddr, []byte) {}) 382 test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: randToken, To: testLocalAnnounced, Expiration: futureExp}) 383 } 384 385 // This test checks that reply matching of pong verifies the sender IP address. 386 func TestUDPv4_pingMatchIP(t *testing.T) { 387 test := newUDPTest(t) 388 defer test.close() 389 390 test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp}) 391 test.waitPacketOut(func(*pongV4, *net.UDPAddr, []byte) {}) 392 393 test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) { 394 wrongAddr := &net.UDPAddr{IP: net.IP{33, 44, 1, 2}, Port: 30000} 395 test.packetInFrom(errUnsolicitedReply, test.remotekey, wrongAddr, &pongV4{ 396 ReplyTok: hash, 397 To: testLocalAnnounced, 398 Expiration: futureExp, 399 }) 400 }) 401 } 402 403 func TestUDPv4_successfulPing(t *testing.T) { 404 test := newUDPTest(t) 405 added := make(chan *node, 1) 406 test.table.nodeAddedHook = func(n *node) { added <- n } 407 defer test.close() 408 409 // The remote side sends a ping packet to initiate the exchange. 410 go test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp}) 411 412 // The ping is replied to. 413 test.waitPacketOut(func(p *pongV4, to *net.UDPAddr, hash []byte) { 414 pinghash := test.sent[0][:macSize] 415 if !bytes.Equal(p.ReplyTok, pinghash) { 416 t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash) 417 } 418 wantTo := rpcEndpoint{ 419 // The mirrored UDP address is the UDP packet sender 420 IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port), 421 // The mirrored TCP port is the one from the ping packet 422 TCP: testRemote.TCP, 423 } 424 if !reflect.DeepEqual(p.To, wantTo) { 425 t.Errorf("got pong.To %v, want %v", p.To, wantTo) 426 } 427 }) 428 429 // Remote is unknown, the table pings back. 430 test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) { 431 if !reflect.DeepEqual(p.From, test.udp.ourEndpoint()) { 432 t.Errorf("got ping.From %#v, want %#v", p.From, test.udp.ourEndpoint()) 433 } 434 wantTo := rpcEndpoint{ 435 // The mirrored UDP address is the UDP packet sender. 436 IP: test.remoteaddr.IP, 437 UDP: uint16(test.remoteaddr.Port), 438 TCP: 0, 439 } 440 if !reflect.DeepEqual(p.To, wantTo) { 441 t.Errorf("got ping.To %v, want %v", p.To, wantTo) 442 } 443 test.packetIn(nil, &pongV4{ReplyTok: hash, Expiration: futureExp}) 444 }) 445 446 // The node should be added to the table shortly after getting the 447 // pong packet. 448 select { 449 case n := <-added: 450 rid := encodePubkey(&test.remotekey.PublicKey).id() 451 if n.ID() != rid { 452 t.Errorf("node has wrong ID: got %v, want %v", n.ID(), rid) 453 } 454 if !n.IP().Equal(test.remoteaddr.IP) { 455 t.Errorf("node has wrong IP: got %v, want: %v", n.IP(), test.remoteaddr.IP) 456 } 457 if n.UDP() != test.remoteaddr.Port { 458 t.Errorf("node has wrong UDP port: got %v, want: %v", n.UDP(), test.remoteaddr.Port) 459 } 460 if n.TCP() != int(testRemote.TCP) { 461 t.Errorf("node has wrong TCP port: got %v, want: %v", n.TCP(), testRemote.TCP) 462 } 463 case <-time.After(2 * time.Second): 464 t.Errorf("node was not added within 2 seconds") 465 } 466 } 467 468 // This test checks that EIP-868 requests work. 469 func TestUDPv4_EIP868(t *testing.T) { 470 test := newUDPTest(t) 471 defer test.close() 472 473 test.udp.localNode.Set(enr.WithEntry("foo", "bar")) 474 wantNode := test.udp.localNode.Node() 475 476 // ENR requests aren't allowed before endpoint proof. 477 test.packetIn(errUnknownNode, &enrRequestV4{Expiration: futureExp}) 478 479 // Perform endpoint proof and check for sequence number in packet tail. 480 test.packetIn(nil, &pingV4{Expiration: futureExp}) 481 test.waitPacketOut(func(p *pongV4, addr *net.UDPAddr, hash []byte) { 482 if seq := seqFromTail(p.Rest); seq != wantNode.Seq() { 483 t.Errorf("wrong sequence number in pong: %d, want %d", seq, wantNode.Seq()) 484 } 485 }) 486 test.waitPacketOut(func(p *pingV4, addr *net.UDPAddr, hash []byte) { 487 if seq := seqFromTail(p.Rest); seq != wantNode.Seq() { 488 t.Errorf("wrong sequence number in ping: %d, want %d", seq, wantNode.Seq()) 489 } 490 test.packetIn(nil, &pongV4{Expiration: futureExp, ReplyTok: hash}) 491 }) 492 493 // Request should work now. 494 test.packetIn(nil, &enrRequestV4{Expiration: futureExp}) 495 test.waitPacketOut(func(p *enrResponseV4, addr *net.UDPAddr, hash []byte) { 496 n, err := enode.New(enode.ValidSchemes, &p.Record) 497 if err != nil { 498 t.Fatalf("invalid record: %v", err) 499 } 500 if !reflect.DeepEqual(n, wantNode) { 501 t.Fatalf("wrong node in enrResponse: %v", n) 502 } 503 }) 504 } 505 506 // EIP-8 test vectors. 507 var testPackets = []struct { 508 input string 509 wantPacket interface{} 510 }{ 511 { 512 input: "71dbda3a79554728d4f94411e42ee1f8b0d561c10e1e5f5893367948c6a7d70bb87b235fa28a77070271b6c164a2dce8c7e13a5739b53b5e96f2e5acb0e458a02902f5965d55ecbeb2ebb6cabb8b2b232896a36b737666c55265ad0a68412f250001ea04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a355", 513 wantPacket: &pingV4{ 514 Version: 4, 515 From: rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544}, 516 To: rpcEndpoint{net.ParseIP("::1"), 2222, 3333}, 517 Expiration: 1136239445, 518 Rest: []rlp.RawValue{}, 519 }, 520 }, 521 { 522 input: "e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663aaa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a3550102", 523 wantPacket: &pingV4{ 524 Version: 4, 525 From: rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544}, 526 To: rpcEndpoint{net.ParseIP("::1"), 2222, 3333}, 527 Expiration: 1136239445, 528 Rest: []rlp.RawValue{{0x01}, {0x02}}, 529 }, 530 }, 531 { 532 input: "577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba76023fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee1917084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c76d922dc3", 533 wantPacket: &pingV4{ 534 Version: 555, 535 From: rpcEndpoint{net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 3322, 5544}, 536 To: rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338}, 537 Expiration: 1136239445, 538 Rest: []rlp.RawValue{{0xC5, 0x01, 0x02, 0x03, 0x04, 0x05}}, 539 }, 540 }, 541 { 542 input: "09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b2069869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f055542124e", 543 wantPacket: &pongV4{ 544 To: rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338}, 545 ReplyTok: common.Hex2Bytes("fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c954"), 546 Expiration: 1136239445, 547 Rest: []rlp.RawValue{{0xC6, 0x01, 0x02, 0x03, 0xC2, 0x04, 0x05}, {0x06}}, 548 }, 549 }, 550 { 551 input: "c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260add7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396", 552 wantPacket: &findnodeV4{ 553 Target: hexEncPubkey("ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f"), 554 Expiration: 1136239445, 555 Rest: []rlp.RawValue{{0x82, 0x99, 0x99}, {0x83, 0x99, 0x99, 0x99}}, 556 }, 557 }, 558 { 559 input: "c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db8403155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d313198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df738443b9a355010203b525a138aa34383fec3d2719a0", 560 wantPacket: &neighborsV4{ 561 Nodes: []rpcNode{ 562 { 563 ID: hexEncPubkey("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"), 564 IP: net.ParseIP("99.33.22.55").To4(), 565 UDP: 4444, 566 TCP: 4445, 567 }, 568 { 569 ID: hexEncPubkey("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"), 570 IP: net.ParseIP("1.2.3.4").To4(), 571 UDP: 1, 572 TCP: 1, 573 }, 574 { 575 ID: hexEncPubkey("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"), 576 IP: net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 577 UDP: 3333, 578 TCP: 3333, 579 }, 580 { 581 ID: hexEncPubkey("8dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73"), 582 IP: net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 583 UDP: 999, 584 TCP: 1000, 585 }, 586 }, 587 Expiration: 1136239445, 588 Rest: []rlp.RawValue{{0x01}, {0x02}, {0x03}}, 589 }, 590 }, 591 } 592 593 func TestUDPv4_forwardCompatibility(t *testing.T) { 594 testkey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 595 wantNodeKey := encodePubkey(&testkey.PublicKey) 596 597 for _, test := range testPackets { 598 input, err := hex.DecodeString(test.input) 599 if err != nil { 600 t.Fatalf("invalid hex: %s", test.input) 601 } 602 packet, nodekey, _, err := decodeV4(input) 603 if err != nil { 604 t.Errorf("did not accept packet %s\n%v", test.input, err) 605 continue 606 } 607 if !reflect.DeepEqual(packet, test.wantPacket) { 608 t.Errorf("got %s\nwant %s", spew.Sdump(packet), spew.Sdump(test.wantPacket)) 609 } 610 if nodekey != wantNodeKey { 611 t.Errorf("got id %v\nwant id %v", nodekey, wantNodeKey) 612 } 613 } 614 } 615 616 // dgramPipe is a fake UDP socket. It queues all sent datagrams. 617 type dgramPipe struct { 618 mu *sync.Mutex 619 cond *sync.Cond 620 closing chan struct{} 621 closed bool 622 queue []dgram 623 } 624 625 type dgram struct { 626 to net.UDPAddr 627 data []byte 628 } 629 630 func newpipe() *dgramPipe { 631 mu := new(sync.Mutex) 632 return &dgramPipe{ 633 closing: make(chan struct{}), 634 cond: &sync.Cond{L: mu}, 635 mu: mu, 636 } 637 } 638 639 // WriteToUDP queues a datagram. 640 func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) { 641 msg := make([]byte, len(b)) 642 copy(msg, b) 643 c.mu.Lock() 644 defer c.mu.Unlock() 645 if c.closed { 646 return 0, errors.New("closed") 647 } 648 c.queue = append(c.queue, dgram{*to, b}) 649 c.cond.Signal() 650 return len(b), nil 651 } 652 653 // ReadFromUDP just hangs until the pipe is closed. 654 func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { 655 <-c.closing 656 return 0, nil, io.EOF 657 } 658 659 func (c *dgramPipe) Close() error { 660 c.mu.Lock() 661 defer c.mu.Unlock() 662 if !c.closed { 663 close(c.closing) 664 c.closed = true 665 } 666 c.cond.Broadcast() 667 return nil 668 } 669 670 func (c *dgramPipe) LocalAddr() net.Addr { 671 return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)} 672 } 673 674 func (c *dgramPipe) receive() (dgram, bool) { 675 c.mu.Lock() 676 defer c.mu.Unlock() 677 for len(c.queue) == 0 && !c.closed { 678 c.cond.Wait() 679 } 680 if c.closed { 681 return dgram{}, false 682 } 683 p := c.queue[0] 684 copy(c.queue, c.queue[1:]) 685 c.queue = c.queue[:len(c.queue)-1] 686 return p, true 687 }