chain_makers.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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/ethdb"
  24. "github.com/ethereum/go-ethereum/event"
  25. "github.com/ethereum/go-ethereum/pow"
  26. )
  27. // FakePow is a non-validating proof of work implementation.
  28. // It returns true from Verify for any block.
  29. type FakePow struct{}
  30. func (f FakePow) Search(block pow.Block, stop <-chan struct{}, index int) (uint64, []byte) {
  31. return 0, nil
  32. }
  33. func (f FakePow) Verify(block pow.Block) bool { return true }
  34. func (f FakePow) GetHashrate() int64 { return 0 }
  35. func (f FakePow) Turbo(bool) {}
  36. // So we can deterministically seed different blockchains
  37. var (
  38. canonicalSeed = 1
  39. forkSeed = 2
  40. )
  41. // BlockGen creates blocks for testing.
  42. // See GenerateChain for a detailed explanation.
  43. type BlockGen struct {
  44. i int
  45. parent *types.Block
  46. chain []*types.Block
  47. header *types.Header
  48. statedb *state.StateDB
  49. gasPool *GasPool
  50. txs []*types.Transaction
  51. receipts []*types.Receipt
  52. uncles []*types.Header
  53. }
  54. // SetCoinbase sets the coinbase of the generated block.
  55. // It can be called at most once.
  56. func (b *BlockGen) SetCoinbase(addr common.Address) {
  57. if b.gasPool != nil {
  58. if len(b.txs) > 0 {
  59. panic("coinbase must be set before adding transactions")
  60. }
  61. panic("coinbase can only be set once")
  62. }
  63. b.header.Coinbase = addr
  64. b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
  65. }
  66. // SetExtra sets the extra data field of the generated block.
  67. func (b *BlockGen) SetExtra(data []byte) {
  68. b.header.Extra = data
  69. }
  70. // AddTx adds a transaction to the generated block. If no coinbase has
  71. // been set, the block's coinbase is set to the zero address.
  72. //
  73. // AddTx panics if the transaction cannot be executed. In addition to
  74. // the protocol-imposed limitations (gas limit, etc.), there are some
  75. // further limitations on the content of transactions that can be
  76. // added. Notably, contract code relying on the BLOCKHASH instruction
  77. // will panic during execution.
  78. func (b *BlockGen) AddTx(tx *types.Transaction) {
  79. if b.gasPool == nil {
  80. b.SetCoinbase(common.Address{})
  81. }
  82. _, gas, err := ApplyMessage(NewEnv(b.statedb, nil, tx, b.header), tx, b.gasPool)
  83. if err != nil {
  84. panic(err)
  85. }
  86. root := b.statedb.IntermediateRoot()
  87. b.header.GasUsed.Add(b.header.GasUsed, gas)
  88. receipt := types.NewReceipt(root.Bytes(), b.header.GasUsed)
  89. logs := b.statedb.GetLogs(tx.Hash())
  90. receipt.SetLogs(logs)
  91. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  92. b.txs = append(b.txs, tx)
  93. b.receipts = append(b.receipts, receipt)
  94. }
  95. // AddUncheckedReceipts forcefully adds a receipts to the block without a
  96. // backing transaction.
  97. //
  98. // AddUncheckedReceipts will cause consensus failures when used during real
  99. // chain processing. This is best used in conjuction with raw block insertion.
  100. func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
  101. b.receipts = append(b.receipts, receipt)
  102. }
  103. // TxNonce returns the next valid transaction nonce for the
  104. // account at addr. It panics if the account does not exist.
  105. func (b *BlockGen) TxNonce(addr common.Address) uint64 {
  106. if !b.statedb.HasAccount(addr) {
  107. panic("account does not exist")
  108. }
  109. return b.statedb.GetNonce(addr)
  110. }
  111. // AddUncle adds an uncle header to the generated block.
  112. func (b *BlockGen) AddUncle(h *types.Header) {
  113. b.uncles = append(b.uncles, h)
  114. }
  115. // PrevBlock returns a previously generated block by number. It panics if
  116. // num is greater or equal to the number of the block being generated.
  117. // For index -1, PrevBlock returns the parent block given to GenerateChain.
  118. func (b *BlockGen) PrevBlock(index int) *types.Block {
  119. if index >= b.i {
  120. panic("block index out of range")
  121. }
  122. if index == -1 {
  123. return b.parent
  124. }
  125. return b.chain[index]
  126. }
  127. // OffsetTime modifies the time instance of a block, implicitly changing its
  128. // associated difficulty. It's useful to test scenarios where forking is not
  129. // tied to chain length directly.
  130. func (b *BlockGen) OffsetTime(seconds int64) {
  131. b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
  132. if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
  133. panic("block time out of range")
  134. }
  135. b.header.Difficulty = CalcDifficulty(b.header.Time.Uint64(), b.parent.Time().Uint64(), b.parent.Number(), b.parent.Difficulty())
  136. }
  137. // GenerateChain creates a chain of n blocks. The first block's
  138. // parent will be the provided parent. db is used to store
  139. // intermediate states and should contain the parent's state trie.
  140. //
  141. // The generator function is called with a new block generator for
  142. // every block. Any transactions and uncles added to the generator
  143. // become part of the block. If gen is nil, the blocks will be empty
  144. // and their coinbase will be the zero address.
  145. //
  146. // Blocks created by GenerateChain do not contain valid proof of work
  147. // values. Inserting them into BlockChain requires use of FakePow or
  148. // a similar non-validating proof of work implementation.
  149. func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) []*types.Block {
  150. statedb, err := state.New(parent.Root(), db)
  151. if err != nil {
  152. panic(err)
  153. }
  154. blocks := make(types.Blocks, n)
  155. genblock := func(i int, h *types.Header) *types.Block {
  156. b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
  157. if gen != nil {
  158. gen(i, b)
  159. }
  160. AccumulateRewards(statedb, h, b.uncles)
  161. root, err := statedb.Commit()
  162. if err != nil {
  163. panic(fmt.Sprintf("state write error: %v", err))
  164. }
  165. h.Root = root
  166. return types.NewBlock(h, b.txs, b.uncles, b.receipts)
  167. }
  168. for i := 0; i < n; i++ {
  169. header := makeHeader(parent, statedb)
  170. block := genblock(i, header)
  171. blocks[i] = block
  172. parent = block
  173. }
  174. return blocks
  175. }
  176. func makeHeader(parent *types.Block, state *state.StateDB) *types.Header {
  177. var time *big.Int
  178. if parent.Time() == nil {
  179. time = big.NewInt(10)
  180. } else {
  181. time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
  182. }
  183. return &types.Header{
  184. Root: state.IntermediateRoot(),
  185. ParentHash: parent.Hash(),
  186. Coinbase: parent.Coinbase(),
  187. Difficulty: CalcDifficulty(time.Uint64(), new(big.Int).Sub(time, big.NewInt(10)).Uint64(), parent.Number(), parent.Difficulty()),
  188. GasLimit: CalcGasLimit(parent),
  189. GasUsed: new(big.Int),
  190. Number: new(big.Int).Add(parent.Number(), common.Big1),
  191. Time: time,
  192. }
  193. }
  194. // newCanonical creates a new deterministic canonical chain by running
  195. // InsertChain on the result of makeChain.
  196. func newCanonical(n int, db ethdb.Database) (*BlockProcessor, error) {
  197. evmux := &event.TypeMux{}
  198. WriteTestNetGenesisBlock(db, 0)
  199. chainman, _ := NewBlockChain(db, FakePow{}, evmux)
  200. bman := NewBlockProcessor(db, FakePow{}, chainman, evmux)
  201. bman.bc.SetProcessor(bman)
  202. parent := bman.bc.CurrentBlock()
  203. if n == 0 {
  204. return bman, nil
  205. }
  206. lchain := makeChain(parent, n, db, canonicalSeed)
  207. _, err := bman.bc.InsertChain(lchain)
  208. return bman, err
  209. }
  210. func makeChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
  211. return GenerateChain(parent, db, n, func(i int, b *BlockGen) {
  212. b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
  213. })
  214. }