state_processor.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/consensus"
  21. "github.com/ethereum/go-ethereum/consensus/misc"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/core/vm"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/params"
  27. )
  28. // StateProcessor is a basic Processor, which takes care of transitioning
  29. // state from one point to another.
  30. //
  31. // StateProcessor implements Processor.
  32. type StateProcessor struct {
  33. config *params.ChainConfig // Chain configuration options
  34. bc *BlockChain // Canonical block chain
  35. engine consensus.Engine // Consensus engine used for block rewards
  36. }
  37. // NewStateProcessor initialises a new StateProcessor.
  38. func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
  39. return &StateProcessor{
  40. config: config,
  41. bc: bc,
  42. engine: engine,
  43. }
  44. }
  45. // Process processes the state changes according to the Ethereum rules by running
  46. // the transaction messages using the statedb and applying any rewards to both
  47. // the processor (coinbase) and any included uncles.
  48. //
  49. // Process returns the receipts and logs accumulated during the process and
  50. // returns the amount of gas that was used in the process. If any of the
  51. // transactions failed to execute due to insufficient gas it will return an error.
  52. func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
  53. var (
  54. receipts types.Receipts
  55. usedGas = new(uint64)
  56. header = block.Header()
  57. allLogs []*types.Log
  58. gp = new(GasPool).AddGas(block.GasLimit())
  59. )
  60. // Mutate the block and state according to any hard-fork specs
  61. if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
  62. misc.ApplyDAOHardFork(statedb)
  63. }
  64. blockContext := NewEVMBlockContext(header, p.bc, nil)
  65. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
  66. // Iterate over and process the individual transactions
  67. for i, tx := range block.Transactions() {
  68. msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number))
  69. if err != nil {
  70. return nil, nil, 0, err
  71. }
  72. statedb.Prepare(tx.Hash(), block.Hash(), i)
  73. receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedGas, vmenv)
  74. if err != nil {
  75. return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
  76. }
  77. receipts = append(receipts, receipt)
  78. allLogs = append(allLogs, receipt.Logs...)
  79. }
  80. // Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
  81. p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
  82. return receipts, allLogs, *usedGas, nil
  83. }
  84. func applyTransaction(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, error) {
  85. // Create a new context to be used in the EVM environment
  86. txContext := NewEVMTxContext(msg)
  87. // Add addresses to access list if applicable
  88. if config.IsYoloV2(header.Number) {
  89. statedb.AddAddressToAccessList(msg.From())
  90. if dst := msg.To(); dst != nil {
  91. statedb.AddAddressToAccessList(*dst)
  92. // If it's a create-tx, the destination will be added inside evm.create
  93. }
  94. for _, addr := range evm.ActivePrecompiles() {
  95. statedb.AddAddressToAccessList(addr)
  96. }
  97. }
  98. // Update the evm with the new transaction context.
  99. evm.Reset(txContext, statedb)
  100. // Apply the transaction to the current state (included in the env)
  101. result, err := ApplyMessage(evm, msg, gp)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Update the state with pending changes
  106. var root []byte
  107. if config.IsByzantium(header.Number) {
  108. statedb.Finalise(true)
  109. } else {
  110. root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
  111. }
  112. *usedGas += result.UsedGas
  113. // Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
  114. // based on the eip phase, we're passing whether the root touch-delete accounts.
  115. receipt := types.NewReceipt(root, result.Failed(), *usedGas)
  116. receipt.TxHash = tx.Hash()
  117. receipt.GasUsed = result.UsedGas
  118. // if the transaction created a contract, store the creation address in the receipt.
  119. if msg.To() == nil {
  120. receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
  121. }
  122. // Set the receipt logs and create a bloom for filtering
  123. receipt.Logs = statedb.GetLogs(tx.Hash())
  124. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  125. receipt.BlockHash = statedb.BlockHash()
  126. receipt.BlockNumber = header.Number
  127. receipt.TransactionIndex = uint(statedb.TxIndex())
  128. return receipt, err
  129. }
  130. // ApplyTransaction attempts to apply a transaction to the given state database
  131. // and uses the input parameters for its environment. It returns the receipt
  132. // for the transaction, gas used and an error if the transaction failed,
  133. // indicating the block was invalid.
  134. 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) {
  135. msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
  136. if err != nil {
  137. return nil, err
  138. }
  139. // Create a new context to be used in the EVM environment
  140. blockContext := NewEVMBlockContext(header, bc, author)
  141. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
  142. return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
  143. }