github.com/jimmyx0x/go-ethereum@v1.10.28/les/downloader/testchain_test.go (about)

     1  // Copyright 2018 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  	"sync"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/consensus/ethash"
    26  	"github.com/ethereum/go-ethereum/core"
    27  	"github.com/ethereum/go-ethereum/core/rawdb"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/params"
    31  )
    32  
    33  // Test chain parameters.
    34  var (
    35  	testKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    36  	testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
    37  	testDB      = rawdb.NewMemoryDatabase()
    38  
    39  	gspec = core.Genesis{
    40  		Alloc:   core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
    41  		BaseFee: big.NewInt(params.InitialBaseFee),
    42  	}
    43  	testGenesis = gspec.MustCommit(testDB)
    44  )
    45  
    46  // The common prefix of all test chains:
    47  var testChainBase = newTestChain(blockCacheMaxItems+200, testGenesis)
    48  
    49  // Different forks on top of the base chain:
    50  var testChainForkLightA, testChainForkLightB, testChainForkHeavy *testChain
    51  
    52  func init() {
    53  	var forkLen = int(fullMaxForkAncestry + 50)
    54  	var wg sync.WaitGroup
    55  	wg.Add(3)
    56  	go func() { testChainForkLightA = testChainBase.makeFork(forkLen, false, 1); wg.Done() }()
    57  	go func() { testChainForkLightB = testChainBase.makeFork(forkLen, false, 2); wg.Done() }()
    58  	go func() { testChainForkHeavy = testChainBase.makeFork(forkLen, true, 3); wg.Done() }()
    59  	wg.Wait()
    60  }
    61  
    62  type testChain struct {
    63  	genesis  *types.Block
    64  	chain    []common.Hash
    65  	headerm  map[common.Hash]*types.Header
    66  	blockm   map[common.Hash]*types.Block
    67  	receiptm map[common.Hash][]*types.Receipt
    68  	tdm      map[common.Hash]*big.Int
    69  }
    70  
    71  // newTestChain creates a blockchain of the given length.
    72  func newTestChain(length int, genesis *types.Block) *testChain {
    73  	tc := new(testChain).copy(length)
    74  	tc.genesis = genesis
    75  	tc.chain = append(tc.chain, genesis.Hash())
    76  	tc.headerm[tc.genesis.Hash()] = tc.genesis.Header()
    77  	tc.tdm[tc.genesis.Hash()] = tc.genesis.Difficulty()
    78  	tc.blockm[tc.genesis.Hash()] = tc.genesis
    79  	tc.generate(length-1, 0, genesis, false)
    80  	return tc
    81  }
    82  
    83  // makeFork creates a fork on top of the test chain.
    84  func (tc *testChain) makeFork(length int, heavy bool, seed byte) *testChain {
    85  	fork := tc.copy(tc.len() + length)
    86  	fork.generate(length, seed, tc.headBlock(), heavy)
    87  	return fork
    88  }
    89  
    90  // shorten creates a copy of the chain with the given length. It panics if the
    91  // length is longer than the number of available blocks.
    92  func (tc *testChain) shorten(length int) *testChain {
    93  	if length > tc.len() {
    94  		panic(fmt.Errorf("can't shorten test chain to %d blocks, it's only %d blocks long", length, tc.len()))
    95  	}
    96  	return tc.copy(length)
    97  }
    98  
    99  func (tc *testChain) copy(newlen int) *testChain {
   100  	cpy := &testChain{
   101  		genesis:  tc.genesis,
   102  		headerm:  make(map[common.Hash]*types.Header, newlen),
   103  		blockm:   make(map[common.Hash]*types.Block, newlen),
   104  		receiptm: make(map[common.Hash][]*types.Receipt, newlen),
   105  		tdm:      make(map[common.Hash]*big.Int, newlen),
   106  	}
   107  	for i := 0; i < len(tc.chain) && i < newlen; i++ {
   108  		hash := tc.chain[i]
   109  		cpy.chain = append(cpy.chain, tc.chain[i])
   110  		cpy.tdm[hash] = tc.tdm[hash]
   111  		cpy.blockm[hash] = tc.blockm[hash]
   112  		cpy.headerm[hash] = tc.headerm[hash]
   113  		cpy.receiptm[hash] = tc.receiptm[hash]
   114  	}
   115  	return cpy
   116  }
   117  
   118  // generate creates a chain of n blocks starting at and including parent.
   119  // the returned hash chain is ordered head->parent. In addition, every 22th block
   120  // contains a transaction and every 5th an uncle to allow testing correct block
   121  // reassembly.
   122  func (tc *testChain) generate(n int, seed byte, parent *types.Block, heavy bool) {
   123  	// start := time.Now()
   124  	// defer func() { fmt.Printf("test chain generated in %v\n", time.Since(start)) }()
   125  
   126  	blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) {
   127  		block.SetCoinbase(common.Address{seed})
   128  		// If a heavy chain is requested, delay blocks to raise difficulty
   129  		if heavy {
   130  			block.OffsetTime(-1)
   131  		}
   132  		// Include transactions to the miner to make blocks more interesting.
   133  		if parent == tc.genesis && i%22 == 0 {
   134  			signer := types.MakeSigner(params.TestChainConfig, block.Number())
   135  			tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey)
   136  			if err != nil {
   137  				panic(err)
   138  			}
   139  			block.AddTx(tx)
   140  		}
   141  		// if the block number is a multiple of 5, add a bonus uncle to the block
   142  		if i > 0 && i%5 == 0 {
   143  			block.AddUncle(&types.Header{
   144  				ParentHash: block.PrevBlock(i - 1).Hash(),
   145  				Number:     big.NewInt(block.Number().Int64() - 1),
   146  			})
   147  		}
   148  	})
   149  
   150  	// Convert the block-chain into a hash-chain and header/block maps
   151  	td := new(big.Int).Set(tc.td(parent.Hash()))
   152  	for i, b := range blocks {
   153  		td := td.Add(td, b.Difficulty())
   154  		hash := b.Hash()
   155  		tc.chain = append(tc.chain, hash)
   156  		tc.blockm[hash] = b
   157  		tc.headerm[hash] = b.Header()
   158  		tc.receiptm[hash] = receipts[i]
   159  		tc.tdm[hash] = new(big.Int).Set(td)
   160  	}
   161  }
   162  
   163  // len returns the total number of blocks in the chain.
   164  func (tc *testChain) len() int {
   165  	return len(tc.chain)
   166  }
   167  
   168  // headBlock returns the head of the chain.
   169  func (tc *testChain) headBlock() *types.Block {
   170  	return tc.blockm[tc.chain[len(tc.chain)-1]]
   171  }
   172  
   173  // td returns the total difficulty of the given block.
   174  func (tc *testChain) td(hash common.Hash) *big.Int {
   175  	return tc.tdm[hash]
   176  }
   177  
   178  // headersByHash returns headers in order from the given hash.
   179  func (tc *testChain) headersByHash(origin common.Hash, amount int, skip int, reverse bool) []*types.Header {
   180  	num, _ := tc.hashToNumber(origin)
   181  	return tc.headersByNumber(num, amount, skip, reverse)
   182  }
   183  
   184  // headersByNumber returns headers from the given number.
   185  func (tc *testChain) headersByNumber(origin uint64, amount int, skip int, reverse bool) []*types.Header {
   186  	result := make([]*types.Header, 0, amount)
   187  
   188  	if !reverse {
   189  		for num := origin; num < uint64(len(tc.chain)) && len(result) < amount; num += uint64(skip) + 1 {
   190  			if header, ok := tc.headerm[tc.chain[int(num)]]; ok {
   191  				result = append(result, header)
   192  			}
   193  		}
   194  	} else {
   195  		for num := int64(origin); num >= 0 && len(result) < amount; num -= int64(skip) + 1 {
   196  			if header, ok := tc.headerm[tc.chain[int(num)]]; ok {
   197  				result = append(result, header)
   198  			}
   199  		}
   200  	}
   201  	return result
   202  }
   203  
   204  // receipts returns the receipts of the given block hashes.
   205  func (tc *testChain) receipts(hashes []common.Hash) [][]*types.Receipt {
   206  	results := make([][]*types.Receipt, 0, len(hashes))
   207  	for _, hash := range hashes {
   208  		if receipt, ok := tc.receiptm[hash]; ok {
   209  			results = append(results, receipt)
   210  		}
   211  	}
   212  	return results
   213  }
   214  
   215  // bodies returns the block bodies of the given block hashes.
   216  func (tc *testChain) bodies(hashes []common.Hash) ([][]*types.Transaction, [][]*types.Header) {
   217  	transactions := make([][]*types.Transaction, 0, len(hashes))
   218  	uncles := make([][]*types.Header, 0, len(hashes))
   219  	for _, hash := range hashes {
   220  		if block, ok := tc.blockm[hash]; ok {
   221  			transactions = append(transactions, block.Transactions())
   222  			uncles = append(uncles, block.Uncles())
   223  		}
   224  	}
   225  	return transactions, uncles
   226  }
   227  
   228  func (tc *testChain) hashToNumber(target common.Hash) (uint64, bool) {
   229  	for num, hash := range tc.chain {
   230  		if hash == target {
   231  			return uint64(num), true
   232  		}
   233  	}
   234  	return 0, false
   235  }