github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/eth/downloader/downloader_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 downloader 18 19 import ( 20 "errors" 21 "fmt" 22 "math/big" 23 "strings" 24 "sync" 25 "sync/atomic" 26 "testing" 27 "time" 28 29 "github.com/CommerciumBlockchain/go-commercium" 30 "github.com/CommerciumBlockchain/go-commercium/common" 31 "github.com/CommerciumBlockchain/go-commercium/core/rawdb" 32 "github.com/CommerciumBlockchain/go-commercium/core/types" 33 "github.com/CommerciumBlockchain/go-commercium/ethdb" 34 "github.com/CommerciumBlockchain/go-commercium/event" 35 "github.com/CommerciumBlockchain/go-commercium/trie" 36 ) 37 38 // Reduce some of the parameters to make the tester faster. 39 func init() { 40 fullMaxForkAncestry = 10000 41 lightMaxForkAncestry = 10000 42 blockCacheMaxItems = 1024 43 fsHeaderContCheck = 500 * time.Millisecond 44 } 45 46 // downloadTester is a test simulator for mocking out local block chain. 47 type downloadTester struct { 48 downloader *Downloader 49 50 genesis *types.Block // Genesis blocks used by the tester and peers 51 stateDb ethdb.Database // Database used by the tester for syncing from peers 52 peerDb ethdb.Database // Database of the peers containing all data 53 peers map[string]*downloadTesterPeer 54 55 ownHashes []common.Hash // Hash chain belonging to the tester 56 ownHeaders map[common.Hash]*types.Header // Headers belonging to the tester 57 ownBlocks map[common.Hash]*types.Block // Blocks belonging to the tester 58 ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester 59 ownChainTd map[common.Hash]*big.Int // Total difficulties of the blocks in the local chain 60 61 ancientHeaders map[common.Hash]*types.Header // Ancient headers belonging to the tester 62 ancientBlocks map[common.Hash]*types.Block // Ancient blocks belonging to the tester 63 ancientReceipts map[common.Hash]types.Receipts // Ancient receipts belonging to the tester 64 ancientChainTd map[common.Hash]*big.Int // Ancient total difficulties of the blocks in the local chain 65 66 lock sync.RWMutex 67 } 68 69 // newTester creates a new downloader test mocker. 70 func newTester() *downloadTester { 71 tester := &downloadTester{ 72 genesis: testGenesis, 73 peerDb: testDB, 74 peers: make(map[string]*downloadTesterPeer), 75 ownHashes: []common.Hash{testGenesis.Hash()}, 76 ownHeaders: map[common.Hash]*types.Header{testGenesis.Hash(): testGenesis.Header()}, 77 ownBlocks: map[common.Hash]*types.Block{testGenesis.Hash(): testGenesis}, 78 ownReceipts: map[common.Hash]types.Receipts{testGenesis.Hash(): nil}, 79 ownChainTd: map[common.Hash]*big.Int{testGenesis.Hash(): testGenesis.Difficulty()}, 80 81 // Initialize ancient store with test genesis block 82 ancientHeaders: map[common.Hash]*types.Header{testGenesis.Hash(): testGenesis.Header()}, 83 ancientBlocks: map[common.Hash]*types.Block{testGenesis.Hash(): testGenesis}, 84 ancientReceipts: map[common.Hash]types.Receipts{testGenesis.Hash(): nil}, 85 ancientChainTd: map[common.Hash]*big.Int{testGenesis.Hash(): testGenesis.Difficulty()}, 86 } 87 tester.stateDb = rawdb.NewMemoryDatabase() 88 tester.stateDb.Put(testGenesis.Root().Bytes(), []byte{0x00}) 89 90 tester.downloader = New(0, tester.stateDb, trie.NewSyncBloom(1, tester.stateDb), new(event.TypeMux), tester, nil, tester.dropPeer) 91 return tester 92 } 93 94 // terminate aborts any operations on the embedded downloader and releases all 95 // held resources. 96 func (dl *downloadTester) terminate() { 97 dl.downloader.Terminate() 98 } 99 100 // sync starts synchronizing with a remote peer, blocking until it completes. 101 func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error { 102 dl.lock.RLock() 103 hash := dl.peers[id].chain.headBlock().Hash() 104 // If no particular TD was requested, load from the peer's blockchain 105 if td == nil { 106 td = dl.peers[id].chain.td(hash) 107 } 108 dl.lock.RUnlock() 109 110 // Synchronise with the chosen peer and ensure proper cleanup afterwards 111 err := dl.downloader.synchronise(id, hash, td, mode) 112 select { 113 case <-dl.downloader.cancelCh: 114 // Ok, downloader fully cancelled after sync cycle 115 default: 116 // Downloader is still accepting packets, can block a peer up 117 panic("downloader active post sync cycle") // panic will be caught by tester 118 } 119 return err 120 } 121 122 // HasHeader checks if a header is present in the testers canonical chain. 123 func (dl *downloadTester) HasHeader(hash common.Hash, number uint64) bool { 124 return dl.GetHeaderByHash(hash) != nil 125 } 126 127 // HasBlock checks if a block is present in the testers canonical chain. 128 func (dl *downloadTester) HasBlock(hash common.Hash, number uint64) bool { 129 return dl.GetBlockByHash(hash) != nil 130 } 131 132 // HasFastBlock checks if a block is present in the testers canonical chain. 133 func (dl *downloadTester) HasFastBlock(hash common.Hash, number uint64) bool { 134 dl.lock.RLock() 135 defer dl.lock.RUnlock() 136 137 if _, ok := dl.ancientReceipts[hash]; ok { 138 return true 139 } 140 _, ok := dl.ownReceipts[hash] 141 return ok 142 } 143 144 // GetHeader retrieves a header from the testers canonical chain. 145 func (dl *downloadTester) GetHeaderByHash(hash common.Hash) *types.Header { 146 dl.lock.RLock() 147 defer dl.lock.RUnlock() 148 return dl.getHeaderByHash(hash) 149 } 150 151 // getHeaderByHash returns the header if found either within ancients or own blocks) 152 // This method assumes that the caller holds at least the read-lock (dl.lock) 153 func (dl *downloadTester) getHeaderByHash(hash common.Hash) *types.Header { 154 header := dl.ancientHeaders[hash] 155 if header != nil { 156 return header 157 } 158 return dl.ownHeaders[hash] 159 } 160 161 // GetBlock retrieves a block from the testers canonical chain. 162 func (dl *downloadTester) GetBlockByHash(hash common.Hash) *types.Block { 163 dl.lock.RLock() 164 defer dl.lock.RUnlock() 165 166 block := dl.ancientBlocks[hash] 167 if block != nil { 168 return block 169 } 170 return dl.ownBlocks[hash] 171 } 172 173 // CurrentHeader retrieves the current head header from the canonical chain. 174 func (dl *downloadTester) CurrentHeader() *types.Header { 175 dl.lock.RLock() 176 defer dl.lock.RUnlock() 177 178 for i := len(dl.ownHashes) - 1; i >= 0; i-- { 179 if header := dl.ancientHeaders[dl.ownHashes[i]]; header != nil { 180 return header 181 } 182 if header := dl.ownHeaders[dl.ownHashes[i]]; header != nil { 183 return header 184 } 185 } 186 return dl.genesis.Header() 187 } 188 189 // CurrentBlock retrieves the current head block from the canonical chain. 190 func (dl *downloadTester) CurrentBlock() *types.Block { 191 dl.lock.RLock() 192 defer dl.lock.RUnlock() 193 194 for i := len(dl.ownHashes) - 1; i >= 0; i-- { 195 if block := dl.ancientBlocks[dl.ownHashes[i]]; block != nil { 196 if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil { 197 return block 198 } 199 return block 200 } 201 if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil { 202 if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil { 203 return block 204 } 205 } 206 } 207 return dl.genesis 208 } 209 210 // CurrentFastBlock retrieves the current head fast-sync block from the canonical chain. 211 func (dl *downloadTester) CurrentFastBlock() *types.Block { 212 dl.lock.RLock() 213 defer dl.lock.RUnlock() 214 215 for i := len(dl.ownHashes) - 1; i >= 0; i-- { 216 if block := dl.ancientBlocks[dl.ownHashes[i]]; block != nil { 217 return block 218 } 219 if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil { 220 return block 221 } 222 } 223 return dl.genesis 224 } 225 226 // FastSyncCommitHead manually sets the head block to a given hash. 227 func (dl *downloadTester) FastSyncCommitHead(hash common.Hash) error { 228 // For now only check that the state trie is correct 229 if block := dl.GetBlockByHash(hash); block != nil { 230 _, err := trie.NewSecure(block.Root(), trie.NewDatabase(dl.stateDb)) 231 return err 232 } 233 return fmt.Errorf("non existent block: %x", hash[:4]) 234 } 235 236 // GetTd retrieves the block's total difficulty from the canonical chain. 237 func (dl *downloadTester) GetTd(hash common.Hash, number uint64) *big.Int { 238 dl.lock.RLock() 239 defer dl.lock.RUnlock() 240 241 return dl.getTd(hash) 242 } 243 244 // getTd retrieves the block's total difficulty if found either within 245 // ancients or own blocks). 246 // This method assumes that the caller holds at least the read-lock (dl.lock) 247 func (dl *downloadTester) getTd(hash common.Hash) *big.Int { 248 if td := dl.ancientChainTd[hash]; td != nil { 249 return td 250 } 251 return dl.ownChainTd[hash] 252 } 253 254 // InsertHeaderChain injects a new batch of headers into the simulated chain. 255 func (dl *downloadTester) InsertHeaderChain(headers []*types.Header, checkFreq int) (i int, err error) { 256 dl.lock.Lock() 257 defer dl.lock.Unlock() 258 // Do a quick check, as the blockchain.InsertHeaderChain doesn't insert anything in case of errors 259 if dl.getHeaderByHash(headers[0].ParentHash) == nil { 260 return 0, fmt.Errorf("InsertHeaderChain: unknown parent at first position, parent of number %d", headers[0].Number) 261 } 262 var hashes []common.Hash 263 for i := 1; i < len(headers); i++ { 264 hash := headers[i-1].Hash() 265 if headers[i].ParentHash != headers[i-1].Hash() { 266 return i, fmt.Errorf("non-contiguous import at position %d", i) 267 } 268 hashes = append(hashes, hash) 269 } 270 hashes = append(hashes, headers[len(headers)-1].Hash()) 271 // Do a full insert if pre-checks passed 272 for i, header := range headers { 273 hash := hashes[i] 274 if dl.getHeaderByHash(hash) != nil { 275 continue 276 } 277 if dl.getHeaderByHash(header.ParentHash) == nil { 278 // This _should_ be impossible, due to precheck and induction 279 return i, fmt.Errorf("InsertHeaderChain: unknown parent at position %d", i) 280 } 281 dl.ownHashes = append(dl.ownHashes, hash) 282 dl.ownHeaders[hash] = header 283 284 td := dl.getTd(header.ParentHash) 285 dl.ownChainTd[hash] = new(big.Int).Add(td, header.Difficulty) 286 } 287 return len(headers), nil 288 } 289 290 // InsertChain injects a new batch of blocks into the simulated chain. 291 func (dl *downloadTester) InsertChain(blocks types.Blocks) (i int, err error) { 292 dl.lock.Lock() 293 defer dl.lock.Unlock() 294 for i, block := range blocks { 295 if parent, ok := dl.ownBlocks[block.ParentHash()]; !ok { 296 return i, fmt.Errorf("InsertChain: unknown parent at position %d / %d", i, len(blocks)) 297 } else if _, err := dl.stateDb.Get(parent.Root().Bytes()); err != nil { 298 return i, fmt.Errorf("InsertChain: unknown parent state %x: %v", parent.Root(), err) 299 } 300 if hdr := dl.getHeaderByHash(block.Hash()); hdr == nil { 301 dl.ownHashes = append(dl.ownHashes, block.Hash()) 302 dl.ownHeaders[block.Hash()] = block.Header() 303 } 304 dl.ownBlocks[block.Hash()] = block 305 dl.ownReceipts[block.Hash()] = make(types.Receipts, 0) 306 dl.stateDb.Put(block.Root().Bytes(), []byte{0x00}) 307 td := dl.getTd(block.ParentHash()) 308 dl.ownChainTd[block.Hash()] = new(big.Int).Add(td, block.Difficulty()) 309 } 310 return len(blocks), nil 311 } 312 313 // InsertReceiptChain injects a new batch of receipts into the simulated chain. 314 func (dl *downloadTester) InsertReceiptChain(blocks types.Blocks, receipts []types.Receipts, ancientLimit uint64) (i int, err error) { 315 dl.lock.Lock() 316 defer dl.lock.Unlock() 317 318 for i := 0; i < len(blocks) && i < len(receipts); i++ { 319 if _, ok := dl.ownHeaders[blocks[i].Hash()]; !ok { 320 return i, errors.New("unknown owner") 321 } 322 if _, ok := dl.ancientBlocks[blocks[i].ParentHash()]; !ok { 323 if _, ok := dl.ownBlocks[blocks[i].ParentHash()]; !ok { 324 return i, errors.New("InsertReceiptChain: unknown parent") 325 } 326 } 327 if blocks[i].NumberU64() <= ancientLimit { 328 dl.ancientBlocks[blocks[i].Hash()] = blocks[i] 329 dl.ancientReceipts[blocks[i].Hash()] = receipts[i] 330 331 // Migrate from active db to ancient db 332 dl.ancientHeaders[blocks[i].Hash()] = blocks[i].Header() 333 dl.ancientChainTd[blocks[i].Hash()] = new(big.Int).Add(dl.ancientChainTd[blocks[i].ParentHash()], blocks[i].Difficulty()) 334 delete(dl.ownHeaders, blocks[i].Hash()) 335 delete(dl.ownChainTd, blocks[i].Hash()) 336 } else { 337 dl.ownBlocks[blocks[i].Hash()] = blocks[i] 338 dl.ownReceipts[blocks[i].Hash()] = receipts[i] 339 } 340 } 341 return len(blocks), nil 342 } 343 344 // SetHead rewinds the local chain to a new head. 345 func (dl *downloadTester) SetHead(head uint64) error { 346 dl.lock.Lock() 347 defer dl.lock.Unlock() 348 349 // Find the hash of the head to reset to 350 var hash common.Hash 351 for h, header := range dl.ownHeaders { 352 if header.Number.Uint64() == head { 353 hash = h 354 } 355 } 356 for h, header := range dl.ancientHeaders { 357 if header.Number.Uint64() == head { 358 hash = h 359 } 360 } 361 if hash == (common.Hash{}) { 362 return fmt.Errorf("unknown head to set: %d", head) 363 } 364 // Find the offset in the header chain 365 var offset int 366 for o, h := range dl.ownHashes { 367 if h == hash { 368 offset = o 369 break 370 } 371 } 372 // Remove all the hashes and associated data afterwards 373 for i := offset + 1; i < len(dl.ownHashes); i++ { 374 delete(dl.ownChainTd, dl.ownHashes[i]) 375 delete(dl.ownHeaders, dl.ownHashes[i]) 376 delete(dl.ownReceipts, dl.ownHashes[i]) 377 delete(dl.ownBlocks, dl.ownHashes[i]) 378 379 delete(dl.ancientChainTd, dl.ownHashes[i]) 380 delete(dl.ancientHeaders, dl.ownHashes[i]) 381 delete(dl.ancientReceipts, dl.ownHashes[i]) 382 delete(dl.ancientBlocks, dl.ownHashes[i]) 383 } 384 dl.ownHashes = dl.ownHashes[:offset+1] 385 return nil 386 } 387 388 // Rollback removes some recently added elements from the chain. 389 func (dl *downloadTester) Rollback(hashes []common.Hash) { 390 } 391 392 // newPeer registers a new block download source into the downloader. 393 func (dl *downloadTester) newPeer(id string, version uint, chain *testChain) error { 394 dl.lock.Lock() 395 defer dl.lock.Unlock() 396 397 peer := &downloadTesterPeer{dl: dl, id: id, chain: chain} 398 dl.peers[id] = peer 399 return dl.downloader.RegisterPeer(id, version, peer) 400 } 401 402 // dropPeer simulates a hard peer removal from the connection pool. 403 func (dl *downloadTester) dropPeer(id string) { 404 dl.lock.Lock() 405 defer dl.lock.Unlock() 406 407 delete(dl.peers, id) 408 dl.downloader.UnregisterPeer(id) 409 } 410 411 type downloadTesterPeer struct { 412 dl *downloadTester 413 id string 414 chain *testChain 415 missingStates map[common.Hash]bool // State entries that fast sync should not return 416 } 417 418 // Head constructs a function to retrieve a peer's current head hash 419 // and total difficulty. 420 func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) { 421 b := dlp.chain.headBlock() 422 return b.Hash(), dlp.chain.td(b.Hash()) 423 } 424 425 // RequestHeadersByHash constructs a GetBlockHeaders function based on a hashed 426 // origin; associated with a particular peer in the download tester. The returned 427 // function can be used to retrieve batches of headers from the particular peer. 428 func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error { 429 result := dlp.chain.headersByHash(origin, amount, skip, reverse) 430 go dlp.dl.downloader.DeliverHeaders(dlp.id, result) 431 return nil 432 } 433 434 // RequestHeadersByNumber constructs a GetBlockHeaders function based on a numbered 435 // origin; associated with a particular peer in the download tester. The returned 436 // function can be used to retrieve batches of headers from the particular peer. 437 func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error { 438 result := dlp.chain.headersByNumber(origin, amount, skip, reverse) 439 go dlp.dl.downloader.DeliverHeaders(dlp.id, result) 440 return nil 441 } 442 443 // RequestBodies constructs a getBlockBodies method associated with a particular 444 // peer in the download tester. The returned function can be used to retrieve 445 // batches of block bodies from the particularly requested peer. 446 func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash) error { 447 txs, uncles := dlp.chain.bodies(hashes) 448 go dlp.dl.downloader.DeliverBodies(dlp.id, txs, uncles) 449 return nil 450 } 451 452 // RequestReceipts constructs a getReceipts method associated with a particular 453 // peer in the download tester. The returned function can be used to retrieve 454 // batches of block receipts from the particularly requested peer. 455 func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash) error { 456 receipts := dlp.chain.receipts(hashes) 457 go dlp.dl.downloader.DeliverReceipts(dlp.id, receipts) 458 return nil 459 } 460 461 // RequestNodeData constructs a getNodeData method associated with a particular 462 // peer in the download tester. The returned function can be used to retrieve 463 // batches of node state data from the particularly requested peer. 464 func (dlp *downloadTesterPeer) RequestNodeData(hashes []common.Hash) error { 465 dlp.dl.lock.RLock() 466 defer dlp.dl.lock.RUnlock() 467 468 results := make([][]byte, 0, len(hashes)) 469 for _, hash := range hashes { 470 if data, err := dlp.dl.peerDb.Get(hash.Bytes()); err == nil { 471 if !dlp.missingStates[hash] { 472 results = append(results, data) 473 } 474 } 475 } 476 go dlp.dl.downloader.DeliverNodeData(dlp.id, results) 477 return nil 478 } 479 480 // assertOwnChain checks if the local chain contains the correct number of items 481 // of the various chain components. 482 func assertOwnChain(t *testing.T, tester *downloadTester, length int) { 483 // Mark this method as a helper to report errors at callsite, not in here 484 t.Helper() 485 486 assertOwnForkedChain(t, tester, 1, []int{length}) 487 } 488 489 // assertOwnForkedChain checks if the local forked chain contains the correct 490 // number of items of the various chain components. 491 func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) { 492 // Mark this method as a helper to report errors at callsite, not in here 493 t.Helper() 494 495 // Initialize the counters for the first fork 496 headers, blocks, receipts := lengths[0], lengths[0], lengths[0] 497 498 // Update the counters for each subsequent fork 499 for _, length := range lengths[1:] { 500 headers += length - common 501 blocks += length - common 502 receipts += length - common 503 } 504 if tester.downloader.getMode() == LightSync { 505 blocks, receipts = 1, 1 506 } 507 if hs := len(tester.ownHeaders) + len(tester.ancientHeaders) - 1; hs != headers { 508 t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers) 509 } 510 if bs := len(tester.ownBlocks) + len(tester.ancientBlocks) - 1; bs != blocks { 511 t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks) 512 } 513 if rs := len(tester.ownReceipts) + len(tester.ancientReceipts) - 1; rs != receipts { 514 t.Fatalf("synchronised receipts mismatch: have %v, want %v", rs, receipts) 515 } 516 } 517 518 // Tests that simple synchronization against a canonical chain works correctly. 519 // In this test common ancestor lookup should be short circuited and not require 520 // binary searching. 521 func TestCanonicalSynchronisation64Full(t *testing.T) { testCanonicalSynchronisation(t, 64, FullSync) } 522 func TestCanonicalSynchronisation64Fast(t *testing.T) { testCanonicalSynchronisation(t, 64, FastSync) } 523 func TestCanonicalSynchronisation65Full(t *testing.T) { testCanonicalSynchronisation(t, 65, FullSync) } 524 func TestCanonicalSynchronisation65Fast(t *testing.T) { testCanonicalSynchronisation(t, 65, FastSync) } 525 func TestCanonicalSynchronisation65Light(t *testing.T) { 526 testCanonicalSynchronisation(t, 65, LightSync) 527 } 528 529 func testCanonicalSynchronisation(t *testing.T, protocol uint, mode SyncMode) { 530 t.Parallel() 531 532 tester := newTester() 533 defer tester.terminate() 534 535 // Create a small enough block chain to download 536 chain := testChainBase.shorten(blockCacheMaxItems - 15) 537 tester.newPeer("peer", protocol, chain) 538 539 // Synchronise with the peer and make sure all relevant data was retrieved 540 if err := tester.sync("peer", nil, mode); err != nil { 541 t.Fatalf("failed to synchronise blocks: %v", err) 542 } 543 assertOwnChain(t, tester, chain.len()) 544 } 545 546 // Tests that if a large batch of blocks are being downloaded, it is throttled 547 // until the cached blocks are retrieved. 548 func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) } 549 func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) } 550 func TestThrottling65Full(t *testing.T) { testThrottling(t, 65, FullSync) } 551 func TestThrottling65Fast(t *testing.T) { testThrottling(t, 65, FastSync) } 552 553 func testThrottling(t *testing.T, protocol uint, mode SyncMode) { 554 t.Parallel() 555 tester := newTester() 556 557 // Create a long block chain to download and the tester 558 targetBlocks := testChainBase.len() - 1 559 tester.newPeer("peer", protocol, testChainBase) 560 561 // Wrap the importer to allow stepping 562 blocked, proceed := uint32(0), make(chan struct{}) 563 tester.downloader.chainInsertHook = func(results []*fetchResult) { 564 atomic.StoreUint32(&blocked, uint32(len(results))) 565 <-proceed 566 } 567 // Start a synchronisation concurrently 568 errc := make(chan error, 1) 569 go func() { 570 errc <- tester.sync("peer", nil, mode) 571 }() 572 // Iteratively take some blocks, always checking the retrieval count 573 for { 574 // Check the retrieval count synchronously (! reason for this ugly block) 575 tester.lock.RLock() 576 retrieved := len(tester.ownBlocks) 577 tester.lock.RUnlock() 578 if retrieved >= targetBlocks+1 { 579 break 580 } 581 // Wait a bit for sync to throttle itself 582 var cached, frozen int 583 for start := time.Now(); time.Since(start) < 3*time.Second; { 584 time.Sleep(25 * time.Millisecond) 585 586 tester.lock.Lock() 587 { 588 tester.downloader.queue.resultCache.lock.Lock() 589 cached = tester.downloader.queue.resultCache.countCompleted() 590 tester.downloader.queue.resultCache.lock.Unlock() 591 frozen = int(atomic.LoadUint32(&blocked)) 592 retrieved = len(tester.ownBlocks) 593 594 } 595 tester.lock.Unlock() 596 597 if cached == blockCacheMaxItems || 598 cached == blockCacheMaxItems-reorgProtHeaderDelay || 599 retrieved+cached+frozen == targetBlocks+1 || 600 retrieved+cached+frozen == targetBlocks+1-reorgProtHeaderDelay { 601 break 602 } 603 } 604 // Make sure we filled up the cache, then exhaust it 605 time.Sleep(25 * time.Millisecond) // give it a chance to screw up 606 tester.lock.RLock() 607 retrieved = len(tester.ownBlocks) 608 tester.lock.RUnlock() 609 if cached != blockCacheMaxItems && cached != blockCacheMaxItems-reorgProtHeaderDelay && retrieved+cached+frozen != targetBlocks+1 && retrieved+cached+frozen != targetBlocks+1-reorgProtHeaderDelay { 610 t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheMaxItems, retrieved, frozen, targetBlocks+1) 611 } 612 613 // Permit the blocked blocks to import 614 if atomic.LoadUint32(&blocked) > 0 { 615 atomic.StoreUint32(&blocked, uint32(0)) 616 proceed <- struct{}{} 617 } 618 } 619 // Check that we haven't pulled more blocks than available 620 assertOwnChain(t, tester, targetBlocks+1) 621 if err := <-errc; err != nil { 622 t.Fatalf("block synchronization failed: %v", err) 623 } 624 tester.terminate() 625 626 } 627 628 // Tests that simple synchronization against a forked chain works correctly. In 629 // this test common ancestor lookup should *not* be short circuited, and a full 630 // binary search should be executed. 631 func TestForkedSync64Full(t *testing.T) { testForkedSync(t, 64, FullSync) } 632 func TestForkedSync64Fast(t *testing.T) { testForkedSync(t, 64, FastSync) } 633 func TestForkedSync65Full(t *testing.T) { testForkedSync(t, 65, FullSync) } 634 func TestForkedSync65Fast(t *testing.T) { testForkedSync(t, 65, FastSync) } 635 func TestForkedSync65Light(t *testing.T) { testForkedSync(t, 65, LightSync) } 636 637 func testForkedSync(t *testing.T, protocol uint, mode SyncMode) { 638 t.Parallel() 639 640 tester := newTester() 641 defer tester.terminate() 642 643 chainA := testChainForkLightA.shorten(testChainBase.len() + 80) 644 chainB := testChainForkLightB.shorten(testChainBase.len() + 80) 645 tester.newPeer("fork A", protocol, chainA) 646 tester.newPeer("fork B", protocol, chainB) 647 // Synchronise with the peer and make sure all blocks were retrieved 648 if err := tester.sync("fork A", nil, mode); err != nil { 649 t.Fatalf("failed to synchronise blocks: %v", err) 650 } 651 assertOwnChain(t, tester, chainA.len()) 652 653 // Synchronise with the second peer and make sure that fork is pulled too 654 if err := tester.sync("fork B", nil, mode); err != nil { 655 t.Fatalf("failed to synchronise blocks: %v", err) 656 } 657 assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()}) 658 } 659 660 // Tests that synchronising against a much shorter but much heavyer fork works 661 // corrently and is not dropped. 662 func TestHeavyForkedSync64Full(t *testing.T) { testHeavyForkedSync(t, 64, FullSync) } 663 func TestHeavyForkedSync64Fast(t *testing.T) { testHeavyForkedSync(t, 64, FastSync) } 664 func TestHeavyForkedSync65Full(t *testing.T) { testHeavyForkedSync(t, 65, FullSync) } 665 func TestHeavyForkedSync65Fast(t *testing.T) { testHeavyForkedSync(t, 65, FastSync) } 666 func TestHeavyForkedSync65Light(t *testing.T) { testHeavyForkedSync(t, 65, LightSync) } 667 668 func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) { 669 t.Parallel() 670 671 tester := newTester() 672 defer tester.terminate() 673 674 chainA := testChainForkLightA.shorten(testChainBase.len() + 80) 675 chainB := testChainForkHeavy.shorten(testChainBase.len() + 80) 676 tester.newPeer("light", protocol, chainA) 677 tester.newPeer("heavy", protocol, chainB) 678 679 // Synchronise with the peer and make sure all blocks were retrieved 680 if err := tester.sync("light", nil, mode); err != nil { 681 t.Fatalf("failed to synchronise blocks: %v", err) 682 } 683 assertOwnChain(t, tester, chainA.len()) 684 685 // Synchronise with the second peer and make sure that fork is pulled too 686 if err := tester.sync("heavy", nil, mode); err != nil { 687 t.Fatalf("failed to synchronise blocks: %v", err) 688 } 689 assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()}) 690 } 691 692 // Tests that chain forks are contained within a certain interval of the current 693 // chain head, ensuring that malicious peers cannot waste resources by feeding 694 // long dead chains. 695 func TestBoundedForkedSync64Full(t *testing.T) { testBoundedForkedSync(t, 64, FullSync) } 696 func TestBoundedForkedSync64Fast(t *testing.T) { testBoundedForkedSync(t, 64, FastSync) } 697 func TestBoundedForkedSync65Full(t *testing.T) { testBoundedForkedSync(t, 65, FullSync) } 698 func TestBoundedForkedSync65Fast(t *testing.T) { testBoundedForkedSync(t, 65, FastSync) } 699 func TestBoundedForkedSync65Light(t *testing.T) { testBoundedForkedSync(t, 65, LightSync) } 700 701 func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) { 702 t.Parallel() 703 704 tester := newTester() 705 defer tester.terminate() 706 707 chainA := testChainForkLightA 708 chainB := testChainForkLightB 709 tester.newPeer("original", protocol, chainA) 710 tester.newPeer("rewriter", protocol, chainB) 711 712 // Synchronise with the peer and make sure all blocks were retrieved 713 if err := tester.sync("original", nil, mode); err != nil { 714 t.Fatalf("failed to synchronise blocks: %v", err) 715 } 716 assertOwnChain(t, tester, chainA.len()) 717 718 // Synchronise with the second peer and ensure that the fork is rejected to being too old 719 if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor { 720 t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor) 721 } 722 } 723 724 // Tests that chain forks are contained within a certain interval of the current 725 // chain head for short but heavy forks too. These are a bit special because they 726 // take different ancestor lookup paths. 727 func TestBoundedHeavyForkedSync64Full(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FullSync) } 728 func TestBoundedHeavyForkedSync64Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FastSync) } 729 func TestBoundedHeavyForkedSync65Full(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FullSync) } 730 func TestBoundedHeavyForkedSync65Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FastSync) } 731 func TestBoundedHeavyForkedSync65Light(t *testing.T) { testBoundedHeavyForkedSync(t, 65, LightSync) } 732 733 func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) { 734 t.Parallel() 735 tester := newTester() 736 737 // Create a long enough forked chain 738 chainA := testChainForkLightA 739 chainB := testChainForkHeavy 740 tester.newPeer("original", protocol, chainA) 741 742 // Synchronise with the peer and make sure all blocks were retrieved 743 if err := tester.sync("original", nil, mode); err != nil { 744 t.Fatalf("failed to synchronise blocks: %v", err) 745 } 746 assertOwnChain(t, tester, chainA.len()) 747 748 tester.newPeer("heavy-rewriter", protocol, chainB) 749 // Synchronise with the second peer and ensure that the fork is rejected to being too old 750 if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor { 751 t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor) 752 } 753 tester.terminate() 754 } 755 756 // Tests that an inactive downloader will not accept incoming block headers, 757 // bodies and receipts. 758 func TestInactiveDownloader63(t *testing.T) { 759 t.Parallel() 760 761 tester := newTester() 762 defer tester.terminate() 763 764 // Check that neither block headers nor bodies are accepted 765 if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive { 766 t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive) 767 } 768 if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive { 769 t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive) 770 } 771 if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive { 772 t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive) 773 } 774 } 775 776 // Tests that a canceled download wipes all previously accumulated state. 777 func TestCancel64Full(t *testing.T) { testCancel(t, 64, FullSync) } 778 func TestCancel64Fast(t *testing.T) { testCancel(t, 64, FastSync) } 779 func TestCancel65Full(t *testing.T) { testCancel(t, 65, FullSync) } 780 func TestCancel65Fast(t *testing.T) { testCancel(t, 65, FastSync) } 781 func TestCancel65Light(t *testing.T) { testCancel(t, 65, LightSync) } 782 783 func testCancel(t *testing.T, protocol uint, mode SyncMode) { 784 t.Parallel() 785 786 tester := newTester() 787 defer tester.terminate() 788 789 chain := testChainBase.shorten(MaxHeaderFetch) 790 tester.newPeer("peer", protocol, chain) 791 792 // Make sure canceling works with a pristine downloader 793 tester.downloader.Cancel() 794 if !tester.downloader.queue.Idle() { 795 t.Errorf("download queue not idle") 796 } 797 // Synchronise with the peer, but cancel afterwards 798 if err := tester.sync("peer", nil, mode); err != nil { 799 t.Fatalf("failed to synchronise blocks: %v", err) 800 } 801 tester.downloader.Cancel() 802 if !tester.downloader.queue.Idle() { 803 t.Errorf("download queue not idle") 804 } 805 } 806 807 // Tests that synchronisation from multiple peers works as intended (multi thread sanity test). 808 func TestMultiSynchronisation64Full(t *testing.T) { testMultiSynchronisation(t, 64, FullSync) } 809 func TestMultiSynchronisation64Fast(t *testing.T) { testMultiSynchronisation(t, 64, FastSync) } 810 func TestMultiSynchronisation65Full(t *testing.T) { testMultiSynchronisation(t, 65, FullSync) } 811 func TestMultiSynchronisation65Fast(t *testing.T) { testMultiSynchronisation(t, 65, FastSync) } 812 func TestMultiSynchronisation65Light(t *testing.T) { testMultiSynchronisation(t, 65, LightSync) } 813 814 func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) { 815 t.Parallel() 816 817 tester := newTester() 818 defer tester.terminate() 819 820 // Create various peers with various parts of the chain 821 targetPeers := 8 822 chain := testChainBase.shorten(targetPeers * 100) 823 824 for i := 0; i < targetPeers; i++ { 825 id := fmt.Sprintf("peer #%d", i) 826 tester.newPeer(id, protocol, chain.shorten(chain.len()/(i+1))) 827 } 828 if err := tester.sync("peer #0", nil, mode); err != nil { 829 t.Fatalf("failed to synchronise blocks: %v", err) 830 } 831 assertOwnChain(t, tester, chain.len()) 832 } 833 834 // Tests that synchronisations behave well in multi-version protocol environments 835 // and not wreak havoc on other nodes in the network. 836 func TestMultiProtoSynchronisation64Full(t *testing.T) { testMultiProtoSync(t, 64, FullSync) } 837 func TestMultiProtoSynchronisation64Fast(t *testing.T) { testMultiProtoSync(t, 64, FastSync) } 838 func TestMultiProtoSynchronisation65Full(t *testing.T) { testMultiProtoSync(t, 65, FullSync) } 839 func TestMultiProtoSynchronisation65Fast(t *testing.T) { testMultiProtoSync(t, 65, FastSync) } 840 func TestMultiProtoSynchronisation65Light(t *testing.T) { testMultiProtoSync(t, 65, LightSync) } 841 842 func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) { 843 t.Parallel() 844 845 tester := newTester() 846 defer tester.terminate() 847 848 // Create a small enough block chain to download 849 chain := testChainBase.shorten(blockCacheMaxItems - 15) 850 851 // Create peers of every type 852 tester.newPeer("peer 63", 63, chain) 853 tester.newPeer("peer 64", 64, chain) 854 tester.newPeer("peer 65", 65, chain) 855 856 // Synchronise with the requested peer and make sure all blocks were retrieved 857 if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil { 858 t.Fatalf("failed to synchronise blocks: %v", err) 859 } 860 assertOwnChain(t, tester, chain.len()) 861 862 // Check that no peers have been dropped off 863 for _, version := range []int{63, 64, 65} { 864 peer := fmt.Sprintf("peer %d", version) 865 if _, ok := tester.peers[peer]; !ok { 866 t.Errorf("%s dropped", peer) 867 } 868 } 869 } 870 871 // Tests that if a block is empty (e.g. header only), no body request should be 872 // made, and instead the header should be assembled into a whole block in itself. 873 func TestEmptyShortCircuit64Full(t *testing.T) { testEmptyShortCircuit(t, 64, FullSync) } 874 func TestEmptyShortCircuit64Fast(t *testing.T) { testEmptyShortCircuit(t, 64, FastSync) } 875 func TestEmptyShortCircuit65Full(t *testing.T) { testEmptyShortCircuit(t, 65, FullSync) } 876 func TestEmptyShortCircuit65Fast(t *testing.T) { testEmptyShortCircuit(t, 65, FastSync) } 877 func TestEmptyShortCircuit65Light(t *testing.T) { testEmptyShortCircuit(t, 65, LightSync) } 878 879 func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) { 880 t.Parallel() 881 882 tester := newTester() 883 defer tester.terminate() 884 885 // Create a block chain to download 886 chain := testChainBase 887 tester.newPeer("peer", protocol, chain) 888 889 // Instrument the downloader to signal body requests 890 bodiesHave, receiptsHave := int32(0), int32(0) 891 tester.downloader.bodyFetchHook = func(headers []*types.Header) { 892 atomic.AddInt32(&bodiesHave, int32(len(headers))) 893 } 894 tester.downloader.receiptFetchHook = func(headers []*types.Header) { 895 atomic.AddInt32(&receiptsHave, int32(len(headers))) 896 } 897 // Synchronise with the peer and make sure all blocks were retrieved 898 if err := tester.sync("peer", nil, mode); err != nil { 899 t.Fatalf("failed to synchronise blocks: %v", err) 900 } 901 assertOwnChain(t, tester, chain.len()) 902 903 // Validate the number of block bodies that should have been requested 904 bodiesNeeded, receiptsNeeded := 0, 0 905 for _, block := range chain.blockm { 906 if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) { 907 bodiesNeeded++ 908 } 909 } 910 for _, receipt := range chain.receiptm { 911 if mode == FastSync && len(receipt) > 0 { 912 receiptsNeeded++ 913 } 914 } 915 if int(bodiesHave) != bodiesNeeded { 916 t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded) 917 } 918 if int(receiptsHave) != receiptsNeeded { 919 t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded) 920 } 921 } 922 923 // Tests that headers are enqueued continuously, preventing malicious nodes from 924 // stalling the downloader by feeding gapped header chains. 925 func TestMissingHeaderAttack64Full(t *testing.T) { testMissingHeaderAttack(t, 64, FullSync) } 926 func TestMissingHeaderAttack64Fast(t *testing.T) { testMissingHeaderAttack(t, 64, FastSync) } 927 func TestMissingHeaderAttack65Full(t *testing.T) { testMissingHeaderAttack(t, 65, FullSync) } 928 func TestMissingHeaderAttack65Fast(t *testing.T) { testMissingHeaderAttack(t, 65, FastSync) } 929 func TestMissingHeaderAttack65Light(t *testing.T) { testMissingHeaderAttack(t, 65, LightSync) } 930 931 func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { 932 t.Parallel() 933 934 tester := newTester() 935 defer tester.terminate() 936 937 chain := testChainBase.shorten(blockCacheMaxItems - 15) 938 brokenChain := chain.shorten(chain.len()) 939 delete(brokenChain.headerm, brokenChain.chain[brokenChain.len()/2]) 940 tester.newPeer("attack", protocol, brokenChain) 941 942 if err := tester.sync("attack", nil, mode); err == nil { 943 t.Fatalf("succeeded attacker synchronisation") 944 } 945 // Synchronise with the valid peer and make sure sync succeeds 946 tester.newPeer("valid", protocol, chain) 947 if err := tester.sync("valid", nil, mode); err != nil { 948 t.Fatalf("failed to synchronise blocks: %v", err) 949 } 950 assertOwnChain(t, tester, chain.len()) 951 } 952 953 // Tests that if requested headers are shifted (i.e. first is missing), the queue 954 // detects the invalid numbering. 955 func TestShiftedHeaderAttack64Full(t *testing.T) { testShiftedHeaderAttack(t, 64, FullSync) } 956 func TestShiftedHeaderAttack64Fast(t *testing.T) { testShiftedHeaderAttack(t, 64, FastSync) } 957 func TestShiftedHeaderAttack65Full(t *testing.T) { testShiftedHeaderAttack(t, 65, FullSync) } 958 func TestShiftedHeaderAttack65Fast(t *testing.T) { testShiftedHeaderAttack(t, 65, FastSync) } 959 func TestShiftedHeaderAttack65Light(t *testing.T) { testShiftedHeaderAttack(t, 65, LightSync) } 960 961 func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { 962 t.Parallel() 963 964 tester := newTester() 965 defer tester.terminate() 966 967 chain := testChainBase.shorten(blockCacheMaxItems - 15) 968 969 // Attempt a full sync with an attacker feeding shifted headers 970 brokenChain := chain.shorten(chain.len()) 971 delete(brokenChain.headerm, brokenChain.chain[1]) 972 delete(brokenChain.blockm, brokenChain.chain[1]) 973 delete(brokenChain.receiptm, brokenChain.chain[1]) 974 tester.newPeer("attack", protocol, brokenChain) 975 if err := tester.sync("attack", nil, mode); err == nil { 976 t.Fatalf("succeeded attacker synchronisation") 977 } 978 979 // Synchronise with the valid peer and make sure sync succeeds 980 tester.newPeer("valid", protocol, chain) 981 if err := tester.sync("valid", nil, mode); err != nil { 982 t.Fatalf("failed to synchronise blocks: %v", err) 983 } 984 assertOwnChain(t, tester, chain.len()) 985 } 986 987 // Tests that upon detecting an invalid header, the recent ones are rolled back 988 // for various failure scenarios. Afterwards a full sync is attempted to make 989 // sure no state was corrupted. 990 func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) } 991 func TestInvalidHeaderRollback65Fast(t *testing.T) { testInvalidHeaderRollback(t, 65, FastSync) } 992 993 func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) { 994 t.Parallel() 995 996 tester := newTester() 997 998 // Create a small enough block chain to download 999 targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks 1000 chain := testChainBase.shorten(targetBlocks) 1001 1002 // Attempt to sync with an attacker that feeds junk during the fast sync phase. 1003 // This should result in the last fsHeaderSafetyNet headers being rolled back. 1004 missing := fsHeaderSafetyNet + MaxHeaderFetch + 1 1005 fastAttackChain := chain.shorten(chain.len()) 1006 delete(fastAttackChain.headerm, fastAttackChain.chain[missing]) 1007 tester.newPeer("fast-attack", protocol, fastAttackChain) 1008 1009 if err := tester.sync("fast-attack", nil, mode); err == nil { 1010 t.Fatalf("succeeded fast attacker synchronisation") 1011 } 1012 if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch { 1013 t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch) 1014 } 1015 1016 // Attempt to sync with an attacker that feeds junk during the block import phase. 1017 // This should result in both the last fsHeaderSafetyNet number of headers being 1018 // rolled back, and also the pivot point being reverted to a non-block status. 1019 missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1 1020 blockAttackChain := chain.shorten(chain.len()) 1021 delete(fastAttackChain.headerm, fastAttackChain.chain[missing]) // Make sure the fast-attacker doesn't fill in 1022 delete(blockAttackChain.headerm, blockAttackChain.chain[missing]) 1023 tester.newPeer("block-attack", protocol, blockAttackChain) 1024 1025 if err := tester.sync("block-attack", nil, mode); err == nil { 1026 t.Fatalf("succeeded block attacker synchronisation") 1027 } 1028 if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch { 1029 t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch) 1030 } 1031 if mode == FastSync { 1032 if head := tester.CurrentBlock().NumberU64(); head != 0 { 1033 t.Errorf("fast sync pivot block #%d not rolled back", head) 1034 } 1035 } 1036 1037 // Attempt to sync with an attacker that withholds promised blocks after the 1038 // fast sync pivot point. This could be a trial to leave the node with a bad 1039 // but already imported pivot block. 1040 withholdAttackChain := chain.shorten(chain.len()) 1041 tester.newPeer("withhold-attack", protocol, withholdAttackChain) 1042 tester.downloader.syncInitHook = func(uint64, uint64) { 1043 for i := missing; i < withholdAttackChain.len(); i++ { 1044 delete(withholdAttackChain.headerm, withholdAttackChain.chain[i]) 1045 } 1046 tester.downloader.syncInitHook = nil 1047 } 1048 if err := tester.sync("withhold-attack", nil, mode); err == nil { 1049 t.Fatalf("succeeded withholding attacker synchronisation") 1050 } 1051 if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch { 1052 t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch) 1053 } 1054 if mode == FastSync { 1055 if head := tester.CurrentBlock().NumberU64(); head != 0 { 1056 t.Errorf("fast sync pivot block #%d not rolled back", head) 1057 } 1058 } 1059 1060 // synchronise with the valid peer and make sure sync succeeds. Since the last rollback 1061 // should also disable fast syncing for this process, verify that we did a fresh full 1062 // sync. Note, we can't assert anything about the receipts since we won't purge the 1063 // database of them, hence we can't use assertOwnChain. 1064 tester.newPeer("valid", protocol, chain) 1065 if err := tester.sync("valid", nil, mode); err != nil { 1066 t.Fatalf("failed to synchronise blocks: %v", err) 1067 } 1068 if hs := len(tester.ownHeaders); hs != chain.len() { 1069 t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, chain.len()) 1070 } 1071 if mode != LightSync { 1072 if bs := len(tester.ownBlocks); bs != chain.len() { 1073 t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, chain.len()) 1074 } 1075 } 1076 tester.terminate() 1077 } 1078 1079 // Tests that a peer advertising a high TD doesn't get to stall the downloader 1080 // afterwards by not sending any useful hashes. 1081 func TestHighTDStarvationAttack64Full(t *testing.T) { testHighTDStarvationAttack(t, 64, FullSync) } 1082 func TestHighTDStarvationAttack64Fast(t *testing.T) { testHighTDStarvationAttack(t, 64, FastSync) } 1083 func TestHighTDStarvationAttack65Full(t *testing.T) { testHighTDStarvationAttack(t, 65, FullSync) } 1084 func TestHighTDStarvationAttack65Fast(t *testing.T) { testHighTDStarvationAttack(t, 65, FastSync) } 1085 func TestHighTDStarvationAttack65Light(t *testing.T) { testHighTDStarvationAttack(t, 65, LightSync) } 1086 1087 func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) { 1088 t.Parallel() 1089 1090 tester := newTester() 1091 1092 chain := testChainBase.shorten(1) 1093 tester.newPeer("attack", protocol, chain) 1094 if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer { 1095 t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer) 1096 } 1097 tester.terminate() 1098 } 1099 1100 // Tests that misbehaving peers are disconnected, whilst behaving ones are not. 1101 func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) } 1102 func TestBlockHeaderAttackerDropping65(t *testing.T) { testBlockHeaderAttackerDropping(t, 65) } 1103 1104 func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) { 1105 t.Parallel() 1106 1107 // Define the disconnection requirement for individual hash fetch errors 1108 tests := []struct { 1109 result error 1110 drop bool 1111 }{ 1112 {nil, false}, // Sync succeeded, all is well 1113 {errBusy, false}, // Sync is already in progress, no problem 1114 {errUnknownPeer, false}, // Peer is unknown, was already dropped, don't double drop 1115 {errBadPeer, true}, // Peer was deemed bad for some reason, drop it 1116 {errStallingPeer, true}, // Peer was detected to be stalling, drop it 1117 {errUnsyncedPeer, true}, // Peer was detected to be unsynced, drop it 1118 {errNoPeers, false}, // No peers to download from, soft race, no issue 1119 {errTimeout, true}, // No hashes received in due time, drop the peer 1120 {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end 1121 {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser 1122 {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter 1123 {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop 1124 {errInvalidBody, false}, // A bad peer was detected, but not the sync origin 1125 {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin 1126 {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop 1127 } 1128 // Run the tests and check disconnection status 1129 tester := newTester() 1130 defer tester.terminate() 1131 chain := testChainBase.shorten(1) 1132 1133 for i, tt := range tests { 1134 // Register a new peer and ensure its presence 1135 id := fmt.Sprintf("test %d", i) 1136 if err := tester.newPeer(id, protocol, chain); err != nil { 1137 t.Fatalf("test %d: failed to register new peer: %v", i, err) 1138 } 1139 if _, ok := tester.peers[id]; !ok { 1140 t.Fatalf("test %d: registered peer not found", i) 1141 } 1142 // Simulate a synchronisation and check the required result 1143 tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result } 1144 1145 tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync) 1146 if _, ok := tester.peers[id]; !ok != tt.drop { 1147 t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop) 1148 } 1149 } 1150 } 1151 1152 // Tests that synchronisation progress (origin block number, current block number 1153 // and highest block number) is tracked and updated correctly. 1154 func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) } 1155 func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) } 1156 func TestSyncProgress65Full(t *testing.T) { testSyncProgress(t, 65, FullSync) } 1157 func TestSyncProgress65Fast(t *testing.T) { testSyncProgress(t, 65, FastSync) } 1158 func TestSyncProgress65Light(t *testing.T) { testSyncProgress(t, 65, LightSync) } 1159 1160 func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) { 1161 t.Parallel() 1162 1163 tester := newTester() 1164 defer tester.terminate() 1165 chain := testChainBase.shorten(blockCacheMaxItems - 15) 1166 1167 // Set a sync init hook to catch progress changes 1168 starting := make(chan struct{}) 1169 progress := make(chan struct{}) 1170 1171 tester.downloader.syncInitHook = func(origin, latest uint64) { 1172 starting <- struct{}{} 1173 <-progress 1174 } 1175 checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{}) 1176 1177 // Synchronise half the blocks and check initial progress 1178 tester.newPeer("peer-half", protocol, chain.shorten(chain.len()/2)) 1179 pending := new(sync.WaitGroup) 1180 pending.Add(1) 1181 1182 go func() { 1183 defer pending.Done() 1184 if err := tester.sync("peer-half", nil, mode); err != nil { 1185 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1186 } 1187 }() 1188 <-starting 1189 checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{ 1190 HighestBlock: uint64(chain.len()/2 - 1), 1191 }) 1192 progress <- struct{}{} 1193 pending.Wait() 1194 1195 // Synchronise all the blocks and check continuation progress 1196 tester.newPeer("peer-full", protocol, chain) 1197 pending.Add(1) 1198 go func() { 1199 defer pending.Done() 1200 if err := tester.sync("peer-full", nil, mode); err != nil { 1201 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1202 } 1203 }() 1204 <-starting 1205 checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{ 1206 StartingBlock: uint64(chain.len()/2 - 1), 1207 CurrentBlock: uint64(chain.len()/2 - 1), 1208 HighestBlock: uint64(chain.len() - 1), 1209 }) 1210 1211 // Check final progress after successful sync 1212 progress <- struct{}{} 1213 pending.Wait() 1214 checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{ 1215 StartingBlock: uint64(chain.len()/2 - 1), 1216 CurrentBlock: uint64(chain.len() - 1), 1217 HighestBlock: uint64(chain.len() - 1), 1218 }) 1219 } 1220 1221 func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) { 1222 // Mark this method as a helper to report errors at callsite, not in here 1223 t.Helper() 1224 1225 p := d.Progress() 1226 p.KnownStates, p.PulledStates = 0, 0 1227 want.KnownStates, want.PulledStates = 0, 0 1228 if p != want { 1229 t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want) 1230 } 1231 } 1232 1233 // Tests that synchronisation progress (origin block number and highest block 1234 // number) is tracked and updated correctly in case of a fork (or manual head 1235 // revertal). 1236 func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) } 1237 func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) } 1238 func TestForkedSyncProgress65Full(t *testing.T) { testForkedSyncProgress(t, 65, FullSync) } 1239 func TestForkedSyncProgress65Fast(t *testing.T) { testForkedSyncProgress(t, 65, FastSync) } 1240 func TestForkedSyncProgress65Light(t *testing.T) { testForkedSyncProgress(t, 65, LightSync) } 1241 1242 func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { 1243 t.Parallel() 1244 1245 tester := newTester() 1246 defer tester.terminate() 1247 chainA := testChainForkLightA.shorten(testChainBase.len() + MaxHeaderFetch) 1248 chainB := testChainForkLightB.shorten(testChainBase.len() + MaxHeaderFetch) 1249 1250 // Set a sync init hook to catch progress changes 1251 starting := make(chan struct{}) 1252 progress := make(chan struct{}) 1253 1254 tester.downloader.syncInitHook = func(origin, latest uint64) { 1255 starting <- struct{}{} 1256 <-progress 1257 } 1258 checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{}) 1259 1260 // Synchronise with one of the forks and check progress 1261 tester.newPeer("fork A", protocol, chainA) 1262 pending := new(sync.WaitGroup) 1263 pending.Add(1) 1264 go func() { 1265 defer pending.Done() 1266 if err := tester.sync("fork A", nil, mode); err != nil { 1267 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1268 } 1269 }() 1270 <-starting 1271 1272 checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{ 1273 HighestBlock: uint64(chainA.len() - 1), 1274 }) 1275 progress <- struct{}{} 1276 pending.Wait() 1277 1278 // Simulate a successful sync above the fork 1279 tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight 1280 1281 // Synchronise with the second fork and check progress resets 1282 tester.newPeer("fork B", protocol, chainB) 1283 pending.Add(1) 1284 go func() { 1285 defer pending.Done() 1286 if err := tester.sync("fork B", nil, mode); err != nil { 1287 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1288 } 1289 }() 1290 <-starting 1291 checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{ 1292 StartingBlock: uint64(testChainBase.len()) - 1, 1293 CurrentBlock: uint64(chainA.len() - 1), 1294 HighestBlock: uint64(chainB.len() - 1), 1295 }) 1296 1297 // Check final progress after successful sync 1298 progress <- struct{}{} 1299 pending.Wait() 1300 checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{ 1301 StartingBlock: uint64(testChainBase.len()) - 1, 1302 CurrentBlock: uint64(chainB.len() - 1), 1303 HighestBlock: uint64(chainB.len() - 1), 1304 }) 1305 } 1306 1307 // Tests that if synchronisation is aborted due to some failure, then the progress 1308 // origin is not updated in the next sync cycle, as it should be considered the 1309 // continuation of the previous sync and not a new instance. 1310 func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) } 1311 func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) } 1312 func TestFailedSyncProgress65Full(t *testing.T) { testFailedSyncProgress(t, 65, FullSync) } 1313 func TestFailedSyncProgress65Fast(t *testing.T) { testFailedSyncProgress(t, 65, FastSync) } 1314 func TestFailedSyncProgress65Light(t *testing.T) { testFailedSyncProgress(t, 65, LightSync) } 1315 1316 func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { 1317 t.Parallel() 1318 1319 tester := newTester() 1320 defer tester.terminate() 1321 chain := testChainBase.shorten(blockCacheMaxItems - 15) 1322 1323 // Set a sync init hook to catch progress changes 1324 starting := make(chan struct{}) 1325 progress := make(chan struct{}) 1326 1327 tester.downloader.syncInitHook = func(origin, latest uint64) { 1328 starting <- struct{}{} 1329 <-progress 1330 } 1331 checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{}) 1332 1333 // Attempt a full sync with a faulty peer 1334 brokenChain := chain.shorten(chain.len()) 1335 missing := brokenChain.len() / 2 1336 delete(brokenChain.headerm, brokenChain.chain[missing]) 1337 delete(brokenChain.blockm, brokenChain.chain[missing]) 1338 delete(brokenChain.receiptm, brokenChain.chain[missing]) 1339 tester.newPeer("faulty", protocol, brokenChain) 1340 1341 pending := new(sync.WaitGroup) 1342 pending.Add(1) 1343 go func() { 1344 defer pending.Done() 1345 if err := tester.sync("faulty", nil, mode); err == nil { 1346 panic("succeeded faulty synchronisation") 1347 } 1348 }() 1349 <-starting 1350 checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{ 1351 HighestBlock: uint64(brokenChain.len() - 1), 1352 }) 1353 progress <- struct{}{} 1354 pending.Wait() 1355 afterFailedSync := tester.downloader.Progress() 1356 1357 // Synchronise with a good peer and check that the progress origin remind the same 1358 // after a failure 1359 tester.newPeer("valid", protocol, chain) 1360 pending.Add(1) 1361 go func() { 1362 defer pending.Done() 1363 if err := tester.sync("valid", nil, mode); err != nil { 1364 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1365 } 1366 }() 1367 <-starting 1368 checkProgress(t, tester.downloader, "completing", afterFailedSync) 1369 1370 // Check final progress after successful sync 1371 progress <- struct{}{} 1372 pending.Wait() 1373 checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{ 1374 CurrentBlock: uint64(chain.len() - 1), 1375 HighestBlock: uint64(chain.len() - 1), 1376 }) 1377 } 1378 1379 // Tests that if an attacker fakes a chain height, after the attack is detected, 1380 // the progress height is successfully reduced at the next sync invocation. 1381 func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) } 1382 func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) } 1383 func TestFakedSyncProgress65Full(t *testing.T) { testFakedSyncProgress(t, 65, FullSync) } 1384 func TestFakedSyncProgress65Fast(t *testing.T) { testFakedSyncProgress(t, 65, FastSync) } 1385 func TestFakedSyncProgress65Light(t *testing.T) { testFakedSyncProgress(t, 65, LightSync) } 1386 1387 func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { 1388 t.Parallel() 1389 1390 tester := newTester() 1391 defer tester.terminate() 1392 chain := testChainBase.shorten(blockCacheMaxItems - 15) 1393 1394 // Set a sync init hook to catch progress changes 1395 starting := make(chan struct{}) 1396 progress := make(chan struct{}) 1397 tester.downloader.syncInitHook = func(origin, latest uint64) { 1398 starting <- struct{}{} 1399 <-progress 1400 } 1401 checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{}) 1402 1403 // Create and sync with an attacker that promises a higher chain than available. 1404 brokenChain := chain.shorten(chain.len()) 1405 numMissing := 5 1406 for i := brokenChain.len() - 2; i > brokenChain.len()-numMissing; i-- { 1407 delete(brokenChain.headerm, brokenChain.chain[i]) 1408 } 1409 tester.newPeer("attack", protocol, brokenChain) 1410 1411 pending := new(sync.WaitGroup) 1412 pending.Add(1) 1413 go func() { 1414 defer pending.Done() 1415 if err := tester.sync("attack", nil, mode); err == nil { 1416 panic("succeeded attacker synchronisation") 1417 } 1418 }() 1419 <-starting 1420 checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{ 1421 HighestBlock: uint64(brokenChain.len() - 1), 1422 }) 1423 progress <- struct{}{} 1424 pending.Wait() 1425 afterFailedSync := tester.downloader.Progress() 1426 1427 // Synchronise with a good peer and check that the progress height has been reduced to 1428 // the true value. 1429 validChain := chain.shorten(chain.len() - numMissing) 1430 tester.newPeer("valid", protocol, validChain) 1431 pending.Add(1) 1432 1433 go func() { 1434 defer pending.Done() 1435 if err := tester.sync("valid", nil, mode); err != nil { 1436 panic(fmt.Sprintf("failed to synchronise blocks: %v", err)) 1437 } 1438 }() 1439 <-starting 1440 checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{ 1441 CurrentBlock: afterFailedSync.CurrentBlock, 1442 HighestBlock: uint64(validChain.len() - 1), 1443 }) 1444 1445 // Check final progress after successful sync. 1446 progress <- struct{}{} 1447 pending.Wait() 1448 checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{ 1449 CurrentBlock: uint64(validChain.len() - 1), 1450 HighestBlock: uint64(validChain.len() - 1), 1451 }) 1452 } 1453 1454 // This test reproduces an issue where unexpected deliveries would 1455 // block indefinitely if they arrived at the right time. 1456 func TestDeliverHeadersHang64Full(t *testing.T) { testDeliverHeadersHang(t, 64, FullSync) } 1457 func TestDeliverHeadersHang64Fast(t *testing.T) { testDeliverHeadersHang(t, 64, FastSync) } 1458 func TestDeliverHeadersHang65Full(t *testing.T) { testDeliverHeadersHang(t, 65, FullSync) } 1459 func TestDeliverHeadersHang65Fast(t *testing.T) { testDeliverHeadersHang(t, 65, FastSync) } 1460 func TestDeliverHeadersHang65Light(t *testing.T) { testDeliverHeadersHang(t, 65, LightSync) } 1461 1462 func testDeliverHeadersHang(t *testing.T, protocol uint, mode SyncMode) { 1463 t.Parallel() 1464 1465 master := newTester() 1466 defer master.terminate() 1467 chain := testChainBase.shorten(15) 1468 1469 for i := 0; i < 200; i++ { 1470 tester := newTester() 1471 tester.peerDb = master.peerDb 1472 tester.newPeer("peer", protocol, chain) 1473 1474 // Whenever the downloader requests headers, flood it with 1475 // a lot of unrequested header deliveries. 1476 tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{ 1477 peer: tester.downloader.peers.peers["peer"].peer, 1478 tester: tester, 1479 } 1480 if err := tester.sync("peer", nil, mode); err != nil { 1481 t.Errorf("test %d: sync failed: %v", i, err) 1482 } 1483 tester.terminate() 1484 } 1485 } 1486 1487 type floodingTestPeer struct { 1488 peer Peer 1489 tester *downloadTester 1490 } 1491 1492 func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() } 1493 func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error { 1494 return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse) 1495 } 1496 func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error { 1497 return ftp.peer.RequestBodies(hashes) 1498 } 1499 func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error { 1500 return ftp.peer.RequestReceipts(hashes) 1501 } 1502 func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error { 1503 return ftp.peer.RequestNodeData(hashes) 1504 } 1505 1506 func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error { 1507 deliveriesDone := make(chan struct{}, 500) 1508 for i := 0; i < cap(deliveriesDone)-1; i++ { 1509 peer := fmt.Sprintf("fake-peer%d", i) 1510 go func() { 1511 ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}}) 1512 deliveriesDone <- struct{}{} 1513 }() 1514 } 1515 1516 // None of the extra deliveries should block. 1517 timeout := time.After(60 * time.Second) 1518 launched := false 1519 for i := 0; i < cap(deliveriesDone); i++ { 1520 select { 1521 case <-deliveriesDone: 1522 if !launched { 1523 // Start delivering the requested headers 1524 // after one of the flooding responses has arrived. 1525 go func() { 1526 ftp.peer.RequestHeadersByNumber(from, count, skip, reverse) 1527 deliveriesDone <- struct{}{} 1528 }() 1529 launched = true 1530 } 1531 case <-timeout: 1532 panic("blocked") 1533 } 1534 } 1535 return nil 1536 } 1537 1538 func TestRemoteHeaderRequestSpan(t *testing.T) { 1539 testCases := []struct { 1540 remoteHeight uint64 1541 localHeight uint64 1542 expected []int 1543 }{ 1544 // Remote is way higher. We should ask for the remote head and go backwards 1545 {1500, 1000, 1546 []int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499}, 1547 }, 1548 {15000, 13006, 1549 []int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999}, 1550 }, 1551 // Remote is pretty close to us. We don't have to fetch as many 1552 {1200, 1150, 1553 []int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199}, 1554 }, 1555 // Remote is equal to us (so on a fork with higher td) 1556 // We should get the closest couple of ancestors 1557 {1500, 1500, 1558 []int{1497, 1499}, 1559 }, 1560 // We're higher than the remote! Odd 1561 {1000, 1500, 1562 []int{997, 999}, 1563 }, 1564 // Check some weird edgecases that it behaves somewhat rationally 1565 {0, 1500, 1566 []int{0, 2}, 1567 }, 1568 {6000000, 0, 1569 []int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999}, 1570 }, 1571 {0, 0, 1572 []int{0, 2}, 1573 }, 1574 } 1575 reqs := func(from, count, span int) []int { 1576 var r []int 1577 num := from 1578 for len(r) < count { 1579 r = append(r, num) 1580 num += span + 1 1581 } 1582 return r 1583 } 1584 for i, tt := range testCases { 1585 from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight) 1586 data := reqs(int(from), count, span) 1587 1588 if max != uint64(data[len(data)-1]) { 1589 t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max) 1590 } 1591 failed := false 1592 if len(data) != len(tt.expected) { 1593 failed = true 1594 t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data)) 1595 } else { 1596 for j, n := range data { 1597 if n != tt.expected[j] { 1598 failed = true 1599 break 1600 } 1601 } 1602 } 1603 if failed { 1604 res := strings.Replace(fmt.Sprint(data), " ", ",", -1) 1605 exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1) 1606 t.Logf("got: %v\n", res) 1607 t.Logf("exp: %v\n", exp) 1608 t.Errorf("test %d: wrong values", i) 1609 } 1610 } 1611 } 1612 1613 // Tests that peers below a pre-configured checkpoint block are prevented from 1614 // being fast-synced from, avoiding potential cheap eclipse attacks. 1615 func TestCheckpointEnforcement64Full(t *testing.T) { testCheckpointEnforcement(t, 64, FullSync) } 1616 func TestCheckpointEnforcement64Fast(t *testing.T) { testCheckpointEnforcement(t, 64, FastSync) } 1617 func TestCheckpointEnforcement65Full(t *testing.T) { testCheckpointEnforcement(t, 65, FullSync) } 1618 func TestCheckpointEnforcement65Fast(t *testing.T) { testCheckpointEnforcement(t, 65, FastSync) } 1619 func TestCheckpointEnforcement65Light(t *testing.T) { testCheckpointEnforcement(t, 65, LightSync) } 1620 1621 func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) { 1622 t.Parallel() 1623 1624 // Create a new tester with a particular hard coded checkpoint block 1625 tester := newTester() 1626 defer tester.terminate() 1627 1628 tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256 1629 chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1) 1630 1631 // Attempt to sync with the peer and validate the result 1632 tester.newPeer("peer", protocol, chain) 1633 1634 var expect error 1635 if mode == FastSync || mode == LightSync { 1636 expect = errUnsyncedPeer 1637 } 1638 if err := tester.sync("peer", nil, mode); !errors.Is(err, expect) { 1639 t.Fatalf("block sync error mismatch: have %v, want %v", err, expect) 1640 } 1641 if mode == FastSync || mode == LightSync { 1642 assertOwnChain(t, tester, 1) 1643 } else { 1644 assertOwnChain(t, tester, chain.len()) 1645 } 1646 }