github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/eth/downloader/queue_test.go (about)

     1  // Copyright 2019 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 downloader
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"math/rand"
    23  	"sync"
    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/rawdb"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/log"
    33  	"github.com/ethereum/go-ethereum/params"
    34  	"github.com/ethereum/go-ethereum/trie"
    35  )
    36  
    37  var (
    38  	testdb  = rawdb.NewMemoryDatabase()
    39  	genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000000000))
    40  )
    41  
    42  // makeChain creates a chain of n blocks starting at and including parent.
    43  // the returned hash chain is ordered head->parent. In addition, every 3rd block
    44  // contains a transaction and every 5th an uncle to allow testing correct block
    45  // reassembly.
    46  func makeChain(n int, seed byte, parent *types.Block, empty bool) ([]*types.Block, []types.Receipts) {
    47  	blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testdb, n, func(i int, block *core.BlockGen) {
    48  		block.SetCoinbase(common.Address{seed})
    49  		// Add one tx to every secondblock
    50  		if !empty && i%2 == 0 {
    51  			signer := types.MakeSigner(params.TestChainConfig, block.Number())
    52  			tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey)
    53  			if err != nil {
    54  				panic(err)
    55  			}
    56  			block.AddTx(tx)
    57  		}
    58  	})
    59  	return blocks, receipts
    60  }
    61  
    62  type chainData struct {
    63  	blocks []*types.Block
    64  	offset int
    65  }
    66  
    67  var (
    68  	chain           *chainData
    69  	chainLongerFork *chainData
    70  	emptyChain      *chainData
    71  )
    72  
    73  func init() {
    74  	// Create a chain of blocks to import
    75  	targetBlocks := 128
    76  	blocks, _ := makeChain(targetBlocks, 0, genesis, false)
    77  	chain = &chainData{blocks, 0}
    78  
    79  	blocks, _ = makeChain(targetBlocks, 0, genesis, true)
    80  	emptyChain = &chainData{blocks, 0}
    81  
    82  	chainLongerForkBlocks, _ := makeChain(1024, 0, blocks[len(blocks)-1], false)
    83  	chainLongerFork = &chainData{chainLongerForkBlocks, 0}
    84  }
    85  
    86  func (chain *chainData) headers() []*types.Header {
    87  	hdrs := make([]*types.Header, len(chain.blocks))
    88  	for i, b := range chain.blocks {
    89  		hdrs[i] = b.Header()
    90  	}
    91  	return hdrs
    92  }
    93  
    94  func (chain *chainData) Len() int {
    95  	return len(chain.blocks)
    96  }
    97  
    98  func dummyPeer(id string) *peerConnection {
    99  	p := &peerConnection{
   100  		id:      id,
   101  		lacking: make(map[common.Hash]struct{}),
   102  	}
   103  	return p
   104  }
   105  
   106  func TestBasics(t *testing.T) {
   107  	numOfBlocks := len(emptyChain.blocks)
   108  	numOfReceipts := len(emptyChain.blocks) / 2
   109  
   110  	q := newQueue(10, 10)
   111  	if !q.Idle() {
   112  		t.Errorf("new queue should be idle")
   113  	}
   114  	q.Prepare(1, SnapSync)
   115  	if res := q.Results(false); len(res) != 0 {
   116  		t.Fatal("new queue should have 0 results")
   117  	}
   118  
   119  	// Schedule a batch of headers
   120  	headers := chain.headers()
   121  	hashes := make([]common.Hash, len(headers))
   122  	for i, header := range headers {
   123  		hashes[i] = header.Hash()
   124  	}
   125  	q.Schedule(headers, hashes, 1)
   126  	if q.Idle() {
   127  		t.Errorf("queue should not be idle")
   128  	}
   129  	if got, exp := q.PendingBodies(), chain.Len(); got != exp {
   130  		t.Errorf("wrong pending block count, got %d, exp %d", got, exp)
   131  	}
   132  	// Only non-empty receipts get added to task-queue
   133  	if got, exp := q.PendingReceipts(), 64; got != exp {
   134  		t.Errorf("wrong pending receipt count, got %d, exp %d", got, exp)
   135  	}
   136  	// Items are now queued for downloading, next step is that we tell the
   137  	// queue that a certain peer will deliver them for us
   138  	{
   139  		peer := dummyPeer("peer-1")
   140  		fetchReq, _, throttle := q.ReserveBodies(peer, 50)
   141  		if !throttle {
   142  			// queue size is only 10, so throttling should occur
   143  			t.Fatal("should throttle")
   144  		}
   145  		// But we should still get the first things to fetch
   146  		if got, exp := len(fetchReq.Headers), 5; got != exp {
   147  			t.Fatalf("expected %d requests, got %d", exp, got)
   148  		}
   149  		if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp {
   150  			t.Fatalf("expected header %d, got %d", exp, got)
   151  		}
   152  	}
   153  	if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got {
   154  		t.Errorf("expected block task queue to be %d, got %d", exp, got)
   155  	}
   156  	if exp, got := q.receiptTaskQueue.Size(), numOfReceipts; exp != got {
   157  		t.Errorf("expected receipt task queue to be %d, got %d", exp, got)
   158  	}
   159  	{
   160  		peer := dummyPeer("peer-2")
   161  		fetchReq, _, throttle := q.ReserveBodies(peer, 50)
   162  
   163  		// The second peer should hit throttling
   164  		if !throttle {
   165  			t.Fatalf("should not throttle")
   166  		}
   167  		// And not get any fetches at all, since it was throttled to begin with
   168  		if fetchReq != nil {
   169  			t.Fatalf("should have no fetches, got %d", len(fetchReq.Headers))
   170  		}
   171  	}
   172  	if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got {
   173  		t.Errorf("expected block task queue to be %d, got %d", exp, got)
   174  	}
   175  	if exp, got := q.receiptTaskQueue.Size(), numOfReceipts; exp != got {
   176  		t.Errorf("expected receipt task queue to be %d, got %d", exp, got)
   177  	}
   178  	{
   179  		// The receipt delivering peer should not be affected
   180  		// by the throttling of body deliveries
   181  		peer := dummyPeer("peer-3")
   182  		fetchReq, _, throttle := q.ReserveReceipts(peer, 50)
   183  		if !throttle {
   184  			// queue size is only 10, so throttling should occur
   185  			t.Fatal("should throttle")
   186  		}
   187  		// But we should still get the first things to fetch
   188  		if got, exp := len(fetchReq.Headers), 5; got != exp {
   189  			t.Fatalf("expected %d requests, got %d", exp, got)
   190  		}
   191  		if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp {
   192  			t.Fatalf("expected header %d, got %d", exp, got)
   193  		}
   194  
   195  	}
   196  	if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got {
   197  		t.Errorf("expected block task queue to be %d, got %d", exp, got)
   198  	}
   199  	if exp, got := q.receiptTaskQueue.Size(), numOfReceipts-5; exp != got {
   200  		t.Errorf("expected receipt task queue to be %d, got %d", exp, got)
   201  	}
   202  	if got, exp := q.resultCache.countCompleted(), 0; got != exp {
   203  		t.Errorf("wrong processable count, got %d, exp %d", got, exp)
   204  	}
   205  }
   206  
   207  func TestEmptyBlocks(t *testing.T) {
   208  	numOfBlocks := len(emptyChain.blocks)
   209  
   210  	q := newQueue(10, 10)
   211  
   212  	q.Prepare(1, SnapSync)
   213  
   214  	// Schedule a batch of headers
   215  	headers := emptyChain.headers()
   216  	hashes := make([]common.Hash, len(headers))
   217  	for i, header := range headers {
   218  		hashes[i] = header.Hash()
   219  	}
   220  	q.Schedule(headers, hashes, 1)
   221  	if q.Idle() {
   222  		t.Errorf("queue should not be idle")
   223  	}
   224  	if got, exp := q.PendingBodies(), len(emptyChain.blocks); got != exp {
   225  		t.Errorf("wrong pending block count, got %d, exp %d", got, exp)
   226  	}
   227  	if got, exp := q.PendingReceipts(), 0; got != exp {
   228  		t.Errorf("wrong pending receipt count, got %d, exp %d", got, exp)
   229  	}
   230  	// They won't be processable, because the fetchresults haven't been
   231  	// created yet
   232  	if got, exp := q.resultCache.countCompleted(), 0; got != exp {
   233  		t.Errorf("wrong processable count, got %d, exp %d", got, exp)
   234  	}
   235  
   236  	// Items are now queued for downloading, next step is that we tell the
   237  	// queue that a certain peer will deliver them for us
   238  	// That should trigger all of them to suddenly become 'done'
   239  	{
   240  		// Reserve blocks
   241  		peer := dummyPeer("peer-1")
   242  		fetchReq, _, _ := q.ReserveBodies(peer, 50)
   243  
   244  		// there should be nothing to fetch, blocks are empty
   245  		if fetchReq != nil {
   246  			t.Fatal("there should be no body fetch tasks remaining")
   247  		}
   248  
   249  	}
   250  	if q.blockTaskQueue.Size() != numOfBlocks-10 {
   251  		t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size())
   252  	}
   253  	if q.receiptTaskQueue.Size() != 0 {
   254  		t.Errorf("expected receipt task queue to be %d, got %d", 0, q.receiptTaskQueue.Size())
   255  	}
   256  	{
   257  		peer := dummyPeer("peer-3")
   258  		fetchReq, _, _ := q.ReserveReceipts(peer, 50)
   259  
   260  		// there should be nothing to fetch, blocks are empty
   261  		if fetchReq != nil {
   262  			t.Fatal("there should be no body fetch tasks remaining")
   263  		}
   264  	}
   265  	if q.blockTaskQueue.Size() != numOfBlocks-10 {
   266  		t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size())
   267  	}
   268  	if q.receiptTaskQueue.Size() != 0 {
   269  		t.Errorf("expected receipt task queue to be %d, got %d", 0, q.receiptTaskQueue.Size())
   270  	}
   271  	if got, exp := q.resultCache.countCompleted(), 10; got != exp {
   272  		t.Errorf("wrong processable count, got %d, exp %d", got, exp)
   273  	}
   274  }
   275  
   276  // XTestDelivery does some more extensive testing of events that happen,
   277  // blocks that become known and peers that make reservations and deliveries.
   278  // disabled since it's not really a unit-test, but can be executed to test
   279  // some more advanced scenarios
   280  func XTestDelivery(t *testing.T) {
   281  	// the outside network, holding blocks
   282  	blo, rec := makeChain(128, 0, genesis, false)
   283  	world := newNetwork()
   284  	world.receipts = rec
   285  	world.chain = blo
   286  	world.progress(10)
   287  	if false {
   288  		log.Root().SetHandler(log.StdoutHandler)
   289  
   290  	}
   291  	q := newQueue(10, 10)
   292  	var wg sync.WaitGroup
   293  	q.Prepare(1, SnapSync)
   294  	wg.Add(1)
   295  	go func() {
   296  		// deliver headers
   297  		defer wg.Done()
   298  		c := 1
   299  		for {
   300  			//fmt.Printf("getting headers from %d\n", c)
   301  			headers := world.headers(c)
   302  			hashes := make([]common.Hash, len(headers))
   303  			for i, header := range headers {
   304  				hashes[i] = header.Hash()
   305  			}
   306  			l := len(headers)
   307  			//fmt.Printf("scheduling %d headers, first %d last %d\n",
   308  			//	l, headers[0].Number.Uint64(), headers[len(headers)-1].Number.Uint64())
   309  			q.Schedule(headers, hashes, uint64(c))
   310  			c += l
   311  		}
   312  	}()
   313  	wg.Add(1)
   314  	go func() {
   315  		// collect results
   316  		defer wg.Done()
   317  		tot := 0
   318  		for {
   319  			res := q.Results(true)
   320  			tot += len(res)
   321  			fmt.Printf("got %d results, %d tot\n", len(res), tot)
   322  			// Now we can forget about these
   323  			world.forget(res[len(res)-1].Header.Number.Uint64())
   324  
   325  		}
   326  	}()
   327  	wg.Add(1)
   328  	go func() {
   329  		defer wg.Done()
   330  		// reserve body fetch
   331  		i := 4
   332  		for {
   333  			peer := dummyPeer(fmt.Sprintf("peer-%d", i))
   334  			f, _, _ := q.ReserveBodies(peer, rand.Intn(30))
   335  			if f != nil {
   336  				var (
   337  					emptyList []*types.Header
   338  					txset     [][]*types.Transaction
   339  					uncleset  [][]*types.Header
   340  				)
   341  				numToSkip := rand.Intn(len(f.Headers))
   342  				for _, hdr := range f.Headers[0 : len(f.Headers)-numToSkip] {
   343  					txset = append(txset, world.getTransactions(hdr.Number.Uint64()))
   344  					uncleset = append(uncleset, emptyList)
   345  				}
   346  				var (
   347  					txsHashes   = make([]common.Hash, len(txset))
   348  					uncleHashes = make([]common.Hash, len(uncleset))
   349  				)
   350  				hasher := trie.NewStackTrie(nil)
   351  				for i, txs := range txset {
   352  					txsHashes[i] = types.DeriveSha(types.Transactions(txs), hasher)
   353  				}
   354  				for i, uncles := range uncleset {
   355  					uncleHashes[i] = types.CalcUncleHash(uncles)
   356  				}
   357  				time.Sleep(100 * time.Millisecond)
   358  				_, err := q.DeliverBodies(peer.id, txset, txsHashes, uncleset, uncleHashes)
   359  				if err != nil {
   360  					fmt.Printf("delivered %d bodies %v\n", len(txset), err)
   361  				}
   362  			} else {
   363  				i++
   364  				time.Sleep(200 * time.Millisecond)
   365  			}
   366  		}
   367  	}()
   368  	go func() {
   369  		defer wg.Done()
   370  		// reserve receiptfetch
   371  		peer := dummyPeer("peer-3")
   372  		for {
   373  			f, _, _ := q.ReserveReceipts(peer, rand.Intn(50))
   374  			if f != nil {
   375  				var rcs [][]*types.Receipt
   376  				for _, hdr := range f.Headers {
   377  					rcs = append(rcs, world.getReceipts(hdr.Number.Uint64()))
   378  				}
   379  				hasher := trie.NewStackTrie(nil)
   380  				hashes := make([]common.Hash, len(rcs))
   381  				for i, receipt := range rcs {
   382  					hashes[i] = types.DeriveSha(types.Receipts(receipt), hasher)
   383  				}
   384  				_, err := q.DeliverReceipts(peer.id, rcs, hashes)
   385  				if err != nil {
   386  					fmt.Printf("delivered %d receipts %v\n", len(rcs), err)
   387  				}
   388  				time.Sleep(100 * time.Millisecond)
   389  			} else {
   390  				time.Sleep(200 * time.Millisecond)
   391  			}
   392  		}
   393  	}()
   394  	wg.Add(1)
   395  	go func() {
   396  		defer wg.Done()
   397  		for i := 0; i < 50; i++ {
   398  			time.Sleep(300 * time.Millisecond)
   399  			//world.tick()
   400  			//fmt.Printf("trying to progress\n")
   401  			world.progress(rand.Intn(100))
   402  		}
   403  		for i := 0; i < 50; i++ {
   404  			time.Sleep(2990 * time.Millisecond)
   405  
   406  		}
   407  	}()
   408  	wg.Add(1)
   409  	go func() {
   410  		defer wg.Done()
   411  		for {
   412  			time.Sleep(990 * time.Millisecond)
   413  			fmt.Printf("world block tip is %d\n",
   414  				world.chain[len(world.chain)-1].Header().Number.Uint64())
   415  			fmt.Println(q.Stats())
   416  		}
   417  	}()
   418  	wg.Wait()
   419  }
   420  
   421  func newNetwork() *network {
   422  	var l sync.RWMutex
   423  	return &network{
   424  		cond:   sync.NewCond(&l),
   425  		offset: 1, // block 1 is at blocks[0]
   426  	}
   427  }
   428  
   429  // represents the network
   430  type network struct {
   431  	offset   int
   432  	chain    []*types.Block
   433  	receipts []types.Receipts
   434  	lock     sync.RWMutex
   435  	cond     *sync.Cond
   436  }
   437  
   438  func (n *network) getTransactions(blocknum uint64) types.Transactions {
   439  	index := blocknum - uint64(n.offset)
   440  	return n.chain[index].Transactions()
   441  }
   442  func (n *network) getReceipts(blocknum uint64) types.Receipts {
   443  	index := blocknum - uint64(n.offset)
   444  	if got := n.chain[index].Header().Number.Uint64(); got != blocknum {
   445  		fmt.Printf("Err, got %d exp %d\n", got, blocknum)
   446  		panic("sd")
   447  	}
   448  	return n.receipts[index]
   449  }
   450  
   451  func (n *network) forget(blocknum uint64) {
   452  	index := blocknum - uint64(n.offset)
   453  	n.chain = n.chain[index:]
   454  	n.receipts = n.receipts[index:]
   455  	n.offset = int(blocknum)
   456  
   457  }
   458  func (n *network) progress(numBlocks int) {
   459  
   460  	n.lock.Lock()
   461  	defer n.lock.Unlock()
   462  	//fmt.Printf("progressing...\n")
   463  	newBlocks, newR := makeChain(numBlocks, 0, n.chain[len(n.chain)-1], false)
   464  	n.chain = append(n.chain, newBlocks...)
   465  	n.receipts = append(n.receipts, newR...)
   466  	n.cond.Broadcast()
   467  
   468  }
   469  
   470  func (n *network) headers(from int) []*types.Header {
   471  	numHeaders := 128
   472  	var hdrs []*types.Header
   473  	index := from - n.offset
   474  
   475  	for index >= len(n.chain) {
   476  		// wait for progress
   477  		n.cond.L.Lock()
   478  		//fmt.Printf("header going into wait\n")
   479  		n.cond.Wait()
   480  		index = from - n.offset
   481  		n.cond.L.Unlock()
   482  	}
   483  	n.lock.RLock()
   484  	defer n.lock.RUnlock()
   485  	for i, b := range n.chain[index:] {
   486  		hdrs = append(hdrs, b.Header())
   487  		if i >= numHeaders {
   488  			break
   489  		}
   490  	}
   491  	return hdrs
   492  }