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