chain_makers.go 11 KB

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