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