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