github.com/klaytn/klaytn@v1.10.2/blockchain/chain_makers.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from core/chain_makers.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package blockchain
    22  
    23  import (
    24  	"fmt"
    25  	"math/big"
    26  
    27  	"github.com/klaytn/klaytn/blockchain/state"
    28  	"github.com/klaytn/klaytn/blockchain/types"
    29  	"github.com/klaytn/klaytn/blockchain/vm"
    30  	"github.com/klaytn/klaytn/common"
    31  	"github.com/klaytn/klaytn/consensus"
    32  	"github.com/klaytn/klaytn/consensus/misc"
    33  	"github.com/klaytn/klaytn/params"
    34  	"github.com/klaytn/klaytn/storage/database"
    35  	"github.com/klaytn/klaytn/storage/statedb"
    36  )
    37  
    38  // BlockGen creates blocks for testing.
    39  // See GenerateChain for a detailed explanation.
    40  type BlockGen struct {
    41  	i           int
    42  	parent      *types.Block
    43  	chain       []*types.Block
    44  	chainReader consensus.ChainReader
    45  	header      *types.Header
    46  	statedb     *state.StateDB
    47  
    48  	txs      []*types.Transaction
    49  	receipts []*types.Receipt
    50  
    51  	config *params.ChainConfig
    52  	engine consensus.Engine
    53  }
    54  
    55  // SetRewardbase sets the rewardbase field of the generated block.
    56  func (b *BlockGen) SetRewardbase(addr common.Address) {
    57  	b.header.Rewardbase = addr
    58  }
    59  
    60  // SetExtra sets the extra data field of the generated block.
    61  func (b *BlockGen) SetExtra(data []byte) {
    62  	b.header.Extra = data
    63  }
    64  
    65  func (b *BlockGen) SetVoteData(data []byte) {
    66  	b.header.Vote = data
    67  }
    68  
    69  // AddTx adds a transaction to the generated block.
    70  // In gxhash, arbitrary address is used as a block author's address.
    71  //
    72  // AddTx panics if the transaction cannot be executed. In addition to
    73  // the protocol-imposed limitations (gas limit, etc.), there are some
    74  // further limitations on the content of transactions that can be
    75  // added. Notably, contract code relying on the BLOCKHASH instruction
    76  // will panic during execution.
    77  func (b *BlockGen) AddTx(tx *types.Transaction) {
    78  	b.AddTxWithChain(nil, tx)
    79  }
    80  
    81  // AddTxWithChain adds a transaction to the generated block.
    82  // In gxhash, arbitrary address is used as a block author's address.
    83  //
    84  // AddTxWithChain panics if the transaction cannot be executed. In addition to
    85  // the protocol-imposed limitations (gas limit, etc.), there are some
    86  // further limitations on the content of transactions that can be
    87  // added. If contract code relies on the BLOCKHASH instruction,
    88  // the block in chain will be returned.
    89  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
    90  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
    91  	receipt, _, err := bc.ApplyTransaction(b.config, &params.AuthorAddressForTesting, b.statedb, b.header, tx, &b.header.GasUsed, &vm.Config{})
    92  	if err != nil {
    93  		panic(err)
    94  	}
    95  	b.txs = append(b.txs, tx)
    96  	b.receipts = append(b.receipts, receipt)
    97  }
    98  
    99  // AddUncheckedTx forcefully adds a transaction to the block without any
   100  // validation.
   101  //
   102  // AddUncheckedTx will cause consensus failures when used during real
   103  // chain processing. This is best used in conjunction with raw block insertion.
   104  func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
   105  	b.txs = append(b.txs, tx)
   106  }
   107  
   108  // Number returns the block number of the block being generated.
   109  func (b *BlockGen) Number() *big.Int {
   110  	return new(big.Int).Set(b.header.Number)
   111  }
   112  
   113  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   114  // backing transaction.
   115  //
   116  // AddUncheckedReceipt will cause consensus failures when used during real
   117  // chain processing. This is best used in conjunction with raw block insertion.
   118  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   119  	b.receipts = append(b.receipts, receipt)
   120  }
   121  
   122  // TxNonce returns the next valid transaction nonce for the
   123  // account at addr. It panics if the account does not exist.
   124  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   125  	if !b.statedb.Exist(addr) {
   126  		panic("account does not exist")
   127  	}
   128  	return b.statedb.GetNonce(addr)
   129  }
   130  
   131  // PrevBlock returns a previously generated block by number. It panics if
   132  // num is greater or equal to the number of the block being generated.
   133  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   134  func (b *BlockGen) PrevBlock(index int) *types.Block {
   135  	if index >= b.i {
   136  		panic("block index out of range")
   137  	}
   138  	if index == -1 {
   139  		return b.parent
   140  	}
   141  	return b.chain[index]
   142  }
   143  
   144  // OffsetTime modifies the time instance of a block, implicitly changing its
   145  // associated blockscore. It's useful to test scenarios where forking is not
   146  // tied to chain length directly.
   147  func (b *BlockGen) OffsetTime(seconds int64) {
   148  	b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
   149  	if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
   150  		panic("block time out of range")
   151  	}
   152  	b.header.BlockScore = b.engine.CalcBlockScore(b.chainReader, b.header.Time.Uint64(), b.parent.Header())
   153  }
   154  
   155  // GenerateChain creates a chain of n blocks. The first block's
   156  // parent will be the provided parent. db is used to store
   157  // intermediate states and should contain the parent's state trie.
   158  //
   159  // The generator function is called with a new block generator for
   160  // every block. Any transactions added to the generator
   161  // become part of the block. If gen is nil, the blocks will be empty.
   162  //
   163  // Blocks created by GenerateChain do not contain valid proof of work
   164  // values. Inserting them into BlockChain requires use of FakePow or
   165  // a similar non-validating proof of work implementation.
   166  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db database.DBManager, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   167  	if config == nil {
   168  		config = params.TestChainConfig
   169  	}
   170  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   171  	genblock := func(i int, parent *types.Block, stateDB *state.StateDB) (*types.Block, types.Receipts) {
   172  		// TODO(karalabe): This is needed for clique, which depends on multiple blocks.
   173  		// It's nonetheless ugly to spin up a blockchain here. Get rid of this somehow.
   174  		cacheConfig := &CacheConfig{
   175  			ArchiveMode:         false,
   176  			CacheSize:           512,
   177  			BlockInterval:       DefaultBlockInterval,
   178  			TriesInMemory:       DefaultTriesInMemory,
   179  			TrieNodeCacheConfig: statedb.GetEmptyTrieNodeCacheConfig(),
   180  			SnapshotCacheSize:   512,
   181  			SnapshotAsyncGen:    true,
   182  		}
   183  		blockchain, _ := NewBlockChain(db, cacheConfig, config, engine, vm.Config{})
   184  		defer blockchain.Stop()
   185  
   186  		b := &BlockGen{i: i, parent: parent, chain: blocks, chainReader: blockchain, statedb: stateDB, config: config, engine: engine}
   187  		b.header = makeHeader(b.chainReader, parent, stateDB, b.engine)
   188  
   189  		// Execute any user modifications to the block and finalize it
   190  		if gen != nil {
   191  			gen(i, b)
   192  		}
   193  
   194  		if b.engine != nil {
   195  			block, err := b.engine.Finalize(b.chainReader, b.header, stateDB, b.txs, b.receipts)
   196  			if err != nil {
   197  				panic(fmt.Sprintf("block finalize error: %v", err))
   198  			}
   199  			// Write state changes to db
   200  			root, err := stateDB.Commit(true)
   201  			if err != nil {
   202  				panic(fmt.Sprintf("state write error: %v", err))
   203  			}
   204  			if err := stateDB.Database().TrieDB().Commit(root, false, block.NumberU64()); err != nil {
   205  				panic(fmt.Sprintf("trie write error: %v", err))
   206  			}
   207  			return block, b.receipts
   208  		}
   209  		return nil, nil
   210  	}
   211  	for i := 0; i < n; i++ {
   212  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   213  		if err != nil {
   214  			panic(err)
   215  		}
   216  		block, receipt := genblock(i, parent, statedb)
   217  		blocks[i] = block
   218  		receipts[i] = receipt
   219  		parent = block
   220  	}
   221  	return blocks, receipts
   222  }
   223  
   224  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   225  	var time *big.Int
   226  	if parent.Time() == nil {
   227  		time = big.NewInt(10)
   228  	} else {
   229  		time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
   230  	}
   231  
   232  	header := &types.Header{
   233  		Root:       state.IntermediateRoot(true),
   234  		ParentHash: parent.Hash(),
   235  		BlockScore: engine.CalcBlockScore(chain, time.Uint64(), &types.Header{
   236  			Number:     parent.Number(),
   237  			Time:       new(big.Int).Sub(time, big.NewInt(10)),
   238  			BlockScore: parent.BlockScore(),
   239  		}),
   240  		Number: new(big.Int).Add(parent.Number(), common.Big1),
   241  		Time:   time,
   242  	}
   243  	if chain.Config().IsMagmaForkEnabled(header.Number) {
   244  		header.BaseFee = misc.NextMagmaBlockBaseFee(parent.Header(), chain.Config().Governance.KIP71)
   245  	}
   246  	return header
   247  }
   248  
   249  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   250  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db database.DBManager, seed int) []*types.Header {
   251  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   252  	headers := make([]*types.Header, len(blocks))
   253  	for i, block := range blocks {
   254  		headers[i] = block.Header()
   255  	}
   256  	return headers
   257  }
   258  
   259  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   260  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db database.DBManager, seed int) []*types.Block {
   261  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   262  		b.SetRewardbase(common.Address{0: byte(seed), 19: byte(i)})
   263  	})
   264  	return blocks
   265  }
   266  
   267  type fakeChainReader struct {
   268  	config  *params.ChainConfig
   269  	genesis *types.Block
   270  }
   271  
   272  // Config returns the chain configuration.
   273  func (cr *fakeChainReader) Config() *params.ChainConfig {
   274  	return cr.config
   275  }
   276  
   277  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   278  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   279  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   280  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   281  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }