github.com/aquanetwork/aquachain@v1.7.8/aqua/fetcher/fetcher_test.go (about)

     1  // Copyright 2015 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain 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  	"gitlab.com/aquachain/aquachain/aquadb"
    28  	"gitlab.com/aquachain/aquachain/common"
    29  	"gitlab.com/aquachain/aquachain/consensus/aquahash"
    30  	"gitlab.com/aquachain/aquachain/core"
    31  	"gitlab.com/aquachain/aquachain/core/types"
    32  	"gitlab.com/aquachain/aquachain/crypto"
    33  	"gitlab.com/aquachain/aquachain/params"
    34  )
    35  
    36  var (
    37  	testdb       = aquadb.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, aquahash.NewFaker(), testdb, n, func(i int, block *core.BlockGen) {
    50  		block.SetCoinbase(common.Address{seed})
    51  		block.SetVersion(params.TestChainConfig.GetBlockVersion(block.Number()))
    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(params.TestChainConfig.GetBlockVersion, 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 TestSequentialAnnouncements64(t *testing.T) { testSequentialAnnouncements(t, 64) }
   277  func TestSequentialAnnouncements65(t *testing.T) { testSequentialAnnouncements(t, 65) }
   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("valid", blocks, -gatherSlack)
   286  	bodyFetcher := tester.makeBodyFetcher("valid", 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 TestConcurrentAnnouncements64(t *testing.T) { testConcurrentAnnouncements(t, 64) }
   302  func TestConcurrentAnnouncements65(t *testing.T) { testConcurrentAnnouncements(t, 65) }
   303  
   304  func testConcurrentAnnouncements(t *testing.T, protocol int) {
   305  	// Create a chain of blocks to import
   306  	targetBlocks := 4 * hashLimit
   307  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   308  
   309  	// Assemble a tester with a built in counter for the requests
   310  	tester := newTester()
   311  	firstHeaderFetcher := tester.makeHeaderFetcher("first", blocks, -gatherSlack)
   312  	firstBodyFetcher := tester.makeBodyFetcher("first", blocks, 0)
   313  	secondHeaderFetcher := tester.makeHeaderFetcher("second", blocks, -gatherSlack)
   314  	secondBodyFetcher := tester.makeBodyFetcher("second", blocks, 0)
   315  
   316  	counter := uint32(0)
   317  	firstHeaderWrapper := func(hash common.Hash) error {
   318  		atomic.AddUint32(&counter, 1)
   319  		return firstHeaderFetcher(hash)
   320  	}
   321  	secondHeaderWrapper := func(hash common.Hash) error {
   322  		atomic.AddUint32(&counter, 1)
   323  		return secondHeaderFetcher(hash)
   324  	}
   325  	// Iteratively announce blocks until all are imported
   326  	imported := make(chan *types.Block)
   327  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   328  
   329  	for i := len(hashes) - 2; i >= 0; i-- {
   330  		tester.fetcher.Notify("first", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), firstHeaderWrapper, firstBodyFetcher)
   331  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout+time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   332  		tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout-time.Millisecond), secondHeaderWrapper, secondBodyFetcher)
   333  		verifyImportEvent(t, imported, true)
   334  	}
   335  	verifyImportDone(t, imported)
   336  
   337  	// Make sure no blocks were retrieved twice
   338  	if int(counter) != targetBlocks {
   339  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, targetBlocks)
   340  	}
   341  }
   342  
   343  // Tests that announcements arriving while a previous is being fetched still
   344  // results in a valid import.
   345  func TestOverlappingAnnouncements64(t *testing.T) { testOverlappingAnnouncements(t, 64) }
   346  func TestOverlappingAnnouncements65(t *testing.T) { testOverlappingAnnouncements(t, 65) }
   347  
   348  func testOverlappingAnnouncements(t *testing.T, protocol int) {
   349  	// Create a chain of blocks to import
   350  	targetBlocks := 4 * hashLimit
   351  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   352  
   353  	tester := newTester()
   354  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   355  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   356  
   357  	// Iteratively announce blocks, but overlap them continuously
   358  	overlap := 16
   359  	imported := make(chan *types.Block, len(hashes)-1)
   360  	for i := 0; i < overlap; i++ {
   361  		imported <- nil
   362  	}
   363  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   364  
   365  	for i := len(hashes) - 2; i >= 0; i-- {
   366  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   367  		select {
   368  		case <-imported:
   369  		case <-time.After(time.Second):
   370  			t.Fatalf("block %d: import timeout", len(hashes)-i)
   371  		}
   372  	}
   373  	// Wait for all the imports to complete and check count
   374  	verifyImportCount(t, imported, overlap)
   375  }
   376  
   377  // Tests that announces already being retrieved will not be duplicated.
   378  func TestPendingDeduplication64(t *testing.T) { testPendingDeduplication(t, 64) }
   379  func TestPendingDeduplication65(t *testing.T) { testPendingDeduplication(t, 65) }
   380  
   381  func testPendingDeduplication(t *testing.T, protocol int) {
   382  	// Create a hash and corresponding block
   383  	hashes, blocks := makeChain(1, 0, genesis)
   384  
   385  	// Assemble a tester with a built in counter and delayed fetcher
   386  	tester := newTester()
   387  	headerFetcher := tester.makeHeaderFetcher("repeater", blocks, -gatherSlack)
   388  	bodyFetcher := tester.makeBodyFetcher("repeater", blocks, 0)
   389  
   390  	delay := 50 * time.Millisecond
   391  	counter := uint32(0)
   392  	headerWrapper := func(hash common.Hash) error {
   393  		atomic.AddUint32(&counter, 1)
   394  
   395  		// Simulate a long running fetch
   396  		go func() {
   397  			time.Sleep(delay)
   398  			headerFetcher(hash)
   399  		}()
   400  		return nil
   401  	}
   402  	// Announce the same block many times until it's fetched (wait for any pending ops)
   403  	for tester.getBlock(hashes[0]) == nil {
   404  		tester.fetcher.Notify("repeater", hashes[0], 1, time.Now().Add(-arriveTimeout), headerWrapper, bodyFetcher)
   405  		time.Sleep(time.Millisecond)
   406  	}
   407  	time.Sleep(delay)
   408  
   409  	// Check that all blocks were imported and none fetched twice
   410  	if imported := len(tester.blocks); imported != 2 {
   411  		t.Fatalf("synchronised block mismatch: have %v, want %v", imported, 2)
   412  	}
   413  	if int(counter) != 1 {
   414  		t.Fatalf("retrieval count mismatch: have %v, want %v", counter, 1)
   415  	}
   416  }
   417  
   418  // Tests that announcements retrieved in a random order are cached and eventually
   419  // imported when all the gaps are filled in.
   420  func TestRandomArrivalImport64(t *testing.T) { testRandomArrivalImport(t, 64) }
   421  func TestRandomArrivalImport65(t *testing.T) { testRandomArrivalImport(t, 65) }
   422  
   423  func testRandomArrivalImport(t *testing.T, protocol int) {
   424  	// Create a chain of blocks to import, and choose one to delay
   425  	targetBlocks := maxQueueDist
   426  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   427  	skip := targetBlocks / 2
   428  
   429  	tester := newTester()
   430  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   431  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   432  
   433  	// Iteratively announce blocks, skipping one entry
   434  	imported := make(chan *types.Block, len(hashes)-1)
   435  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   436  
   437  	for i := len(hashes) - 1; i >= 0; i-- {
   438  		if i != skip {
   439  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   440  			time.Sleep(time.Millisecond)
   441  		}
   442  	}
   443  	// Finally announce the skipped entry and check full import
   444  	tester.fetcher.Notify("valid", hashes[skip], uint64(len(hashes)-skip-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   445  	verifyImportCount(t, imported, len(hashes)-1)
   446  }
   447  
   448  // Tests that direct block enqueues (due to block propagation vs. hash announce)
   449  // are correctly schedule, filling and import queue gaps.
   450  func TestQueueGapFill64(t *testing.T) { testQueueGapFill(t, 64) }
   451  func TestQueueGapFill65(t *testing.T) { testQueueGapFill(t, 65) }
   452  
   453  func testQueueGapFill(t *testing.T, protocol int) {
   454  	// Create a chain of blocks to import, and choose one to not announce at all
   455  	targetBlocks := maxQueueDist
   456  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   457  	skip := targetBlocks / 2
   458  
   459  	tester := newTester()
   460  	headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   461  	bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   462  
   463  	// Iteratively announce blocks, skipping one entry
   464  	imported := make(chan *types.Block, len(hashes)-1)
   465  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   466  
   467  	for i := len(hashes) - 1; i >= 0; i-- {
   468  		if i != skip {
   469  			tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   470  			time.Sleep(time.Millisecond)
   471  		}
   472  	}
   473  	// Fill the missing block directly as if propagated
   474  	tester.fetcher.Enqueue("valid", blocks[hashes[skip]])
   475  	verifyImportCount(t, imported, len(hashes)-1)
   476  }
   477  
   478  // Tests that blocks arriving from various sources (multiple propagations, hash
   479  // announces, etc) do not get scheduled for import multiple times.
   480  func TestImportDeduplication64(t *testing.T) { testImportDeduplication(t, 64) }
   481  func TestImportDeduplication65(t *testing.T) { testImportDeduplication(t, 65) }
   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("valid", blocks, -gatherSlack)
   490  	bodyFetcher := tester.makeBodyFetcher("valid", 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 TestDistantAnnouncementDiscarding64(t *testing.T) { testDistantAnnouncementDiscarding(t, 64) }
   555  func TestDistantAnnouncementDiscarding65(t *testing.T) { testDistantAnnouncementDiscarding(t, 65) }
   556  
   557  func testDistantAnnouncementDiscarding(t *testing.T, protocol int) {
   558  	// Create a long chain to import and define the discard boundaries
   559  	hashes, blocks := makeChain(3*maxQueueDist, 0, genesis)
   560  	head := hashes[len(hashes)/2]
   561  
   562  	low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1
   563  
   564  	// Create a tester and simulate a head block being the middle of the above chain
   565  	tester := newTester()
   566  
   567  	tester.lock.Lock()
   568  	tester.hashes = []common.Hash{head}
   569  	tester.blocks = map[common.Hash]*types.Block{head: blocks[head]}
   570  	tester.lock.Unlock()
   571  
   572  	headerFetcher := tester.makeHeaderFetcher("lower", blocks, -gatherSlack)
   573  	bodyFetcher := tester.makeBodyFetcher("lower", blocks, 0)
   574  
   575  	fetching := make(chan struct{}, 2)
   576  	tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- struct{}{} }
   577  
   578  	// Ensure that a block with a lower number than the threshold is discarded
   579  	tester.fetcher.Notify("lower", hashes[low], blocks[hashes[low]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   580  	select {
   581  	case <-time.After(50 * time.Millisecond):
   582  	case <-fetching:
   583  		t.Fatalf("fetcher requested stale header")
   584  	}
   585  	// Ensure that a block with a higher number than the threshold is discarded
   586  	tester.fetcher.Notify("higher", hashes[high], blocks[hashes[high]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher)
   587  	select {
   588  	case <-time.After(50 * time.Millisecond):
   589  	case <-fetching:
   590  		t.Fatalf("fetcher requested future header")
   591  	}
   592  }
   593  
   594  // Tests that peers announcing blocks with invalid numbers (i.e. not matching
   595  // the headers provided afterwards) get dropped as malicious.
   596  func TestInvalidNumberAnnouncement64(t *testing.T) { testInvalidNumberAnnouncement(t, 64) }
   597  func TestInvalidNumberAnnouncement65(t *testing.T) { testInvalidNumberAnnouncement(t, 65) }
   598  
   599  func testInvalidNumberAnnouncement(t *testing.T, protocol int) {
   600  	// Create a single block to import and check numbers against
   601  	hashes, blocks := makeChain(1, 0, genesis)
   602  
   603  	tester := newTester()
   604  	badHeaderFetcher := tester.makeHeaderFetcher("bad", blocks, -gatherSlack)
   605  	badBodyFetcher := tester.makeBodyFetcher("bad", blocks, 0)
   606  
   607  	imported := make(chan *types.Block)
   608  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   609  
   610  	// Announce a block with a bad number, check for immediate drop
   611  	tester.fetcher.Notify("bad", hashes[0], 2, time.Now().Add(-arriveTimeout), badHeaderFetcher, badBodyFetcher)
   612  	verifyImportEvent(t, imported, false)
   613  
   614  	tester.lock.RLock()
   615  	dropped := tester.drops["bad"]
   616  	tester.lock.RUnlock()
   617  
   618  	if !dropped {
   619  		t.Fatalf("peer with invalid numbered announcement not dropped")
   620  	}
   621  
   622  	goodHeaderFetcher := tester.makeHeaderFetcher("good", blocks, -gatherSlack)
   623  	goodBodyFetcher := tester.makeBodyFetcher("good", blocks, 0)
   624  	// Make sure a good announcement passes without a drop
   625  	tester.fetcher.Notify("good", hashes[0], 1, time.Now().Add(-arriveTimeout), goodHeaderFetcher, goodBodyFetcher)
   626  	verifyImportEvent(t, imported, true)
   627  
   628  	tester.lock.RLock()
   629  	dropped = tester.drops["good"]
   630  	tester.lock.RUnlock()
   631  
   632  	if dropped {
   633  		t.Fatalf("peer with valid numbered announcement dropped")
   634  	}
   635  	verifyImportDone(t, imported)
   636  }
   637  
   638  // Tests that if a block is empty (i.e. header only), no body request should be
   639  // made, and instead the header should be assembled into a whole block in itself.
   640  func TestEmptyBlockShortCircuit64(t *testing.T) { testEmptyBlockShortCircuit(t, 64) }
   641  func TestEmptyBlockShortCircuit65(t *testing.T) { testEmptyBlockShortCircuit(t, 65) }
   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("valid", blocks, -gatherSlack)
   649  	bodyFetcher := tester.makeBodyFetcher("valid", 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 TestHashMemoryExhaustionAttack64(t *testing.T) { testHashMemoryExhaustionAttack(t, 64) }
   681  func TestHashMemoryExhaustionAttack65(t *testing.T) { testHashMemoryExhaustionAttack(t, 65) }
   682  
   683  func testHashMemoryExhaustionAttack(t *testing.T, protocol int) {
   684  	// Create a tester with instrumented import hooks
   685  	tester := newTester()
   686  
   687  	imported, announces := make(chan *types.Block), int32(0)
   688  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   689  	tester.fetcher.announceChangeHook = func(hash common.Hash, added bool) {
   690  		if added {
   691  			atomic.AddInt32(&announces, 1)
   692  		} else {
   693  			atomic.AddInt32(&announces, -1)
   694  		}
   695  	}
   696  	// Create a valid chain and an infinite junk chain
   697  	targetBlocks := hashLimit + 2*maxQueueDist
   698  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   699  	validHeaderFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack)
   700  	validBodyFetcher := tester.makeBodyFetcher("valid", blocks, 0)
   701  
   702  	attack, _ := makeChain(targetBlocks, 0, unknownBlock)
   703  	attackerHeaderFetcher := tester.makeHeaderFetcher("attacker", nil, -gatherSlack)
   704  	attackerBodyFetcher := tester.makeBodyFetcher("attacker", nil, 0)
   705  
   706  	// Feed the tester a huge hashset from the attacker, and a limited from the valid peer
   707  	for i := 0; i < len(attack); i++ {
   708  		if i < maxQueueDist {
   709  			tester.fetcher.Notify("valid", hashes[len(hashes)-2-i], uint64(i+1), time.Now(), validHeaderFetcher, validBodyFetcher)
   710  		}
   711  		tester.fetcher.Notify("attacker", attack[i], 1 /* don't distance drop */, time.Now(), attackerHeaderFetcher, attackerBodyFetcher)
   712  	}
   713  	if count := atomic.LoadInt32(&announces); count != hashLimit+maxQueueDist {
   714  		t.Fatalf("queued announce count mismatch: have %d, want %d", count, hashLimit+maxQueueDist)
   715  	}
   716  	// Wait for fetches to complete
   717  	verifyImportCount(t, imported, maxQueueDist)
   718  
   719  	// Feed the remaining valid hashes to ensure DOS protection state remains clean
   720  	for i := len(hashes) - maxQueueDist - 2; i >= 0; i-- {
   721  		tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), validHeaderFetcher, validBodyFetcher)
   722  		verifyImportEvent(t, imported, true)
   723  	}
   724  	verifyImportDone(t, imported)
   725  }
   726  
   727  // Tests that blocks sent to the fetcher (either through propagation or via hash
   728  // announces and retrievals) don't pile up indefinitely, exhausting available
   729  // system memory.
   730  func TestBlockMemoryExhaustionAttack(t *testing.T) {
   731  	// Create a tester with instrumented import hooks
   732  	tester := newTester()
   733  
   734  	imported, enqueued := make(chan *types.Block), int32(0)
   735  	tester.fetcher.importedHook = func(block *types.Block) { imported <- block }
   736  	tester.fetcher.queueChangeHook = func(hash common.Hash, added bool) {
   737  		if added {
   738  			atomic.AddInt32(&enqueued, 1)
   739  		} else {
   740  			atomic.AddInt32(&enqueued, -1)
   741  		}
   742  	}
   743  	// Create a valid chain and a batch of dangling (but in range) blocks
   744  	targetBlocks := hashLimit + 2*maxQueueDist
   745  	hashes, blocks := makeChain(targetBlocks, 0, genesis)
   746  	attack := make(map[common.Hash]*types.Block)
   747  	for i := byte(0); len(attack) < blockLimit+2*maxQueueDist; i++ {
   748  		hashes, blocks := makeChain(maxQueueDist-1, i, unknownBlock)
   749  		for _, hash := range hashes[:maxQueueDist-2] {
   750  			attack[hash] = blocks[hash]
   751  		}
   752  	}
   753  	// Try to feed all the attacker blocks make sure only a limited batch is accepted
   754  	for _, block := range attack {
   755  		tester.fetcher.Enqueue("attacker", block)
   756  	}
   757  	time.Sleep(200 * time.Millisecond)
   758  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit {
   759  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit)
   760  	}
   761  	// Queue up a batch of valid blocks, and check that a new peer is allowed to do so
   762  	for i := 0; i < maxQueueDist-1; i++ {
   763  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-3-i]])
   764  	}
   765  	time.Sleep(100 * time.Millisecond)
   766  	if queued := atomic.LoadInt32(&enqueued); queued != blockLimit+maxQueueDist-1 {
   767  		t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit+maxQueueDist-1)
   768  	}
   769  	// Insert the missing piece (and sanity check the import)
   770  	tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2]])
   771  	verifyImportCount(t, imported, maxQueueDist)
   772  
   773  	// Insert the remaining blocks in chunks to ensure clean DOS protection
   774  	for i := maxQueueDist; i < len(hashes)-1; i++ {
   775  		tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2-i]])
   776  		verifyImportEvent(t, imported, true)
   777  	}
   778  	verifyImportDone(t, imported)
   779  }