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