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