github.com/anthdm/go-ethereum@v1.8.4-0.20180412101906-60516c83b011/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.GenesisGasLimit}, 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), 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  
   188  		for _, hash := range hashes {
   189  			if block, ok := closure[hash]; ok {
   190  				transactions = append(transactions, block.Transactions())
   191  				uncles = append(uncles, block.Uncles())
   192  			}
   193  		}
   194  		// Return on a new thread
   195  		go f.fetcher.FilterBodies(peer, transactions, uncles, time.Now().Add(drift))
   196  
   197  		return nil
   198  	}
   199  }
   200  
   201  // verifyFetchingEvent verifies that one single event arrive on an fetching channel.
   202  func verifyFetchingEvent(t *testing.T, fetching chan []common.Hash, arrive bool) {
   203  	if arrive {
   204  		select {
   205  		case <-fetching:
   206  		case <-time.After(time.Second):
   207  			t.Fatalf("fetching timeout")
   208  		}
   209  	} else {
   210  		select {
   211  		case <-fetching:
   212  			t.Fatalf("fetching invoked")
   213  		case <-time.After(10 * time.Millisecond):
   214  		}
   215  	}
   216  }
   217  
   218  // verifyCompletingEvent verifies that one single event arrive on an completing channel.
   219  func verifyCompletingEvent(t *testing.T, completing chan []common.Hash, arrive bool) {
   220  	if arrive {
   221  		select {
   222  		case <-completing:
   223  		case <-time.After(time.Second):
   224  			t.Fatalf("completing timeout")
   225  		}
   226  	} else {
   227  		select {
   228  		case <-completing:
   229  			t.Fatalf("completing invoked")
   230  		case <-time.After(10 * time.Millisecond):
   231  		}
   232  	}
   233  }
   234  
   235  // verifyImportEvent verifies that one single event arrive on an import channel.
   236  func verifyImportEvent(t *testing.T, imported chan *types.Block, arrive bool) {
   237  	if arrive {
   238  		select {
   239  		case <-imported:
   240  		case <-time.After(time.Second):
   241  			t.Fatalf("import timeout")
   242  		}
   243  	} else {
   244  		select {
   245  		case <-imported:
   246  			t.Fatalf("import invoked")
   247  		case <-time.After(10 * time.Millisecond):
   248  		}
   249  	}
   250  }
   251  
   252  // verifyImportCount verifies that exactly count number of events arrive on an
   253  // import hook channel.
   254  func verifyImportCount(t *testing.T, imported chan *types.Block, count int) {
   255  	for i := 0; i < count; i++ {
   256  		select {
   257  		case <-imported:
   258  		case <-time.After(time.Second):
   259  			t.Fatalf("block %d: import timeout", i+1)
   260  		}
   261  	}
   262  	verifyImportDone(t, imported)
   263  }
   264  
   265  // verifyImportDone verifies that no more events are arriving on an import channel.
   266  func verifyImportDone(t *testing.T, imported chan *types.Block) {
   267  	select {
   268  	case <-imported:
   269  		t.Fatalf("extra block imported")
   270  	case <-time.After(50 * time.Millisecond):
   271  	}
   272  }
   273  
   274  // Tests that a fetcher accepts block announcements and initiates retrievals for
   275  // them, successfully importing into the local chain.
   276  func TestSequentialAnnouncements62(t *testing.T) { testSequentialAnnouncements(t, 62) }
   277  func TestSequentialAnnouncements63(t *testing.T) { testSequentialAnnouncements(t, 63) }
   278  func TestSequentialAnnouncements64(t *testing.T) { testSequentialAnnouncements(t, 64) }
   279  
   280  func testSequentialAnnouncements(t *testing.T, protocol int) {
   281  	// Create a chain of blocks to import
   282  	targetBlocks := 4 * hashLimit
   283  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   284  
   285  	tester := newTester()
   286  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   287  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   288  
   289  	// Iteratively announce blocks until all are imported
   290  	imported := make(chan *types.Block)
   291  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   292  
   293  	for i := len(hashes) - 2; i >= 0; i-- {
   294  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   295  		verifyImportEvent(t, imported, true)
   296  	}
   297  	verifyImportDone(t, imported)
   298  }
   299  
   300  // Tests that if blocks are announced by multiple peers (or even the same buggy
   301  // peer), they will only get downloaded at most once.
   302  func TestConcurrentAnnouncements62(t *testing.T) { testConcurrentAnnouncements(t, 62) }
   303  func TestConcurrentAnnouncements63(t *testing.T) { testConcurrentAnnouncements(t, 63) }
   304  func TestConcurrentAnnouncements64(t *testing.T) { testConcurrentAnnouncements(t, 64) }
   305  
   306  func testConcurrentAnnouncements(t *testing.T, protocol int) {
   307  	// Create a chain of blocks to import
   308  	targetBlocks := 4 * hashLimit
   309  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   310  
   311  	// Assemble a tester with a built in counter for the requests
   312  	tester := newTester()
   313  	firstHeaderFetcher := tester.makeHeaderFetcher("first", blocks, -gatherSlack)
   314  	firstBodyFetcher := tester.makeBodyFetcher("first", blocks, 0)
   315  	secondHeaderFetcher := tester.makeHeaderFetcher("second", blocks, -gatherSlack)
   316  	secondBodyFetcher := tester.makeBodyFetcher("second", blocks, 0)
   317  
   318  	counter := uint32(0)
   319  	firstHeaderWrapper := func(hash common.Hash) error {
   320  		atomic.AddUint32(&counter, 1)
   321  		return firstHeaderFetcher(hash)
   322  	}
   323  	secondHeaderWrapper := func(hash common.Hash) error {
   324  		atomic.AddUint32(&counter, 1)
   325  		return secondHeaderFetcher(hash)
   326  	}
   327  	// Iteratively announce blocks until all are imported
   328  	imported := make(chan *types.Block)
   329  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   330  
   331  	for i := len(hashes) - 2; i >= 0; i-- {
   332  		tester.fetcher.Notify("first", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), firstHeaderWrapper, firstBodyFetcher)
   333  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout+time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   334  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout-time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   335  		verifyImportEvent(t, imported, true)
   336  	}
   337  	verifyImportDone(t, imported)
   338  
   339  	// Make sure no blocks were retrieved twice
   340  	if int(counter) != targetBlocks {
   341  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, targetBlocks)
   342  	}
   343  }
   344  
   345  // Tests that announcements arriving while a previous is being fetched still
   346  // results in a valid import.
   347  func TestOverlappingAnnouncements62(t *testing.T) { testOverlappingAnnouncements(t, 62) }
   348  func TestOverlappingAnnouncements63(t *testing.T) { testOverlappingAnnouncements(t, 63) }
   349  func TestOverlappingAnnouncements64(t *testing.T) { testOverlappingAnnouncements(t, 64) }
   350  
   351  func testOverlappingAnnouncements(t *testing.T, protocol int) {
   352  	// Create a chain of blocks to import
   353  	targetBlocks := 4 * hashLimit
   354  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   355  
   356  	tester := newTester()
   357  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   358  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   359  
   360  	// Iteratively announce blocks, but overlap them continuously
   361  	overlap := 16
   362  	imported := make(chan *types.Block, len(hashes)-1)
   363  	for i := 0; i < overlap; i++ {
   364  		imported <- nil
   365  	}
   366  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   367  
   368  	for i := len(hashes) - 2; i >= 0; i-- {
   369  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   370  		select {
   371  		case <-imported:
   372  		case <-time.After(time.Second):
   373  			t.Fatalf("block %d: import timeout", len(hashes)-i)
   374  		}
   375  	}
   376  	// Wait for all the imports to complete and check count
   377  	verifyImportCount(t, imported, overlap)
   378  }
   379  
   380  // Tests that announces already being retrieved will not be duplicated.
   381  func TestPendingDeduplication62(t *testing.T) { testPendingDeduplication(t, 62) }
   382  func TestPendingDeduplication63(t *testing.T) { testPendingDeduplication(t, 63) }
   383  func TestPendingDeduplication64(t *testing.T) { testPendingDeduplication(t, 64) }
   384  
   385  func testPendingDeduplication(t *testing.T, protocol int) {
   386  	// Create a hash and corresponding block
   387  	hashes, blocks := makeChain(1, 0, genesis)
   388  
   389  	// Assemble a tester with a built in counter and delayed fetcher
   390  	tester := newTester()
   391  	headerFetcher := tester.makeHeaderFetcher("repeater", blocks, -gatherSlack)
   392  	bodyFetcher := tester.makeBodyFetcher("repeater", blocks, 0)
   393  
   394  	delay := 50 * time.Millisecond
   395  	counter := uint32(0)
   396  	headerWrapper := func(hash common.Hash) error {
   397  		atomic.AddUint32(&counter, 1)
   398  
   399  		// Simulate a long running fetch
   400  		go func() {
   401  			time.Sleep(delay)
   402  			headerFetcher(hash)
   403  		}()
   404  		return nil
   405  	}
   406  	// Announce the same block many times until it's fetched (wait for any pending ops)
   407  	for tester.getBlock(hashes[0]) == nil {
   408  		tester.fetcher.Notify("repeater", hashes[0], 1, time.Now().Add(-arriveTimeout), headerWrapper, bodyFetcher)
   409  		time.Sleep(time.Millisecond)
   410  	}
   411  	time.Sleep(delay)
   412  
   413  	// Check that all blocks were imported and none fetched twice
   414  	if imported := len(tester.blocks); imported != 2 {
   415  		t.Fatalf("synchronised block mismatch: have %v, want %v", imported, 2)
   416  	}
   417  	if int(counter) != 1 {
   418  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, 1)
   419  	}
   420  }
   421  
   422  // Tests that announcements retrieved in a random order are cached and eventually
   423  // imported when all the gaps are filled in.
   424  func TestRandomArrivalImport62(t *testing.T) { testRandomArrivalImport(t, 62) }
   425  func TestRandomArrivalImport63(t *testing.T) { testRandomArrivalImport(t, 63) }
   426  func TestRandomArrivalImport64(t *testing.T) { testRandomArrivalImport(t, 64) }
   427  
   428  func testRandomArrivalImport(t *testing.T, protocol int) {
   429  	// Create a chain of blocks to import, and choose one to delay
   430  	targetBlocks := maxQueueDist
   431  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   432  	skip := targetBlocks / 2
   433  
   434  	tester := newTester()
   435  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   436  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   437  
   438  	// Iteratively announce blocks, skipping one entry
   439  	imported := make(chan *types.Block, len(hashes)-1)
   440  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   441  
   442  	for i := len(hashes) - 1; i >= 0; i-- {
   443  		if i != skip {
   444  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   445  			time.Sleep(time.Millisecond)
   446  		}
   447  	}
   448  	// Finally announce the skipped entry and check full import
   449  	tester.fetcher.Notify("valid", hashes[skip], uint64(len(hashes)-skip-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   450  	verifyImportCount(t, imported, len(hashes)-1)
   451  }
   452  
   453  // Tests that direct block enqueues (due to block propagation vs. hash announce)
   454  // are correctly schedule, filling and import queue gaps.
   455  func TestQueueGapFill62(t *testing.T) { testQueueGapFill(t, 62) }
   456  func TestQueueGapFill63(t *testing.T) { testQueueGapFill(t, 63) }
   457  func TestQueueGapFill64(t *testing.T) { testQueueGapFill(t, 64) }
   458  
   459  func testQueueGapFill(t *testing.T, protocol int) {
   460  	// Create a chain of blocks to import, and choose one to not announce at all
   461  	targetBlocks := maxQueueDist
   462  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   463  	skip := targetBlocks / 2
   464  
   465  	tester := newTester()
   466  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   467  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   468  
   469  	// Iteratively announce blocks, skipping one entry
   470  	imported := make(chan *types.Block, len(hashes)-1)
   471  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   472  
   473  	for i := len(hashes) - 1; i >= 0; i-- {
   474  		if i != skip {
   475  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   476  			time.Sleep(time.Millisecond)
   477  		}
   478  	}
   479  	// Fill the missing block directly as if propagated
   480  	tester.fetcher.Enqueue("valid", blocks[hashes[skip]])
   481  	verifyImportCount(t, imported, len(hashes)-1)
   482  }
   483  
   484  // Tests that blocks arriving from various sources (multiple propagations, hash
   485  // announces, etc) do not get scheduled for import multiple times.
   486  func TestImportDeduplication62(t *testing.T) { testImportDeduplication(t, 62) }
   487  func TestImportDeduplication63(t *testing.T) { testImportDeduplication(t, 63) }
   488  func TestImportDeduplication64(t *testing.T) { testImportDeduplication(t, 64) }
   489  
   490  func testImportDeduplication(t *testing.T, protocol int) {
   491  	// Create two blocks to import (one for duplication, the other for stalling)
   492  	hashes, blocks := makeChain(2, 0, genesis)
   493  
   494  	// Create the tester and wrap the importer with a counter
   495  	tester := newTester()
   496  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   497  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   498  
   499  	counter := uint32(0)
   500  	tester.fetcher.insertChain = func(blocks types.Blocks) (int, error) {
   501  		atomic.AddUint32(&counter, uint32(len(blocks)))
   502  		return tester.insertChain(blocks)
   503  	}
   504  	// Instrument the fetching and imported events
   505  	fetching := make(chan []common.Hash)
   506  	imported := make(chan *types.Block, len(hashes)-1)
   507  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes }
   508  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   509  
   510  	// Announce the duplicating block, wait for retrieval, and also propagate directly
   511  	tester.fetcher.Notify("valid", hashes[0], 1, time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   512  	<-fetching
   513  
   514  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   515  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   516  	tester.fetcher.Enqueue("valid", blocks[hashes[0]])
   517  
   518  	// Fill the missing block directly as if propagated, and check import uniqueness
   519  	tester.fetcher.Enqueue("valid", blocks[hashes[1]])
   520  	verifyImportCount(t, imported, 2)
   521  
   522  	if counter != 2 {
   523  		t.Fatalf("import invocation count mismatch: have %v, want %v", counter, 2)
   524  	}
   525  }
   526  
   527  // Tests that blocks with numbers much lower or higher than out current head get
   528  // discarded to prevent wasting resources on useless blocks from faulty peers.
   529  func TestDistantPropagationDiscarding(t *testing.T) {
   530  	// Create a long chain to import and define the discard boundaries
   531  	hashes, blocks := makeChain(3*maxQueueDist, 0, genesis)
   532  	head := hashes[len(hashes)/2]
   533  
   534  	low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1
   535  
   536  	// Create a tester and simulate a head block being the middle of the above chain
   537  	tester := newTester()
   538  
   539  	tester.lock.Lock()
   540  	tester.hashes = []common.Hash{head}
   541  	tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
   542  	tester.lock.Unlock()
   543  
   544  	// Ensure that a block with a lower number than the threshold is discarded
   545  	tester.fetcher.Enqueue("lower", blocks[hashes[low]])
   546  	time.Sleep(10 * time.Millisecond)
   547  	if !tester.fetcher.queue.Empty() {
   548  		t.Fatalf("fetcher queued stale block")
   549  	}
   550  	// Ensure that a block with a higher number than the threshold is discarded
   551  	tester.fetcher.Enqueue("higher", blocks[hashes[high]])
   552  	time.Sleep(10 * time.Millisecond)
   553  	if !tester.fetcher.queue.Empty() {
   554  		t.Fatalf("fetcher queued future block")
   555  	}
   556  }
   557  
   558  // Tests that announcements with numbers much lower or higher than out current
   559  // head get discarded to prevent wasting resources on useless blocks from faulty
   560  // peers.
   561  func TestDistantAnnouncementDiscarding62(t *testing.T) { testDistantAnnouncementDiscarding(t, 62) }
   562  func TestDistantAnnouncementDiscarding63(t *testing.T) { testDistantAnnouncementDiscarding(t, 63) }
   563  func TestDistantAnnouncementDiscarding64(t *testing.T) { testDistantAnnouncementDiscarding(t, 64) }
   564  
   565  func testDistantAnnouncementDiscarding(t *testing.T, protocol int) {
   566  	// Create a long chain to import and define the discard boundaries
   567  	hashes, blocks := makeChain(3*maxQueueDist, 0, genesis)
   568  	head := hashes[len(hashes)/2]
   569  
   570  	low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1
   571  
   572  	// Create a tester and simulate a head block being the middle of the above chain
   573  	tester := newTester()
   574  
   575  	tester.lock.Lock()
   576  	tester.hashes = []common.Hash{head}
   577  	tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
   578  	tester.lock.Unlock()
   579  
   580  	headerFetcher := tester.makeHeaderFetcher("lower", blocks, -gatherSlack)
   581  	bodyFetcher := tester.makeBodyFetcher("lower", blocks, 0)
   582  
   583  	fetching := make(chan struct{}, 2)
   584  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- struct{}{} }
   585  
   586  	// Ensure that a block with a lower number than the threshold is discarded
   587  	tester.fetcher.Notify("lower", hashes[low], blocks[hashes[low]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   588  	select {
   589  	case <-time.After(50 * time.Millisecond):
   590  	case <-fetching:
   591  		t.Fatalf("fetcher requested stale header")
   592  	}
   593  	// Ensure that a block with a higher number than the threshold is discarded
   594  	tester.fetcher.Notify("higher", hashes[high], blocks[hashes[high]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   595  	select {
   596  	case <-time.After(50 * time.Millisecond):
   597  	case <-fetching:
   598  		t.Fatalf("fetcher requested future header")
   599  	}
   600  }
   601  
   602  // Tests that peers announcing blocks with invalid numbers (i.e. not matching
   603  // the headers provided afterwards) get dropped as malicious.
   604  func TestInvalidNumberAnnouncement62(t *testing.T) { testInvalidNumberAnnouncement(t, 62) }
   605  func TestInvalidNumberAnnouncement63(t *testing.T) { testInvalidNumberAnnouncement(t, 63) }
   606  func TestInvalidNumberAnnouncement64(t *testing.T) { testInvalidNumberAnnouncement(t, 64) }
   607  
   608  func testInvalidNumberAnnouncement(t *testing.T, protocol int) {
   609  	// Create a single block to import and check numbers against
   610  	hashes, blocks := makeChain(1, 0, genesis)
   611  
   612  	tester := newTester()
   613  	badHeaderFetcher := tester.makeHeaderFetcher("bad", blocks, -gatherSlack)
   614  	badBodyFetcher := tester.makeBodyFetcher("bad", blocks, 0)
   615  
   616  	imported := make(chan *types.Block)
   617  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   618  
   619  	// Announce a block with a bad number, check for immediate drop
   620  	tester.fetcher.Notify("bad", hashes[0], 2, time.Now().Add(-arriveTimeout), badHeaderFetcher, badBodyFetcher)
   621  	verifyImportEvent(t, imported, false)
   622  
   623  	tester.lock.RLock()
   624  	dropped := tester.drops["bad"]
   625  	tester.lock.RUnlock()
   626  
   627  	if !dropped {
   628  		t.Fatalf("peer with invalid numbered announcement not dropped")
   629  	}
   630  
   631  	goodHeaderFetcher := tester.makeHeaderFetcher("good", blocks, -gatherSlack)
   632  	goodBodyFetcher := tester.makeBodyFetcher("good", blocks, 0)
   633  	// Make sure a good announcement passes without a drop
   634  	tester.fetcher.Notify("good", hashes[0], 1, time.Now().Add(-arriveTimeout), goodHeaderFetcher, goodBodyFetcher)
   635  	verifyImportEvent(t, imported, true)
   636  
   637  	tester.lock.RLock()
   638  	dropped = tester.drops["good"]
   639  	tester.lock.RUnlock()
   640  
   641  	if dropped {
   642  		t.Fatalf("peer with valid numbered announcement dropped")
   643  	}
   644  	verifyImportDone(t, imported)
   645  }
   646  
   647  // Tests that if a block is empty (i.e. header only), no body request should be
   648  // made, and instead the header should be assembled into a whole block in itself.
   649  func TestEmptyBlockShortCircuit62(t *testing.T) { testEmptyBlockShortCircuit(t, 62) }
   650  func TestEmptyBlockShortCircuit63(t *testing.T) { testEmptyBlockShortCircuit(t, 63) }
   651  func TestEmptyBlockShortCircuit64(t *testing.T) { testEmptyBlockShortCircuit(t, 64) }
   652  
   653  func testEmptyBlockShortCircuit(t *testing.T, protocol int) {
   654  	// Create a chain of blocks to import
   655  	hashes, blocks := makeChain(32, 0, genesis)
   656  
   657  	tester := newTester()
   658  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   659  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   660  
   661  	// Add a monitoring hook for all internal events
   662  	fetching := make(chan []common.Hash)
   663  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes }
   664  
   665  	completing := make(chan []common.Hash)
   666  	tester.fetcher.completingHook = func(hashes []common.Hash) { completing <- hashes }
   667  
   668  	imported := make(chan *types.Block)
   669  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   670  
   671  	// Iteratively announce blocks until all are imported
   672  	for i := len(hashes) - 2; i >= 0; i-- {
   673  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   674  
   675  		// All announces should fetch the header
   676  		verifyFetchingEvent(t, fetching, true)
   677  
   678  		// Only blocks with data contents should request bodies
   679  		verifyCompletingEvent(t, completing, len(blocks[hashes[i]].Transactions()) > 0 || len(blocks[hashes[i]].Uncles()) > 0)
   680  
   681  		// Irrelevant of the construct, import should succeed
   682  		verifyImportEvent(t, imported, true)
   683  	}
   684  	verifyImportDone(t, imported)
   685  }
   686  
   687  // Tests that a peer is unable to use unbounded memory with sending infinite
   688  // block announcements to a node, but that even in the face of such an attack,
   689  // the fetcher remains operational.
   690  func TestHashMemoryExhaustionAttack62(t *testing.T) { testHashMemoryExhaustionAttack(t, 62) }
   691  func TestHashMemoryExhaustionAttack63(t *testing.T) { testHashMemoryExhaustionAttack(t, 63) }
   692  func TestHashMemoryExhaustionAttack64(t *testing.T) { testHashMemoryExhaustionAttack(t, 64) }
   693  
   694  func testHashMemoryExhaustionAttack(t *testing.T, protocol int) {
   695  	// Create a tester with instrumented import hooks
   696  	tester := newTester()
   697  
   698  	imported, announces := make(chan *types.Block), int32(0)
   699  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   700  	tester.fetcher.announceChangeHook = func(hash common.Hash, added bool) {
   701  		if added {
   702  			atomic.AddInt32(&announces, 1)
   703  		} else {
   704  			atomic.AddInt32(&announces, -1)
   705  		}
   706  	}
   707  	// Create a valid chain and an infinite junk chain
   708  	targetBlocks := hashLimit + 2*maxQueueDist
   709  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   710  	validHeaderFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   711  	validBodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   712  
   713  	attack, _ := makeChain(targetBlocks, 0, unknownBlock)
   714  	attackerHeaderFetcher := tester.makeHeaderFetcher("attacker", nil, -gatherSlack)
   715  	attackerBodyFetcher := tester.makeBodyFetcher("attacker", nil, 0)
   716  
   717  	// Feed the tester a huge hashset from the attacker, and a limited from the valid peer
   718  	for i := 0; i < len(attack); i++ {
   719  		if i < maxQueueDist {
   720  			tester.fetcher.Notify("valid", hashes[len(hashes)-2-i], uint64(i+1), time.Now(), validHeaderFetcher, validBodyFetcher)
   721  		}
   722  		tester.fetcher.Notify("attacker", attack[i], 1 /* don't distance drop */, time.Now(), attackerHeaderFetcher, attackerBodyFetcher)
   723  	}
   724  	if count := atomic.LoadInt32(&announces); count != hashLimit+maxQueueDist {
   725  		t.Fatalf("queued announce count mismatch: have %d, want %d", count, hashLimit+maxQueueDist)
   726  	}
   727  	// Wait for fetches to complete
   728  	verifyImportCount(t, imported, maxQueueDist)
   729  
   730  	// Feed the remaining valid hashes to ensure DOS protection state remains clean
   731  	for i := len(hashes) - maxQueueDist - 2; i >= 0; i-- {
   732  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), validHeaderFetcher, validBodyFetcher)
   733  		verifyImportEvent(t, imported, true)
   734  	}
   735  	verifyImportDone(t, imported)
   736  }
   737  
   738  // Tests that blocks sent to the fetcher (either through propagation or via hash
   739  // announces and retrievals) don't pile up indefinitely, exhausting available
   740  // system memory.
   741  func TestBlockMemoryExhaustionAttack(t *testing.T) {
   742  	// Create a tester with instrumented import hooks
   743  	tester := newTester()
   744  
   745  	imported, enqueued := make(chan *types.Block), int32(0)
   746  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   747  	tester.fetcher.queueChangeHook = func(hash common.Hash, added bool) {
   748  		if added {
   749  			atomic.AddInt32(&enqueued, 1)
   750  		} else {
   751  			atomic.AddInt32(&enqueued, -1)
   752  		}
   753  	}
   754  	// Create a valid chain and a batch of dangling (but in range) blocks
   755  	targetBlocks := hashLimit + 2*maxQueueDist
   756  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   757  	attack := make(map[common.Hash]*types.Block)
   758  	for i := byte(0); len(attack) < blockLimit+2*maxQueueDist; i++ {
   759  		hashes, blocks := makeChain(maxQueueDist-1, i, unknownBlock)
   760  		for _, hash := range hashes[:maxQueueDist-2] {
   761  			attack[hash] = blocks[hash]
   762  		}
   763  	}
   764  	// Try to feed all the attacker blocks make sure only a limited batch is accepted
   765  	for _, block := range attack {
   766  		tester.fetcher.Enqueue("attacker", block)
   767  	}
   768  	time.Sleep(200 * time.Millisecond)
   769  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit {
   770  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit)
   771  	}
   772  	// Queue up a batch of valid blocks, and check that a new peer is allowed to do so
   773  	for i := 0; i < maxQueueDist-1; i++ {
   774  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-3-i]])
   775  	}
   776  	time.Sleep(100 * time.Millisecond)
   777  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit+maxQueueDist-1 {
   778  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit+maxQueueDist-1)
   779  	}
   780  	// Insert the missing piece (and sanity check the import)
   781  	tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2]])
   782  	verifyImportCount(t, imported, maxQueueDist)
   783  
   784  	// Insert the remaining blocks in chunks to ensure clean DOS protection
   785  	for i := maxQueueDist; i < len(hashes)-1; i++ {
   786  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2-i]])
   787  		verifyImportEvent(t, imported, true)
   788  	}
   789  	verifyImportDone(t, imported)
   790  }