github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/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  	"os"
    24  	"strings"
    25  	"sync"
    26  	"sync/atomic"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/ethereum/go-ethereum"
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/consensus/ethash"
    33  	"github.com/ethereum/go-ethereum/core"
    34  	"github.com/ethereum/go-ethereum/core/rawdb"
    35  	"github.com/ethereum/go-ethereum/core/types"
    36  	"github.com/ethereum/go-ethereum/core/vm"
    37  	"github.com/ethereum/go-ethereum/eth/protocols/eth"
    38  	"github.com/ethereum/go-ethereum/eth/protocols/snap"
    39  	"github.com/ethereum/go-ethereum/event"
    40  	"github.com/ethereum/go-ethereum/log"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rlp"
    43  	"github.com/ethereum/go-ethereum/trie"
    44  )
    45  
    46  // downloadTester is a test simulator for mocking out local block chain.
    47  type downloadTester struct {
    48  	freezer    string
    49  	chain      *core.BlockChain
    50  	downloader *Downloader
    51  
    52  	peers map[string]*downloadTesterPeer
    53  	lock  sync.RWMutex
    54  }
    55  
    56  // newTester creates a new downloader test mocker.
    57  func newTester(t *testing.T) *downloadTester {
    58  	return newTesterWithNotification(t, nil)
    59  }
    60  
    61  // newTester creates a new downloader test mocker.
    62  func newTesterWithNotification(t *testing.T, success func()) *downloadTester {
    63  	freezer := t.TempDir()
    64  	db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), freezer, "", false)
    65  	if err != nil {
    66  		panic(err)
    67  	}
    68  	t.Cleanup(func() {
    69  		db.Close()
    70  	})
    71  	core.GenesisBlockForTesting(db, testAddress, big.NewInt(1000000000000000))
    72  
    73  	chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  	tester := &downloadTester{
    78  		freezer: freezer,
    79  		chain:   chain,
    80  		peers:   make(map[string]*downloadTesterPeer),
    81  	}
    82  	tester.downloader = New(0, db, new(event.TypeMux), tester.chain, nil, tester.dropPeer, success)
    83  	return tester
    84  }
    85  
    86  // terminate aborts any operations on the embedded downloader and releases all
    87  // held resources.
    88  func (dl *downloadTester) terminate() {
    89  	dl.downloader.Terminate()
    90  	dl.chain.Stop()
    91  
    92  	os.RemoveAll(dl.freezer)
    93  }
    94  
    95  // sync starts synchronizing with a remote peer, blocking until it completes.
    96  func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error {
    97  	head := dl.peers[id].chain.CurrentBlock()
    98  	if td == nil {
    99  		// If no particular TD was requested, load from the peer's blockchain
   100  		td = dl.peers[id].chain.GetTd(head.Hash(), head.NumberU64())
   101  	}
   102  	// Synchronise with the chosen peer and ensure proper cleanup afterwards
   103  	err := dl.downloader.synchronise(id, head.Hash(), td, nil, mode, false, nil)
   104  	select {
   105  	case <-dl.downloader.cancelCh:
   106  		// Ok, downloader fully cancelled after sync cycle
   107  	default:
   108  		// Downloader is still accepting packets, can block a peer up
   109  		panic("downloader active post sync cycle") // panic will be caught by tester
   110  	}
   111  	return err
   112  }
   113  
   114  // newPeer registers a new block download source into the downloader.
   115  func (dl *downloadTester) newPeer(id string, version uint, blocks []*types.Block) *downloadTesterPeer {
   116  	dl.lock.Lock()
   117  	defer dl.lock.Unlock()
   118  
   119  	peer := &downloadTesterPeer{
   120  		dl:              dl,
   121  		id:              id,
   122  		chain:           newTestBlockchain(blocks),
   123  		withholdHeaders: make(map[common.Hash]struct{}),
   124  	}
   125  	dl.peers[id] = peer
   126  
   127  	if err := dl.downloader.RegisterPeer(id, version, peer); err != nil {
   128  		panic(err)
   129  	}
   130  	if err := dl.downloader.SnapSyncer.Register(peer); err != nil {
   131  		panic(err)
   132  	}
   133  	return peer
   134  }
   135  
   136  // dropPeer simulates a hard peer removal from the connection pool.
   137  func (dl *downloadTester) dropPeer(id string) {
   138  	dl.lock.Lock()
   139  	defer dl.lock.Unlock()
   140  
   141  	delete(dl.peers, id)
   142  	dl.downloader.SnapSyncer.Unregister(id)
   143  	dl.downloader.UnregisterPeer(id)
   144  }
   145  
   146  type downloadTesterPeer struct {
   147  	dl    *downloadTester
   148  	id    string
   149  	chain *core.BlockChain
   150  
   151  	withholdHeaders map[common.Hash]struct{}
   152  }
   153  
   154  // Head constructs a function to retrieve a peer's current head hash
   155  // and total difficulty.
   156  func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) {
   157  	head := dlp.chain.CurrentBlock()
   158  	return head.Hash(), dlp.chain.GetTd(head.Hash(), head.NumberU64())
   159  }
   160  
   161  func unmarshalRlpHeaders(rlpdata []rlp.RawValue) []*types.Header {
   162  	var headers = make([]*types.Header, len(rlpdata))
   163  	for i, data := range rlpdata {
   164  		var h types.Header
   165  		if err := rlp.DecodeBytes(data, &h); err != nil {
   166  			panic(err)
   167  		}
   168  		headers[i] = &h
   169  	}
   170  	return headers
   171  }
   172  
   173  // RequestHeadersByHash constructs a GetBlockHeaders function based on a hashed
   174  // origin; associated with a particular peer in the download tester. The returned
   175  // function can be used to retrieve batches of headers from the particular peer.
   176  func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool, sink chan *eth.Response) (*eth.Request, error) {
   177  	// Service the header query via the live handler code
   178  	rlpHeaders := eth.ServiceGetBlockHeadersQuery(dlp.chain, &eth.GetBlockHeadersPacket{
   179  		Origin: eth.HashOrNumber{
   180  			Hash: origin,
   181  		},
   182  		Amount:  uint64(amount),
   183  		Skip:    uint64(skip),
   184  		Reverse: reverse,
   185  	}, nil)
   186  	headers := unmarshalRlpHeaders(rlpHeaders)
   187  	// If a malicious peer is simulated withholding headers, delete them
   188  	for hash := range dlp.withholdHeaders {
   189  		for i, header := range headers {
   190  			if header.Hash() == hash {
   191  				headers = append(headers[:i], headers[i+1:]...)
   192  				break
   193  			}
   194  		}
   195  	}
   196  	hashes := make([]common.Hash, len(headers))
   197  	for i, header := range headers {
   198  		hashes[i] = header.Hash()
   199  	}
   200  	// Deliver the headers to the downloader
   201  	req := &eth.Request{
   202  		Peer: dlp.id,
   203  	}
   204  	res := &eth.Response{
   205  		Req:  req,
   206  		Res:  (*eth.BlockHeadersPacket)(&headers),
   207  		Meta: hashes,
   208  		Time: 1,
   209  		Done: make(chan error, 1), // Ignore the returned status
   210  	}
   211  	go func() {
   212  		sink <- res
   213  	}()
   214  	return req, nil
   215  }
   216  
   217  // RequestHeadersByNumber constructs a GetBlockHeaders function based on a numbered
   218  // origin; associated with a particular peer in the download tester. The returned
   219  // function can be used to retrieve batches of headers from the particular peer.
   220  func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool, sink chan *eth.Response) (*eth.Request, error) {
   221  	// Service the header query via the live handler code
   222  	rlpHeaders := eth.ServiceGetBlockHeadersQuery(dlp.chain, &eth.GetBlockHeadersPacket{
   223  		Origin: eth.HashOrNumber{
   224  			Number: origin,
   225  		},
   226  		Amount:  uint64(amount),
   227  		Skip:    uint64(skip),
   228  		Reverse: reverse,
   229  	}, nil)
   230  	headers := unmarshalRlpHeaders(rlpHeaders)
   231  	// If a malicious peer is simulated withholding headers, delete them
   232  	for hash := range dlp.withholdHeaders {
   233  		for i, header := range headers {
   234  			if header.Hash() == hash {
   235  				headers = append(headers[:i], headers[i+1:]...)
   236  				break
   237  			}
   238  		}
   239  	}
   240  	hashes := make([]common.Hash, len(headers))
   241  	for i, header := range headers {
   242  		hashes[i] = header.Hash()
   243  	}
   244  	// Deliver the headers to the downloader
   245  	req := &eth.Request{
   246  		Peer: dlp.id,
   247  	}
   248  	res := &eth.Response{
   249  		Req:  req,
   250  		Res:  (*eth.BlockHeadersPacket)(&headers),
   251  		Meta: hashes,
   252  		Time: 1,
   253  		Done: make(chan error, 1), // Ignore the returned status
   254  	}
   255  	go func() {
   256  		sink <- res
   257  	}()
   258  	return req, nil
   259  }
   260  
   261  // RequestBodies constructs a getBlockBodies method associated with a particular
   262  // peer in the download tester. The returned function can be used to retrieve
   263  // batches of block bodies from the particularly requested peer.
   264  func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash, sink chan *eth.Response) (*eth.Request, error) {
   265  	blobs := eth.ServiceGetBlockBodiesQuery(dlp.chain, hashes)
   266  
   267  	bodies := make([]*eth.BlockBody, len(blobs))
   268  	for i, blob := range blobs {
   269  		bodies[i] = new(eth.BlockBody)
   270  		rlp.DecodeBytes(blob, bodies[i])
   271  	}
   272  	var (
   273  		txsHashes   = make([]common.Hash, len(bodies))
   274  		uncleHashes = make([]common.Hash, len(bodies))
   275  	)
   276  	hasher := trie.NewStackTrie(nil)
   277  	for i, body := range bodies {
   278  		txsHashes[i] = types.DeriveSha(types.Transactions(body.Transactions), hasher)
   279  		uncleHashes[i] = types.CalcUncleHash(body.Uncles)
   280  	}
   281  	req := &eth.Request{
   282  		Peer: dlp.id,
   283  	}
   284  	res := &eth.Response{
   285  		Req:  req,
   286  		Res:  (*eth.BlockBodiesPacket)(&bodies),
   287  		Meta: [][]common.Hash{txsHashes, uncleHashes},
   288  		Time: 1,
   289  		Done: make(chan error, 1), // Ignore the returned status
   290  	}
   291  	go func() {
   292  		sink <- res
   293  	}()
   294  	return req, nil
   295  }
   296  
   297  // RequestReceipts constructs a getReceipts method associated with a particular
   298  // peer in the download tester. The returned function can be used to retrieve
   299  // batches of block receipts from the particularly requested peer.
   300  func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash, sink chan *eth.Response) (*eth.Request, error) {
   301  	blobs := eth.ServiceGetReceiptsQuery(dlp.chain, hashes)
   302  
   303  	receipts := make([][]*types.Receipt, len(blobs))
   304  	for i, blob := range blobs {
   305  		rlp.DecodeBytes(blob, &receipts[i])
   306  	}
   307  	hasher := trie.NewStackTrie(nil)
   308  	hashes = make([]common.Hash, len(receipts))
   309  	for i, receipt := range receipts {
   310  		hashes[i] = types.DeriveSha(types.Receipts(receipt), hasher)
   311  	}
   312  	req := &eth.Request{
   313  		Peer: dlp.id,
   314  	}
   315  	res := &eth.Response{
   316  		Req:  req,
   317  		Res:  (*eth.ReceiptsPacket)(&receipts),
   318  		Meta: hashes,
   319  		Time: 1,
   320  		Done: make(chan error, 1), // Ignore the returned status
   321  	}
   322  	go func() {
   323  		sink <- res
   324  	}()
   325  	return req, nil
   326  }
   327  
   328  // ID retrieves the peer's unique identifier.
   329  func (dlp *downloadTesterPeer) ID() string {
   330  	return dlp.id
   331  }
   332  
   333  // RequestAccountRange fetches a batch of accounts rooted in a specific account
   334  // trie, starting with the origin.
   335  func (dlp *downloadTesterPeer) RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error {
   336  	// Create the request and service it
   337  	req := &snap.GetAccountRangePacket{
   338  		ID:     id,
   339  		Root:   root,
   340  		Origin: origin,
   341  		Limit:  limit,
   342  		Bytes:  bytes,
   343  	}
   344  	slimaccs, proofs := snap.ServiceGetAccountRangeQuery(dlp.chain, req)
   345  
   346  	// We need to convert to non-slim format, delegate to the packet code
   347  	res := &snap.AccountRangePacket{
   348  		ID:       id,
   349  		Accounts: slimaccs,
   350  		Proof:    proofs,
   351  	}
   352  	hashes, accounts, _ := res.Unpack()
   353  
   354  	go dlp.dl.downloader.SnapSyncer.OnAccounts(dlp, id, hashes, accounts, proofs)
   355  	return nil
   356  }
   357  
   358  // RequestStorageRanges fetches a batch of storage slots belonging to one or
   359  // more accounts. If slots from only one accout is requested, an origin marker
   360  // may also be used to retrieve from there.
   361  func (dlp *downloadTesterPeer) RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error {
   362  	// Create the request and service it
   363  	req := &snap.GetStorageRangesPacket{
   364  		ID:       id,
   365  		Accounts: accounts,
   366  		Root:     root,
   367  		Origin:   origin,
   368  		Limit:    limit,
   369  		Bytes:    bytes,
   370  	}
   371  	storage, proofs := snap.ServiceGetStorageRangesQuery(dlp.chain, req)
   372  
   373  	// We need to convert to demultiplex, delegate to the packet code
   374  	res := &snap.StorageRangesPacket{
   375  		ID:    id,
   376  		Slots: storage,
   377  		Proof: proofs,
   378  	}
   379  	hashes, slots := res.Unpack()
   380  
   381  	go dlp.dl.downloader.SnapSyncer.OnStorage(dlp, id, hashes, slots, proofs)
   382  	return nil
   383  }
   384  
   385  // RequestByteCodes fetches a batch of bytecodes by hash.
   386  func (dlp *downloadTesterPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error {
   387  	req := &snap.GetByteCodesPacket{
   388  		ID:     id,
   389  		Hashes: hashes,
   390  		Bytes:  bytes,
   391  	}
   392  	codes := snap.ServiceGetByteCodesQuery(dlp.chain, req)
   393  	go dlp.dl.downloader.SnapSyncer.OnByteCodes(dlp, id, codes)
   394  	return nil
   395  }
   396  
   397  // RequestTrieNodes fetches a batch of account or storage trie nodes rooted in
   398  // a specificstate trie.
   399  func (dlp *downloadTesterPeer) RequestTrieNodes(id uint64, root common.Hash, paths []snap.TrieNodePathSet, bytes uint64) error {
   400  	req := &snap.GetTrieNodesPacket{
   401  		ID:    id,
   402  		Root:  root,
   403  		Paths: paths,
   404  		Bytes: bytes,
   405  	}
   406  	nodes, _ := snap.ServiceGetTrieNodesQuery(dlp.chain, req, time.Now())
   407  	go dlp.dl.downloader.SnapSyncer.OnTrieNodes(dlp, id, nodes)
   408  	return nil
   409  }
   410  
   411  // Log retrieves the peer's own contextual logger.
   412  func (dlp *downloadTesterPeer) Log() log.Logger {
   413  	return log.New("peer", dlp.id)
   414  }
   415  
   416  // assertOwnChain checks if the local chain contains the correct number of items
   417  // of the various chain components.
   418  func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
   419  	// Mark this method as a helper to report errors at callsite, not in here
   420  	t.Helper()
   421  
   422  	headers, blocks, receipts := length, length, length
   423  	if tester.downloader.getMode() == LightSync {
   424  		blocks, receipts = 1, 1
   425  	}
   426  	if hs := int(tester.chain.CurrentHeader().Number.Uint64()) + 1; hs != headers {
   427  		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
   428  	}
   429  	if bs := int(tester.chain.CurrentBlock().NumberU64()) + 1; bs != blocks {
   430  		t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
   431  	}
   432  	if rs := int(tester.chain.CurrentFastBlock().NumberU64()) + 1; rs != receipts {
   433  		t.Fatalf("synchronised receipts mismatch: have %v, want %v", rs, receipts)
   434  	}
   435  }
   436  
   437  func TestCanonicalSynchronisation66Full(t *testing.T)  { testCanonSync(t, eth.ETH66, FullSync) }
   438  func TestCanonicalSynchronisation66Snap(t *testing.T)  { testCanonSync(t, eth.ETH66, SnapSync) }
   439  func TestCanonicalSynchronisation66Light(t *testing.T) { testCanonSync(t, eth.ETH66, LightSync) }
   440  func TestCanonicalSynchronisation67Full(t *testing.T)  { testCanonSync(t, eth.ETH67, FullSync) }
   441  func TestCanonicalSynchronisation67Snap(t *testing.T)  { testCanonSync(t, eth.ETH67, SnapSync) }
   442  func TestCanonicalSynchronisation67Light(t *testing.T) { testCanonSync(t, eth.ETH67, LightSync) }
   443  
   444  func testCanonSync(t *testing.T, protocol uint, mode SyncMode) {
   445  	tester := newTester(t)
   446  	defer tester.terminate()
   447  
   448  	// Create a small enough block chain to download
   449  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
   450  	tester.newPeer("peer", protocol, chain.blocks[1:])
   451  
   452  	// Synchronise with the peer and make sure all relevant data was retrieved
   453  	if err := tester.sync("peer", nil, mode); err != nil {
   454  		t.Fatalf("failed to synchronise blocks: %v", err)
   455  	}
   456  	assertOwnChain(t, tester, len(chain.blocks))
   457  }
   458  
   459  // Tests that if a large batch of blocks are being downloaded, it is throttled
   460  // until the cached blocks are retrieved.
   461  func TestThrottling66Full(t *testing.T) { testThrottling(t, eth.ETH66, FullSync) }
   462  func TestThrottling66Snap(t *testing.T) { testThrottling(t, eth.ETH66, SnapSync) }
   463  func TestThrottling67Full(t *testing.T) { testThrottling(t, eth.ETH67, FullSync) }
   464  func TestThrottling67Snap(t *testing.T) { testThrottling(t, eth.ETH67, SnapSync) }
   465  
   466  func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
   467  	tester := newTester(t)
   468  	defer tester.terminate()
   469  
   470  	// Create a long block chain to download and the tester
   471  	targetBlocks := len(testChainBase.blocks) - 1
   472  	tester.newPeer("peer", protocol, testChainBase.blocks[1:])
   473  
   474  	// Wrap the importer to allow stepping
   475  	blocked, proceed := uint32(0), make(chan struct{})
   476  	tester.downloader.chainInsertHook = func(results []*fetchResult) {
   477  		atomic.StoreUint32(&blocked, uint32(len(results)))
   478  		<-proceed
   479  	}
   480  	// Start a synchronisation concurrently
   481  	errc := make(chan error, 1)
   482  	go func() {
   483  		errc <- tester.sync("peer", nil, mode)
   484  	}()
   485  	// Iteratively take some blocks, always checking the retrieval count
   486  	for {
   487  		// Check the retrieval count synchronously (! reason for this ugly block)
   488  		tester.lock.RLock()
   489  		retrieved := int(tester.chain.CurrentFastBlock().Number().Uint64()) + 1
   490  		tester.lock.RUnlock()
   491  		if retrieved >= targetBlocks+1 {
   492  			break
   493  		}
   494  		// Wait a bit for sync to throttle itself
   495  		var cached, frozen int
   496  		for start := time.Now(); time.Since(start) < 3*time.Second; {
   497  			time.Sleep(25 * time.Millisecond)
   498  
   499  			tester.lock.Lock()
   500  			tester.downloader.queue.lock.Lock()
   501  			tester.downloader.queue.resultCache.lock.Lock()
   502  			{
   503  				cached = tester.downloader.queue.resultCache.countCompleted()
   504  				frozen = int(atomic.LoadUint32(&blocked))
   505  				retrieved = int(tester.chain.CurrentFastBlock().Number().Uint64()) + 1
   506  			}
   507  			tester.downloader.queue.resultCache.lock.Unlock()
   508  			tester.downloader.queue.lock.Unlock()
   509  			tester.lock.Unlock()
   510  
   511  			if cached == blockCacheMaxItems ||
   512  				cached == blockCacheMaxItems-reorgProtHeaderDelay ||
   513  				retrieved+cached+frozen == targetBlocks+1 ||
   514  				retrieved+cached+frozen == targetBlocks+1-reorgProtHeaderDelay {
   515  				break
   516  			}
   517  		}
   518  		// Make sure we filled up the cache, then exhaust it
   519  		time.Sleep(25 * time.Millisecond) // give it a chance to screw up
   520  		tester.lock.RLock()
   521  		retrieved = int(tester.chain.CurrentFastBlock().Number().Uint64()) + 1
   522  		tester.lock.RUnlock()
   523  		if cached != blockCacheMaxItems && cached != blockCacheMaxItems-reorgProtHeaderDelay && retrieved+cached+frozen != targetBlocks+1 && retrieved+cached+frozen != targetBlocks+1-reorgProtHeaderDelay {
   524  			t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheMaxItems, retrieved, frozen, targetBlocks+1)
   525  		}
   526  		// Permit the blocked blocks to import
   527  		if atomic.LoadUint32(&blocked) > 0 {
   528  			atomic.StoreUint32(&blocked, uint32(0))
   529  			proceed <- struct{}{}
   530  		}
   531  	}
   532  	// Check that we haven't pulled more blocks than available
   533  	assertOwnChain(t, tester, targetBlocks+1)
   534  	if err := <-errc; err != nil {
   535  		t.Fatalf("block synchronization failed: %v", err)
   536  	}
   537  }
   538  
   539  // Tests that simple synchronization against a forked chain works correctly. In
   540  // this test common ancestor lookup should *not* be short circuited, and a full
   541  // binary search should be executed.
   542  func TestForkedSync66Full(t *testing.T)  { testForkedSync(t, eth.ETH66, FullSync) }
   543  func TestForkedSync66Snap(t *testing.T)  { testForkedSync(t, eth.ETH66, SnapSync) }
   544  func TestForkedSync66Light(t *testing.T) { testForkedSync(t, eth.ETH66, LightSync) }
   545  func TestForkedSync67Full(t *testing.T)  { testForkedSync(t, eth.ETH67, FullSync) }
   546  func TestForkedSync67Snap(t *testing.T)  { testForkedSync(t, eth.ETH67, SnapSync) }
   547  func TestForkedSync67Light(t *testing.T) { testForkedSync(t, eth.ETH67, LightSync) }
   548  
   549  func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
   550  	tester := newTester(t)
   551  	defer tester.terminate()
   552  
   553  	chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80)
   554  	chainB := testChainForkLightB.shorten(len(testChainBase.blocks) + 81)
   555  	tester.newPeer("fork A", protocol, chainA.blocks[1:])
   556  	tester.newPeer("fork B", protocol, chainB.blocks[1:])
   557  	// Synchronise with the peer and make sure all blocks were retrieved
   558  	if err := tester.sync("fork A", nil, mode); err != nil {
   559  		t.Fatalf("failed to synchronise blocks: %v", err)
   560  	}
   561  	assertOwnChain(t, tester, len(chainA.blocks))
   562  
   563  	// Synchronise with the second peer and make sure that fork is pulled too
   564  	if err := tester.sync("fork B", nil, mode); err != nil {
   565  		t.Fatalf("failed to synchronise blocks: %v", err)
   566  	}
   567  	assertOwnChain(t, tester, len(chainB.blocks))
   568  }
   569  
   570  // Tests that synchronising against a much shorter but much heavyer fork works
   571  // corrently and is not dropped.
   572  func TestHeavyForkedSync66Full(t *testing.T)  { testHeavyForkedSync(t, eth.ETH66, FullSync) }
   573  func TestHeavyForkedSync66Snap(t *testing.T)  { testHeavyForkedSync(t, eth.ETH66, SnapSync) }
   574  func TestHeavyForkedSync66Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, LightSync) }
   575  func TestHeavyForkedSync67Full(t *testing.T)  { testHeavyForkedSync(t, eth.ETH67, FullSync) }
   576  func TestHeavyForkedSync67Snap(t *testing.T)  { testHeavyForkedSync(t, eth.ETH67, SnapSync) }
   577  func TestHeavyForkedSync67Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH67, LightSync) }
   578  
   579  func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
   580  	tester := newTester(t)
   581  	defer tester.terminate()
   582  
   583  	chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80)
   584  	chainB := testChainForkHeavy.shorten(len(testChainBase.blocks) + 79)
   585  	tester.newPeer("light", protocol, chainA.blocks[1:])
   586  	tester.newPeer("heavy", protocol, chainB.blocks[1:])
   587  
   588  	// Synchronise with the peer and make sure all blocks were retrieved
   589  	if err := tester.sync("light", nil, mode); err != nil {
   590  		t.Fatalf("failed to synchronise blocks: %v", err)
   591  	}
   592  	assertOwnChain(t, tester, len(chainA.blocks))
   593  
   594  	// Synchronise with the second peer and make sure that fork is pulled too
   595  	if err := tester.sync("heavy", nil, mode); err != nil {
   596  		t.Fatalf("failed to synchronise blocks: %v", err)
   597  	}
   598  	assertOwnChain(t, tester, len(chainB.blocks))
   599  }
   600  
   601  // Tests that chain forks are contained within a certain interval of the current
   602  // chain head, ensuring that malicious peers cannot waste resources by feeding
   603  // long dead chains.
   604  func TestBoundedForkedSync66Full(t *testing.T)  { testBoundedForkedSync(t, eth.ETH66, FullSync) }
   605  func TestBoundedForkedSync66Snap(t *testing.T)  { testBoundedForkedSync(t, eth.ETH66, SnapSync) }
   606  func TestBoundedForkedSync66Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, LightSync) }
   607  func TestBoundedForkedSync67Full(t *testing.T)  { testBoundedForkedSync(t, eth.ETH67, FullSync) }
   608  func TestBoundedForkedSync67Snap(t *testing.T)  { testBoundedForkedSync(t, eth.ETH67, SnapSync) }
   609  func TestBoundedForkedSync67Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH67, LightSync) }
   610  
   611  func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
   612  	tester := newTester(t)
   613  	defer tester.terminate()
   614  
   615  	chainA := testChainForkLightA
   616  	chainB := testChainForkLightB
   617  	tester.newPeer("original", protocol, chainA.blocks[1:])
   618  	tester.newPeer("rewriter", protocol, chainB.blocks[1:])
   619  
   620  	// Synchronise with the peer and make sure all blocks were retrieved
   621  	if err := tester.sync("original", nil, mode); err != nil {
   622  		t.Fatalf("failed to synchronise blocks: %v", err)
   623  	}
   624  	assertOwnChain(t, tester, len(chainA.blocks))
   625  
   626  	// Synchronise with the second peer and ensure that the fork is rejected to being too old
   627  	if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
   628  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   629  	}
   630  }
   631  
   632  // Tests that chain forks are contained within a certain interval of the current
   633  // chain head for short but heavy forks too. These are a bit special because they
   634  // take different ancestor lookup paths.
   635  func TestBoundedHeavyForkedSync66Full(t *testing.T) {
   636  	testBoundedHeavyForkedSync(t, eth.ETH66, FullSync)
   637  }
   638  func TestBoundedHeavyForkedSync66Snap(t *testing.T) {
   639  	testBoundedHeavyForkedSync(t, eth.ETH66, SnapSync)
   640  }
   641  func TestBoundedHeavyForkedSync66Light(t *testing.T) {
   642  	testBoundedHeavyForkedSync(t, eth.ETH66, LightSync)
   643  }
   644  func TestBoundedHeavyForkedSync67Full(t *testing.T) {
   645  	testBoundedHeavyForkedSync(t, eth.ETH67, FullSync)
   646  }
   647  func TestBoundedHeavyForkedSync67Snap(t *testing.T) {
   648  	testBoundedHeavyForkedSync(t, eth.ETH67, SnapSync)
   649  }
   650  func TestBoundedHeavyForkedSync67Light(t *testing.T) {
   651  	testBoundedHeavyForkedSync(t, eth.ETH67, LightSync)
   652  }
   653  
   654  func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
   655  	tester := newTester(t)
   656  	defer tester.terminate()
   657  
   658  	// Create a long enough forked chain
   659  	chainA := testChainForkLightA
   660  	chainB := testChainForkHeavy
   661  	tester.newPeer("original", protocol, chainA.blocks[1:])
   662  
   663  	// Synchronise with the peer and make sure all blocks were retrieved
   664  	if err := tester.sync("original", nil, mode); err != nil {
   665  		t.Fatalf("failed to synchronise blocks: %v", err)
   666  	}
   667  	assertOwnChain(t, tester, len(chainA.blocks))
   668  
   669  	tester.newPeer("heavy-rewriter", protocol, chainB.blocks[1:])
   670  	// Synchronise with the second peer and ensure that the fork is rejected to being too old
   671  	if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
   672  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   673  	}
   674  }
   675  
   676  // Tests that a canceled download wipes all previously accumulated state.
   677  func TestCancel66Full(t *testing.T)  { testCancel(t, eth.ETH66, FullSync) }
   678  func TestCancel66Snap(t *testing.T)  { testCancel(t, eth.ETH66, SnapSync) }
   679  func TestCancel66Light(t *testing.T) { testCancel(t, eth.ETH66, LightSync) }
   680  func TestCancel67Full(t *testing.T)  { testCancel(t, eth.ETH67, FullSync) }
   681  func TestCancel67Snap(t *testing.T)  { testCancel(t, eth.ETH67, SnapSync) }
   682  func TestCancel67Light(t *testing.T) { testCancel(t, eth.ETH67, LightSync) }
   683  
   684  func testCancel(t *testing.T, protocol uint, mode SyncMode) {
   685  	tester := newTester(t)
   686  	defer tester.terminate()
   687  
   688  	chain := testChainBase.shorten(MaxHeaderFetch)
   689  	tester.newPeer("peer", protocol, chain.blocks[1:])
   690  
   691  	// Make sure canceling works with a pristine downloader
   692  	tester.downloader.Cancel()
   693  	if !tester.downloader.queue.Idle() {
   694  		t.Errorf("download queue not idle")
   695  	}
   696  	// Synchronise with the peer, but cancel afterwards
   697  	if err := tester.sync("peer", nil, mode); err != nil {
   698  		t.Fatalf("failed to synchronise blocks: %v", err)
   699  	}
   700  	tester.downloader.Cancel()
   701  	if !tester.downloader.queue.Idle() {
   702  		t.Errorf("download queue not idle")
   703  	}
   704  }
   705  
   706  // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
   707  func TestMultiSynchronisation66Full(t *testing.T)  { testMultiSynchronisation(t, eth.ETH66, FullSync) }
   708  func TestMultiSynchronisation66Snap(t *testing.T)  { testMultiSynchronisation(t, eth.ETH66, SnapSync) }
   709  func TestMultiSynchronisation66Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, LightSync) }
   710  func TestMultiSynchronisation67Full(t *testing.T)  { testMultiSynchronisation(t, eth.ETH67, FullSync) }
   711  func TestMultiSynchronisation67Snap(t *testing.T)  { testMultiSynchronisation(t, eth.ETH67, SnapSync) }
   712  func TestMultiSynchronisation67Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH67, LightSync) }
   713  
   714  func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
   715  	tester := newTester(t)
   716  	defer tester.terminate()
   717  
   718  	// Create various peers with various parts of the chain
   719  	targetPeers := 8
   720  	chain := testChainBase.shorten(targetPeers * 100)
   721  
   722  	for i := 0; i < targetPeers; i++ {
   723  		id := fmt.Sprintf("peer #%d", i)
   724  		tester.newPeer(id, protocol, chain.shorten(len(chain.blocks) / (i + 1)).blocks[1:])
   725  	}
   726  	if err := tester.sync("peer #0", nil, mode); err != nil {
   727  		t.Fatalf("failed to synchronise blocks: %v", err)
   728  	}
   729  	assertOwnChain(t, tester, len(chain.blocks))
   730  }
   731  
   732  // Tests that synchronisations behave well in multi-version protocol environments
   733  // and not wreak havoc on other nodes in the network.
   734  func TestMultiProtoSynchronisation66Full(t *testing.T)  { testMultiProtoSync(t, eth.ETH66, FullSync) }
   735  func TestMultiProtoSynchronisation66Snap(t *testing.T)  { testMultiProtoSync(t, eth.ETH66, SnapSync) }
   736  func TestMultiProtoSynchronisation66Light(t *testing.T) { testMultiProtoSync(t, eth.ETH66, LightSync) }
   737  func TestMultiProtoSynchronisation67Full(t *testing.T)  { testMultiProtoSync(t, eth.ETH67, FullSync) }
   738  func TestMultiProtoSynchronisation67Snap(t *testing.T)  { testMultiProtoSync(t, eth.ETH67, SnapSync) }
   739  func TestMultiProtoSynchronisation67Light(t *testing.T) { testMultiProtoSync(t, eth.ETH67, LightSync) }
   740  
   741  func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
   742  	tester := newTester(t)
   743  	defer tester.terminate()
   744  
   745  	// Create a small enough block chain to download
   746  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
   747  
   748  	// Create peers of every type
   749  	tester.newPeer("peer 66", eth.ETH66, chain.blocks[1:])
   750  	tester.newPeer("peer 67", eth.ETH67, chain.blocks[1:])
   751  
   752  	// Synchronise with the requested peer and make sure all blocks were retrieved
   753  	if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
   754  		t.Fatalf("failed to synchronise blocks: %v", err)
   755  	}
   756  	assertOwnChain(t, tester, len(chain.blocks))
   757  
   758  	// Check that no peers have been dropped off
   759  	for _, version := range []int{66, 67} {
   760  		peer := fmt.Sprintf("peer %d", version)
   761  		if _, ok := tester.peers[peer]; !ok {
   762  			t.Errorf("%s dropped", peer)
   763  		}
   764  	}
   765  }
   766  
   767  // Tests that if a block is empty (e.g. header only), no body request should be
   768  // made, and instead the header should be assembled into a whole block in itself.
   769  func TestEmptyShortCircuit66Full(t *testing.T)  { testEmptyShortCircuit(t, eth.ETH66, FullSync) }
   770  func TestEmptyShortCircuit66Snap(t *testing.T)  { testEmptyShortCircuit(t, eth.ETH66, SnapSync) }
   771  func TestEmptyShortCircuit66Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, LightSync) }
   772  func TestEmptyShortCircuit67Full(t *testing.T)  { testEmptyShortCircuit(t, eth.ETH67, FullSync) }
   773  func TestEmptyShortCircuit67Snap(t *testing.T)  { testEmptyShortCircuit(t, eth.ETH67, SnapSync) }
   774  func TestEmptyShortCircuit67Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH67, LightSync) }
   775  
   776  func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
   777  	tester := newTester(t)
   778  	defer tester.terminate()
   779  
   780  	// Create a block chain to download
   781  	chain := testChainBase
   782  	tester.newPeer("peer", protocol, chain.blocks[1:])
   783  
   784  	// Instrument the downloader to signal body requests
   785  	bodiesHave, receiptsHave := int32(0), int32(0)
   786  	tester.downloader.bodyFetchHook = func(headers []*types.Header) {
   787  		atomic.AddInt32(&bodiesHave, int32(len(headers)))
   788  	}
   789  	tester.downloader.receiptFetchHook = func(headers []*types.Header) {
   790  		atomic.AddInt32(&receiptsHave, int32(len(headers)))
   791  	}
   792  	// Synchronise with the peer and make sure all blocks were retrieved
   793  	if err := tester.sync("peer", nil, mode); err != nil {
   794  		t.Fatalf("failed to synchronise blocks: %v", err)
   795  	}
   796  	assertOwnChain(t, tester, len(chain.blocks))
   797  
   798  	// Validate the number of block bodies that should have been requested
   799  	bodiesNeeded, receiptsNeeded := 0, 0
   800  	for _, block := range chain.blocks[1:] {
   801  		if mode != LightSync && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
   802  			bodiesNeeded++
   803  		}
   804  	}
   805  	for _, block := range chain.blocks[1:] {
   806  		if mode == SnapSync && len(block.Transactions()) > 0 {
   807  			receiptsNeeded++
   808  		}
   809  	}
   810  	if int(bodiesHave) != bodiesNeeded {
   811  		t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
   812  	}
   813  	if int(receiptsHave) != receiptsNeeded {
   814  		t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
   815  	}
   816  }
   817  
   818  // Tests that headers are enqueued continuously, preventing malicious nodes from
   819  // stalling the downloader by feeding gapped header chains.
   820  func TestMissingHeaderAttack66Full(t *testing.T)  { testMissingHeaderAttack(t, eth.ETH66, FullSync) }
   821  func TestMissingHeaderAttack66Snap(t *testing.T)  { testMissingHeaderAttack(t, eth.ETH66, SnapSync) }
   822  func TestMissingHeaderAttack66Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, LightSync) }
   823  func TestMissingHeaderAttack67Full(t *testing.T)  { testMissingHeaderAttack(t, eth.ETH67, FullSync) }
   824  func TestMissingHeaderAttack67Snap(t *testing.T)  { testMissingHeaderAttack(t, eth.ETH67, SnapSync) }
   825  func TestMissingHeaderAttack67Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH67, LightSync) }
   826  
   827  func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
   828  	tester := newTester(t)
   829  	defer tester.terminate()
   830  
   831  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
   832  
   833  	attacker := tester.newPeer("attack", protocol, chain.blocks[1:])
   834  	attacker.withholdHeaders[chain.blocks[len(chain.blocks)/2-1].Hash()] = struct{}{}
   835  
   836  	if err := tester.sync("attack", nil, mode); err == nil {
   837  		t.Fatalf("succeeded attacker synchronisation")
   838  	}
   839  	// Synchronise with the valid peer and make sure sync succeeds
   840  	tester.newPeer("valid", protocol, chain.blocks[1:])
   841  	if err := tester.sync("valid", nil, mode); err != nil {
   842  		t.Fatalf("failed to synchronise blocks: %v", err)
   843  	}
   844  	assertOwnChain(t, tester, len(chain.blocks))
   845  }
   846  
   847  // Tests that if requested headers are shifted (i.e. first is missing), the queue
   848  // detects the invalid numbering.
   849  func TestShiftedHeaderAttack66Full(t *testing.T)  { testShiftedHeaderAttack(t, eth.ETH66, FullSync) }
   850  func TestShiftedHeaderAttack66Snap(t *testing.T)  { testShiftedHeaderAttack(t, eth.ETH66, SnapSync) }
   851  func TestShiftedHeaderAttack66Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, LightSync) }
   852  func TestShiftedHeaderAttack67Full(t *testing.T)  { testShiftedHeaderAttack(t, eth.ETH67, FullSync) }
   853  func TestShiftedHeaderAttack67Snap(t *testing.T)  { testShiftedHeaderAttack(t, eth.ETH67, SnapSync) }
   854  func TestShiftedHeaderAttack67Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH67, LightSync) }
   855  
   856  func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
   857  	tester := newTester(t)
   858  	defer tester.terminate()
   859  
   860  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
   861  
   862  	// Attempt a full sync with an attacker feeding shifted headers
   863  	attacker := tester.newPeer("attack", protocol, chain.blocks[1:])
   864  	attacker.withholdHeaders[chain.blocks[1].Hash()] = struct{}{}
   865  
   866  	if err := tester.sync("attack", nil, mode); err == nil {
   867  		t.Fatalf("succeeded attacker synchronisation")
   868  	}
   869  	// Synchronise with the valid peer and make sure sync succeeds
   870  	tester.newPeer("valid", protocol, chain.blocks[1:])
   871  	if err := tester.sync("valid", nil, mode); err != nil {
   872  		t.Fatalf("failed to synchronise blocks: %v", err)
   873  	}
   874  	assertOwnChain(t, tester, len(chain.blocks))
   875  }
   876  
   877  // Tests that upon detecting an invalid header, the recent ones are rolled back
   878  // for various failure scenarios. Afterwards a full sync is attempted to make
   879  // sure no state was corrupted.
   880  func TestInvalidHeaderRollback66Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH66, SnapSync) }
   881  func TestInvalidHeaderRollback67Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH67, SnapSync) }
   882  
   883  func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
   884  	tester := newTester(t)
   885  	defer tester.terminate()
   886  
   887  	// Create a small enough block chain to download
   888  	targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
   889  	chain := testChainBase.shorten(targetBlocks)
   890  
   891  	// Attempt to sync with an attacker that feeds junk during the fast sync phase.
   892  	// This should result in the last fsHeaderSafetyNet headers being rolled back.
   893  	missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
   894  
   895  	fastAttacker := tester.newPeer("fast-attack", protocol, chain.blocks[1:])
   896  	fastAttacker.withholdHeaders[chain.blocks[missing].Hash()] = struct{}{}
   897  
   898  	if err := tester.sync("fast-attack", nil, mode); err == nil {
   899  		t.Fatalf("succeeded fast attacker synchronisation")
   900  	}
   901  	if head := tester.chain.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
   902  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
   903  	}
   904  	// Attempt to sync with an attacker that feeds junk during the block import phase.
   905  	// This should result in both the last fsHeaderSafetyNet number of headers being
   906  	// rolled back, and also the pivot point being reverted to a non-block status.
   907  	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
   908  
   909  	blockAttacker := tester.newPeer("block-attack", protocol, chain.blocks[1:])
   910  	fastAttacker.withholdHeaders[chain.blocks[missing].Hash()] = struct{}{} // Make sure the fast-attacker doesn't fill in
   911  	blockAttacker.withholdHeaders[chain.blocks[missing].Hash()] = struct{}{}
   912  
   913  	if err := tester.sync("block-attack", nil, mode); err == nil {
   914  		t.Fatalf("succeeded block attacker synchronisation")
   915  	}
   916  	if head := tester.chain.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
   917  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
   918  	}
   919  	if mode == SnapSync {
   920  		if head := tester.chain.CurrentBlock().NumberU64(); head != 0 {
   921  			t.Errorf("fast sync pivot block #%d not rolled back", head)
   922  		}
   923  	}
   924  	// Attempt to sync with an attacker that withholds promised blocks after the
   925  	// fast sync pivot point. This could be a trial to leave the node with a bad
   926  	// but already imported pivot block.
   927  	withholdAttacker := tester.newPeer("withhold-attack", protocol, chain.blocks[1:])
   928  
   929  	tester.downloader.syncInitHook = func(uint64, uint64) {
   930  		for i := missing; i < len(chain.blocks); i++ {
   931  			withholdAttacker.withholdHeaders[chain.blocks[i].Hash()] = struct{}{}
   932  		}
   933  		tester.downloader.syncInitHook = nil
   934  	}
   935  	if err := tester.sync("withhold-attack", nil, mode); err == nil {
   936  		t.Fatalf("succeeded withholding attacker synchronisation")
   937  	}
   938  	if head := tester.chain.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
   939  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
   940  	}
   941  	if mode == SnapSync {
   942  		if head := tester.chain.CurrentBlock().NumberU64(); head != 0 {
   943  			t.Errorf("fast sync pivot block #%d not rolled back", head)
   944  		}
   945  	}
   946  	// Synchronise with the valid peer and make sure sync succeeds. Since the last rollback
   947  	// should also disable fast syncing for this process, verify that we did a fresh full
   948  	// sync. Note, we can't assert anything about the receipts since we won't purge the
   949  	// database of them, hence we can't use assertOwnChain.
   950  	tester.newPeer("valid", protocol, chain.blocks[1:])
   951  	if err := tester.sync("valid", nil, mode); err != nil {
   952  		t.Fatalf("failed to synchronise blocks: %v", err)
   953  	}
   954  	assertOwnChain(t, tester, len(chain.blocks))
   955  }
   956  
   957  // Tests that a peer advertising a high TD doesn't get to stall the downloader
   958  // afterwards by not sending any useful hashes.
   959  func TestHighTDStarvationAttack66Full(t *testing.T) {
   960  	testHighTDStarvationAttack(t, eth.ETH66, FullSync)
   961  }
   962  func TestHighTDStarvationAttack66Snap(t *testing.T) {
   963  	testHighTDStarvationAttack(t, eth.ETH66, SnapSync)
   964  }
   965  func TestHighTDStarvationAttack66Light(t *testing.T) {
   966  	testHighTDStarvationAttack(t, eth.ETH66, LightSync)
   967  }
   968  func TestHighTDStarvationAttack67Full(t *testing.T) {
   969  	testHighTDStarvationAttack(t, eth.ETH67, FullSync)
   970  }
   971  func TestHighTDStarvationAttack67Snap(t *testing.T) {
   972  	testHighTDStarvationAttack(t, eth.ETH67, SnapSync)
   973  }
   974  func TestHighTDStarvationAttack67Light(t *testing.T) {
   975  	testHighTDStarvationAttack(t, eth.ETH67, LightSync)
   976  }
   977  
   978  func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) {
   979  	tester := newTester(t)
   980  	defer tester.terminate()
   981  
   982  	chain := testChainBase.shorten(1)
   983  	tester.newPeer("attack", protocol, chain.blocks[1:])
   984  	if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
   985  		t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
   986  	}
   987  }
   988  
   989  // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
   990  func TestBlockHeaderAttackerDropping66(t *testing.T) { testBlockHeaderAttackerDropping(t, eth.ETH66) }
   991  func TestBlockHeaderAttackerDropping67(t *testing.T) { testBlockHeaderAttackerDropping(t, eth.ETH67) }
   992  
   993  func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
   994  	// Define the disconnection requirement for individual hash fetch errors
   995  	tests := []struct {
   996  		result error
   997  		drop   bool
   998  	}{
   999  		{nil, false},                        // Sync succeeded, all is well
  1000  		{errBusy, false},                    // Sync is already in progress, no problem
  1001  		{errUnknownPeer, false},             // Peer is unknown, was already dropped, don't double drop
  1002  		{errBadPeer, true},                  // Peer was deemed bad for some reason, drop it
  1003  		{errStallingPeer, true},             // Peer was detected to be stalling, drop it
  1004  		{errUnsyncedPeer, true},             // Peer was detected to be unsynced, drop it
  1005  		{errNoPeers, false},                 // No peers to download from, soft race, no issue
  1006  		{errTimeout, true},                  // No hashes received in due time, drop the peer
  1007  		{errEmptyHeaderSet, true},           // No headers were returned as a response, drop as it's a dead end
  1008  		{errPeersUnavailable, true},         // Nobody had the advertised blocks, drop the advertiser
  1009  		{errInvalidAncestor, true},          // Agreed upon ancestor is not acceptable, drop the chain rewriter
  1010  		{errInvalidChain, true},             // Hash chain was detected as invalid, definitely drop
  1011  		{errInvalidBody, false},             // A bad peer was detected, but not the sync origin
  1012  		{errInvalidReceipt, false},          // A bad peer was detected, but not the sync origin
  1013  		{errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1014  	}
  1015  	// Run the tests and check disconnection status
  1016  	tester := newTester(t)
  1017  	defer tester.terminate()
  1018  	chain := testChainBase.shorten(1)
  1019  
  1020  	for i, tt := range tests {
  1021  		// Register a new peer and ensure its presence
  1022  		id := fmt.Sprintf("test %d", i)
  1023  		tester.newPeer(id, protocol, chain.blocks[1:])
  1024  		if _, ok := tester.peers[id]; !ok {
  1025  			t.Fatalf("test %d: registered peer not found", i)
  1026  		}
  1027  		// Simulate a synchronisation and check the required result
  1028  		tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1029  
  1030  		tester.downloader.LegacySync(id, tester.chain.Genesis().Hash(), big.NewInt(1000), nil, FullSync)
  1031  		if _, ok := tester.peers[id]; !ok != tt.drop {
  1032  			t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1033  		}
  1034  	}
  1035  }
  1036  
  1037  // Tests that synchronisation progress (origin block number, current block number
  1038  // and highest block number) is tracked and updated correctly.
  1039  func TestSyncProgress66Full(t *testing.T)  { testSyncProgress(t, eth.ETH66, FullSync) }
  1040  func TestSyncProgress66Snap(t *testing.T)  { testSyncProgress(t, eth.ETH66, SnapSync) }
  1041  func TestSyncProgress66Light(t *testing.T) { testSyncProgress(t, eth.ETH66, LightSync) }
  1042  func TestSyncProgress67Full(t *testing.T)  { testSyncProgress(t, eth.ETH67, FullSync) }
  1043  func TestSyncProgress67Snap(t *testing.T)  { testSyncProgress(t, eth.ETH67, SnapSync) }
  1044  func TestSyncProgress67Light(t *testing.T) { testSyncProgress(t, eth.ETH67, LightSync) }
  1045  
  1046  func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1047  	tester := newTester(t)
  1048  	defer tester.terminate()
  1049  
  1050  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1051  
  1052  	// Set a sync init hook to catch progress changes
  1053  	starting := make(chan struct{})
  1054  	progress := make(chan struct{})
  1055  
  1056  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1057  		starting <- struct{}{}
  1058  		<-progress
  1059  	}
  1060  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1061  
  1062  	// Synchronise half the blocks and check initial progress
  1063  	tester.newPeer("peer-half", protocol, chain.shorten(len(chain.blocks) / 2).blocks[1:])
  1064  	pending := new(sync.WaitGroup)
  1065  	pending.Add(1)
  1066  
  1067  	go func() {
  1068  		defer pending.Done()
  1069  		if err := tester.sync("peer-half", nil, mode); err != nil {
  1070  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1071  		}
  1072  	}()
  1073  	<-starting
  1074  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1075  		HighestBlock: uint64(len(chain.blocks)/2 - 1),
  1076  	})
  1077  	progress <- struct{}{}
  1078  	pending.Wait()
  1079  
  1080  	// Synchronise all the blocks and check continuation progress
  1081  	tester.newPeer("peer-full", protocol, chain.blocks[1:])
  1082  	pending.Add(1)
  1083  	go func() {
  1084  		defer pending.Done()
  1085  		if err := tester.sync("peer-full", nil, mode); err != nil {
  1086  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1087  		}
  1088  	}()
  1089  	<-starting
  1090  	checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1091  		StartingBlock: uint64(len(chain.blocks)/2 - 1),
  1092  		CurrentBlock:  uint64(len(chain.blocks)/2 - 1),
  1093  		HighestBlock:  uint64(len(chain.blocks) - 1),
  1094  	})
  1095  
  1096  	// Check final progress after successful sync
  1097  	progress <- struct{}{}
  1098  	pending.Wait()
  1099  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1100  		StartingBlock: uint64(len(chain.blocks)/2 - 1),
  1101  		CurrentBlock:  uint64(len(chain.blocks) - 1),
  1102  		HighestBlock:  uint64(len(chain.blocks) - 1),
  1103  	})
  1104  }
  1105  
  1106  func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) {
  1107  	// Mark this method as a helper to report errors at callsite, not in here
  1108  	t.Helper()
  1109  
  1110  	p := d.Progress()
  1111  	if p.StartingBlock != want.StartingBlock || p.CurrentBlock != want.CurrentBlock || p.HighestBlock != want.HighestBlock {
  1112  		t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want)
  1113  	}
  1114  }
  1115  
  1116  // Tests that synchronisation progress (origin block number and highest block
  1117  // number) is tracked and updated correctly in case of a fork (or manual head
  1118  // revertal).
  1119  func TestForkedSyncProgress66Full(t *testing.T)  { testForkedSyncProgress(t, eth.ETH66, FullSync) }
  1120  func TestForkedSyncProgress66Snap(t *testing.T)  { testForkedSyncProgress(t, eth.ETH66, SnapSync) }
  1121  func TestForkedSyncProgress66Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, LightSync) }
  1122  func TestForkedSyncProgress67Full(t *testing.T)  { testForkedSyncProgress(t, eth.ETH67, FullSync) }
  1123  func TestForkedSyncProgress67Snap(t *testing.T)  { testForkedSyncProgress(t, eth.ETH67, SnapSync) }
  1124  func TestForkedSyncProgress67Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH67, LightSync) }
  1125  
  1126  func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1127  	tester := newTester(t)
  1128  	defer tester.terminate()
  1129  
  1130  	chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + MaxHeaderFetch)
  1131  	chainB := testChainForkLightB.shorten(len(testChainBase.blocks) + MaxHeaderFetch)
  1132  
  1133  	// Set a sync init hook to catch progress changes
  1134  	starting := make(chan struct{})
  1135  	progress := make(chan struct{})
  1136  
  1137  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1138  		starting <- struct{}{}
  1139  		<-progress
  1140  	}
  1141  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1142  
  1143  	// Synchronise with one of the forks and check progress
  1144  	tester.newPeer("fork A", protocol, chainA.blocks[1:])
  1145  	pending := new(sync.WaitGroup)
  1146  	pending.Add(1)
  1147  	go func() {
  1148  		defer pending.Done()
  1149  		if err := tester.sync("fork A", nil, mode); err != nil {
  1150  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1151  		}
  1152  	}()
  1153  	<-starting
  1154  
  1155  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1156  		HighestBlock: uint64(len(chainA.blocks) - 1),
  1157  	})
  1158  	progress <- struct{}{}
  1159  	pending.Wait()
  1160  
  1161  	// Simulate a successful sync above the fork
  1162  	tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1163  
  1164  	// Synchronise with the second fork and check progress resets
  1165  	tester.newPeer("fork B", protocol, chainB.blocks[1:])
  1166  	pending.Add(1)
  1167  	go func() {
  1168  		defer pending.Done()
  1169  		if err := tester.sync("fork B", nil, mode); err != nil {
  1170  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1171  		}
  1172  	}()
  1173  	<-starting
  1174  	checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{
  1175  		StartingBlock: uint64(len(testChainBase.blocks)) - 1,
  1176  		CurrentBlock:  uint64(len(chainA.blocks) - 1),
  1177  		HighestBlock:  uint64(len(chainB.blocks) - 1),
  1178  	})
  1179  
  1180  	// Check final progress after successful sync
  1181  	progress <- struct{}{}
  1182  	pending.Wait()
  1183  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1184  		StartingBlock: uint64(len(testChainBase.blocks)) - 1,
  1185  		CurrentBlock:  uint64(len(chainB.blocks) - 1),
  1186  		HighestBlock:  uint64(len(chainB.blocks) - 1),
  1187  	})
  1188  }
  1189  
  1190  // Tests that if synchronisation is aborted due to some failure, then the progress
  1191  // origin is not updated in the next sync cycle, as it should be considered the
  1192  // continuation of the previous sync and not a new instance.
  1193  func TestFailedSyncProgress66Full(t *testing.T)  { testFailedSyncProgress(t, eth.ETH66, FullSync) }
  1194  func TestFailedSyncProgress66Snap(t *testing.T)  { testFailedSyncProgress(t, eth.ETH66, SnapSync) }
  1195  func TestFailedSyncProgress66Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, LightSync) }
  1196  func TestFailedSyncProgress67Full(t *testing.T)  { testFailedSyncProgress(t, eth.ETH67, FullSync) }
  1197  func TestFailedSyncProgress67Snap(t *testing.T)  { testFailedSyncProgress(t, eth.ETH67, SnapSync) }
  1198  func TestFailedSyncProgress67Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH67, LightSync) }
  1199  
  1200  func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1201  	tester := newTester(t)
  1202  	defer tester.terminate()
  1203  
  1204  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1205  
  1206  	// Set a sync init hook to catch progress changes
  1207  	starting := make(chan struct{})
  1208  	progress := make(chan struct{})
  1209  
  1210  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1211  		starting <- struct{}{}
  1212  		<-progress
  1213  	}
  1214  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1215  
  1216  	// Attempt a full sync with a faulty peer
  1217  	missing := len(chain.blocks)/2 - 1
  1218  
  1219  	faulter := tester.newPeer("faulty", protocol, chain.blocks[1:])
  1220  	faulter.withholdHeaders[chain.blocks[missing].Hash()] = struct{}{}
  1221  
  1222  	pending := new(sync.WaitGroup)
  1223  	pending.Add(1)
  1224  	go func() {
  1225  		defer pending.Done()
  1226  		if err := tester.sync("faulty", nil, mode); err == nil {
  1227  			panic("succeeded faulty synchronisation")
  1228  		}
  1229  	}()
  1230  	<-starting
  1231  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1232  		HighestBlock: uint64(len(chain.blocks) - 1),
  1233  	})
  1234  	progress <- struct{}{}
  1235  	pending.Wait()
  1236  	afterFailedSync := tester.downloader.Progress()
  1237  
  1238  	// Synchronise with a good peer and check that the progress origin remind the same
  1239  	// after a failure
  1240  	tester.newPeer("valid", protocol, chain.blocks[1:])
  1241  	pending.Add(1)
  1242  	go func() {
  1243  		defer pending.Done()
  1244  		if err := tester.sync("valid", nil, mode); err != nil {
  1245  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1246  		}
  1247  	}()
  1248  	<-starting
  1249  	checkProgress(t, tester.downloader, "completing", afterFailedSync)
  1250  
  1251  	// Check final progress after successful sync
  1252  	progress <- struct{}{}
  1253  	pending.Wait()
  1254  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1255  		CurrentBlock: uint64(len(chain.blocks) - 1),
  1256  		HighestBlock: uint64(len(chain.blocks) - 1),
  1257  	})
  1258  }
  1259  
  1260  // Tests that if an attacker fakes a chain height, after the attack is detected,
  1261  // the progress height is successfully reduced at the next sync invocation.
  1262  func TestFakedSyncProgress66Full(t *testing.T)  { testFakedSyncProgress(t, eth.ETH66, FullSync) }
  1263  func TestFakedSyncProgress66Snap(t *testing.T)  { testFakedSyncProgress(t, eth.ETH66, SnapSync) }
  1264  func TestFakedSyncProgress66Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, LightSync) }
  1265  func TestFakedSyncProgress67Full(t *testing.T)  { testFakedSyncProgress(t, eth.ETH67, FullSync) }
  1266  func TestFakedSyncProgress67Snap(t *testing.T)  { testFakedSyncProgress(t, eth.ETH67, SnapSync) }
  1267  func TestFakedSyncProgress67Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH67, LightSync) }
  1268  
  1269  func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1270  	tester := newTester(t)
  1271  	defer tester.terminate()
  1272  
  1273  	chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1274  
  1275  	// Set a sync init hook to catch progress changes
  1276  	starting := make(chan struct{})
  1277  	progress := make(chan struct{})
  1278  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1279  		starting <- struct{}{}
  1280  		<-progress
  1281  	}
  1282  	checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1283  
  1284  	// Create and sync with an attacker that promises a higher chain than available.
  1285  	attacker := tester.newPeer("attack", protocol, chain.blocks[1:])
  1286  	numMissing := 5
  1287  	for i := len(chain.blocks) - 2; i > len(chain.blocks)-numMissing; i-- {
  1288  		attacker.withholdHeaders[chain.blocks[i].Hash()] = struct{}{}
  1289  	}
  1290  	pending := new(sync.WaitGroup)
  1291  	pending.Add(1)
  1292  	go func() {
  1293  		defer pending.Done()
  1294  		if err := tester.sync("attack", nil, mode); err == nil {
  1295  			panic("succeeded attacker synchronisation")
  1296  		}
  1297  	}()
  1298  	<-starting
  1299  	checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1300  		HighestBlock: uint64(len(chain.blocks) - 1),
  1301  	})
  1302  	progress <- struct{}{}
  1303  	pending.Wait()
  1304  	afterFailedSync := tester.downloader.Progress()
  1305  
  1306  	// Synchronise with a good peer and check that the progress height has been reduced to
  1307  	// the true value.
  1308  	validChain := chain.shorten(len(chain.blocks) - numMissing)
  1309  	tester.newPeer("valid", protocol, validChain.blocks[1:])
  1310  	pending.Add(1)
  1311  
  1312  	go func() {
  1313  		defer pending.Done()
  1314  		if err := tester.sync("valid", nil, mode); err != nil {
  1315  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1316  		}
  1317  	}()
  1318  	<-starting
  1319  	checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1320  		CurrentBlock: afterFailedSync.CurrentBlock,
  1321  		HighestBlock: uint64(len(validChain.blocks) - 1),
  1322  	})
  1323  	// Check final progress after successful sync.
  1324  	progress <- struct{}{}
  1325  	pending.Wait()
  1326  	checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1327  		CurrentBlock: uint64(len(validChain.blocks) - 1),
  1328  		HighestBlock: uint64(len(validChain.blocks) - 1),
  1329  	})
  1330  }
  1331  
  1332  func TestRemoteHeaderRequestSpan(t *testing.T) {
  1333  	testCases := []struct {
  1334  		remoteHeight uint64
  1335  		localHeight  uint64
  1336  		expected     []int
  1337  	}{
  1338  		// Remote is way higher. We should ask for the remote head and go backwards
  1339  		{1500, 1000,
  1340  			[]int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499},
  1341  		},
  1342  		{15000, 13006,
  1343  			[]int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999},
  1344  		},
  1345  		// Remote is pretty close to us. We don't have to fetch as many
  1346  		{1200, 1150,
  1347  			[]int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199},
  1348  		},
  1349  		// Remote is equal to us (so on a fork with higher td)
  1350  		// We should get the closest couple of ancestors
  1351  		{1500, 1500,
  1352  			[]int{1497, 1499},
  1353  		},
  1354  		// We're higher than the remote! Odd
  1355  		{1000, 1500,
  1356  			[]int{997, 999},
  1357  		},
  1358  		// Check some weird edgecases that it behaves somewhat rationally
  1359  		{0, 1500,
  1360  			[]int{0, 2},
  1361  		},
  1362  		{6000000, 0,
  1363  			[]int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999},
  1364  		},
  1365  		{0, 0,
  1366  			[]int{0, 2},
  1367  		},
  1368  	}
  1369  	reqs := func(from, count, span int) []int {
  1370  		var r []int
  1371  		num := from
  1372  		for len(r) < count {
  1373  			r = append(r, num)
  1374  			num += span + 1
  1375  		}
  1376  		return r
  1377  	}
  1378  	for i, tt := range testCases {
  1379  		from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight)
  1380  		data := reqs(int(from), count, span)
  1381  
  1382  		if max != uint64(data[len(data)-1]) {
  1383  			t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max)
  1384  		}
  1385  		failed := false
  1386  		if len(data) != len(tt.expected) {
  1387  			failed = true
  1388  			t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data))
  1389  		} else {
  1390  			for j, n := range data {
  1391  				if n != tt.expected[j] {
  1392  					failed = true
  1393  					break
  1394  				}
  1395  			}
  1396  		}
  1397  		if failed {
  1398  			res := strings.ReplaceAll(fmt.Sprint(data), " ", ",")
  1399  			exp := strings.ReplaceAll(fmt.Sprint(tt.expected), " ", ",")
  1400  			t.Logf("got: %v\n", res)
  1401  			t.Logf("exp: %v\n", exp)
  1402  			t.Errorf("test %d: wrong values", i)
  1403  		}
  1404  	}
  1405  }
  1406  
  1407  // Tests that peers below a pre-configured checkpoint block are prevented from
  1408  // being fast-synced from, avoiding potential cheap eclipse attacks.
  1409  func TestCheckpointEnforcement66Full(t *testing.T) { testCheckpointEnforcement(t, eth.ETH66, FullSync) }
  1410  func TestCheckpointEnforcement66Snap(t *testing.T) { testCheckpointEnforcement(t, eth.ETH66, SnapSync) }
  1411  func TestCheckpointEnforcement66Light(t *testing.T) {
  1412  	testCheckpointEnforcement(t, eth.ETH66, LightSync)
  1413  }
  1414  func TestCheckpointEnforcement67Full(t *testing.T) { testCheckpointEnforcement(t, eth.ETH67, FullSync) }
  1415  func TestCheckpointEnforcement67Snap(t *testing.T) { testCheckpointEnforcement(t, eth.ETH67, SnapSync) }
  1416  func TestCheckpointEnforcement67Light(t *testing.T) {
  1417  	testCheckpointEnforcement(t, eth.ETH67, LightSync)
  1418  }
  1419  
  1420  func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) {
  1421  	// Create a new tester with a particular hard coded checkpoint block
  1422  	tester := newTester(t)
  1423  	defer tester.terminate()
  1424  
  1425  	tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
  1426  	chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1)
  1427  
  1428  	// Attempt to sync with the peer and validate the result
  1429  	tester.newPeer("peer", protocol, chain.blocks[1:])
  1430  
  1431  	var expect error
  1432  	if mode == SnapSync || mode == LightSync {
  1433  		expect = errUnsyncedPeer
  1434  	}
  1435  	if err := tester.sync("peer", nil, mode); !errors.Is(err, expect) {
  1436  		t.Fatalf("block sync error mismatch: have %v, want %v", err, expect)
  1437  	}
  1438  	if mode == SnapSync || mode == LightSync {
  1439  		assertOwnChain(t, tester, 1)
  1440  	} else {
  1441  		assertOwnChain(t, tester, len(chain.blocks))
  1442  	}
  1443  }
  1444  
  1445  // Tests that peers below a pre-configured checkpoint block are prevented from
  1446  // being fast-synced from, avoiding potential cheap eclipse attacks.
  1447  func TestBeaconSync66Full(t *testing.T) { testBeaconSync(t, eth.ETH66, FullSync) }
  1448  func TestBeaconSync66Snap(t *testing.T) { testBeaconSync(t, eth.ETH66, SnapSync) }
  1449  
  1450  func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) {
  1451  	//log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
  1452  
  1453  	var cases = []struct {
  1454  		name  string // The name of testing scenario
  1455  		local int    // The length of local chain(canonical chain assumed), 0 means genesis is the head
  1456  	}{
  1457  		{name: "Beacon sync since genesis", local: 0},
  1458  		{name: "Beacon sync with short local chain", local: 1},
  1459  		{name: "Beacon sync with long local chain", local: blockCacheMaxItems - 15 - fsMinFullBlocks/2},
  1460  		{name: "Beacon sync with full local chain", local: blockCacheMaxItems - 15 - 1},
  1461  	}
  1462  	for _, c := range cases {
  1463  		t.Run(c.name, func(t *testing.T) {
  1464  			success := make(chan struct{})
  1465  			tester := newTesterWithNotification(t, func() {
  1466  				close(success)
  1467  			})
  1468  			defer tester.terminate()
  1469  
  1470  			chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1471  			tester.newPeer("peer", protocol, chain.blocks[1:])
  1472  
  1473  			// Build the local chain segment if it's required
  1474  			if c.local > 0 {
  1475  				tester.chain.InsertChain(chain.blocks[1 : c.local+1])
  1476  			}
  1477  			if err := tester.downloader.BeaconSync(mode, chain.blocks[len(chain.blocks)-1].Header()); err != nil {
  1478  				t.Fatalf("Failed to beacon sync chain %v %v", c.name, err)
  1479  			}
  1480  			select {
  1481  			case <-success:
  1482  				// Ok, downloader fully cancelled after sync cycle
  1483  				if bs := int(tester.chain.CurrentBlock().NumberU64()) + 1; bs != len(chain.blocks) {
  1484  					t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, len(chain.blocks))
  1485  				}
  1486  			case <-time.NewTimer(time.Second * 3).C:
  1487  				t.Fatalf("Failed to sync chain in three seconds")
  1488  			}
  1489  		})
  1490  	}
  1491  }