chain_makers.go 6.0 KB

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