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