chain_makers.go 9.4 KB

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