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