chain_makers.go 10 KB

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