github.com/guiltylotus/go-ethereum@v1.9.7/eth/downloader/downloader_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package downloader
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  	"strings"
    24  	"sync"
    25  	"sync/atomic"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum"
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/core/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/event"
    35  	"github.com/ethereum/go-ethereum/trie"
    36  )
    37  
    38  // Reduce some of the parameters to make the tester faster.
    39  func init() {
    40  	maxForkAncestry = 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) { testCanonicalSynchronisation(t, 64, LightSync) }
   490  
   491  func testCanonicalSynchronisation(t *testing.T, protocol int, mode SyncMode) {
   492  	t.Parallel()
   493  
   494  	tester := newTester()
   495  	defer tester.terminate()
   496  
   497  	// Create a small enough block chain to download
   498  	chain := testChainBase.shorten(blockCacheItems - 15)
   499  	tester.newPeer("peer", protocol, chain)
   500  
   501  	// Synchronise with the peer and make sure all relevant data was retrieved
   502  	if err := tester.sync("peer", nil, mode); err != nil {
   503  		t.Fatalf("failed to synchronise blocks: %v", err)
   504  	}
   505  	assertOwnChain(t, tester, chain.len())
   506  }
   507  
   508  // Tests that if a large batch of blocks are being downloaded, it is throttled
   509  // until the cached blocks are retrieved.
   510  func TestThrottling62(t *testing.T)     { testThrottling(t, 62, FullSync) }
   511  func TestThrottling63Full(t *testing.T) { testThrottling(t, 63, FullSync) }
   512  func TestThrottling63Fast(t *testing.T) { testThrottling(t, 63, FastSync) }
   513  func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
   514  func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
   515  
   516  func testThrottling(t *testing.T, protocol int, mode SyncMode) {
   517  	t.Parallel()
   518  	tester := newTester()
   519  	defer tester.terminate()
   520  
   521  	// Create a long block chain to download and the tester
   522  	targetBlocks := testChainBase.len() - 1
   523  	tester.newPeer("peer", protocol, testChainBase)
   524  
   525  	// Wrap the importer to allow stepping
   526  	blocked, proceed := uint32(0), make(chan struct{})
   527  	tester.downloader.chainInsertHook = func(results []*fetchResult) {
   528  		atomic.StoreUint32(&blocked, uint32(len(results)))
   529  		<-proceed
   530  	}
   531  	// Start a synchronisation concurrently
   532  	errc := make(chan error)
   533  	go func() {
   534  		errc <- tester.sync("peer", nil, mode)
   535  	}()
   536  	// Iteratively take some blocks, always checking the retrieval count
   537  	for {
   538  		// Check the retrieval count synchronously (! reason for this ugly block)
   539  		tester.lock.RLock()
   540  		retrieved := len(tester.ownBlocks)
   541  		tester.lock.RUnlock()
   542  		if retrieved >= targetBlocks+1 {
   543  			break
   544  		}
   545  		// Wait a bit for sync to throttle itself
   546  		var cached, frozen int
   547  		for start := time.Now(); time.Since(start) < 3*time.Second; {
   548  			time.Sleep(25 * time.Millisecond)
   549  
   550  			tester.lock.Lock()
   551  			tester.downloader.queue.lock.Lock()
   552  			cached = len(tester.downloader.queue.blockDonePool)
   553  			if mode == FastSync {
   554  				if receipts := len(tester.downloader.queue.receiptDonePool); receipts < cached {
   555  					cached = receipts
   556  				}
   557  			}
   558  			frozen = int(atomic.LoadUint32(&blocked))
   559  			retrieved = len(tester.ownBlocks)
   560  			tester.downloader.queue.lock.Unlock()
   561  			tester.lock.Unlock()
   562  
   563  			if cached == blockCacheItems || cached == blockCacheItems-reorgProtHeaderDelay || retrieved+cached+frozen == targetBlocks+1 || retrieved+cached+frozen == targetBlocks+1-reorgProtHeaderDelay {
   564  				break
   565  			}
   566  		}
   567  		// Make sure we filled up the cache, then exhaust it
   568  		time.Sleep(25 * time.Millisecond) // give it a chance to screw up
   569  
   570  		tester.lock.RLock()
   571  		retrieved = len(tester.ownBlocks)
   572  		tester.lock.RUnlock()
   573  		if cached != blockCacheItems && cached != blockCacheItems-reorgProtHeaderDelay && retrieved+cached+frozen != targetBlocks+1 && retrieved+cached+frozen != targetBlocks+1-reorgProtHeaderDelay {
   574  			t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheItems, retrieved, frozen, targetBlocks+1)
   575  		}
   576  		// Permit the blocked blocks to import
   577  		if atomic.LoadUint32(&blocked) > 0 {
   578  			atomic.StoreUint32(&blocked, uint32(0))
   579  			proceed <- struct{}{}
   580  		}
   581  	}
   582  	// Check that we haven't pulled more blocks than available
   583  	assertOwnChain(t, tester, targetBlocks+1)
   584  	if err := <-errc; err != nil {
   585  		t.Fatalf("block synchronization failed: %v", err)
   586  	}
   587  }
   588  
   589  // Tests that simple synchronization against a forked chain works correctly. In
   590  // this test common ancestor lookup should *not* be short circuited, and a full
   591  // binary search should be executed.
   592  func TestForkedSync62(t *testing.T)      { testForkedSync(t, 62, FullSync) }
   593  func TestForkedSync63Full(t *testing.T)  { testForkedSync(t, 63, FullSync) }
   594  func TestForkedSync63Fast(t *testing.T)  { testForkedSync(t, 63, FastSync) }
   595  func TestForkedSync64Full(t *testing.T)  { testForkedSync(t, 64, FullSync) }
   596  func TestForkedSync64Fast(t *testing.T)  { testForkedSync(t, 64, FastSync) }
   597  func TestForkedSync64Light(t *testing.T) { testForkedSync(t, 64, LightSync) }
   598  
   599  func testForkedSync(t *testing.T, protocol int, mode SyncMode) {
   600  	t.Parallel()
   601  
   602  	tester := newTester()
   603  	defer tester.terminate()
   604  
   605  	chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
   606  	chainB := testChainForkLightB.shorten(testChainBase.len() + 80)
   607  	tester.newPeer("fork A", protocol, chainA)
   608  	tester.newPeer("fork B", protocol, chainB)
   609  
   610  	// Synchronise with the peer and make sure all blocks were retrieved
   611  	if err := tester.sync("fork A", nil, mode); err != nil {
   612  		t.Fatalf("failed to synchronise blocks: %v", err)
   613  	}
   614  	assertOwnChain(t, tester, chainA.len())
   615  
   616  	// Synchronise with the second peer and make sure that fork is pulled too
   617  	if err := tester.sync("fork B", nil, mode); err != nil {
   618  		t.Fatalf("failed to synchronise blocks: %v", err)
   619  	}
   620  	assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()})
   621  }
   622  
   623  // Tests that synchronising against a much shorter but much heavyer fork works
   624  // corrently and is not dropped.
   625  func TestHeavyForkedSync62(t *testing.T)      { testHeavyForkedSync(t, 62, FullSync) }
   626  func TestHeavyForkedSync63Full(t *testing.T)  { testHeavyForkedSync(t, 63, FullSync) }
   627  func TestHeavyForkedSync63Fast(t *testing.T)  { testHeavyForkedSync(t, 63, FastSync) }
   628  func TestHeavyForkedSync64Full(t *testing.T)  { testHeavyForkedSync(t, 64, FullSync) }
   629  func TestHeavyForkedSync64Fast(t *testing.T)  { testHeavyForkedSync(t, 64, FastSync) }
   630  func TestHeavyForkedSync64Light(t *testing.T) { testHeavyForkedSync(t, 64, LightSync) }
   631  
   632  func testHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
   633  	t.Parallel()
   634  
   635  	tester := newTester()
   636  	defer tester.terminate()
   637  
   638  	chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
   639  	chainB := testChainForkHeavy.shorten(testChainBase.len() + 80)
   640  	tester.newPeer("light", protocol, chainA)
   641  	tester.newPeer("heavy", protocol, chainB)
   642  
   643  	// Synchronise with the peer and make sure all blocks were retrieved
   644  	if err := tester.sync("light", 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("heavy", 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 chain forks are contained within a certain interval of the current
   657  // chain head, ensuring that malicious peers cannot waste resources by feeding
   658  // long dead chains.
   659  func TestBoundedForkedSync62(t *testing.T)      { testBoundedForkedSync(t, 62, FullSync) }
   660  func TestBoundedForkedSync63Full(t *testing.T)  { testBoundedForkedSync(t, 63, FullSync) }
   661  func TestBoundedForkedSync63Fast(t *testing.T)  { testBoundedForkedSync(t, 63, FastSync) }
   662  func TestBoundedForkedSync64Full(t *testing.T)  { testBoundedForkedSync(t, 64, FullSync) }
   663  func TestBoundedForkedSync64Fast(t *testing.T)  { testBoundedForkedSync(t, 64, FastSync) }
   664  func TestBoundedForkedSync64Light(t *testing.T) { testBoundedForkedSync(t, 64, LightSync) }
   665  
   666  func testBoundedForkedSync(t *testing.T, protocol int, mode SyncMode) {
   667  	t.Parallel()
   668  
   669  	tester := newTester()
   670  	defer tester.terminate()
   671  
   672  	chainA := testChainForkLightA
   673  	chainB := testChainForkLightB
   674  	tester.newPeer("original", protocol, chainA)
   675  	tester.newPeer("rewriter", protocol, chainB)
   676  
   677  	// Synchronise with the peer and make sure all blocks were retrieved
   678  	if err := tester.sync("original", nil, mode); err != nil {
   679  		t.Fatalf("failed to synchronise blocks: %v", err)
   680  	}
   681  	assertOwnChain(t, tester, chainA.len())
   682  
   683  	// Synchronise with the second peer and ensure that the fork is rejected to being too old
   684  	if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
   685  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   686  	}
   687  }
   688  
   689  // Tests that chain forks are contained within a certain interval of the current
   690  // chain head for short but heavy forks too. These are a bit special because they
   691  // take different ancestor lookup paths.
   692  func TestBoundedHeavyForkedSync62(t *testing.T)      { testBoundedHeavyForkedSync(t, 62, FullSync) }
   693  func TestBoundedHeavyForkedSync63Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FullSync) }
   694  func TestBoundedHeavyForkedSync63Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FastSync) }
   695  func TestBoundedHeavyForkedSync64Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FullSync) }
   696  func TestBoundedHeavyForkedSync64Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FastSync) }
   697  func TestBoundedHeavyForkedSync64Light(t *testing.T) { testBoundedHeavyForkedSync(t, 64, LightSync) }
   698  
   699  func testBoundedHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
   700  	t.Parallel()
   701  
   702  	tester := newTester()
   703  	defer tester.terminate()
   704  
   705  	// Create a long enough forked chain
   706  	chainA := testChainForkLightA
   707  	chainB := testChainForkHeavy
   708  	tester.newPeer("original", protocol, chainA)
   709  	tester.newPeer("heavy-rewriter", protocol, chainB)
   710  
   711  	// Synchronise with the peer and make sure all blocks were retrieved
   712  	if err := tester.sync("original", nil, mode); err != nil {
   713  		t.Fatalf("failed to synchronise blocks: %v", err)
   714  	}
   715  	assertOwnChain(t, tester, chainA.len())
   716  
   717  	// Synchronise with the second peer and ensure that the fork is rejected to being too old
   718  	if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
   719  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   720  	}
   721  }
   722  
   723  // Tests that an inactive downloader will not accept incoming block headers and
   724  // bodies.
   725  func TestInactiveDownloader62(t *testing.T) {
   726  	t.Parallel()
   727  
   728  	tester := newTester()
   729  	defer tester.terminate()
   730  
   731  	// Check that neither block headers nor bodies are accepted
   732  	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
   733  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   734  	}
   735  	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
   736  		t.Errorf("error mismatch: have %v, want  %v", err, errNoSyncActive)
   737  	}
   738  }
   739  
   740  // Tests that an inactive downloader will not accept incoming block headers,
   741  // bodies and receipts.
   742  func TestInactiveDownloader63(t *testing.T) {
   743  	t.Parallel()
   744  
   745  	tester := newTester()
   746  	defer tester.terminate()
   747  
   748  	// Check that neither block headers nor bodies are accepted
   749  	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
   750  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   751  	}
   752  	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
   753  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   754  	}
   755  	if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
   756  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   757  	}
   758  }
   759  
   760  // Tests that a canceled download wipes all previously accumulated state.
   761  func TestCancel62(t *testing.T)      { testCancel(t, 62, FullSync) }
   762  func TestCancel63Full(t *testing.T)  { testCancel(t, 63, FullSync) }
   763  func TestCancel63Fast(t *testing.T)  { testCancel(t, 63, FastSync) }
   764  func TestCancel64Full(t *testing.T)  { testCancel(t, 64, FullSync) }
   765  func TestCancel64Fast(t *testing.T)  { testCancel(t, 64, FastSync) }
   766  func TestCancel64Light(t *testing.T) { testCancel(t, 64, LightSync) }
   767  
   768  func testCancel(t *testing.T, protocol int, mode SyncMode) {
   769  	t.Parallel()
   770  
   771  	tester := newTester()
   772  	defer tester.terminate()
   773  
   774  	chain := testChainBase.shorten(MaxHeaderFetch)
   775  	tester.newPeer("peer", protocol, chain)
   776  
   777  	// Make sure canceling works with a pristine downloader
   778  	tester.downloader.Cancel()
   779  	if !tester.downloader.queue.Idle() {
   780  		t.Errorf("download queue not idle")
   781  	}
   782  	// Synchronise with the peer, but cancel afterwards
   783  	if err := tester.sync("peer", nil, mode); err != nil {
   784  		t.Fatalf("failed to synchronise blocks: %v", err)
   785  	}
   786  	tester.downloader.Cancel()
   787  	if !tester.downloader.queue.Idle() {
   788  		t.Errorf("download queue not idle")
   789  	}
   790  }
   791  
   792  // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
   793  func TestMultiSynchronisation62(t *testing.T)      { testMultiSynchronisation(t, 62, FullSync) }
   794  func TestMultiSynchronisation63Full(t *testing.T)  { testMultiSynchronisation(t, 63, FullSync) }
   795  func TestMultiSynchronisation63Fast(t *testing.T)  { testMultiSynchronisation(t, 63, FastSync) }
   796  func TestMultiSynchronisation64Full(t *testing.T)  { testMultiSynchronisation(t, 64, FullSync) }
   797  func TestMultiSynchronisation64Fast(t *testing.T)  { testMultiSynchronisation(t, 64, FastSync) }
   798  func TestMultiSynchronisation64Light(t *testing.T) { testMultiSynchronisation(t, 64, LightSync) }
   799  
   800  func testMultiSynchronisation(t *testing.T, protocol int, mode SyncMode) {
   801  	t.Parallel()
   802  
   803  	tester := newTester()
   804  	defer tester.terminate()
   805  
   806  	// Create various peers with various parts of the chain
   807  	targetPeers := 8
   808  	chain := testChainBase.shorten(targetPeers * 100)
   809  
   810  	for i := 0; i < targetPeers; i++ {
   811  		id := fmt.Sprintf("peer #%d", i)
   812  		tester.newPeer(id, protocol, chain.shorten(chain.len()/(i+1)))
   813  	}
   814  	if err := tester.sync("peer #0", nil, mode); err != nil {
   815  		t.Fatalf("failed to synchronise blocks: %v", err)
   816  	}
   817  	assertOwnChain(t, tester, chain.len())
   818  }
   819  
   820  // Tests that synchronisations behave well in multi-version protocol environments
   821  // and not wreak havoc on other nodes in the network.
   822  func TestMultiProtoSynchronisation62(t *testing.T)      { testMultiProtoSync(t, 62, FullSync) }
   823  func TestMultiProtoSynchronisation63Full(t *testing.T)  { testMultiProtoSync(t, 63, FullSync) }
   824  func TestMultiProtoSynchronisation63Fast(t *testing.T)  { testMultiProtoSync(t, 63, FastSync) }
   825  func TestMultiProtoSynchronisation64Full(t *testing.T)  { testMultiProtoSync(t, 64, FullSync) }
   826  func TestMultiProtoSynchronisation64Fast(t *testing.T)  { testMultiProtoSync(t, 64, FastSync) }
   827  func TestMultiProtoSynchronisation64Light(t *testing.T) { testMultiProtoSync(t, 64, LightSync) }
   828  
   829  func testMultiProtoSync(t *testing.T, protocol int, mode SyncMode) {
   830  	t.Parallel()
   831  
   832  	tester := newTester()
   833  	defer tester.terminate()
   834  
   835  	// Create a small enough block chain to download
   836  	chain := testChainBase.shorten(blockCacheItems - 15)
   837  
   838  	// Create peers of every type
   839  	tester.newPeer("peer 62", 62, chain)
   840  	tester.newPeer("peer 63", 63, chain)
   841  	tester.newPeer("peer 64", 64, chain)
   842  
   843  	// Synchronise with the requested peer and make sure all blocks were retrieved
   844  	if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
   845  		t.Fatalf("failed to synchronise blocks: %v", err)
   846  	}
   847  	assertOwnChain(t, tester, chain.len())
   848  
   849  	// Check that no peers have been dropped off
   850  	for _, version := range []int{62, 63, 64} {
   851  		peer := fmt.Sprintf("peer %d", version)
   852  		if _, ok := tester.peers[peer]; !ok {
   853  			t.Errorf("%s dropped", peer)
   854  		}
   855  	}
   856  }
   857  
   858  // Tests that if a block is empty (e.g. header only), no body request should be
   859  // made, and instead the header should be assembled into a whole block in itself.
   860  func TestEmptyShortCircuit62(t *testing.T)      { testEmptyShortCircuit(t, 62, FullSync) }
   861  func TestEmptyShortCircuit63Full(t *testing.T)  { testEmptyShortCircuit(t, 63, FullSync) }
   862  func TestEmptyShortCircuit63Fast(t *testing.T)  { testEmptyShortCircuit(t, 63, FastSync) }
   863  func TestEmptyShortCircuit64Full(t *testing.T)  { testEmptyShortCircuit(t, 64, FullSync) }
   864  func TestEmptyShortCircuit64Fast(t *testing.T)  { testEmptyShortCircuit(t, 64, FastSync) }
   865  func TestEmptyShortCircuit64Light(t *testing.T) { testEmptyShortCircuit(t, 64, LightSync) }
   866  
   867  func testEmptyShortCircuit(t *testing.T, protocol int, mode SyncMode) {
   868  	t.Parallel()
   869  
   870  	tester := newTester()
   871  	defer tester.terminate()
   872  
   873  	// Create a block chain to download
   874  	chain := testChainBase
   875  	tester.newPeer("peer", protocol, chain)
   876  
   877  	// Instrument the downloader to signal body requests
   878  	bodiesHave, receiptsHave := int32(0), int32(0)
   879  	tester.downloader.bodyFetchHook = func(headers []*types.Header) {
   880  		atomic.AddInt32(&bodiesHave, int32(len(headers)))
   881  	}
   882  	tester.downloader.receiptFetchHook = func(headers []*types.Header) {
   883  		atomic.AddInt32(&receiptsHave, int32(len(headers)))
   884  	}
   885  	// Synchronise with the peer and make sure all blocks were retrieved
   886  	if err := tester.sync("peer", nil, mode); err != nil {
   887  		t.Fatalf("failed to synchronise blocks: %v", err)
   888  	}
   889  	assertOwnChain(t, tester, chain.len())
   890  
   891  	// Validate the number of block bodies that should have been requested
   892  	bodiesNeeded, receiptsNeeded := 0, 0
   893  	for _, block := range chain.blockm {
   894  		if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
   895  			bodiesNeeded++
   896  		}
   897  	}
   898  	for _, receipt := range chain.receiptm {
   899  		if mode == FastSync && len(receipt) > 0 {
   900  			receiptsNeeded++
   901  		}
   902  	}
   903  	if int(bodiesHave) != bodiesNeeded {
   904  		t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
   905  	}
   906  	if int(receiptsHave) != receiptsNeeded {
   907  		t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
   908  	}
   909  }
   910  
   911  // Tests that headers are enqueued continuously, preventing malicious nodes from
   912  // stalling the downloader by feeding gapped header chains.
   913  func TestMissingHeaderAttack62(t *testing.T)      { testMissingHeaderAttack(t, 62, FullSync) }
   914  func TestMissingHeaderAttack63Full(t *testing.T)  { testMissingHeaderAttack(t, 63, FullSync) }
   915  func TestMissingHeaderAttack63Fast(t *testing.T)  { testMissingHeaderAttack(t, 63, FastSync) }
   916  func TestMissingHeaderAttack64Full(t *testing.T)  { testMissingHeaderAttack(t, 64, FullSync) }
   917  func TestMissingHeaderAttack64Fast(t *testing.T)  { testMissingHeaderAttack(t, 64, FastSync) }
   918  func TestMissingHeaderAttack64Light(t *testing.T) { testMissingHeaderAttack(t, 64, LightSync) }
   919  
   920  func testMissingHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
   921  	t.Parallel()
   922  
   923  	tester := newTester()
   924  	defer tester.terminate()
   925  
   926  	chain := testChainBase.shorten(blockCacheItems - 15)
   927  	brokenChain := chain.shorten(chain.len())
   928  	delete(brokenChain.headerm, brokenChain.chain[brokenChain.len()/2])
   929  	tester.newPeer("attack", protocol, brokenChain)
   930  
   931  	if err := tester.sync("attack", nil, mode); err == nil {
   932  		t.Fatalf("succeeded attacker synchronisation")
   933  	}
   934  	// Synchronise with the valid peer and make sure sync succeeds
   935  	tester.newPeer("valid", protocol, chain)
   936  	if err := tester.sync("valid", nil, mode); err != nil {
   937  		t.Fatalf("failed to synchronise blocks: %v", err)
   938  	}
   939  	assertOwnChain(t, tester, chain.len())
   940  }
   941  
   942  // Tests that if requested headers are shifted (i.e. first is missing), the queue
   943  // detects the invalid numbering.
   944  func TestShiftedHeaderAttack62(t *testing.T)      { testShiftedHeaderAttack(t, 62, FullSync) }
   945  func TestShiftedHeaderAttack63Full(t *testing.T)  { testShiftedHeaderAttack(t, 63, FullSync) }
   946  func TestShiftedHeaderAttack63Fast(t *testing.T)  { testShiftedHeaderAttack(t, 63, FastSync) }
   947  func TestShiftedHeaderAttack64Full(t *testing.T)  { testShiftedHeaderAttack(t, 64, FullSync) }
   948  func TestShiftedHeaderAttack64Fast(t *testing.T)  { testShiftedHeaderAttack(t, 64, FastSync) }
   949  func TestShiftedHeaderAttack64Light(t *testing.T) { testShiftedHeaderAttack(t, 64, LightSync) }
   950  
   951  func testShiftedHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
   952  	t.Parallel()
   953  
   954  	tester := newTester()
   955  	defer tester.terminate()
   956  
   957  	chain := testChainBase.shorten(blockCacheItems - 15)
   958  
   959  	// Attempt a full sync with an attacker feeding shifted headers
   960  	brokenChain := chain.shorten(chain.len())
   961  	delete(brokenChain.headerm, brokenChain.chain[1])
   962  	delete(brokenChain.blockm, brokenChain.chain[1])
   963  	delete(brokenChain.receiptm, brokenChain.chain[1])
   964  	tester.newPeer("attack", protocol, brokenChain)
   965  	if err := tester.sync("attack", nil, mode); err == nil {
   966  		t.Fatalf("succeeded attacker synchronisation")
   967  	}
   968  
   969  	// Synchronise with the valid peer and make sure sync succeeds
   970  	tester.newPeer("valid", protocol, chain)
   971  	if err := tester.sync("valid", nil, mode); err != nil {
   972  		t.Fatalf("failed to synchronise blocks: %v", err)
   973  	}
   974  	assertOwnChain(t, tester, chain.len())
   975  }
   976  
   977  // Tests that upon detecting an invalid header, the recent ones are rolled back
   978  // for various failure scenarios. Afterwards a full sync is attempted to make
   979  // sure no state was corrupted.
   980  func TestInvalidHeaderRollback63Fast(t *testing.T)  { testInvalidHeaderRollback(t, 63, FastSync) }
   981  func TestInvalidHeaderRollback64Fast(t *testing.T)  { testInvalidHeaderRollback(t, 64, FastSync) }
   982  func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }
   983  
   984  func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
   985  	t.Parallel()
   986  
   987  	tester := newTester()
   988  	defer tester.terminate()
   989  
   990  	// Create a small enough block chain to download
   991  	targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
   992  	chain := testChainBase.shorten(targetBlocks)
   993  
   994  	// Attempt to sync with an attacker that feeds junk during the fast sync phase.
   995  	// This should result in the last fsHeaderSafetyNet headers being rolled back.
   996  	missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
   997  	fastAttackChain := chain.shorten(chain.len())
   998  	delete(fastAttackChain.headerm, fastAttackChain.chain[missing])
   999  	tester.newPeer("fast-attack", protocol, fastAttackChain)
  1000  
  1001  	if err := tester.sync("fast-attack", nil, mode); err == nil {
  1002  		t.Fatalf("succeeded fast attacker synchronisation")
  1003  	}
  1004  	if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  1005  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  1006  	}
  1007  
  1008  	// Attempt to sync with an attacker that feeds junk during the block import phase.
  1009  	// This should result in both the last fsHeaderSafetyNet number of headers being
  1010  	// rolled back, and also the pivot point being reverted to a non-block status.
  1011  	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1012  	blockAttackChain := chain.shorten(chain.len())
  1013  	delete(fastAttackChain.headerm, fastAttackChain.chain[missing]) // Make sure the fast-attacker doesn't fill in
  1014  	delete(blockAttackChain.headerm, blockAttackChain.chain[missing])
  1015  	tester.newPeer("block-attack", protocol, blockAttackChain)
  1016  
  1017  	if err := tester.sync("block-attack", nil, mode); err == nil {
  1018  		t.Fatalf("succeeded block attacker synchronisation")
  1019  	}
  1020  	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1021  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1022  	}
  1023  	if mode == FastSync {
  1024  		if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1025  			t.Errorf("fast sync pivot block #%d not rolled back", head)
  1026  		}
  1027  	}
  1028  
  1029  	// Attempt to sync with an attacker that withholds promised blocks after the
  1030  	// fast sync pivot point. This could be a trial to leave the node with a bad
  1031  	// but already imported pivot block.
  1032  	withholdAttackChain := chain.shorten(chain.len())
  1033  	tester.newPeer("withhold-attack", protocol, withholdAttackChain)
  1034  	tester.downloader.syncInitHook = func(uint64, uint64) {
  1035  		for i := missing; i < withholdAttackChain.len(); i++ {
  1036  			delete(withholdAttackChain.headerm, withholdAttackChain.chain[i])
  1037  		}
  1038  		tester.downloader.syncInitHook = nil
  1039  	}
  1040  	if err := tester.sync("withhold-attack", nil, mode); err == nil {
  1041  		t.Fatalf("succeeded withholding attacker synchronisation")
  1042  	}
  1043  	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1044  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1045  	}
  1046  	if mode == FastSync {
  1047  		if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1048  			t.Errorf("fast sync pivot block #%d not rolled back", head)
  1049  		}
  1050  	}
  1051  
  1052  	// synchronise with the valid peer and make sure sync succeeds. Since the last rollback
  1053  	// should also disable fast syncing for this process, verify that we did a fresh full
  1054  	// sync. Note, we can't assert anything about the receipts since we won't purge the
  1055  	// database of them, hence we can't use assertOwnChain.
  1056  	tester.newPeer("valid", protocol, chain)
  1057  	if err := tester.sync("valid", nil, mode); err != nil {
  1058  		t.Fatalf("failed to synchronise blocks: %v", err)
  1059  	}
  1060  	if hs := len(tester.ownHeaders); hs != chain.len() {
  1061  		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, chain.len())
  1062  	}
  1063  	if mode != LightSync {
  1064  		if bs := len(tester.ownBlocks); bs != chain.len() {
  1065  			t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, chain.len())
  1066  		}
  1067  	}
  1068  }
  1069  
  1070  // Tests that a peer advertising an high TD doesn't get to stall the downloader
  1071  // afterwards by not sending any useful hashes.
  1072  func TestHighTDStarvationAttack62(t *testing.T)      { testHighTDStarvationAttack(t, 62, FullSync) }
  1073  func TestHighTDStarvationAttack63Full(t *testing.T)  { testHighTDStarvationAttack(t, 63, FullSync) }
  1074  func TestHighTDStarvationAttack63Fast(t *testing.T)  { testHighTDStarvationAttack(t, 63, FastSync) }
  1075  func TestHighTDStarvationAttack64Full(t *testing.T)  { testHighTDStarvationAttack(t, 64, FullSync) }
  1076  func TestHighTDStarvationAttack64Fast(t *testing.T)  { testHighTDStarvationAttack(t, 64, FastSync) }
  1077  func TestHighTDStarvationAttack64Light(t *testing.T) { testHighTDStarvationAttack(t, 64, LightSync) }
  1078  
  1079  func testHighTDStarvationAttack(t *testing.T, protocol int, mode SyncMode) {
  1080  	t.Parallel()
  1081  
  1082  	tester := newTester()
  1083  	defer tester.terminate()
  1084  
  1085  	chain := testChainBase.shorten(1)
  1086  	tester.newPeer("attack", protocol, chain)
  1087  	if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  1088  		t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  1089  	}
  1090  }
  1091  
  1092  // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
  1093  func TestBlockHeaderAttackerDropping62(t *testing.T) { testBlockHeaderAttackerDropping(t, 62) }
  1094  func TestBlockHeaderAttackerDropping63(t *testing.T) { testBlockHeaderAttackerDropping(t, 63) }
  1095  func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  1096  
  1097  func testBlockHeaderAttackerDropping(t *testing.T, protocol int) {
  1098  	t.Parallel()
  1099  
  1100  	// Define the disconnection requirement for individual hash fetch errors
  1101  	tests := []struct {
  1102  		result error
  1103  		drop   bool
  1104  	}{
  1105  		{nil, false},                        // Sync succeeded, all is well
  1106  		{errBusy, false},                    // Sync is already in progress, no problem
  1107  		{errUnknownPeer, false},             // Peer is unknown, was already dropped, don't double drop
  1108  		{errBadPeer, true},                  // Peer was deemed bad for some reason, drop it
  1109  		{errStallingPeer, true},             // Peer was detected to be stalling, drop it
  1110  		{errUnsyncedPeer, true},             // Peer was detected to be unsynced, drop it
  1111  		{errNoPeers, false},                 // No peers to download from, soft race, no issue
  1112  		{errTimeout, true},                  // No hashes received in due time, drop the peer
  1113  		{errEmptyHeaderSet, true},           // No headers were returned as a response, drop as it's a dead end
  1114  		{errPeersUnavailable, true},         // Nobody had the advertised blocks, drop the advertiser
  1115  		{errInvalidAncestor, true},          // Agreed upon ancestor is not acceptable, drop the chain rewriter
  1116  		{errInvalidChain, true},             // Hash chain was detected as invalid, definitely drop
  1117  		{errInvalidBody, false},             // A bad peer was detected, but not the sync origin
  1118  		{errInvalidReceipt, false},          // A bad peer was detected, but not the sync origin
  1119  		{errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1120  	}
  1121  	// Run the tests and check disconnection status
  1122  	tester := newTester()
  1123  	defer tester.terminate()
  1124  	chain := testChainBase.shorten(1)
  1125  
  1126  	for i, tt := range tests {
  1127  		// Register a new peer and ensure it's presence
  1128  		id := fmt.Sprintf("test %d", i)
  1129  		if err := tester.newPeer(id, protocol, chain); err != nil {
  1130  			t.Fatalf("test %d: failed to register new peer: %v", i, err)
  1131  		}
  1132  		if _, ok := tester.peers[id]; !ok {
  1133  			t.Fatalf("test %d: registered peer not found", i)
  1134  		}
  1135  		// Simulate a synchronisation and check the required result
  1136  		tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1137  
  1138  		tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  1139  		if _, ok := tester.peers[id]; !ok != tt.drop {
  1140  			t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1141  		}
  1142  	}
  1143  }
  1144  
  1145  // Tests that synchronisation progress (origin block number, current block number
  1146  // and highest block number) is tracked and updated correctly.
  1147  func TestSyncProgress62(t *testing.T)      { testSyncProgress(t, 62, FullSync) }
  1148  func TestSyncProgress63Full(t *testing.T)  { testSyncProgress(t, 63, FullSync) }
  1149  func TestSyncProgress63Fast(t *testing.T)  { testSyncProgress(t, 63, FastSync) }
  1150  func TestSyncProgress64Full(t *testing.T)  { testSyncProgress(t, 64, FullSync) }
  1151  func TestSyncProgress64Fast(t *testing.T)  { testSyncProgress(t, 64, FastSync) }
  1152  func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }
  1153  
  1154  func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1155  	t.Parallel()
  1156  
  1157  	tester := newTester()
  1158  	defer tester.terminate()
  1159  	chain := testChainBase.shorten(blockCacheItems - 15)
  1160  
  1161  	// Set a sync init hook to catch progress changes
  1162  	starting := make(chan struct{})
  1163  	progress := make(chan struct{})
  1164  
  1165  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1166  		starting <- struct{}{}
  1167  		<-progress
  1168  	}
  1169  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1170  
  1171  	// Synchronise half the blocks and check initial progress
  1172  	tester.newPeer("peer-half", protocol, chain.shorten(chain.len()/2))
  1173  	pending := new(sync.WaitGroup)
  1174  	pending.Add(1)
  1175  
  1176  	go func() {
  1177  		defer pending.Done()
  1178  		if err := tester.sync("peer-half", nil, mode); err != nil {
  1179  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1180  		}
  1181  	}()
  1182  	<-starting
  1183  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1184  		HighestBlock: uint64(chain.len()/2 - 1),
  1185  	})
  1186  	progress <- struct{}{}
  1187  	pending.Wait()
  1188  
  1189  	// Synchronise all the blocks and check continuation progress
  1190  	tester.newPeer("peer-full", protocol, chain)
  1191  	pending.Add(1)
  1192  	go func() {
  1193  		defer pending.Done()
  1194  		if err := tester.sync("peer-full", nil, mode); err != nil {
  1195  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1196  		}
  1197  	}()
  1198  	<-starting
  1199  	checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1200  		StartingBlock: uint64(chain.len()/2 - 1),
  1201  		CurrentBlock:  uint64(chain.len()/2 - 1),
  1202  		HighestBlock:  uint64(chain.len() - 1),
  1203  	})
  1204  
  1205  	// Check final progress after successful sync
  1206  	progress <- struct{}{}
  1207  	pending.Wait()
  1208  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1209  		StartingBlock: uint64(chain.len()/2 - 1),
  1210  		CurrentBlock:  uint64(chain.len() - 1),
  1211  		HighestBlock:  uint64(chain.len() - 1),
  1212  	})
  1213  }
  1214  
  1215  func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) {
  1216  	// Mark this method as a helper to report errors at callsite, not in here
  1217  	t.Helper()
  1218  
  1219  	p := d.Progress()
  1220  	p.KnownStates, p.PulledStates = 0, 0
  1221  	want.KnownStates, want.PulledStates = 0, 0
  1222  	if p != want {
  1223  		t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want)
  1224  	}
  1225  }
  1226  
  1227  // Tests that synchronisation progress (origin block number and highest block
  1228  // number) is tracked and updated correctly in case of a fork (or manual head
  1229  // revertal).
  1230  func TestForkedSyncProgress62(t *testing.T)      { testForkedSyncProgress(t, 62, FullSync) }
  1231  func TestForkedSyncProgress63Full(t *testing.T)  { testForkedSyncProgress(t, 63, FullSync) }
  1232  func TestForkedSyncProgress63Fast(t *testing.T)  { testForkedSyncProgress(t, 63, FastSync) }
  1233  func TestForkedSyncProgress64Full(t *testing.T)  { testForkedSyncProgress(t, 64, FullSync) }
  1234  func TestForkedSyncProgress64Fast(t *testing.T)  { testForkedSyncProgress(t, 64, FastSync) }
  1235  func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }
  1236  
  1237  func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1238  	t.Parallel()
  1239  
  1240  	tester := newTester()
  1241  	defer tester.terminate()
  1242  	chainA := testChainForkLightA.shorten(testChainBase.len() + MaxHashFetch)
  1243  	chainB := testChainForkLightB.shorten(testChainBase.len() + MaxHashFetch)
  1244  
  1245  	// Set a sync init hook to catch progress changes
  1246  	starting := make(chan struct{})
  1247  	progress := make(chan struct{})
  1248  
  1249  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1250  		starting <- struct{}{}
  1251  		<-progress
  1252  	}
  1253  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1254  
  1255  	// Synchronise with one of the forks and check progress
  1256  	tester.newPeer("fork A", protocol, chainA)
  1257  	pending := new(sync.WaitGroup)
  1258  	pending.Add(1)
  1259  	go func() {
  1260  		defer pending.Done()
  1261  		if err := tester.sync("fork A", nil, mode); err != nil {
  1262  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1263  		}
  1264  	}()
  1265  	<-starting
  1266  
  1267  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1268  		HighestBlock: uint64(chainA.len() - 1),
  1269  	})
  1270  	progress <- struct{}{}
  1271  	pending.Wait()
  1272  
  1273  	// Simulate a successful sync above the fork
  1274  	tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1275  
  1276  	// Synchronise with the second fork and check progress resets
  1277  	tester.newPeer("fork B", protocol, chainB)
  1278  	pending.Add(1)
  1279  	go func() {
  1280  		defer pending.Done()
  1281  		if err := tester.sync("fork B", nil, mode); err != nil {
  1282  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1283  		}
  1284  	}()
  1285  	<-starting
  1286  	checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{
  1287  		StartingBlock: uint64(testChainBase.len()) - 1,
  1288  		CurrentBlock:  uint64(chainA.len() - 1),
  1289  		HighestBlock:  uint64(chainB.len() - 1),
  1290  	})
  1291  
  1292  	// Check final progress after successful sync
  1293  	progress <- struct{}{}
  1294  	pending.Wait()
  1295  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1296  		StartingBlock: uint64(testChainBase.len()) - 1,
  1297  		CurrentBlock:  uint64(chainB.len() - 1),
  1298  		HighestBlock:  uint64(chainB.len() - 1),
  1299  	})
  1300  }
  1301  
  1302  // Tests that if synchronisation is aborted due to some failure, then the progress
  1303  // origin is not updated in the next sync cycle, as it should be considered the
  1304  // continuation of the previous sync and not a new instance.
  1305  func TestFailedSyncProgress62(t *testing.T)      { testFailedSyncProgress(t, 62, FullSync) }
  1306  func TestFailedSyncProgress63Full(t *testing.T)  { testFailedSyncProgress(t, 63, FullSync) }
  1307  func TestFailedSyncProgress63Fast(t *testing.T)  { testFailedSyncProgress(t, 63, FastSync) }
  1308  func TestFailedSyncProgress64Full(t *testing.T)  { testFailedSyncProgress(t, 64, FullSync) }
  1309  func TestFailedSyncProgress64Fast(t *testing.T)  { testFailedSyncProgress(t, 64, FastSync) }
  1310  func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }
  1311  
  1312  func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1313  	t.Parallel()
  1314  
  1315  	tester := newTester()
  1316  	defer tester.terminate()
  1317  	chain := testChainBase.shorten(blockCacheItems - 15)
  1318  
  1319  	// Set a sync init hook to catch progress changes
  1320  	starting := make(chan struct{})
  1321  	progress := make(chan struct{})
  1322  
  1323  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1324  		starting <- struct{}{}
  1325  		<-progress
  1326  	}
  1327  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1328  
  1329  	// Attempt a full sync with a faulty peer
  1330  	brokenChain := chain.shorten(chain.len())
  1331  	missing := brokenChain.len() / 2
  1332  	delete(brokenChain.headerm, brokenChain.chain[missing])
  1333  	delete(brokenChain.blockm, brokenChain.chain[missing])
  1334  	delete(brokenChain.receiptm, brokenChain.chain[missing])
  1335  	tester.newPeer("faulty", protocol, brokenChain)
  1336  
  1337  	pending := new(sync.WaitGroup)
  1338  	pending.Add(1)
  1339  	go func() {
  1340  		defer pending.Done()
  1341  		if err := tester.sync("faulty", nil, mode); err == nil {
  1342  			panic("succeeded faulty synchronisation")
  1343  		}
  1344  	}()
  1345  	<-starting
  1346  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1347  		HighestBlock: uint64(brokenChain.len() - 1),
  1348  	})
  1349  	progress <- struct{}{}
  1350  	pending.Wait()
  1351  	afterFailedSync := tester.downloader.Progress()
  1352  
  1353  	// Synchronise with a good peer and check that the progress origin remind the same
  1354  	// after a failure
  1355  	tester.newPeer("valid", protocol, chain)
  1356  	pending.Add(1)
  1357  	go func() {
  1358  		defer pending.Done()
  1359  		if err := tester.sync("valid", nil, mode); err != nil {
  1360  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1361  		}
  1362  	}()
  1363  	<-starting
  1364  	checkProgress(t, tester.downloader, "completing", afterFailedSync)
  1365  
  1366  	// Check final progress after successful sync
  1367  	progress <- struct{}{}
  1368  	pending.Wait()
  1369  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1370  		CurrentBlock: uint64(chain.len() - 1),
  1371  		HighestBlock: uint64(chain.len() - 1),
  1372  	})
  1373  }
  1374  
  1375  // Tests that if an attacker fakes a chain height, after the attack is detected,
  1376  // the progress height is successfully reduced at the next sync invocation.
  1377  func TestFakedSyncProgress62(t *testing.T)      { testFakedSyncProgress(t, 62, FullSync) }
  1378  func TestFakedSyncProgress63Full(t *testing.T)  { testFakedSyncProgress(t, 63, FullSync) }
  1379  func TestFakedSyncProgress63Fast(t *testing.T)  { testFakedSyncProgress(t, 63, FastSync) }
  1380  func TestFakedSyncProgress64Full(t *testing.T)  { testFakedSyncProgress(t, 64, FullSync) }
  1381  func TestFakedSyncProgress64Fast(t *testing.T)  { testFakedSyncProgress(t, 64, FastSync) }
  1382  func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }
  1383  
  1384  func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1385  	t.Parallel()
  1386  
  1387  	tester := newTester()
  1388  	defer tester.terminate()
  1389  	chain := testChainBase.shorten(blockCacheItems - 15)
  1390  
  1391  	// Set a sync init hook to catch progress changes
  1392  	starting := make(chan struct{})
  1393  	progress := make(chan struct{})
  1394  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1395  		starting <- struct{}{}
  1396  		<-progress
  1397  	}
  1398  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1399  
  1400  	// Create and sync with an attacker that promises a higher chain than available.
  1401  	brokenChain := chain.shorten(chain.len())
  1402  	numMissing := 5
  1403  	for i := brokenChain.len() - 2; i > brokenChain.len()-numMissing; i-- {
  1404  		delete(brokenChain.headerm, brokenChain.chain[i])
  1405  	}
  1406  	tester.newPeer("attack", protocol, brokenChain)
  1407  
  1408  	pending := new(sync.WaitGroup)
  1409  	pending.Add(1)
  1410  	go func() {
  1411  		defer pending.Done()
  1412  		if err := tester.sync("attack", nil, mode); err == nil {
  1413  			panic("succeeded attacker synchronisation")
  1414  		}
  1415  	}()
  1416  	<-starting
  1417  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1418  		HighestBlock: uint64(brokenChain.len() - 1),
  1419  	})
  1420  	progress <- struct{}{}
  1421  	pending.Wait()
  1422  	afterFailedSync := tester.downloader.Progress()
  1423  
  1424  	// Synchronise with a good peer and check that the progress height has been reduced to
  1425  	// the true value.
  1426  	validChain := chain.shorten(chain.len() - numMissing)
  1427  	tester.newPeer("valid", protocol, validChain)
  1428  	pending.Add(1)
  1429  
  1430  	go func() {
  1431  		defer pending.Done()
  1432  		if err := tester.sync("valid", nil, mode); err != nil {
  1433  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1434  		}
  1435  	}()
  1436  	<-starting
  1437  	checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1438  		CurrentBlock: afterFailedSync.CurrentBlock,
  1439  		HighestBlock: uint64(validChain.len() - 1),
  1440  	})
  1441  
  1442  	// Check final progress after successful sync.
  1443  	progress <- struct{}{}
  1444  	pending.Wait()
  1445  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1446  		CurrentBlock: uint64(validChain.len() - 1),
  1447  		HighestBlock: uint64(validChain.len() - 1),
  1448  	})
  1449  }
  1450  
  1451  // This test reproduces an issue where unexpected deliveries would
  1452  // block indefinitely if they arrived at the right time.
  1453  func TestDeliverHeadersHang(t *testing.T) {
  1454  	t.Parallel()
  1455  
  1456  	testCases := []struct {
  1457  		protocol int
  1458  		syncMode SyncMode
  1459  	}{
  1460  		{62, FullSync},
  1461  		{63, FullSync},
  1462  		{63, FastSync},
  1463  		{64, FullSync},
  1464  		{64, FastSync},
  1465  		{64, LightSync},
  1466  	}
  1467  	for _, tc := range testCases {
  1468  		t.Run(fmt.Sprintf("protocol %d mode %v", tc.protocol, tc.syncMode), func(t *testing.T) {
  1469  			t.Parallel()
  1470  			testDeliverHeadersHang(t, tc.protocol, tc.syncMode)
  1471  		})
  1472  	}
  1473  }
  1474  
  1475  func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
  1476  	master := newTester()
  1477  	defer master.terminate()
  1478  	chain := testChainBase.shorten(15)
  1479  
  1480  	for i := 0; i < 200; i++ {
  1481  		tester := newTester()
  1482  		tester.peerDb = master.peerDb
  1483  		tester.newPeer("peer", protocol, chain)
  1484  
  1485  		// Whenever the downloader requests headers, flood it with
  1486  		// a lot of unrequested header deliveries.
  1487  		tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1488  			peer:   tester.downloader.peers.peers["peer"].peer,
  1489  			tester: tester,
  1490  		}
  1491  		if err := tester.sync("peer", nil, mode); err != nil {
  1492  			t.Errorf("test %d: sync failed: %v", i, err)
  1493  		}
  1494  		tester.terminate()
  1495  	}
  1496  }
  1497  
  1498  type floodingTestPeer struct {
  1499  	peer   Peer
  1500  	tester *downloadTester
  1501  }
  1502  
  1503  func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1504  func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1505  	return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1506  }
  1507  func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1508  	return ftp.peer.RequestBodies(hashes)
  1509  }
  1510  func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1511  	return ftp.peer.RequestReceipts(hashes)
  1512  }
  1513  func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1514  	return ftp.peer.RequestNodeData(hashes)
  1515  }
  1516  
  1517  func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1518  	deliveriesDone := make(chan struct{}, 500)
  1519  	for i := 0; i < cap(deliveriesDone)-1; i++ {
  1520  		peer := fmt.Sprintf("fake-peer%d", i)
  1521  		go func() {
  1522  			ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1523  			deliveriesDone <- struct{}{}
  1524  		}()
  1525  	}
  1526  
  1527  	// None of the extra deliveries should block.
  1528  	timeout := time.After(60 * time.Second)
  1529  	launched := false
  1530  	for i := 0; i < cap(deliveriesDone); i++ {
  1531  		select {
  1532  		case <-deliveriesDone:
  1533  			if !launched {
  1534  				// Start delivering the requested headers
  1535  				// after one of the flooding responses has arrived.
  1536  				go func() {
  1537  					ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1538  					deliveriesDone <- struct{}{}
  1539  				}()
  1540  				launched = true
  1541  			}
  1542  		case <-timeout:
  1543  			panic("blocked")
  1544  		}
  1545  	}
  1546  	return nil
  1547  }
  1548  
  1549  func TestRemoteHeaderRequestSpan(t *testing.T) {
  1550  	testCases := []struct {
  1551  		remoteHeight uint64
  1552  		localHeight  uint64
  1553  		expected     []int
  1554  	}{
  1555  		// Remote is way higher. We should ask for the remote head and go backwards
  1556  		{1500, 1000,
  1557  			[]int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499},
  1558  		},
  1559  		{15000, 13006,
  1560  			[]int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999},
  1561  		},
  1562  		//Remote is pretty close to us. We don't have to fetch as many
  1563  		{1200, 1150,
  1564  			[]int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199},
  1565  		},
  1566  		// Remote is equal to us (so on a fork with higher td)
  1567  		// We should get the closest couple of ancestors
  1568  		{1500, 1500,
  1569  			[]int{1497, 1499},
  1570  		},
  1571  		// We're higher than the remote! Odd
  1572  		{1000, 1500,
  1573  			[]int{997, 999},
  1574  		},
  1575  		// Check some weird edgecases that it behaves somewhat rationally
  1576  		{0, 1500,
  1577  			[]int{0, 2},
  1578  		},
  1579  		{6000000, 0,
  1580  			[]int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999},
  1581  		},
  1582  		{0, 0,
  1583  			[]int{0, 2},
  1584  		},
  1585  	}
  1586  	reqs := func(from, count, span int) []int {
  1587  		var r []int
  1588  		num := from
  1589  		for len(r) < count {
  1590  			r = append(r, num)
  1591  			num += span + 1
  1592  		}
  1593  		return r
  1594  	}
  1595  	for i, tt := range testCases {
  1596  		from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight)
  1597  		data := reqs(int(from), count, span)
  1598  
  1599  		if max != uint64(data[len(data)-1]) {
  1600  			t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max)
  1601  		}
  1602  		failed := false
  1603  		if len(data) != len(tt.expected) {
  1604  			failed = true
  1605  			t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data))
  1606  		} else {
  1607  			for j, n := range data {
  1608  				if n != tt.expected[j] {
  1609  					failed = true
  1610  					break
  1611  				}
  1612  			}
  1613  		}
  1614  		if failed {
  1615  			res := strings.Replace(fmt.Sprint(data), " ", ",", -1)
  1616  			exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1)
  1617  			t.Logf("got: %v\n", res)
  1618  			t.Logf("exp: %v\n", exp)
  1619  			t.Errorf("test %d: wrong values", i)
  1620  		}
  1621  	}
  1622  }
  1623  
  1624  // Tests that peers below a pre-configured checkpoint block are prevented from
  1625  // being fast-synced from, avoiding potential cheap eclipse attacks.
  1626  func TestCheckpointEnforcement62(t *testing.T)      { testCheckpointEnforcement(t, 62, FullSync) }
  1627  func TestCheckpointEnforcement63Full(t *testing.T)  { testCheckpointEnforcement(t, 63, FullSync) }
  1628  func TestCheckpointEnforcement63Fast(t *testing.T)  { testCheckpointEnforcement(t, 63, FastSync) }
  1629  func TestCheckpointEnforcement64Full(t *testing.T)  { testCheckpointEnforcement(t, 64, FullSync) }
  1630  func TestCheckpointEnforcement64Fast(t *testing.T)  { testCheckpointEnforcement(t, 64, FastSync) }
  1631  func TestCheckpointEnforcement64Light(t *testing.T) { testCheckpointEnforcement(t, 64, LightSync) }
  1632  
  1633  func testCheckpointEnforcement(t *testing.T, protocol int, mode SyncMode) {
  1634  	t.Parallel()
  1635  
  1636  	// Create a new tester with a particular hard coded checkpoint block
  1637  	tester := newTester()
  1638  	defer tester.terminate()
  1639  
  1640  	tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
  1641  	chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1)
  1642  
  1643  	// Attempt to sync with the peer and validate the result
  1644  	tester.newPeer("peer", protocol, chain)
  1645  
  1646  	var expect error
  1647  	if mode == FastSync || mode == LightSync {
  1648  		expect = errUnsyncedPeer
  1649  	}
  1650  	if err := tester.sync("peer", nil, mode); err != expect {
  1651  		t.Fatalf("block sync error mismatch: have %v, want %v", err, expect)
  1652  	}
  1653  	if mode == FastSync || mode == LightSync {
  1654  		assertOwnChain(t, tester, 1)
  1655  	} else {
  1656  		assertOwnChain(t, tester, chain.len())
  1657  	}
  1658  }