state_processor.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. "errors"
  19. "fmt"
  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/crypto"
  27. "github.com/ethereum/go-ethereum/params"
  28. "math/big"
  29. )
  30. // StateProcessor is a basic Processor, which takes care of transitioning
  31. // state from one point to another.
  32. //
  33. // StateProcessor implements Processor.
  34. type StateProcessor struct {
  35. config *params.ChainConfig // Chain configuration options
  36. bc *BlockChain // Canonical block chain
  37. engine consensus.Engine // Consensus engine used for block rewards
  38. }
  39. // NewStateProcessor initialises a new StateProcessor.
  40. func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
  41. return &StateProcessor{
  42. config: config,
  43. bc: bc,
  44. engine: engine,
  45. }
  46. }
  47. // Process processes the state changes according to the Ethereum rules by running
  48. // the transaction messages using the statedb and applying any rewards to both
  49. // the processor (coinbase) and any included uncles.
  50. //
  51. // Process returns the receipts and logs accumulated during the process and
  52. // returns the amount of gas that was used in the process. If any of the
  53. // transactions failed to execute due to insufficient gas it will return an error.
  54. func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
  55. var (
  56. receipts types.Receipts
  57. usedGas = new(uint64)
  58. header = block.Header()
  59. blockHash = block.Hash()
  60. blockNumber = block.Number()
  61. allLogs []*types.Log
  62. gp = new(GasPool).AddGas(block.GasLimit())
  63. )
  64. // Mutate the block and state according to any hard-fork specs
  65. if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
  66. misc.ApplyDAOHardFork(statedb)
  67. }
  68. blockContext := NewEVMBlockContext(header, p.bc, nil)
  69. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
  70. // Iterate over and process the individual transactions
  71. for i, tx := range block.Transactions() {
  72. msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number), header.BaseFee)
  73. if err != nil {
  74. return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
  75. }
  76. statedb.Prepare(tx.Hash(), i)
  77. receipt, err := applyTransaction(msg, p.config, nil, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
  78. if err != nil {
  79. return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
  80. }
  81. receipts = append(receipts, receipt)
  82. allLogs = append(allLogs, receipt.Logs...)
  83. }
  84. // Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
  85. p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
  86. return receipts, allLogs, *usedGas, nil
  87. }
  88. func applyTransaction(msg types.Message, config *params.ChainConfig, author *common.Address, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
  89. // check eip155 sign after EthPow block
  90. if config.IsEthPoWFork(blockNumber) && !tx.Protected() {
  91. return nil, errors.New("only replay-protected (EIP-155) transactions allowed")
  92. }
  93. // Create a new context to be used in the EVM environment.
  94. txContext := NewEVMTxContext(msg)
  95. evm.Reset(txContext, statedb)
  96. // Apply the transaction to the current state (included in the env).
  97. result, err := ApplyMessage(evm, msg, gp)
  98. if err != nil {
  99. return nil, err
  100. }
  101. // Update the state with pending changes.
  102. var root []byte
  103. if config.IsByzantium(blockNumber) {
  104. statedb.Finalise(true)
  105. } else {
  106. root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
  107. }
  108. *usedGas += result.UsedGas
  109. // Create a new receipt for the transaction, storing the intermediate root and gas used
  110. // by the tx.
  111. receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
  112. if result.Failed() {
  113. receipt.Status = types.ReceiptStatusFailed
  114. } else {
  115. receipt.Status = types.ReceiptStatusSuccessful
  116. }
  117. receipt.TxHash = tx.Hash()
  118. receipt.GasUsed = result.UsedGas
  119. // If the transaction created a contract, store the creation address in the receipt.
  120. if msg.To() == nil {
  121. receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
  122. }
  123. // Set the receipt logs and create the bloom filter.
  124. receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
  125. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  126. receipt.BlockHash = blockHash
  127. receipt.BlockNumber = blockNumber
  128. receipt.TransactionIndex = uint(statedb.TxIndex())
  129. return receipt, err
  130. }
  131. func applyTransactionWithResult(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, *ExecutionResult, error) {
  132. // Create a new context to be used in the EVM environment.
  133. txContext := NewEVMTxContext(msg)
  134. evm.Reset(txContext, statedb)
  135. // Apply the transaction to the current state (included in the env).
  136. result, err := ApplyMessage(evm, msg, gp)
  137. if err != nil {
  138. return nil, nil, err
  139. }
  140. // Update the state with pending changes.
  141. var root []byte
  142. if config.IsByzantium(header.Number) {
  143. statedb.Finalise(true)
  144. } else {
  145. root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
  146. }
  147. *usedGas += result.UsedGas
  148. // Create a new receipt for the transaction, storing the intermediate root and gas used
  149. // by the tx.
  150. receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
  151. if result.Failed() {
  152. receipt.Status = types.ReceiptStatusFailed
  153. } else {
  154. receipt.Status = types.ReceiptStatusSuccessful
  155. }
  156. receipt.TxHash = tx.Hash()
  157. receipt.GasUsed = result.UsedGas
  158. // If the transaction created a contract, store the creation address in the receipt.
  159. if msg.To() == nil {
  160. receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
  161. }
  162. // Set the receipt logs and create the bloom filter.
  163. receipt.Logs = statedb.GetLogs(tx.Hash(), header.Hash())
  164. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  165. receipt.BlockHash = header.Hash()
  166. receipt.BlockNumber = header.Number
  167. receipt.TransactionIndex = uint(statedb.TxIndex())
  168. return receipt, result, err
  169. }
  170. // ApplyTransaction attempts to apply a transaction to the given state database
  171. // and uses the input parameters for its environment. It returns the receipt
  172. // for the transaction, gas used and an error if the transaction failed,
  173. // indicating the block was invalid.
  174. func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
  175. msg, err := tx.AsMessage(types.MakeSigner(config, header.Number), header.BaseFee)
  176. if err != nil {
  177. return nil, err
  178. }
  179. // Create a new context to be used in the EVM environment
  180. blockContext := NewEVMBlockContext(header, bc, author)
  181. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
  182. return applyTransaction(msg, config, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
  183. }
  184. func ApplyTransactionWithResult(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, *ExecutionResult, error) {
  185. msg, err := tx.AsMessage(types.MakeSigner(config, header.Number), header.BaseFee)
  186. if err != nil {
  187. return nil, nil, err
  188. }
  189. // Create a new context to be used in the EVM environment
  190. blockContext := NewEVMBlockContext(header, bc, author)
  191. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
  192. return applyTransactionWithResult(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
  193. }