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