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