chain_makers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. // BlockGen creates blocks for testing.
  30. // See GenerateChain for a detailed explanation.
  31. type BlockGen struct {
  32. i int
  33. parent *types.Block
  34. chain []*types.Block
  35. header *types.Header
  36. statedb *state.StateDB
  37. gasPool *GasPool
  38. txs []*types.Transaction
  39. receipts []*types.Receipt
  40. uncles []*types.Header
  41. config *params.ChainConfig
  42. engine consensus.Engine
  43. }
  44. // SetCoinbase sets the coinbase of the generated block.
  45. // It can be called at most once.
  46. func (b *BlockGen) SetCoinbase(addr common.Address) {
  47. if b.gasPool != nil {
  48. if len(b.txs) > 0 {
  49. panic("coinbase must be set before adding transactions")
  50. }
  51. panic("coinbase can only be set once")
  52. }
  53. b.header.Coinbase = addr
  54. b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
  55. }
  56. // SetExtra sets the extra data field of the generated block.
  57. func (b *BlockGen) SetExtra(data []byte) {
  58. b.header.Extra = data
  59. }
  60. // SetNonce sets the nonce field of the generated block.
  61. func (b *BlockGen) SetNonce(nonce types.BlockNonce) {
  62. b.header.Nonce = nonce
  63. }
  64. // SetDifficulty sets the difficulty field of the generated block. This method is
  65. // useful for Clique tests where the difficulty does not depend on time. For the
  66. // ethash tests, please use OffsetTime, which implicitly recalculates the diff.
  67. func (b *BlockGen) SetDifficulty(diff *big.Int) {
  68. b.header.Difficulty = diff
  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. b.AddTxWithChain(nil, tx)
  80. }
  81. // AddTxWithChain adds a transaction to the generated block. If no coinbase has
  82. // been set, the block's coinbase is set to the zero address.
  83. //
  84. // AddTxWithChain panics if the transaction cannot be executed. In addition to
  85. // the protocol-imposed limitations (gas limit, etc.), there are some
  86. // further limitations on the content of transactions that can be
  87. // added. If contract code relies on the BLOCKHASH instruction,
  88. // the block in chain will be returned.
  89. func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
  90. if b.gasPool == nil {
  91. b.SetCoinbase(common.Address{})
  92. }
  93. b.statedb.Prepare(tx.Hash(), len(b.txs))
  94. receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
  95. if err != nil {
  96. panic(err)
  97. }
  98. b.txs = append(b.txs, tx)
  99. b.receipts = append(b.receipts, receipt)
  100. }
  101. // GetBalance returns the balance of the given address at the generated block.
  102. func (b *BlockGen) GetBalance(addr common.Address) *big.Int {
  103. return b.statedb.GetBalance(addr)
  104. }
  105. // AddUncheckedTx forcefully adds a transaction to the block without any
  106. // validation.
  107. //
  108. // AddUncheckedTx will cause consensus failures when used during real
  109. // chain processing. This is best used in conjunction with raw block insertion.
  110. func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
  111. b.txs = append(b.txs, tx)
  112. }
  113. // Number returns the block number of the block being generated.
  114. func (b *BlockGen) Number() *big.Int {
  115. return new(big.Int).Set(b.header.Number)
  116. }
  117. // BaseFee returns the EIP-1559 base fee of the block being generated.
  118. func (b *BlockGen) BaseFee() *big.Int {
  119. return new(big.Int).Set(b.header.BaseFee)
  120. }
  121. // AddUncheckedReceipt forcefully adds a receipts to the block without a
  122. // backing transaction.
  123. //
  124. // AddUncheckedReceipt will cause consensus failures when used during real
  125. // chain processing. This is best used in conjunction with raw block insertion.
  126. func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
  127. b.receipts = append(b.receipts, receipt)
  128. }
  129. // TxNonce returns the next valid transaction nonce for the
  130. // account at addr. It panics if the account does not exist.
  131. func (b *BlockGen) TxNonce(addr common.Address) uint64 {
  132. if !b.statedb.Exist(addr) {
  133. panic("account does not exist")
  134. }
  135. return b.statedb.GetNonce(addr)
  136. }
  137. // AddUncle adds an uncle header to the generated block.
  138. func (b *BlockGen) AddUncle(h *types.Header) {
  139. // The uncle will have the same timestamp and auto-generated difficulty
  140. h.Time = b.header.Time
  141. var parent *types.Header
  142. for i := b.i - 1; i >= 0; i-- {
  143. if b.chain[i].Hash() == h.ParentHash {
  144. parent = b.chain[i].Header()
  145. break
  146. }
  147. }
  148. chainreader := &fakeChainReader{config: b.config}
  149. h.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, parent)
  150. // The gas limit and price should be derived from the parent
  151. h.GasLimit = parent.GasLimit
  152. if b.config.IsLondon(h.Number) {
  153. h.BaseFee = misc.CalcBaseFee(b.config, parent)
  154. if !b.config.IsLondon(parent.Number) {
  155. parentGasLimit := parent.GasLimit * params.ElasticityMultiplier
  156. h.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
  157. }
  158. }
  159. b.uncles = append(b.uncles, h)
  160. }
  161. // PrevBlock returns a previously generated block by number. It panics if
  162. // num is greater or equal to the number of the block being generated.
  163. // For index -1, PrevBlock returns the parent block given to GenerateChain.
  164. func (b *BlockGen) PrevBlock(index int) *types.Block {
  165. if index >= b.i {
  166. panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
  167. }
  168. if index == -1 {
  169. return b.parent
  170. }
  171. return b.chain[index]
  172. }
  173. // OffsetTime modifies the time instance of a block, implicitly changing its
  174. // associated difficulty. It's useful to test scenarios where forking is not
  175. // tied to chain length directly.
  176. func (b *BlockGen) OffsetTime(seconds int64) {
  177. b.header.Time += uint64(seconds)
  178. if b.header.Time <= b.parent.Header().Time {
  179. panic("block time out of range")
  180. }
  181. chainreader := &fakeChainReader{config: b.config}
  182. b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
  183. }
  184. // GenerateChain creates a chain of n blocks. The first block's
  185. // parent will be the provided parent. db is used to store
  186. // intermediate states and should contain the parent's state trie.
  187. //
  188. // The generator function is called with a new block generator for
  189. // every block. Any transactions and uncles added to the generator
  190. // become part of the block. If gen is nil, the blocks will be empty
  191. // and their coinbase will be the zero address.
  192. //
  193. // Blocks created by GenerateChain do not contain valid proof of work
  194. // values. Inserting them into BlockChain requires use of FakePow or
  195. // a similar non-validating proof of work implementation.
  196. func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
  197. if config == nil {
  198. config = params.TestChainConfig
  199. }
  200. blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
  201. chainreader := &fakeChainReader{config: config}
  202. genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
  203. b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
  204. b.header = makeHeader(chainreader, parent, statedb, b.engine)
  205. // Set the difficulty for clique block. The chain maker doesn't have access
  206. // to a chain, so the difficulty will be left unset (nil). Set it here to the
  207. // correct value.
  208. if b.header.Difficulty == nil {
  209. if config.TerminalTotalDifficulty == nil {
  210. // Clique chain
  211. b.header.Difficulty = big.NewInt(2)
  212. } else {
  213. // Post-merge chain
  214. b.header.Difficulty = big.NewInt(0)
  215. }
  216. }
  217. // Mutate the state and block according to any hard-fork specs
  218. if daoBlock := config.DAOForkBlock; daoBlock != nil {
  219. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  220. if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
  221. if config.DAOForkSupport {
  222. b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  223. }
  224. }
  225. }
  226. if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
  227. misc.ApplyDAOHardFork(statedb)
  228. }
  229. // Execute any user modifications to the block
  230. if gen != nil {
  231. gen(i, b)
  232. }
  233. if b.engine != nil {
  234. // Finalize and seal the block
  235. block, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
  236. // Write state changes to db
  237. root, err := statedb.Commit(config.IsEIP158(b.header.Number))
  238. if err != nil {
  239. panic(fmt.Sprintf("state write error: %v", err))
  240. }
  241. if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
  242. panic(fmt.Sprintf("trie write error: %v", err))
  243. }
  244. return block, b.receipts
  245. }
  246. return nil, nil
  247. }
  248. for i := 0; i < n; i++ {
  249. statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
  250. if err != nil {
  251. panic(err)
  252. }
  253. block, receipt := genblock(i, parent, statedb)
  254. blocks[i] = block
  255. receipts[i] = receipt
  256. parent = block
  257. }
  258. return blocks, receipts
  259. }
  260. func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
  261. var time uint64
  262. if parent.Time() == 0 {
  263. time = 10
  264. } else {
  265. time = parent.Time() + 10 // block time is fixed at 10 seconds
  266. }
  267. header := &types.Header{
  268. Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
  269. ParentHash: parent.Hash(),
  270. Coinbase: parent.Coinbase(),
  271. Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
  272. Number: parent.Number(),
  273. Time: time - 10,
  274. Difficulty: parent.Difficulty(),
  275. UncleHash: parent.UncleHash(),
  276. }),
  277. GasLimit: parent.GasLimit(),
  278. Number: new(big.Int).Add(parent.Number(), common.Big1),
  279. Time: time,
  280. }
  281. if chain.Config().IsLondon(header.Number) {
  282. header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header())
  283. if !chain.Config().IsLondon(parent.Number()) {
  284. parentGasLimit := parent.GasLimit() * params.ElasticityMultiplier
  285. header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
  286. }
  287. }
  288. return header
  289. }
  290. // makeHeaderChain creates a deterministic chain of headers rooted at parent.
  291. func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
  292. blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
  293. headers := make([]*types.Header, len(blocks))
  294. for i, block := range blocks {
  295. headers[i] = block.Header()
  296. }
  297. return headers
  298. }
  299. // makeBlockChain creates a deterministic chain of blocks rooted at parent.
  300. func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
  301. blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
  302. b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
  303. })
  304. return blocks
  305. }
  306. type fakeChainReader struct {
  307. config *params.ChainConfig
  308. }
  309. // Config returns the chain configuration.
  310. func (cr *fakeChainReader) Config() *params.ChainConfig {
  311. return cr.config
  312. }
  313. func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil }
  314. func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil }
  315. func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil }
  316. func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
  317. func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }
  318. func (cr *fakeChainReader) GetTd(hash common.Hash, number uint64) *big.Int { return nil }