github.com/phillinzzz/newBsc@v1.1.6/p2p/dnsdisc/client_test.go (about) 1 // Copyright 2018 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 dnsdisc 18 19 import ( 20 "context" 21 "crypto/ecdsa" 22 "errors" 23 "math/rand" 24 "reflect" 25 "testing" 26 "time" 27 28 "github.com/davecgh/go-spew/spew" 29 "github.com/phillinzzz/newBsc/common/mclock" 30 "github.com/phillinzzz/newBsc/crypto" 31 "github.com/phillinzzz/newBsc/internal/testlog" 32 "github.com/phillinzzz/newBsc/log" 33 "github.com/phillinzzz/newBsc/p2p/enode" 34 "github.com/phillinzzz/newBsc/p2p/enr" 35 ) 36 37 const ( 38 signingKeySeed = 0x111111 39 nodesSeed1 = 0x2945237 40 nodesSeed2 = 0x4567299 41 ) 42 43 func TestClientSyncTree(t *testing.T) { 44 r := mapResolver{ 45 "n": "enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA", 46 "C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org", 47 "JWXYDBPXYWG6FX3GMDIBFA6CJ4.n": "enrtree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDACK24", 48 "2XS2367YHAXJFGLZHVAWLQD4ZY.n": "enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA", 49 "H4FHT4B454P6UXFD7JCYQ5PWDY.n": "enr:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI", 50 "MHTDO6TMUBRIA2XWG5LUDACK24.n": "enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o", 51 } 52 var ( 53 wantNodes = testNodes(0x29452, 3) 54 wantLinks = []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"} 55 wantSeq = uint(1) 56 ) 57 58 c := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)}) 59 stree, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n") 60 if err != nil { 61 t.Fatal("sync error:", err) 62 } 63 if !reflect.DeepEqual(sortByID(stree.Nodes()), sortByID(wantNodes)) { 64 t.Errorf("wrong nodes in synced tree:\nhave %v\nwant %v", spew.Sdump(stree.Nodes()), spew.Sdump(wantNodes)) 65 } 66 if !reflect.DeepEqual(stree.Links(), wantLinks) { 67 t.Errorf("wrong links in synced tree: %v", stree.Links()) 68 } 69 if stree.Seq() != wantSeq { 70 t.Errorf("synced tree has wrong seq: %d", stree.Seq()) 71 } 72 } 73 74 // In this test, syncing the tree fails because it contains an invalid ENR entry. 75 func TestClientSyncTreeBadNode(t *testing.T) { 76 // var b strings.Builder 77 // b.WriteString(enrPrefix) 78 // b.WriteString("-----") 79 // badHash := subdomain(&b) 80 // tree, _ := MakeTree(3, nil, []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"}) 81 // tree.entries[badHash] = &b 82 // tree.root.eroot = badHash 83 // url, _ := tree.Sign(testKey(signingKeySeed), "n") 84 // fmt.Println(url) 85 // fmt.Printf("%#v\n", tree.ToTXT("n")) 86 87 r := mapResolver{ 88 "n": "enrtree-root:v1 e=INDMVBZEEQ4ESVYAKGIYU74EAA l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=3 sig=Vl3AmunLur0JZ3sIyJPSH6A3Vvdp4F40jWQeCmkIhmcgwE4VC5U9wpK8C_uL_CMY29fd6FAhspRvq2z_VysTLAA", 89 "C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org", 90 "INDMVBZEEQ4ESVYAKGIYU74EAA.n": "enr:-----", 91 } 92 c := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)}) 93 _, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n") 94 wantErr := nameError{name: "INDMVBZEEQ4ESVYAKGIYU74EAA.n", err: entryError{typ: "enr", err: errInvalidENR}} 95 if err != wantErr { 96 t.Fatalf("expected sync error %q, got %q", wantErr, err) 97 } 98 } 99 100 // This test checks that randomIterator finds all entries. 101 func TestIterator(t *testing.T) { 102 nodes := testNodes(nodesSeed1, 30) 103 tree, url := makeTestTree("n", nodes, nil) 104 r := mapResolver(tree.ToTXT("n")) 105 c := NewClient(Config{ 106 Resolver: r, 107 Logger: testlog.Logger(t, log.LvlTrace), 108 RateLimit: 500, 109 }) 110 it, err := c.NewIterator(url) 111 if err != nil { 112 t.Fatal(err) 113 } 114 115 checkIterator(t, it, nodes) 116 } 117 118 // This test checks if closing randomIterator races. 119 func TestIteratorClose(t *testing.T) { 120 nodes := testNodes(nodesSeed1, 500) 121 tree1, url1 := makeTestTree("t1", nodes, nil) 122 c := NewClient(Config{Resolver: newMapResolver(tree1.ToTXT("t1"))}) 123 it, err := c.NewIterator(url1) 124 if err != nil { 125 t.Fatal(err) 126 } 127 128 done := make(chan struct{}) 129 go func() { 130 for it.Next() { 131 _ = it.Node() 132 } 133 close(done) 134 }() 135 136 time.Sleep(50 * time.Millisecond) 137 it.Close() 138 <-done 139 } 140 141 // This test checks that randomIterator traverses linked trees as well as explicitly added trees. 142 func TestIteratorLinks(t *testing.T) { 143 nodes := testNodes(nodesSeed1, 40) 144 tree1, url1 := makeTestTree("t1", nodes[:10], nil) 145 tree2, url2 := makeTestTree("t2", nodes[10:], []string{url1}) 146 c := NewClient(Config{ 147 Resolver: newMapResolver(tree1.ToTXT("t1"), tree2.ToTXT("t2")), 148 Logger: testlog.Logger(t, log.LvlTrace), 149 RateLimit: 500, 150 }) 151 it, err := c.NewIterator(url2) 152 if err != nil { 153 t.Fatal(err) 154 } 155 156 checkIterator(t, it, nodes) 157 } 158 159 // This test verifies that randomIterator re-checks the root of the tree to catch 160 // updates to nodes. 161 func TestIteratorNodeUpdates(t *testing.T) { 162 var ( 163 clock = new(mclock.Simulated) 164 nodes = testNodes(nodesSeed1, 30) 165 resolver = newMapResolver() 166 c = NewClient(Config{ 167 Resolver: resolver, 168 Logger: testlog.Logger(t, log.LvlTrace), 169 RecheckInterval: 20 * time.Minute, 170 RateLimit: 500, 171 }) 172 ) 173 c.clock = clock 174 tree1, url := makeTestTree("n", nodes[:25], nil) 175 it, err := c.NewIterator(url) 176 if err != nil { 177 t.Fatal(err) 178 } 179 180 // Sync the original tree. 181 resolver.add(tree1.ToTXT("n")) 182 checkIterator(t, it, nodes[:25]) 183 184 // Ensure RandomNode returns the new nodes after the tree is updated. 185 updateSomeNodes(nodesSeed1, nodes) 186 tree2, _ := makeTestTree("n", nodes, nil) 187 resolver.clear() 188 resolver.add(tree2.ToTXT("n")) 189 t.Log("tree updated") 190 191 clock.Run(c.cfg.RecheckInterval + 1*time.Second) 192 checkIterator(t, it, nodes) 193 } 194 195 // This test checks that the tree root is rechecked when a couple of leaf 196 // requests have failed. The test is just like TestIteratorNodeUpdates, but 197 // without advancing the clock by recheckInterval after the tree update. 198 func TestIteratorRootRecheckOnFail(t *testing.T) { 199 var ( 200 clock = new(mclock.Simulated) 201 nodes = testNodes(nodesSeed1, 30) 202 resolver = newMapResolver() 203 c = NewClient(Config{ 204 Resolver: resolver, 205 Logger: testlog.Logger(t, log.LvlTrace), 206 RecheckInterval: 20 * time.Minute, 207 RateLimit: 500, 208 // Disabling the cache is required for this test because the client doesn't 209 // notice leaf failures if all records are cached. 210 CacheLimit: 1, 211 }) 212 ) 213 c.clock = clock 214 tree1, url := makeTestTree("n", nodes[:25], nil) 215 it, err := c.NewIterator(url) 216 if err != nil { 217 t.Fatal(err) 218 } 219 220 // Sync the original tree. 221 resolver.add(tree1.ToTXT("n")) 222 checkIterator(t, it, nodes[:25]) 223 224 // Ensure RandomNode returns the new nodes after the tree is updated. 225 updateSomeNodes(nodesSeed1, nodes) 226 tree2, _ := makeTestTree("n", nodes, nil) 227 resolver.clear() 228 resolver.add(tree2.ToTXT("n")) 229 t.Log("tree updated") 230 231 checkIterator(t, it, nodes) 232 } 233 234 // This test checks that the iterator works correctly when the tree is initially empty. 235 func TestIteratorEmptyTree(t *testing.T) { 236 var ( 237 clock = new(mclock.Simulated) 238 nodes = testNodes(nodesSeed1, 1) 239 resolver = newMapResolver() 240 c = NewClient(Config{ 241 Resolver: resolver, 242 Logger: testlog.Logger(t, log.LvlTrace), 243 RecheckInterval: 20 * time.Minute, 244 RateLimit: 500, 245 }) 246 ) 247 c.clock = clock 248 tree1, url := makeTestTree("n", nil, nil) 249 tree2, _ := makeTestTree("n", nodes, nil) 250 resolver.add(tree1.ToTXT("n")) 251 252 // Start the iterator. 253 node := make(chan *enode.Node) 254 it, err := c.NewIterator(url) 255 if err != nil { 256 t.Fatal(err) 257 } 258 go func() { 259 it.Next() 260 node <- it.Node() 261 }() 262 263 // Wait for the client to get stuck in waitForRootUpdates. 264 clock.WaitForTimers(1) 265 266 // Now update the root. 267 resolver.add(tree2.ToTXT("n")) 268 269 // Wait for it to pick up the root change. 270 clock.Run(c.cfg.RecheckInterval) 271 select { 272 case n := <-node: 273 if n.ID() != nodes[0].ID() { 274 t.Fatalf("wrong node returned") 275 } 276 case <-time.After(5 * time.Second): 277 t.Fatal("it.Next() did not unblock within 5s of real time") 278 } 279 } 280 281 // updateSomeNodes applies ENR updates to some of the given nodes. 282 func updateSomeNodes(keySeed int64, nodes []*enode.Node) { 283 keys := testKeys(nodesSeed1, len(nodes)) 284 for i, n := range nodes[:len(nodes)/2] { 285 r := n.Record() 286 r.Set(enr.IP{127, 0, 0, 1}) 287 r.SetSeq(55) 288 enode.SignV4(r, keys[i]) 289 n2, _ := enode.New(enode.ValidSchemes, r) 290 nodes[i] = n2 291 } 292 } 293 294 // This test verifies that randomIterator re-checks the root of the tree to catch 295 // updates to links. 296 func TestIteratorLinkUpdates(t *testing.T) { 297 var ( 298 clock = new(mclock.Simulated) 299 nodes = testNodes(nodesSeed1, 30) 300 resolver = newMapResolver() 301 c = NewClient(Config{ 302 Resolver: resolver, 303 Logger: testlog.Logger(t, log.LvlTrace), 304 RecheckInterval: 20 * time.Minute, 305 RateLimit: 500, 306 }) 307 ) 308 c.clock = clock 309 tree3, url3 := makeTestTree("t3", nodes[20:30], nil) 310 tree2, url2 := makeTestTree("t2", nodes[10:20], nil) 311 tree1, url1 := makeTestTree("t1", nodes[0:10], []string{url2}) 312 resolver.add(tree1.ToTXT("t1")) 313 resolver.add(tree2.ToTXT("t2")) 314 resolver.add(tree3.ToTXT("t3")) 315 316 it, err := c.NewIterator(url1) 317 if err != nil { 318 t.Fatal(err) 319 } 320 321 // Sync tree1 using RandomNode. 322 checkIterator(t, it, nodes[:20]) 323 324 // Add link to tree3, remove link to tree2. 325 tree1, _ = makeTestTree("t1", nodes[:10], []string{url3}) 326 resolver.add(tree1.ToTXT("t1")) 327 t.Log("tree1 updated") 328 329 clock.Run(c.cfg.RecheckInterval + 1*time.Second) 330 331 var wantNodes []*enode.Node 332 wantNodes = append(wantNodes, tree1.Nodes()...) 333 wantNodes = append(wantNodes, tree3.Nodes()...) 334 checkIterator(t, it, wantNodes) 335 336 // Check that linked trees are GCed when they're no longer referenced. 337 knownTrees := it.(*randomIterator).trees 338 if len(knownTrees) != 2 { 339 t.Errorf("client knows %d trees, want 2", len(knownTrees)) 340 } 341 } 342 343 func checkIterator(t *testing.T, it enode.Iterator, wantNodes []*enode.Node) { 344 t.Helper() 345 346 var ( 347 want = make(map[enode.ID]*enode.Node) 348 maxCalls = len(wantNodes) * 3 349 calls = 0 350 ) 351 for _, n := range wantNodes { 352 want[n.ID()] = n 353 } 354 for ; len(want) > 0 && calls < maxCalls; calls++ { 355 if !it.Next() { 356 t.Fatalf("Next returned false (call %d)", calls) 357 } 358 n := it.Node() 359 delete(want, n.ID()) 360 } 361 t.Logf("checkIterator called Next %d times to find %d nodes", calls, len(wantNodes)) 362 for _, n := range want { 363 t.Errorf("iterator didn't discover node %v", n.ID()) 364 } 365 } 366 367 func makeTestTree(domain string, nodes []*enode.Node, links []string) (*Tree, string) { 368 tree, err := MakeTree(1, nodes, links) 369 if err != nil { 370 panic(err) 371 } 372 url, err := tree.Sign(testKey(signingKeySeed), domain) 373 if err != nil { 374 panic(err) 375 } 376 return tree, url 377 } 378 379 // testKeys creates deterministic private keys for testing. 380 func testKeys(seed int64, n int) []*ecdsa.PrivateKey { 381 rand := rand.New(rand.NewSource(seed)) 382 keys := make([]*ecdsa.PrivateKey, n) 383 for i := 0; i < n; i++ { 384 key, err := ecdsa.GenerateKey(crypto.S256(), rand) 385 if err != nil { 386 panic("can't generate key: " + err.Error()) 387 } 388 keys[i] = key 389 } 390 return keys 391 } 392 393 func testKey(seed int64) *ecdsa.PrivateKey { 394 return testKeys(seed, 1)[0] 395 } 396 397 func testNodes(seed int64, n int) []*enode.Node { 398 keys := testKeys(seed, n) 399 nodes := make([]*enode.Node, n) 400 for i, key := range keys { 401 record := new(enr.Record) 402 record.SetSeq(uint64(i)) 403 enode.SignV4(record, key) 404 n, err := enode.New(enode.ValidSchemes, record) 405 if err != nil { 406 panic(err) 407 } 408 nodes[i] = n 409 } 410 return nodes 411 } 412 413 func testNode(seed int64) *enode.Node { 414 return testNodes(seed, 1)[0] 415 } 416 417 type mapResolver map[string]string 418 419 func newMapResolver(maps ...map[string]string) mapResolver { 420 mr := make(mapResolver) 421 for _, m := range maps { 422 mr.add(m) 423 } 424 return mr 425 } 426 427 func (mr mapResolver) clear() { 428 for k := range mr { 429 delete(mr, k) 430 } 431 } 432 433 func (mr mapResolver) add(m map[string]string) { 434 for k, v := range m { 435 mr[k] = v 436 } 437 } 438 439 func (mr mapResolver) LookupTXT(ctx context.Context, name string) ([]string, error) { 440 if record, ok := mr[name]; ok { 441 return []string{record}, nil 442 } 443 return nil, errors.New("not found") 444 }