gitee.com/moran666666/go-ubiq@v3.0.1+incompatible/core/chain_makers.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 core
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  
    23  	"github.com/ubiq/go-ubiq/common"
    24  	"github.com/ubiq/go-ubiq/consensus"
    25  	"github.com/ubiq/go-ubiq/core/state"
    26  	"github.com/ubiq/go-ubiq/core/types"
    27  	"github.com/ubiq/go-ubiq/core/vm"
    28  	"github.com/ubiq/go-ubiq/ethdb"
    29  	"github.com/ubiq/go-ubiq/params"
    30  )
    31  
    32  // BlockGen creates blocks for testing.
    33  // See GenerateChain for a detailed explanation.
    34  type BlockGen struct {
    35  	i       int
    36  	parent  *types.Block
    37  	chain   []*types.Block
    38  	header  *types.Header
    39  	statedb *state.StateDB
    40  
    41  	gasPool  *GasPool
    42  	txs      []*types.Transaction
    43  	receipts []*types.Receipt
    44  	uncles   []*types.Header
    45  
    46  	config *params.ChainConfig
    47  	engine consensus.Engine
    48  }
    49  
    50  // SetCoinbase sets the coinbase of the generated block.
    51  // It can be called at most once.
    52  func (b *BlockGen) SetCoinbase(addr common.Address) {
    53  	if b.gasPool != nil {
    54  		if len(b.txs) > 0 {
    55  			panic("coinbase must be set before adding transactions")
    56  		}
    57  		panic("coinbase can only be set once")
    58  	}
    59  	b.header.Coinbase = addr
    60  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    61  }
    62  
    63  // SetExtra sets the extra data field of the generated block.
    64  func (b *BlockGen) SetExtra(data []byte) {
    65  	b.header.Extra = data
    66  }
    67  
    68  // SetNonce sets the nonce field of the generated block.
    69  func (b *BlockGen) SetNonce(nonce types.BlockNonce) {
    70  	b.header.Nonce = nonce
    71  }
    72  
    73  // AddTx adds a transaction to the generated block. If no coinbase has
    74  // been set, the block's coinbase is set to the zero address.
    75  //
    76  // AddTx panics if the transaction cannot be executed. In addition to
    77  // the protocol-imposed limitations (gas limit, etc.), there are some
    78  // further limitations on the content of transactions that can be
    79  // added. Notably, contract code relying on the BLOCKHASH instruction
    80  // will panic during execution.
    81  func (b *BlockGen) AddTx(tx *types.Transaction) {
    82  	b.AddTxWithChain(nil, tx)
    83  }
    84  
    85  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
    86  // been set, the block's coinbase is set to the zero address.
    87  //
    88  // AddTxWithChain panics if the transaction cannot be executed. In addition to
    89  // the protocol-imposed limitations (gas limit, etc.), there are some
    90  // further limitations on the content of transactions that can be
    91  // added. If contract code relies on the BLOCKHASH instruction,
    92  // the block in chain will be returned.
    93  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
    94  	if b.gasPool == nil {
    95  		b.SetCoinbase(common.Address{})
    96  	}
    97  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
    98  	receipt, _, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
    99  	if err != nil {
   100  		panic(err)
   101  	}
   102  	b.txs = append(b.txs, tx)
   103  	b.receipts = append(b.receipts, receipt)
   104  }
   105  
   106  // Number returns the block number of the block being generated.
   107  func (b *BlockGen) Number() *big.Int {
   108  	return new(big.Int).Set(b.header.Number)
   109  }
   110  
   111  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   112  // backing transaction.
   113  //
   114  // AddUncheckedReceipt will cause consensus failures when used during real
   115  // chain processing. This is best used in conjunction with raw block insertion.
   116  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   117  	b.receipts = append(b.receipts, receipt)
   118  }
   119  
   120  // TxNonce returns the next valid transaction nonce for the
   121  // account at addr. It panics if the account does not exist.
   122  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   123  	if !b.statedb.Exist(addr) {
   124  		panic("account does not exist")
   125  	}
   126  	return b.statedb.GetNonce(addr)
   127  }
   128  
   129  // AddUncle adds an uncle header to the generated block.
   130  func (b *BlockGen) AddUncle(h *types.Header) {
   131  	b.uncles = append(b.uncles, h)
   132  }
   133  
   134  // PrevBlock returns a previously generated block by number. It panics if
   135  // num is greater or equal to the number of the block being generated.
   136  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   137  func (b *BlockGen) PrevBlock(index int) *types.Block {
   138  	if index >= b.i {
   139  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   140  	}
   141  	if index == -1 {
   142  		return b.parent
   143  	}
   144  	return b.chain[index]
   145  }
   146  
   147  // OffsetTime modifies the time instance of a block, implicitly changing its
   148  // associated difficulty. It's useful to test scenarios where forking is not
   149  // tied to chain length directly.
   150  func (b *BlockGen) OffsetTime(seconds int64) {
   151  	b.header.Time += uint64(seconds)
   152  	if b.header.Time <= b.parent.Header().Time {
   153  		panic("block time out of range")
   154  	}
   155  	chainreader := &fakeChainReader{config: b.config}
   156  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   157  }
   158  
   159  // GenerateChain creates a chain of n blocks. The first block's
   160  // parent will be the provided parent. db is used to store
   161  // intermediate states and should contain the parent's state trie.
   162  //
   163  // The generator function is called with a new block generator for
   164  // every block. Any transactions and uncles added to the generator
   165  // become part of the block. If gen is nil, the blocks will be empty
   166  // and their coinbase will be the zero address.
   167  //
   168  // Blocks created by GenerateChain do not contain valid proof of work
   169  // values. Inserting them into BlockChain requires use of FakePow or
   170  // a similar non-validating proof of work implementation.
   171  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   172  	if config == nil {
   173  		config = params.TestChainConfig
   174  	}
   175  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   176  	chainreader := &fakeChainReader{config: config}
   177  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   178  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   179  		b.header = makeHeader(chainreader, parent, statedb, b.engine)
   180  
   181  		// Execute any user modifications to the block
   182  		if gen != nil {
   183  			gen(i, b)
   184  		}
   185  		if b.engine != nil {
   186  			// Finalize and seal the block
   187  			block, _ := b.engine.Finalize(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
   188  
   189  			// Write state changes to db
   190  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   191  			if err != nil {
   192  				panic(fmt.Sprintf("state write error: %v", err))
   193  			}
   194  			if err := statedb.Database().TrieDB().Commit(root, false); err != nil {
   195  				panic(fmt.Sprintf("trie write error: %v", err))
   196  			}
   197  			return block, b.receipts
   198  		}
   199  		return nil, nil
   200  	}
   201  	for i := 0; i < n; i++ {
   202  		statedb, err := state.New(parent.Root(), state.NewDatabase(db))
   203  		if err != nil {
   204  			panic(err)
   205  		}
   206  		block, receipt := genblock(i, parent, statedb)
   207  		blocks[i] = block
   208  		receipts[i] = receipt
   209  		parent = block
   210  	}
   211  	return blocks, receipts
   212  }
   213  
   214  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   215  	var time uint64
   216  	if parent.Time() == 0 {
   217  		time = 10
   218  	} else {
   219  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   220  	}
   221  
   222  	return &types.Header{
   223  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   224  		ParentHash: parent.Hash(),
   225  		Coinbase:   parent.Coinbase(),
   226  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   227  			Number:     parent.Number(),
   228  			Time:       time - 10,
   229  			Difficulty: parent.Difficulty(),
   230  			UncleHash:  parent.UncleHash(),
   231  		}),
   232  		GasLimit: CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit()),
   233  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   234  		Time:     time,
   235  	}
   236  }
   237  
   238  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   239  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
   240  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   241  	headers := make([]*types.Header, len(blocks))
   242  	for i, block := range blocks {
   243  		headers[i] = block.Header()
   244  	}
   245  	return headers
   246  }
   247  
   248  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   249  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
   250  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   251  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   252  	})
   253  	return blocks
   254  }
   255  
   256  type fakeChainReader struct {
   257  	config  *params.ChainConfig
   258  	genesis *types.Block
   259  }
   260  
   261  // Config returns the chain configuration.
   262  func (cr *fakeChainReader) Config() *params.ChainConfig {
   263  	return cr.config
   264  }
   265  
   266  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   267  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   268  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   269  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   270  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }
   271  func (cr *fakeChainReader) CalcPastMedianTime(number uint64, parent *types.Header) *big.Int { return nil }