github.com/csquan/dpos-go-ethereum@v1.9.7/p2p/discover/v4_lookup_test.go (about) 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 17 package discover 18 19 import ( 20 "crypto/ecdsa" 21 "fmt" 22 "net" 23 "sort" 24 "testing" 25 26 "github.com/ethereum/go-ethereum/crypto" 27 "github.com/ethereum/go-ethereum/p2p/enode" 28 ) 29 30 func TestUDPv4_Lookup(t *testing.T) { 31 t.Parallel() 32 test := newUDPTest(t) 33 34 // Lookup on empty table returns no nodes. 35 targetKey, _ := decodePubkey(lookupTestnet.target) 36 if results := test.udp.LookupPubkey(targetKey); len(results) > 0 { 37 t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results) 38 } 39 40 // Seed table with initial node. 41 fillTable(test.table, []*node{wrapNode(lookupTestnet.node(256, 0))}) 42 43 // Start the lookup. 44 resultC := make(chan []*enode.Node, 1) 45 go func() { 46 resultC <- test.udp.LookupPubkey(targetKey) 47 test.close() 48 }() 49 50 // Answer lookup packets. 51 serveTestnet(test, lookupTestnet) 52 53 // Verify result nodes. 54 results := <-resultC 55 t.Logf("results:") 56 for _, e := range results { 57 t.Logf(" ld=%d, %x", enode.LogDist(lookupTestnet.target.id(), e.ID()), e.ID().Bytes()) 58 } 59 if len(results) != bucketSize { 60 t.Errorf("wrong number of results: got %d, want %d", len(results), bucketSize) 61 } 62 if hasDuplicates(wrapNodes(results)) { 63 t.Errorf("result set contains duplicate entries") 64 } 65 if !sortedByDistanceTo(lookupTestnet.target.id(), wrapNodes(results)) { 66 t.Errorf("result set not sorted by distance to target") 67 } 68 if err := checkNodesEqual(results, lookupTestnet.closest(bucketSize)); err != nil { 69 t.Errorf("results aren't the closest %d nodes\n%v", bucketSize, err) 70 } 71 } 72 73 func TestUDPv4_LookupIterator(t *testing.T) { 74 t.Parallel() 75 test := newUDPTest(t) 76 defer test.close() 77 78 // Seed table with initial nodes. 79 bootnodes := make([]*node, len(lookupTestnet.dists[256])) 80 for i := range lookupTestnet.dists[256] { 81 bootnodes[i] = wrapNode(lookupTestnet.node(256, i)) 82 } 83 fillTable(test.table, bootnodes) 84 go serveTestnet(test, lookupTestnet) 85 86 // Create the iterator and collect the nodes it yields. 87 iter := test.udp.RandomNodes() 88 seen := make(map[enode.ID]*enode.Node) 89 for limit := lookupTestnet.len(); iter.Next() && len(seen) < limit; { 90 seen[iter.Node().ID()] = iter.Node() 91 } 92 iter.Close() 93 94 // Check that all nodes in lookupTestnet were seen by the iterator. 95 results := make([]*enode.Node, 0, len(seen)) 96 for _, n := range seen { 97 results = append(results, n) 98 } 99 sortByID(results) 100 want := lookupTestnet.nodes() 101 if err := checkNodesEqual(results, want); err != nil { 102 t.Fatal(err) 103 } 104 } 105 106 // TestUDPv4_LookupIteratorClose checks that lookupIterator ends when its Close 107 // method is called. 108 func TestUDPv4_LookupIteratorClose(t *testing.T) { 109 t.Parallel() 110 test := newUDPTest(t) 111 defer test.close() 112 113 // Seed table with initial nodes. 114 bootnodes := make([]*node, len(lookupTestnet.dists[256])) 115 for i := range lookupTestnet.dists[256] { 116 bootnodes[i] = wrapNode(lookupTestnet.node(256, i)) 117 } 118 fillTable(test.table, bootnodes) 119 go serveTestnet(test, lookupTestnet) 120 121 it := test.udp.RandomNodes() 122 if ok := it.Next(); !ok || it.Node() == nil { 123 t.Fatalf("iterator didn't return any node") 124 } 125 126 it.Close() 127 128 ncalls := 0 129 for ; ncalls < 100 && it.Next(); ncalls++ { 130 if it.Node() == nil { 131 t.Error("iterator returned Node() == nil node after Next() == true") 132 } 133 } 134 t.Logf("iterator returned %d nodes after close", ncalls) 135 if it.Next() { 136 t.Errorf("Next() == true after close and %d more calls", ncalls) 137 } 138 if n := it.Node(); n != nil { 139 t.Errorf("iterator returned non-nil node after close and %d more calls", ncalls) 140 } 141 } 142 143 func serveTestnet(test *udpTest, testnet *preminedTestnet) { 144 for done := false; !done; { 145 done = test.waitPacketOut(func(p packetV4, to *net.UDPAddr, hash []byte) { 146 n, key := testnet.nodeByAddr(to) 147 switch p.(type) { 148 case *pingV4: 149 test.packetInFrom(nil, key, to, &pongV4{Expiration: futureExp, ReplyTok: hash}) 150 case *findnodeV4: 151 dist := enode.LogDist(n.ID(), testnet.target.id()) 152 nodes := testnet.nodesAtDistance(dist - 1) 153 test.packetInFrom(nil, key, to, &neighborsV4{Expiration: futureExp, Nodes: nodes}) 154 } 155 }) 156 } 157 } 158 159 // This is the test network for the Lookup test. 160 // The nodes were obtained by running lookupTestnet.mine with a random NodeID as target. 161 var lookupTestnet = &preminedTestnet{ 162 target: hexEncPubkey("5d485bdcbe9bc89314a10ae9231e429d33853e3a8fa2af39f5f827370a2e4185e344ace5d16237491dad41f278f1d3785210d29ace76cd627b9147ee340b1125"), 163 dists: [257][]*ecdsa.PrivateKey{ 164 251: { 165 hexEncPrivkey("29738ba0c1a4397d6a65f292eee07f02df8e58d41594ba2be3cf84ce0fc58169"), 166 hexEncPrivkey("511b1686e4e58a917f7f848e9bf5539d206a68f5ad6b54b552c2399fe7d174ae"), 167 hexEncPrivkey("d09e5eaeec0fd596236faed210e55ef45112409a5aa7f3276d26646080dcfaeb"), 168 hexEncPrivkey("c1e20dbbf0d530e50573bd0a260b32ec15eb9190032b4633d44834afc8afe578"), 169 hexEncPrivkey("ed5f38f5702d92d306143e5d9154fb21819777da39af325ea359f453d179e80b"), 170 }, 171 252: { 172 hexEncPrivkey("1c9b1cafbec00848d2c174b858219914b42a7d5c9359b1ca03fd650e8239ae94"), 173 hexEncPrivkey("e0e1e8db4a6f13c1ffdd3e96b72fa7012293ced187c9dcdcb9ba2af37a46fa10"), 174 hexEncPrivkey("3d53823e0a0295cb09f3e11d16c1b44d07dd37cec6f739b8df3a590189fe9fb9"), 175 }, 176 253: { 177 hexEncPrivkey("2d0511ae9bf590166597eeab86b6f27b1ab761761eaea8965487b162f8703847"), 178 hexEncPrivkey("6cfbd7b8503073fc3dbdb746a7c672571648d3bd15197ccf7f7fef3d904f53a2"), 179 hexEncPrivkey("a30599b12827b69120633f15b98a7f6bc9fc2e9a0fd6ae2ebb767c0e64d743ab"), 180 hexEncPrivkey("14a98db9b46a831d67eff29f3b85b1b485bb12ae9796aea98d91be3dc78d8a91"), 181 hexEncPrivkey("2369ff1fc1ff8ca7d20b17e2673adc3365c3674377f21c5d9dafaff21fe12e24"), 182 hexEncPrivkey("9ae91101d6b5048607f41ec0f690ef5d09507928aded2410aabd9237aa2727d7"), 183 hexEncPrivkey("05e3c59090a3fd1ae697c09c574a36fcf9bedd0afa8fe3946f21117319ca4973"), 184 hexEncPrivkey("06f31c5ea632658f718a91a1b1b9ae4b7549d7b3bc61cbc2be5f4a439039f3ad"), 185 }, 186 254: { 187 hexEncPrivkey("dec742079ec00ff4ec1284d7905bc3de2366f67a0769431fd16f80fd68c58a7c"), 188 hexEncPrivkey("ff02c8861fa12fbd129d2a95ea663492ef9c1e51de19dcfbbfe1c59894a28d2b"), 189 hexEncPrivkey("4dded9e4eefcbce4262be4fd9e8a773670ab0b5f448f286ec97dfc8cf681444a"), 190 hexEncPrivkey("750d931e2a8baa2c9268cb46b7cd851f4198018bed22f4dceb09dd334a2395f6"), 191 hexEncPrivkey("ce1435a956a98ffec484cd11489c4f165cf1606819ab6b521cee440f0c677e9e"), 192 hexEncPrivkey("996e7f8d1638be92d7328b4770f47e5420fc4bafecb4324fd33b1f5d9f403a75"), 193 hexEncPrivkey("ebdc44e77a6cc0eb622e58cf3bb903c3da4c91ca75b447b0168505d8fc308b9c"), 194 hexEncPrivkey("46bd1eddcf6431bea66fc19ebc45df191c1c7d6ed552dcdc7392885009c322f0"), 195 }, 196 255: { 197 hexEncPrivkey("da8645f90826e57228d9ea72aff84500060ad111a5d62e4af831ed8e4b5acfb8"), 198 hexEncPrivkey("3c944c5d9af51d4c1d43f5d0f3a1a7ef65d5e82744d669b58b5fed242941a566"), 199 hexEncPrivkey("5ebcde76f1d579eebf6e43b0ffe9157e65ffaa391175d5b9aa988f47df3e33da"), 200 hexEncPrivkey("97f78253a7d1d796e4eaabce721febcc4550dd68fb11cc818378ba807a2cb7de"), 201 hexEncPrivkey("a38cd7dc9b4079d1c0406afd0fdb1165c285f2c44f946eca96fc67772c988c7d"), 202 hexEncPrivkey("d64cbb3ffdf712c372b7a22a176308ef8f91861398d5dbaf326fd89c6eaeef1c"), 203 hexEncPrivkey("d269609743ef29d6446e3355ec647e38d919c82a4eb5837e442efd7f4218944f"), 204 hexEncPrivkey("d8f7bcc4a530efde1d143717007179e0d9ace405ddaaf151c4d863753b7fd64c"), 205 }, 206 256: { 207 hexEncPrivkey("8c5b422155d33ea8e9d46f71d1ad3e7b24cb40051413ffa1a81cff613d243ba9"), 208 hexEncPrivkey("937b1af801def4e8f5a3a8bd225a8bcff1db764e41d3e177f2e9376e8dd87233"), 209 hexEncPrivkey("120260dce739b6f71f171da6f65bc361b5fad51db74cf02d3e973347819a6518"), 210 hexEncPrivkey("1fa56cf25d4b46c2bf94e82355aa631717b63190785ac6bae545a88aadc304a9"), 211 hexEncPrivkey("3c38c503c0376f9b4adcbe935d5f4b890391741c764f61b03cd4d0d42deae002"), 212 hexEncPrivkey("3a54af3e9fa162bc8623cdf3e5d9b70bf30ade1d54cc3abea8659aba6cff471f"), 213 hexEncPrivkey("6799a02ea1999aefdcbcc4d3ff9544478be7365a328d0d0f37c26bd95ade0cda"), 214 hexEncPrivkey("e24a7bc9051058f918646b0f6e3d16884b2a55a15553b89bab910d55ebc36116"), 215 }, 216 }, 217 } 218 219 type preminedTestnet struct { 220 target encPubkey 221 dists [hashBits + 1][]*ecdsa.PrivateKey 222 } 223 224 func (tn *preminedTestnet) len() int { 225 n := 0 226 for _, keys := range tn.dists { 227 n += len(keys) 228 } 229 return n 230 } 231 232 func (tn *preminedTestnet) nodes() []*enode.Node { 233 result := make([]*enode.Node, 0, tn.len()) 234 for dist, keys := range tn.dists { 235 for index := range keys { 236 result = append(result, tn.node(dist, index)) 237 } 238 } 239 sortByID(result) 240 return result 241 } 242 243 func (tn *preminedTestnet) node(dist, index int) *enode.Node { 244 key := tn.dists[dist][index] 245 ip := net.IP{127, byte(dist >> 8), byte(dist), byte(index)} 246 return enode.NewV4(&key.PublicKey, ip, 0, 5000) 247 } 248 249 func (tn *preminedTestnet) nodeByAddr(addr *net.UDPAddr) (*enode.Node, *ecdsa.PrivateKey) { 250 dist := int(addr.IP[1])<<8 + int(addr.IP[2]) 251 index := int(addr.IP[3]) 252 key := tn.dists[dist][index] 253 return tn.node(dist, index), key 254 } 255 256 func (tn *preminedTestnet) nodesAtDistance(dist int) []rpcNode { 257 result := make([]rpcNode, len(tn.dists[dist])) 258 for i := range result { 259 result[i] = nodeToRPC(wrapNode(tn.node(dist, i))) 260 } 261 return result 262 } 263 264 func (tn *preminedTestnet) closest(n int) (nodes []*enode.Node) { 265 for d := range tn.dists { 266 for i := range tn.dists[d] { 267 nodes = append(nodes, tn.node(d, i)) 268 } 269 } 270 sort.Slice(nodes, func(i, j int) bool { 271 return enode.DistCmp(tn.target.id(), nodes[i].ID(), nodes[j].ID()) < 0 272 }) 273 return nodes[:n] 274 } 275 276 var _ = (*preminedTestnet).mine // avoid linter warning about mine being dead code. 277 278 // mine generates a testnet struct literal with nodes at 279 // various distances to the network's target. 280 func (tn *preminedTestnet) mine() { 281 // Clear existing slices first (useful when re-mining). 282 for i := range tn.dists { 283 tn.dists[i] = nil 284 } 285 286 targetSha := tn.target.id() 287 found, need := 0, 40 288 for found < need { 289 k := newkey() 290 ld := enode.LogDist(targetSha, encodePubkey(&k.PublicKey).id()) 291 if len(tn.dists[ld]) < 8 { 292 tn.dists[ld] = append(tn.dists[ld], k) 293 found++ 294 fmt.Printf("found ID with ld %d (%d/%d)\n", ld, found, need) 295 } 296 } 297 fmt.Printf("&preminedTestnet{\n") 298 fmt.Printf(" target: hexEncPubkey(\"%x\"),\n", tn.target[:]) 299 fmt.Printf(" dists: [%d][]*ecdsa.PrivateKey{\n", len(tn.dists)) 300 for ld, ns := range tn.dists { 301 if len(ns) == 0 { 302 continue 303 } 304 fmt.Printf(" %d: {\n", ld) 305 for _, key := range ns { 306 fmt.Printf(" hexEncPrivkey(\"%x\"),\n", crypto.FromECDSA(key)) 307 } 308 fmt.Printf(" },\n") 309 } 310 fmt.Printf(" },\n") 311 fmt.Printf("}\n") 312 }