github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/p2p/discv5/udp_test.go (about) 1 // Copyright 2016 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 discv5 18 19 import ( 20 "encoding/hex" 21 "errors" 22 "io" 23 "net" 24 "reflect" 25 "sync" 26 "testing" 27 "time" 28 29 "github.com/davecgh/go-spew/spew" 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/crypto" 32 "github.com/ethereum/go-ethereum/rlp" 33 ) 34 35 func init() { 36 spew.Config.DisableMethods = true 37 } 38 39 // shared test variables 40 var ( 41 futureExp = uint64(time.Now().Add(10 * time.Hour).Unix()) 42 testTarget = NodeID{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} 43 testRemote = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2} 44 testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4} 45 testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6} 46 ) 47 48 // type udpTest struct { 49 // t *testing.T 50 // pipe *dgramPipe 51 // table *Table 52 // udp *udp 53 // sent [][]byte 54 // localkey, remotekey *ecdsa.PrivateKey 55 // remoteaddr *net.UDPAddr 56 // } 57 // 58 // func newUDPTest(t *testing.T) *udpTest { 59 // test := &udpTest{ 60 // t: t, 61 // pipe: newpipe(), 62 // localkey: newkey(), 63 // remotekey: newkey(), 64 // remoteaddr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 30303}, 65 // } 66 // test.table, test.udp, _ = newUDP(test.localkey, test.pipe, nil, "") 67 // return test 68 // } 69 // 70 // // handles a packet as if it had been sent to the transport. 71 // func (test *udpTest) packetIn(wantError error, ptype byte, data packet) error { 72 // enc, err := encodePacket(test.remotekey, ptype, data) 73 // if err != nil { 74 // return test.errorf("packet (%d) encode error: %v", ptype, err) 75 // } 76 // test.sent = append(test.sent, enc) 77 // if err = test.udp.handlePacket(test.remoteaddr, enc); err != wantError { 78 // return test.errorf("error mismatch: got %q, want %q", err, wantError) 79 // } 80 // return nil 81 // } 82 // 83 // // waits for a packet to be sent by the transport. 84 // // validate should have type func(*udpTest, X) error, where X is a packet type. 85 // func (test *udpTest) waitPacketOut(validate interface{}) error { 86 // dgram := test.pipe.waitPacketOut() 87 // p, _, _, err := decodePacket(dgram) 88 // if err != nil { 89 // return test.errorf("sent packet decode error: %v", err) 90 // } 91 // fn := reflect.ValueOf(validate) 92 // exptype := fn.Type().In(0) 93 // if reflect.TypeOf(p) != exptype { 94 // return test.errorf("sent packet type mismatch, got: %v, want: %v", reflect.TypeOf(p), exptype) 95 // } 96 // fn.Call([]reflect.Value{reflect.ValueOf(p)}) 97 // return nil 98 // } 99 // 100 // func (test *udpTest) errorf(format string, args ...interface{}) error { 101 // _, file, line, ok := runtime.Caller(2) // errorf + waitPacketOut 102 // if ok { 103 // file = filepath.Base(file) 104 // } else { 105 // file = "???" 106 // line = 1 107 // } 108 // err := fmt.Errorf(format, args...) 109 // fmt.Printf("\t%s:%d: %v\n", file, line, err) 110 // test.t.Fail() 111 // return err 112 // } 113 // 114 // func TestUDP_packetErrors(t *testing.T) { 115 // test := newUDPTest(t) 116 // defer test.table.Close() 117 // 118 // test.packetIn(errExpired, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version}) 119 // test.packetIn(errUnsolicitedReply, pongPacket, &pong{ReplyTok: []byte{}, Expiration: futureExp}) 120 // test.packetIn(errUnknownNode, findnodePacket, &findnode{Expiration: futureExp}) 121 // test.packetIn(errUnsolicitedReply, neighborsPacket, &neighbors{Expiration: futureExp}) 122 // } 123 // 124 // func TestUDP_findnode(t *testing.T) { 125 // test := newUDPTest(t) 126 // defer test.table.Close() 127 // 128 // // put a few nodes into the table. their exact 129 // // distribution shouldn't matter much, although we need to 130 // // take care not to overflow any bucket. 131 // targetHash := crypto.Keccak256Hash(testTarget[:]) 132 // nodes := &nodesByDistance{target: targetHash} 133 // for i := 0; i < bucketSize; i++ { 134 // nodes.push(nodeAtDistance(test.table.self.sha, i+2), bucketSize) 135 // } 136 // test.table.stuff(nodes.entries) 137 // 138 // // ensure there's a bond with the test node, 139 // // findnode won't be accepted otherwise. 140 // test.table.db.updateNode(NewNode( 141 // PubkeyID(&test.remotekey.PublicKey), 142 // test.remoteaddr.IP, 143 // uint16(test.remoteaddr.Port), 144 // 99, 145 // )) 146 // // check that closest neighbors are returned. 147 // test.packetIn(nil, findnodePacket, &findnode{Target: testTarget, Expiration: futureExp}) 148 // expected := test.table.closest(targetHash, bucketSize) 149 // 150 // waitNeighbors := func(want []*Node) { 151 // test.waitPacketOut(func(p *neighbors) { 152 // if len(p.Nodes) != len(want) { 153 // t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize) 154 // } 155 // for i := range p.Nodes { 156 // if p.Nodes[i].ID != want[i].ID { 157 // t.Errorf("result mismatch at %d:\n got: %v\n want: %v", i, p.Nodes[i], expected.entries[i]) 158 // } 159 // } 160 // }) 161 // } 162 // waitNeighbors(expected.entries[:maxNeighbors]) 163 // waitNeighbors(expected.entries[maxNeighbors:]) 164 // } 165 // 166 // func TestUDP_findnodeMultiReply(t *testing.T) { 167 // test := newUDPTest(t) 168 // defer test.table.Close() 169 // 170 // // queue a pending findnode request 171 // resultc, errc := make(chan []*Node), make(chan error) 172 // go func() { 173 // rid := PubkeyID(&test.remotekey.PublicKey) 174 // ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget) 175 // if err != nil && len(ns) == 0 { 176 // errc <- err 177 // } else { 178 // resultc <- ns 179 // } 180 // }() 181 // 182 // // wait for the findnode to be sent. 183 // // after it is sent, the transport is waiting for a reply 184 // test.waitPacketOut(func(p *findnode) { 185 // if p.Target != testTarget { 186 // t.Errorf("wrong target: got %v, want %v", p.Target, testTarget) 187 // } 188 // }) 189 // 190 // // send the reply as two packets. 191 // list := []*Node{ 192 // MustParseNode("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304"), 193 // MustParseNode("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303"), 194 // MustParseNode("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17"), 195 // MustParseNode("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303"), 196 // } 197 // rpclist := make([]rpcNode, len(list)) 198 // for i := range list { 199 // rpclist[i] = nodeToRPC(list[i]) 200 // } 201 // test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: rpclist[:2]}) 202 // test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: rpclist[2:]}) 203 // 204 // // check that the sent neighbors are all returned by findnode 205 // select { 206 // case result := <-resultc: 207 // if !reflect.DeepEqual(result, list) { 208 // t.Errorf("neighbors mismatch:\n got: %v\n want: %v", result, list) 209 // } 210 // case err := <-errc: 211 // t.Errorf("findnode error: %v", err) 212 // case <-time.After(5 * time.Second): 213 // t.Error("findnode did not return within 5 seconds") 214 // } 215 // } 216 // 217 // func TestUDP_successfulPing(t *testing.T) { 218 // test := newUDPTest(t) 219 // added := make(chan *Node, 1) 220 // test.table.nodeAddedHook = func(n *Node) { added <- n } 221 // defer test.table.Close() 222 // 223 // // The remote side sends a ping packet to initiate the exchange. 224 // go test.packetIn(nil, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version, Expiration: futureExp}) 225 // 226 // // the ping is replied to. 227 // test.waitPacketOut(func(p *pong) { 228 // pinghash := test.sent[0][:macSize] 229 // if !bytes.Equal(p.ReplyTok, pinghash) { 230 // t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash) 231 // } 232 // wantTo := rpcEndpoint{ 233 // // The mirrored UDP address is the UDP packet sender 234 // IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port), 235 // // The mirrored TCP port is the one from the ping packet 236 // TCP: testRemote.TCP, 237 // } 238 // if !reflect.DeepEqual(p.To, wantTo) { 239 // t.Errorf("got pong.To %v, want %v", p.To, wantTo) 240 // } 241 // }) 242 // 243 // // remote is unknown, the table pings back. 244 // test.waitPacketOut(func(p *ping) error { 245 // if !reflect.DeepEqual(p.From, test.udp.ourEndpoint) { 246 // t.Errorf("got ping.From %v, want %v", p.From, test.udp.ourEndpoint) 247 // } 248 // wantTo := rpcEndpoint{ 249 // // The mirrored UDP address is the UDP packet sender. 250 // IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port), 251 // TCP: 0, 252 // } 253 // if !reflect.DeepEqual(p.To, wantTo) { 254 // t.Errorf("got ping.To %v, want %v", p.To, wantTo) 255 // } 256 // return nil 257 // }) 258 // test.packetIn(nil, pongPacket, &pong{Expiration: futureExp}) 259 // 260 // // the node should be added to the table shortly after getting the 261 // // pong packet. 262 // select { 263 // case n := <-added: 264 // rid := PubkeyID(&test.remotekey.PublicKey) 265 // if n.ID != rid { 266 // t.Errorf("node has wrong ID: got %v, want %v", n.ID, rid) 267 // } 268 // if !bytes.Equal(n.IP, test.remoteaddr.IP) { 269 // t.Errorf("node has wrong IP: got %v, want: %v", n.IP, test.remoteaddr.IP) 270 // } 271 // if int(n.UDP) != test.remoteaddr.Port { 272 // t.Errorf("node has wrong UDP port: got %v, want: %v", n.UDP, test.remoteaddr.Port) 273 // } 274 // if n.TCP != testRemote.TCP { 275 // t.Errorf("node has wrong TCP port: got %v, want: %v", n.TCP, testRemote.TCP) 276 // } 277 // case <-time.After(2 * time.Second): 278 // t.Errorf("node was not added within 2 seconds") 279 // } 280 // } 281 282 var testPackets = []struct { 283 input string 284 wantPacket interface{} 285 }{ 286 { 287 input: "71dbda3a79554728d4f94411e42ee1f8b0d561c10e1e5f5893367948c6a7d70bb87b235fa28a77070271b6c164a2dce8c7e13a5739b53b5e96f2e5acb0e458a02902f5965d55ecbeb2ebb6cabb8b2b232896a36b737666c55265ad0a68412f250001ea04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a355", 288 wantPacket: &ping{ 289 Version: 4, 290 From: rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544}, 291 To: rpcEndpoint{net.ParseIP("::1"), 2222, 3333}, 292 Expiration: 1136239445, 293 Rest: []rlp.RawValue{}, 294 }, 295 }, 296 { 297 input: "e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663aaa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a3550102", 298 wantPacket: &ping{ 299 Version: 4, 300 From: rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544}, 301 To: rpcEndpoint{net.ParseIP("::1"), 2222, 3333}, 302 Expiration: 1136239445, 303 Rest: []rlp.RawValue{{0x01}, {0x02}}, 304 }, 305 }, 306 { 307 input: "577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba76023fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee1917084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c76d922dc3", 308 wantPacket: &ping{ 309 Version: 555, 310 From: rpcEndpoint{net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 3322, 5544}, 311 To: rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338}, 312 Expiration: 1136239445, 313 Rest: []rlp.RawValue{{0xC5, 0x01, 0x02, 0x03, 0x04, 0x05}}, 314 }, 315 }, 316 { 317 input: "09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b2069869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f055542124e", 318 wantPacket: &pong{ 319 To: rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338}, 320 ReplyTok: common.Hex2Bytes("fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c954"), 321 Expiration: 1136239445, 322 Rest: []rlp.RawValue{{0xC6, 0x01, 0x02, 0x03, 0xC2, 0x04, 0x05}, {0x06}}, 323 }, 324 }, 325 { 326 input: "c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260add7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396", 327 wantPacket: &findnode{ 328 Target: MustHexID("ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f"), 329 Expiration: 1136239445, 330 Rest: []rlp.RawValue{{0x82, 0x99, 0x99}, {0x83, 0x99, 0x99, 0x99}}, 331 }, 332 }, 333 { 334 input: "c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db8403155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d313198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df738443b9a355010203b525a138aa34383fec3d2719a0", 335 wantPacket: &neighbors{ 336 Nodes: []rpcNode{ 337 { 338 ID: MustHexID("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"), 339 IP: net.ParseIP("99.33.22.55").To4(), 340 UDP: 4444, 341 TCP: 4445, 342 }, 343 { 344 ID: MustHexID("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"), 345 IP: net.ParseIP("1.2.3.4").To4(), 346 UDP: 1, 347 TCP: 1, 348 }, 349 { 350 ID: MustHexID("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"), 351 IP: net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 352 UDP: 3333, 353 TCP: 3333, 354 }, 355 { 356 ID: MustHexID("8dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73"), 357 IP: net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 358 UDP: 999, 359 TCP: 1000, 360 }, 361 }, 362 Expiration: 1136239445, 363 Rest: []rlp.RawValue{{0x01}, {0x02}, {0x03}}, 364 }, 365 }, 366 } 367 368 func TestForwardCompatibility(t *testing.T) { 369 t.Skip("skipped while working on discovery v5") 370 371 testkey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 372 wantNodeID := PubkeyID(&testkey.PublicKey) 373 374 for _, test := range testPackets { 375 input, err := hex.DecodeString(test.input) 376 if err != nil { 377 t.Fatalf("invalid hex: %s", test.input) 378 } 379 var pkt ingressPacket 380 if err := decodePacket(input, &pkt); err != nil { 381 t.Errorf("did not accept packet %s\n%v", test.input, err) 382 continue 383 } 384 if !reflect.DeepEqual(pkt.data, test.wantPacket) { 385 t.Errorf("got %s\nwant %s", spew.Sdump(pkt.data), spew.Sdump(test.wantPacket)) 386 } 387 if pkt.remoteID != wantNodeID { 388 t.Errorf("got id %v\nwant id %v", pkt.remoteID, wantNodeID) 389 } 390 } 391 } 392 393 // dgramPipe is a fake UDP socket. It queues all sent datagrams. 394 type dgramPipe struct { 395 mu *sync.Mutex 396 cond *sync.Cond 397 closing chan struct{} 398 closed bool 399 queue [][]byte 400 } 401 402 func newpipe() *dgramPipe { 403 mu := new(sync.Mutex) 404 return &dgramPipe{ 405 closing: make(chan struct{}), 406 cond: &sync.Cond{L: mu}, 407 mu: mu, 408 } 409 } 410 411 // WriteToUDP queues a datagram. 412 func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) { 413 msg := make([]byte, len(b)) 414 copy(msg, b) 415 c.mu.Lock() 416 defer c.mu.Unlock() 417 if c.closed { 418 return 0, errors.New("closed") 419 } 420 c.queue = append(c.queue, msg) 421 c.cond.Signal() 422 return len(b), nil 423 } 424 425 // ReadFromUDP just hangs until the pipe is closed. 426 func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { 427 <-c.closing 428 return 0, nil, io.EOF 429 } 430 431 func (c *dgramPipe) Close() error { 432 c.mu.Lock() 433 defer c.mu.Unlock() 434 if !c.closed { 435 close(c.closing) 436 c.closed = true 437 } 438 return nil 439 } 440 441 func (c *dgramPipe) LocalAddr() net.Addr { 442 return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)} 443 } 444 445 func (c *dgramPipe) waitPacketOut() []byte { 446 c.mu.Lock() 447 defer c.mu.Unlock() 448 for len(c.queue) == 0 { 449 c.cond.Wait() 450 } 451 p := c.queue[0] 452 copy(c.queue, c.queue[1:]) 453 c.queue = c.queue[:len(c.queue)-1] 454 return p 455 }