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