chain_makers.go 9.9 KB

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