chain_makers.go 10 KB

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