chain_makers.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "math/big"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/core/state"
  21. "github.com/ethereum/go-ethereum/core/types"
  22. "github.com/ethereum/go-ethereum/event"
  23. "github.com/ethereum/go-ethereum/pow"
  24. )
  25. // FakePow is a non-validating proof of work implementation.
  26. // It returns true from Verify for any block.
  27. type FakePow struct{}
  28. func (f FakePow) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte) {
  29. return 0, nil
  30. }
  31. func (f FakePow) Verify(block pow.Block) bool { return true }
  32. func (f FakePow) GetHashrate() int64 { return 0 }
  33. func (f FakePow) Turbo(bool) {}
  34. // So we can deterministically seed different blockchains
  35. var (
  36. canonicalSeed = 1
  37. forkSeed = 2
  38. )
  39. // BlockGen creates blocks for testing.
  40. // See GenerateChain for a detailed explanation.
  41. type BlockGen struct {
  42. i int
  43. parent *types.Block
  44. chain []*types.Block
  45. header *types.Header
  46. statedb *state.StateDB
  47. coinbase *state.StateObject
  48. txs []*types.Transaction
  49. receipts []*types.Receipt
  50. uncles []*types.Header
  51. }
  52. // SetCoinbase sets the coinbase of the generated block.
  53. // It can be called at most once.
  54. func (b *BlockGen) SetCoinbase(addr common.Address) {
  55. if b.coinbase != nil {
  56. if len(b.txs) > 0 {
  57. panic("coinbase must be set before adding transactions")
  58. }
  59. panic("coinbase can only be set once")
  60. }
  61. b.header.Coinbase = addr
  62. b.coinbase = b.statedb.GetOrNewStateObject(addr)
  63. b.coinbase.SetGasLimit(b.header.GasLimit)
  64. }
  65. // SetExtra sets the extra data field of the generated block.
  66. func (b *BlockGen) SetExtra(data []byte) {
  67. b.header.Extra = data
  68. }
  69. // AddTx adds a transaction to the generated block. If no coinbase has
  70. // been set, the block's coinbase is set to the zero address.
  71. //
  72. // AddTx panics if the transaction cannot be executed. In addition to
  73. // the protocol-imposed limitations (gas limit, etc.), there are some
  74. // further limitations on the content of transactions that can be
  75. // added. Notably, contract code relying on the BLOCKHASH instruction
  76. // will panic during execution.
  77. func (b *BlockGen) AddTx(tx *types.Transaction) {
  78. if b.coinbase == nil {
  79. b.SetCoinbase(common.Address{})
  80. }
  81. _, gas, err := ApplyMessage(NewEnv(b.statedb, nil, tx, b.header), tx, b.coinbase)
  82. if err != nil {
  83. panic(err)
  84. }
  85. b.statedb.SyncIntermediate()
  86. b.header.GasUsed.Add(b.header.GasUsed, gas)
  87. receipt := types.NewReceipt(b.statedb.Root().Bytes(), b.header.GasUsed)
  88. logs := b.statedb.GetLogs(tx.Hash())
  89. receipt.SetLogs(logs)
  90. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  91. b.txs = append(b.txs, tx)
  92. b.receipts = append(b.receipts, receipt)
  93. }
  94. // TxNonce returns the next valid transaction nonce for the
  95. // account at addr. It panics if the account does not exist.
  96. func (b *BlockGen) TxNonce(addr common.Address) uint64 {
  97. if !b.statedb.HasAccount(addr) {
  98. panic("account does not exist")
  99. }
  100. return b.statedb.GetNonce(addr)
  101. }
  102. // AddUncle adds an uncle header to the generated block.
  103. func (b *BlockGen) AddUncle(h *types.Header) {
  104. b.uncles = append(b.uncles, h)
  105. }
  106. // PrevBlock returns a previously generated block by number. It panics if
  107. // num is greater or equal to the number of the block being generated.
  108. // For index -1, PrevBlock returns the parent block given to GenerateChain.
  109. func (b *BlockGen) PrevBlock(index int) *types.Block {
  110. if index >= b.i {
  111. panic("block index out of range")
  112. }
  113. if index == -1 {
  114. return b.parent
  115. }
  116. return b.chain[index]
  117. }
  118. // GenerateChain creates a chain of n blocks. The first block's
  119. // parent will be the provided parent. db is used to store
  120. // intermediate states and should contain the parent's state trie.
  121. //
  122. // The generator function is called with a new block generator for
  123. // every block. Any transactions and uncles added to the generator
  124. // become part of the block. If gen is nil, the blocks will be empty
  125. // and their coinbase will be the zero address.
  126. //
  127. // Blocks created by GenerateChain do not contain valid proof of work
  128. // values. Inserting them into ChainManager requires use of FakePow or
  129. // a similar non-validating proof of work implementation.
  130. func GenerateChain(parent *types.Block, db common.Database, n int, gen func(int, *BlockGen)) []*types.Block {
  131. statedb := state.New(parent.Root(), db)
  132. blocks := make(types.Blocks, n)
  133. genblock := func(i int, h *types.Header) *types.Block {
  134. b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
  135. if gen != nil {
  136. gen(i, b)
  137. }
  138. AccumulateRewards(statedb, h, b.uncles)
  139. statedb.SyncIntermediate()
  140. h.Root = statedb.Root()
  141. return types.NewBlock(h, b.txs, b.uncles, b.receipts)
  142. }
  143. for i := 0; i < n; i++ {
  144. header := makeHeader(parent, statedb)
  145. block := genblock(i, header)
  146. block.Td = CalcTD(block, parent)
  147. blocks[i] = block
  148. parent = block
  149. }
  150. return blocks
  151. }
  152. func makeHeader(parent *types.Block, state *state.StateDB) *types.Header {
  153. time := parent.Time() + 10 // block time is fixed at 10 seconds
  154. return &types.Header{
  155. Root: state.Root(),
  156. ParentHash: parent.Hash(),
  157. Coinbase: parent.Coinbase(),
  158. Difficulty: CalcDifficulty(int64(time), int64(parent.Time()), parent.Difficulty()),
  159. GasLimit: CalcGasLimit(parent),
  160. GasUsed: new(big.Int),
  161. Number: new(big.Int).Add(parent.Number(), common.Big1),
  162. Time: uint64(time),
  163. }
  164. }
  165. // newCanonical creates a new deterministic canonical chain by running
  166. // InsertChain on the result of makeChain.
  167. func newCanonical(n int, db common.Database) (*BlockProcessor, error) {
  168. evmux := &event.TypeMux{}
  169. chainman, _ := NewChainManager(GenesisBlock(0, db), db, db, db, FakePow{}, evmux)
  170. bman := NewBlockProcessor(db, db, FakePow{}, chainman, evmux)
  171. bman.bc.SetProcessor(bman)
  172. parent := bman.bc.CurrentBlock()
  173. if n == 0 {
  174. return bman, nil
  175. }
  176. lchain := makeChain(parent, n, db, canonicalSeed)
  177. _, err := bman.bc.InsertChain(lchain)
  178. return bman, err
  179. }
  180. func makeChain(parent *types.Block, n int, db common.Database, seed int) []*types.Block {
  181. return GenerateChain(parent, db, n, func(i int, b *BlockGen) {
  182. b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
  183. })
  184. }