github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/eth/fetcher/fetcher_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 fetcher
    18  
    19  import (
    20  	"errors"
    21  	"math/big"
    22  	"sync"
    23  	"sync/atomic"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/consensus/ethash"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/ethdb"
    33  	"github.com/ethereum/go-ethereum/params"
    34  )
    35  
    36  var (
    37  	testdb       = ethdb.NewMemDatabase()
    38  	testKey, _   = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    39  	testAddress  = crypto.PubkeyToAddress(testKey.PublicKey)
    40  	genesis      = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
    41  	unknownBlock = types.NewBlock(&types.Header{GasLimit: params.DefaultGasLimit}, nil, nil, nil, nil)
    42  )
    43  
    44  // makeChain creates a chain of n blocks starting at and including parent.
    45  // the returned hash chain is ordered head->parent. In addition, every 3rd block
    46  // contains a transaction and every 5th an uncle to allow testing correct block
    47  // reassembly.
    48  func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common.Hash]*types.Block) {
    49  	blocks, _ := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testdb, n, func(i int, block *core.BlockGen) {
    50  		block.SetCoinbase(common.Address{seed})
    51  
    52  		// If the block number is multiple of 3, send a bonus transaction to the miner
    53  		if parent == genesis && i%3 == 0 {
    54  			signer := types.MakeSigner(params.TestChainConfig, block.Number())
    55  			tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil, nil, nil, nil), signer, testKey)
    56  			if err != nil {
    57  				panic(err)
    58  			}
    59  			block.AddTx(tx)
    60  		}
    61  		// If the block number is a multiple of 5, add a bonus uncle to the block
    62  		if i%5 == 0 {
    63  			block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
    64  		}
    65  	})
    66  	hashes := make([]common.Hash, n+1)
    67  	hashes[len(hashes)-1] = parent.Hash()
    68  	blockm := make(map[common.Hash]*types.Block, n+1)
    69  	blockm[parent.Hash()] = parent
    70  	for i, b := range blocks {
    71  		hashes[len(hashes)-i-2] = b.Hash()
    72  		blockm[b.Hash()] = b
    73  	}
    74  	return hashes, blockm
    75  }
    76  
    77  // fetcherTester is a test simulator for mocking out local block chain.
    78  type fetcherTester struct {
    79  	fetcher *Fetcher
    80  
    81  	hashes []common.Hash                // Hash chain belonging to the tester
    82  	blocks map[common.Hash]*types.Block // Blocks belonging to the tester
    83  	drops  map[string]bool              // Map of peers dropped by the fetcher
    84  
    85  	lock sync.RWMutex
    86  }
    87  
    88  // newTester creates a new fetcher test mocker.
    89  func newTester() *fetcherTester {
    90  	tester := &fetcherTester{
    91  		hashes: []common.Hash{genesis.Hash()},
    92  		blocks: map[common.Hash]*types.Block{genesis.Hash(): genesis},
    93  		drops:  make(map[string]bool),
    94  	}
    95  	tester.fetcher = New(tester.getBlock, tester.verifyHeader, tester.broadcastBlock, tester.chainHeight, tester.insertChain, tester.dropPeer)
    96  	tester.fetcher.Start()
    97  
    98  	return tester
    99  }
   100  
   101  // getBlock retrieves a block from the tester's block chain.
   102  func (f *fetcherTester) getBlock(hash common.Hash) *types.Block {
   103  	f.lock.RLock()
   104  	defer f.lock.RUnlock()
   105  
   106  	return f.blocks[hash]
   107  }
   108  
   109  // verifyHeader is a nop placeholder for the block header verification.
   110  func (f *fetcherTester) verifyHeader(header *types.Header) error {
   111  	return nil
   112  }
   113  
   114  // broadcastBlock is a nop placeholder for the block broadcasting.
   115  func (f *fetcherTester) broadcastBlock(block *types.Block, propagate bool) {
   116  }
   117  
   118  // chainHeight retrieves the current height (block number) of the chain.
   119  func (f *fetcherTester) chainHeight() uint64 {
   120  	f.lock.RLock()
   121  	defer f.lock.RUnlock()
   122  
   123  	return f.blocks[f.hashes[len(f.hashes)-1]].NumberU64()
   124  }
   125  
   126  // insertChain injects a new blocks into the simulated chain.
   127  func (f *fetcherTester) insertChain(blocks types.Blocks) (int, error) {
   128  	f.lock.Lock()
   129  	defer f.lock.Unlock()
   130  
   131  	for i, block := range blocks {
   132  		// Make sure the parent in known
   133  		if _, ok := f.blocks[block.ParentHash()]; !ok {
   134  			return i, errors.New("unknown parent")
   135  		}
   136  		// Discard any new blocks if the same height already exists
   137  		if block.NumberU64() <= f.blocks[f.hashes[len(f.hashes)-1]].NumberU64() {
   138  			return i, nil
   139  		}
   140  		// Otherwise build our current chain
   141  		f.hashes = append(f.hashes, block.Hash())
   142  		f.blocks[block.Hash()] = block
   143  	}
   144  	return 0, nil
   145  }
   146  
   147  // dropPeer is an emulator for the peer removal, simply accumulating the various
   148  // peers dropped by the fetcher.
   149  func (f *fetcherTester) dropPeer(peer string) {
   150  	f.lock.Lock()
   151  	defer f.lock.Unlock()
   152  
   153  	f.drops[peer] = true
   154  }
   155  
   156  // makeHeaderFetcher retrieves a block header fetcher associated with a simulated peer.
   157  func (f *fetcherTester) makeHeaderFetcher(peer string, blocks map[common.Hash]*types.Block, drift time.Duration) headerRequesterFn {
   158  	closure := make(map[common.Hash]*types.Block)
   159  	for hash, block := range blocks {
   160  		closure[hash] = block
   161  	}
   162  	// Create a function that return a header from the closure
   163  	return func(hash common.Hash) error {
   164  		// Gather the blocks to return
   165  		headers := make([]*types.Header, 0, 1)
   166  		if block, ok := closure[hash]; ok {
   167  			headers = append(headers, block.Header())
   168  		}
   169  		// Return on a new thread
   170  		go f.fetcher.FilterHeaders(peer, headers, time.Now().Add(drift))
   171  
   172  		return nil
   173  	}
   174  }
   175  
   176  // makeBodyFetcher retrieves a block body fetcher associated with a simulated peer.
   177  func (f *fetcherTester) makeBodyFetcher(peer string, blocks map[common.Hash]*types.Block, drift time.Duration) bodyRequesterFn {
   178  	closure := make(map[common.Hash]*types.Block)
   179  	for hash, block := range blocks {
   180  		closure[hash] = block
   181  	}
   182  	// Create a function that returns blocks from the closure
   183  	return func(hashes []common.Hash) error {
   184  		// Gather the block bodies to return
   185  		transactions := make([][]*types.Transaction, 0, len(hashes))
   186  		uncles := make([][]*types.Header, 0, len(hashes))
   187  		randomness := make([]*types.Randomness, 0, len(hashes))
   188  		epochSnarkData := make([]*types.EpochSnarkData, 0, len(hashes))
   189  
   190  		for _, hash := range hashes {
   191  			if block, ok := closure[hash]; ok {
   192  				transactions = append(transactions, block.Transactions())
   193  				uncles = append(uncles, block.Uncles())
   194  				randomness = append(randomness, block.Randomness())
   195  				epochSnarkData = append(epochSnarkData, block.EpochSnarkData())
   196  			}
   197  		}
   198  		// Return on a new thread
   199  		go f.fetcher.FilterBodies(peer, transactions, uncles, randomness, epochSnarkData, time.Now().Add(drift))
   200  
   201  		return nil
   202  	}
   203  }
   204  
   205  // verifyFetchingEvent verifies that one single event arrive on a fetching channel.
   206  func verifyFetchingEvent(t *testing.T, fetching chan []common.Hash, arrive bool) {
   207  	if arrive {
   208  		select {
   209  		case <-fetching:
   210  		case <-time.After(time.Second):
   211  			t.Fatalf("fetching timeout")
   212  		}
   213  	} else {
   214  		select {
   215  		case <-fetching:
   216  			t.Fatalf("fetching invoked")
   217  		case <-time.After(10 * time.Millisecond):
   218  		}
   219  	}
   220  }
   221  
   222  // verifyCompletingEvent verifies that one single event arrive on an completing channel.
   223  func verifyCompletingEvent(t *testing.T, completing chan []common.Hash, arrive bool) {
   224  	if arrive {
   225  		select {
   226  		case <-completing:
   227  		case <-time.After(time.Second):
   228  			t.Fatalf("completing timeout")
   229  		}
   230  	} else {
   231  		select {
   232  		case <-completing:
   233  			t.Fatalf("completing invoked")
   234  		case <-time.After(10 * time.Millisecond):
   235  		}
   236  	}
   237  }
   238  
   239  // verifyImportEvent verifies that one single event arrive on an import channel.
   240  func verifyImportEvent(t *testing.T, imported chan *types.Block, arrive bool) {
   241  	if arrive {
   242  		select {
   243  		case <-imported:
   244  		case <-time.After(time.Second):
   245  			t.Fatalf("import timeout")
   246  		}
   247  	} else {
   248  		select {
   249  		case <-imported:
   250  			t.Fatalf("import invoked")
   251  		case <-time.After(10 * time.Millisecond):
   252  		}
   253  	}
   254  }
   255  
   256  // verifyImportCount verifies that exactly count number of events arrive on an
   257  // import hook channel.
   258  func verifyImportCount(t *testing.T, imported chan *types.Block, count int) {
   259  	for i := 0; i < count; i++ {
   260  		select {
   261  		case <-imported:
   262  		case <-time.After(time.Second):
   263  			t.Fatalf("block %d: import timeout", i+1)
   264  		}
   265  	}
   266  	verifyImportDone(t, imported)
   267  }
   268  
   269  // verifyImportDone verifies that no more events are arriving on an import channel.
   270  func verifyImportDone(t *testing.T, imported chan *types.Block) {
   271  	select {
   272  	case <-imported:
   273  		t.Fatalf("extra block imported")
   274  	case <-time.After(50 * time.Millisecond):
   275  	}
   276  }
   277  
   278  // Tests that a fetcher accepts block announcements and initiates retrievals for
   279  // them, successfully importing into the local chain.
   280  func TestSequentialAnnouncements62(t *testing.T) { testSequentialAnnouncements(t, 62) }
   281  func TestSequentialAnnouncements63(t *testing.T) { testSequentialAnnouncements(t, 63) }
   282  func TestSequentialAnnouncements64(t *testing.T) { testSequentialAnnouncements(t, 64) }
   283  
   284  func testSequentialAnnouncements(t *testing.T, protocol int) {
   285  	// Create a chain of blocks to import
   286  	targetBlocks := 4 * hashLimit
   287  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   288  
   289  	tester := newTester()
   290  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   291  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   292  
   293  	// Iteratively announce blocks until all are imported
   294  	imported := make(chan *types.Block)
   295  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   296  
   297  	for i := len(hashes) - 2; i >= 0; i-- {
   298  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   299  		verifyImportEvent(t, imported, true)
   300  	}
   301  	verifyImportDone(t, imported)
   302  }
   303  
   304  // Tests that if blocks are announced by multiple peers (or even the same buggy
   305  // peer), they will only get downloaded at most once.
   306  func TestConcurrentAnnouncements62(t *testing.T) { testConcurrentAnnouncements(t, 62) }
   307  func TestConcurrentAnnouncements63(t *testing.T) { testConcurrentAnnouncements(t, 63) }
   308  func TestConcurrentAnnouncements64(t *testing.T) { testConcurrentAnnouncements(t, 64) }
   309  
   310  func testConcurrentAnnouncements(t *testing.T, protocol int) {
   311  	// Create a chain of blocks to import
   312  	targetBlocks := 4 * hashLimit
   313  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   314  
   315  	// Assemble a tester with a built in counter for the requests
   316  	tester := newTester()
   317  	firstHeaderFetcher := tester.makeHeaderFetcher("first", blocks, -gatherSlack)
   318  	firstBodyFetcher := tester.makeBodyFetcher("first", blocks, 0)
   319  	secondHeaderFetcher := tester.makeHeaderFetcher("second", blocks, -gatherSlack)
   320  	secondBodyFetcher := tester.makeBodyFetcher("second", blocks, 0)
   321  
   322  	counter := uint32(0)
   323  	firstHeaderWrapper := func(hash common.Hash) error {
   324  		atomic.AddUint32(&counter, 1)
   325  		return firstHeaderFetcher(hash)
   326  	}
   327  	secondHeaderWrapper := func(hash common.Hash) error {
   328  		atomic.AddUint32(&counter, 1)
   329  		return secondHeaderFetcher(hash)
   330  	}
   331  	// Iteratively announce blocks until all are imported
   332  	imported := make(chan *types.Block)
   333  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   334  
   335  	for i := len(hashes) - 2; i >= 0; i-- {
   336  		tester.fetcher.Notify("first", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), firstHeaderWrapper, firstBodyFetcher)
   337  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout+time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   338  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout-time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   339  		verifyImportEvent(t, imported, true)
   340  	}
   341  	verifyImportDone(t, imported)
   342  
   343  	// Make sure no blocks were retrieved twice
   344  	if int(counter) != targetBlocks {
   345  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, targetBlocks)
   346  	}
   347  }
   348  
   349  // Tests that announcements arriving while a previous is being fetched still
   350  // results in a valid import.
   351  func TestOverlappingAnnouncements62(t *testing.T) { testOverlappingAnnouncements(t, 62) }
   352  func TestOverlappingAnnouncements63(t *testing.T) { testOverlappingAnnouncements(t, 63) }
   353  func TestOverlappingAnnouncements64(t *testing.T) { testOverlappingAnnouncements(t, 64) }
   354  
   355  func testOverlappingAnnouncements(t *testing.T, protocol int) {
   356  	// Create a chain of blocks to import
   357  	targetBlocks := 4 * hashLimit
   358  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   359  
   360  	tester := newTester()
   361  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   362  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   363  
   364  	// Iteratively announce blocks, but overlap them continuously
   365  	overlap := 16
   366  	imported := make(chan *types.Block, len(hashes)-1)
   367  	for i := 0; i < overlap; i++ {
   368  		imported <- nil
   369  	}
   370  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   371  
   372  	for i := len(hashes) - 2; i >= 0; i-- {
   373  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   374  		select {
   375  		case <-imported:
   376  		case <-time.After(time.Second):
   377  			t.Fatalf("block %d: import timeout", len(hashes)-i)
   378  		}
   379  	}
   380  	// Wait for all the imports to complete and check count
   381  	verifyImportCount(t, imported, overlap)
   382  }
   383  
   384  // Tests that announces already being retrieved will not be duplicated.
   385  func TestPendingDeduplication62(t *testing.T) { testPendingDeduplication(t, 62) }
   386  func TestPendingDeduplication63(t *testing.T) { testPendingDeduplication(t, 63) }
   387  func TestPendingDeduplication64(t *testing.T) { testPendingDeduplication(t, 64) }
   388  
   389  func testPendingDeduplication(t *testing.T, protocol int) {
   390  	// Create a hash and corresponding block
   391  	hashes, blocks := makeChain(1, 0, genesis)
   392  
   393  	// Assemble a tester with a built in counter and delayed fetcher
   394  	tester := newTester()
   395  	headerFetcher := tester.makeHeaderFetcher("repeater", blocks, -gatherSlack)
   396  	bodyFetcher := tester.makeBodyFetcher("repeater", blocks, 0)
   397  
   398  	delay := 50 * time.Millisecond
   399  	counter := uint32(0)
   400  	headerWrapper := func(hash common.Hash) error {
   401  		atomic.AddUint32(&counter, 1)
   402  
   403  		// Simulate a long running fetch
   404  		go func() {
   405  			time.Sleep(delay)
   406  			headerFetcher(hash)
   407  		}()
   408  		return nil
   409  	}
   410  	// Announce the same block many times until it's fetched (wait for any pending ops)
   411  	for tester.getBlock(hashes[0]) == nil {
   412  		tester.fetcher.Notify("repeater", hashes[0], 1, time.Now().Add(-arriveTimeout), headerWrapper, bodyFetcher)
   413  		time.Sleep(time.Millisecond)
   414  	}
   415  	time.Sleep(delay)
   416  
   417  	// Check that all blocks were imported and none fetched twice
   418  	if imported := len(tester.blocks); imported != 2 {
   419  		t.Fatalf("synchronised block mismatch: have %v, want %v", imported, 2)
   420  	}
   421  	if int(counter) != 1 {
   422  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, 1)
   423  	}
   424  }
   425  
   426  // Tests that announcements retrieved in a random order are cached and eventually
   427  // imported when all the gaps are filled in.
   428  func TestRandomArrivalImport62(t *testing.T) { testRandomArrivalImport(t, 62) }
   429  func TestRandomArrivalImport63(t *testing.T) { testRandomArrivalImport(t, 63) }
   430  func TestRandomArrivalImport64(t *testing.T) { testRandomArrivalImport(t, 64) }
   431  
   432  func testRandomArrivalImport(t *testing.T, protocol int) {
   433  	// Create a chain of blocks to import, and choose one to delay
   434  	targetBlocks := maxQueueDist
   435  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   436  	skip := targetBlocks / 2
   437  
   438  	tester := newTester()
   439  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   440  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   441  
   442  	// Iteratively announce blocks, skipping one entry
   443  	imported := make(chan *types.Block, len(hashes)-1)
   444  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   445  
   446  	for i := len(hashes) - 1; i >= 0; i-- {
   447  		if i != skip {
   448  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   449  			time.Sleep(time.Millisecond)
   450  		}
   451  	}
   452  	// Finally announce the skipped entry and check full import
   453  	tester.fetcher.Notify("valid", hashes[skip], uint64(len(hashes)-skip-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   454  	verifyImportCount(t, imported, len(hashes)-1)
   455  }
   456  
   457  // Tests that direct block enqueues (due to block propagation vs. hash announce)
   458  // are correctly schedule, filling and import queue gaps.
   459  func TestQueueGapFill62(t *testing.T) { testQueueGapFill(t, 62) }
   460  func TestQueueGapFill63(t *testing.T) { testQueueGapFill(t, 63) }
   461  func TestQueueGapFill64(t *testing.T) { testQueueGapFill(t, 64) }
   462  
   463  func testQueueGapFill(t *testing.T, protocol int) {
   464  	// Create a chain of blocks to import, and choose one to not announce at all
   465  	targetBlocks := maxQueueDist
   466  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   467  	skip := targetBlocks / 2
   468  
   469  	tester := newTester()
   470  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   471  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   472  
   473  	// Iteratively announce blocks, skipping one entry
   474  	imported := make(chan *types.Block, len(hashes)-1)
   475  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   476  
   477  	for i := len(hashes) - 1; i >= 0; i-- {
   478  		if i != skip {
   479  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   480  			time.Sleep(time.Millisecond)
   481  		}
   482  	}
   483  	// Fill the missing block directly as if propagated
   484  	tester.fetcher.Enqueue("valid", blocks[hashes[skip]])
   485  	verifyImportCount(t, imported, len(hashes)-1)
   486  }
   487  
   488  // Tests that blocks arriving from various sources (multiple propagations, hash
   489  // announces, etc) do not get scheduled for import multiple times.
   490  func TestImportDeduplication62(t *testing.T) { testImportDeduplication(t, 62) }
   491  func TestImportDeduplication63(t *testing.T) { testImportDeduplication(t, 63) }
   492  func TestImportDeduplication64(t *testing.T) { testImportDeduplication(t, 64) }
   493  
   494  func testImportDeduplication(t *testing.T, protocol int) {
   495  	// Create two blocks to import (one for duplication, the other for stalling)
   496  	hashes, blocks := makeChain(2, 0, genesis)
   497  
   498  	// Create the tester and wrap the importer with a counter
   499  	tester := newTester()
   500  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   501  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   502  
   503  	counter := uint32(0)
   504  	tester.fetcher.insertChain = func(blocks types.Blocks) (int, error) {
   505  		atomic.AddUint32(&counter, uint32(len(blocks)))
   506  		return tester.insertChain(blocks)
   507  	}
   508  	// Instrument the fetching and imported events
   509  	fetching := make(chan []common.Hash)
   510  	imported := make(chan *types.Block, len(hashes)-1)
   511  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes }
   512  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   513  
   514  	// Announce the duplicating block, wait for retrieval, and also propagate directly
   515  	tester.fetcher.Notify("valid", hashes[0], 1, time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   516  	<-fetching
   517  
   518  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   519  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   520  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   521  
   522  	// Fill the missing block directly as if propagated, and check import uniqueness
   523  	tester.fetcher.Enqueue("valid", blocks[hashes[1]])
   524  	verifyImportCount(t, imported, 2)
   525  
   526  	if counter != 2 {
   527  		t.Fatalf("import invocation count mismatch: have %v, want %v", counter, 2)
   528  	}
   529  }
   530  
   531  // Tests that blocks with numbers much lower or higher than out current head get
   532  // discarded to prevent wasting resources on useless blocks from faulty peers.
   533  func TestDistantPropagationDiscarding(t *testing.T) {
   534  	// Create a long chain to import and define the discard boundaries
   535  	hashes, blocks := makeChain(3*maxQueueDist, 0, genesis)
   536  	head := hashes[len(hashes)/2]
   537  
   538  	low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1
   539  
   540  	// Create a tester and simulate a head block being the middle of the above chain
   541  	tester := newTester()
   542  
   543  	tester.lock.Lock()
   544  	tester.hashes = []common.Hash{head}
   545  	tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
   546  	tester.lock.Unlock()
   547  
   548  	// Ensure that a block with a lower number than the threshold is discarded
   549  	tester.fetcher.Enqueue("lower", blocks[hashes[low]])
   550  	time.Sleep(10 * time.Millisecond)
   551  	if !tester.fetcher.queue.Empty() {
   552  		t.Fatalf("fetcher queued stale block")
   553  	}
   554  	// Ensure that a block with a higher number than the threshold is discarded
   555  	tester.fetcher.Enqueue("higher", blocks[hashes[high]])
   556  	time.Sleep(10 * time.Millisecond)
   557  	if !tester.fetcher.queue.Empty() {
   558  		t.Fatalf("fetcher queued future block")
   559  	}
   560  }
   561  
   562  // Tests that announcements with numbers much lower or higher than out current
   563  // head get discarded to prevent wasting resources on useless blocks from faulty
   564  // peers.
   565  func TestDistantAnnouncementDiscarding62(t *testing.T) { testDistantAnnouncementDiscarding(t, 62) }
   566  func TestDistantAnnouncementDiscarding63(t *testing.T) { testDistantAnnouncementDiscarding(t, 63) }
   567  func TestDistantAnnouncementDiscarding64(t *testing.T) { testDistantAnnouncementDiscarding(t, 64) }
   568  
   569  func testDistantAnnouncementDiscarding(t *testing.T, protocol int) {
   570  	// Create a long chain to import and define the discard boundaries
   571  	hashes, blocks := makeChain(3*maxQueueDist, 0, genesis)
   572  	head := hashes[len(hashes)/2]
   573  
   574  	low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1
   575  
   576  	// Create a tester and simulate a head block being the middle of the above chain
   577  	tester := newTester()
   578  
   579  	tester.lock.Lock()
   580  	tester.hashes = []common.Hash{head}
   581  	tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
   582  	tester.lock.Unlock()
   583  
   584  	headerFetcher := tester.makeHeaderFetcher("lower", blocks, -gatherSlack)
   585  	bodyFetcher := tester.makeBodyFetcher("lower", blocks, 0)
   586  
   587  	fetching := make(chan struct{}, 2)
   588  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- struct{}{} }
   589  
   590  	// Ensure that a block with a lower number than the threshold is discarded
   591  	tester.fetcher.Notify("lower", hashes[low], blocks[hashes[low]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   592  	select {
   593  	case <-time.After(50 * time.Millisecond):
   594  	case <-fetching:
   595  		t.Fatalf("fetcher requested stale header")
   596  	}
   597  	// Ensure that a block with a higher number than the threshold is discarded
   598  	tester.fetcher.Notify("higher", hashes[high], blocks[hashes[high]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   599  	select {
   600  	case <-time.After(50 * time.Millisecond):
   601  	case <-fetching:
   602  		t.Fatalf("fetcher requested future header")
   603  	}
   604  }
   605  
   606  // Tests that peers announcing blocks with invalid numbers (i.e. not matching
   607  // the headers provided afterwards) get dropped as malicious.
   608  func TestInvalidNumberAnnouncement62(t *testing.T) { testInvalidNumberAnnouncement(t, 62) }
   609  func TestInvalidNumberAnnouncement63(t *testing.T) { testInvalidNumberAnnouncement(t, 63) }
   610  func TestInvalidNumberAnnouncement64(t *testing.T) { testInvalidNumberAnnouncement(t, 64) }
   611  
   612  func testInvalidNumberAnnouncement(t *testing.T, protocol int) {
   613  	// Create a single block to import and check numbers against
   614  	hashes, blocks := makeChain(1, 0, genesis)
   615  
   616  	tester := newTester()
   617  	badHeaderFetcher := tester.makeHeaderFetcher("bad", blocks, -gatherSlack)
   618  	badBodyFetcher := tester.makeBodyFetcher("bad", blocks, 0)
   619  
   620  	imported := make(chan *types.Block)
   621  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   622  
   623  	// Announce a block with a bad number, check for immediate drop
   624  	tester.fetcher.Notify("bad", hashes[0], 2, time.Now().Add(-arriveTimeout), badHeaderFetcher, badBodyFetcher)
   625  	verifyImportEvent(t, imported, false)
   626  
   627  	tester.lock.RLock()
   628  	dropped := tester.drops["bad"]
   629  	tester.lock.RUnlock()
   630  
   631  	if !dropped {
   632  		t.Fatalf("peer with invalid numbered announcement not dropped")
   633  	}
   634  
   635  	goodHeaderFetcher := tester.makeHeaderFetcher("good", blocks, -gatherSlack)
   636  	goodBodyFetcher := tester.makeBodyFetcher("good", blocks, 0)
   637  	// Make sure a good announcement passes without a drop
   638  	tester.fetcher.Notify("good", hashes[0], 1, time.Now().Add(-arriveTimeout), goodHeaderFetcher, goodBodyFetcher)
   639  	verifyImportEvent(t, imported, true)
   640  
   641  	tester.lock.RLock()
   642  	dropped = tester.drops["good"]
   643  	tester.lock.RUnlock()
   644  
   645  	if dropped {
   646  		t.Fatalf("peer with valid numbered announcement dropped")
   647  	}
   648  	verifyImportDone(t, imported)
   649  }
   650  
   651  // Tests that a peer is unable to use unbounded memory with sending infinite
   652  // block announcements to a node, but that even in the face of such an attack,
   653  // the fetcher remains operational.
   654  func TestHashMemoryExhaustionAttack62(t *testing.T) { testHashMemoryExhaustionAttack(t, 62) }
   655  func TestHashMemoryExhaustionAttack63(t *testing.T) { testHashMemoryExhaustionAttack(t, 63) }
   656  func TestHashMemoryExhaustionAttack64(t *testing.T) { testHashMemoryExhaustionAttack(t, 64) }
   657  
   658  func testHashMemoryExhaustionAttack(t *testing.T, protocol int) {
   659  	// Create a tester with instrumented import hooks
   660  	tester := newTester()
   661  
   662  	imported, announces := make(chan *types.Block), int32(0)
   663  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   664  	tester.fetcher.announceChangeHook = func(hash common.Hash, added bool) {
   665  		if added {
   666  			atomic.AddInt32(&announces, 1)
   667  		} else {
   668  			atomic.AddInt32(&announces, -1)
   669  		}
   670  	}
   671  	// Create a valid chain and an infinite junk chain
   672  	targetBlocks := hashLimit + 2*maxQueueDist
   673  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   674  	validHeaderFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   675  	validBodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   676  
   677  	attack, _ := makeChain(targetBlocks, 0, unknownBlock)
   678  	attackerHeaderFetcher := tester.makeHeaderFetcher("attacker", nil, -gatherSlack)
   679  	attackerBodyFetcher := tester.makeBodyFetcher("attacker", nil, 0)
   680  
   681  	// Feed the tester a huge hashset from the attacker, and a limited from the valid peer
   682  	for i := 0; i < len(attack); i++ {
   683  		if i < maxQueueDist {
   684  			tester.fetcher.Notify("valid", hashes[len(hashes)-2-i], uint64(i+1), time.Now(), validHeaderFetcher, validBodyFetcher)
   685  		}
   686  		tester.fetcher.Notify("attacker", attack[i], 1 /* don't distance drop */, time.Now(), attackerHeaderFetcher, attackerBodyFetcher)
   687  	}
   688  	if count := atomic.LoadInt32(&announces); count != hashLimit+maxQueueDist {
   689  		t.Fatalf("queued announce count mismatch: have %d, want %d", count, hashLimit+maxQueueDist)
   690  	}
   691  	// Wait for fetches to complete
   692  	verifyImportCount(t, imported, maxQueueDist)
   693  
   694  	// Feed the remaining valid hashes to ensure DOS protection state remains clean
   695  	for i := len(hashes) - maxQueueDist - 2; i >= 0; i-- {
   696  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), validHeaderFetcher, validBodyFetcher)
   697  		verifyImportEvent(t, imported, true)
   698  	}
   699  	verifyImportDone(t, imported)
   700  }
   701  
   702  // Tests that blocks sent to the fetcher (either through propagation or via hash
   703  // announces and retrievals) don't pile up indefinitely, exhausting available
   704  // system memory.
   705  func TestBlockMemoryExhaustionAttack(t *testing.T) {
   706  	// Create a tester with instrumented import hooks
   707  	tester := newTester()
   708  
   709  	imported, enqueued := make(chan *types.Block), int32(0)
   710  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   711  	tester.fetcher.queueChangeHook = func(hash common.Hash, added bool) {
   712  		if added {
   713  			atomic.AddInt32(&enqueued, 1)
   714  		} else {
   715  			atomic.AddInt32(&enqueued, -1)
   716  		}
   717  	}
   718  	// Create a valid chain and a batch of dangling (but in range) blocks
   719  	targetBlocks := hashLimit + 2*maxQueueDist
   720  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   721  	attack := make(map[common.Hash]*types.Block)
   722  	for i := byte(0); len(attack) < blockLimit+2*maxQueueDist; i++ {
   723  		hashes, blocks := makeChain(maxQueueDist-1, i, unknownBlock)
   724  		for _, hash := range hashes[:maxQueueDist-2] {
   725  			attack[hash] = blocks[hash]
   726  		}
   727  	}
   728  	// Try to feed all the attacker blocks make sure only a limited batch is accepted
   729  	for _, block := range attack {
   730  		tester.fetcher.Enqueue("attacker", block)
   731  	}
   732  	time.Sleep(200 * time.Millisecond)
   733  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit {
   734  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit)
   735  	}
   736  	// Queue up a batch of valid blocks, and check that a new peer is allowed to do so
   737  	for i := 0; i < maxQueueDist-1; i++ {
   738  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-3-i]])
   739  	}
   740  	time.Sleep(100 * time.Millisecond)
   741  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit+maxQueueDist-1 {
   742  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit+maxQueueDist-1)
   743  	}
   744  	// Insert the missing piece (and sanity check the import)
   745  	tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2]])
   746  	verifyImportCount(t, imported, maxQueueDist)
   747  
   748  	// Insert the remaining blocks in chunks to ensure clean DOS protection
   749  	for i := maxQueueDist; i < len(hashes)-1; i++ {
   750  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2-i]])
   751  		verifyImportEvent(t, imported, true)
   752  	}
   753  	verifyImportDone(t, imported)
   754  }