state_processor.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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/systemcontracts"
  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. )
  29. // StateProcessor is a basic Processor, which takes care of transitioning
  30. // state from one point to another.
  31. //
  32. // StateProcessor implements Processor.
  33. type StateProcessor struct {
  34. config *params.ChainConfig // Chain configuration options
  35. bc *BlockChain // Canonical block chain
  36. engine consensus.Engine // Consensus engine used for block rewards
  37. }
  38. // NewStateProcessor initialises a new StateProcessor.
  39. func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
  40. return &StateProcessor{
  41. config: config,
  42. bc: bc,
  43. engine: engine,
  44. }
  45. }
  46. // Process processes the state changes according to the Ethereum rules by running
  47. // the transaction messages using the statedb and applying any rewards to both
  48. // the processor (coinbase) and any included uncles.
  49. //
  50. // Process returns the receipts and logs accumulated during the process and
  51. // returns the amount of gas that was used in the process. If any of the
  52. // transactions failed to execute due to insufficient gas it will return an error.
  53. func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
  54. var (
  55. usedGas = new(uint64)
  56. header = block.Header()
  57. allLogs []*types.Log
  58. gp = new(GasPool).AddGas(block.GasLimit())
  59. )
  60. var receipts = make([]*types.Receipt, 0)
  61. // Mutate the block and state according to any hard-fork specs
  62. if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
  63. misc.ApplyDAOHardFork(statedb)
  64. }
  65. // Handle upgrade build-in system contract code
  66. systemcontracts.UpgradeBuildInSystemContract(p.config, block.Number(), statedb)
  67. blockContext := NewEVMBlockContext(header, p.bc, nil)
  68. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
  69. // Iterate over and process the individual transactions
  70. posa, isPoSA := p.engine.(consensus.PoSA)
  71. commonTxs := make([]*types.Transaction, 0, len(block.Transactions()))
  72. // usually do have two tx, one for validator set contract, another for system reward contract.
  73. systemTxs := make([]*types.Transaction, 0, 2)
  74. signer := types.MakeSigner(p.config, header.Number)
  75. for i, tx := range block.Transactions() {
  76. if isPoSA {
  77. if isSystemTx, err := posa.IsSystemTransaction(tx, block.Header()); err != nil {
  78. return nil, nil, 0, err
  79. } else if isSystemTx {
  80. systemTxs = append(systemTxs, tx)
  81. continue
  82. }
  83. }
  84. msg, err := tx.AsMessage(signer)
  85. if err != nil {
  86. return nil, nil, 0, err
  87. }
  88. statedb.Prepare(tx.Hash(), block.Hash(), i)
  89. receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedGas, vmenv)
  90. if err != nil {
  91. return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
  92. }
  93. commonTxs = append(commonTxs, tx)
  94. receipts = append(receipts, receipt)
  95. }
  96. // Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
  97. err := p.engine.Finalize(p.bc, header, statedb, &commonTxs, block.Uncles(), &receipts, &systemTxs, usedGas)
  98. if err != nil {
  99. return receipts, allLogs, *usedGas, err
  100. }
  101. for _, receipt := range receipts {
  102. allLogs = append(allLogs, receipt.Logs...)
  103. }
  104. return receipts, allLogs, *usedGas, nil
  105. }
  106. 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) {
  107. // Create a new context to be used in the EVM environment.
  108. txContext := NewEVMTxContext(msg)
  109. evm.Reset(txContext, statedb)
  110. // Apply the transaction to the current state (included in the env).
  111. result, err := ApplyMessage(evm, msg, gp)
  112. if err != nil {
  113. return nil, err
  114. }
  115. // Update the state with pending changes.
  116. var root []byte
  117. if config.IsByzantium(header.Number) {
  118. statedb.Finalise(true)
  119. } else {
  120. root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
  121. }
  122. *usedGas += result.UsedGas
  123. // Create a new receipt for the transaction, storing the intermediate root and gas used
  124. // by the tx.
  125. receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
  126. if result.Failed() {
  127. receipt.Status = types.ReceiptStatusFailed
  128. } else {
  129. receipt.Status = types.ReceiptStatusSuccessful
  130. }
  131. receipt.TxHash = tx.Hash()
  132. receipt.GasUsed = result.UsedGas
  133. // If the transaction created a contract, store the creation address in the receipt.
  134. if msg.To() == nil {
  135. receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
  136. }
  137. // Set the receipt logs and create the bloom filter.
  138. receipt.Logs = statedb.GetLogs(tx.Hash())
  139. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  140. receipt.BlockHash = statedb.BlockHash()
  141. receipt.BlockNumber = header.Number
  142. receipt.TransactionIndex = uint(statedb.TxIndex())
  143. return receipt, err
  144. }
  145. // ApplyTransaction attempts to apply a transaction to the given state database
  146. // and uses the input parameters for its environment. It returns the receipt
  147. // for the transaction, gas used and an error if the transaction failed,
  148. // indicating the block was invalid.
  149. 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) {
  150. msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
  151. if err != nil {
  152. return nil, err
  153. }
  154. // Create a new context to be used in the EVM environment
  155. blockContext := NewEVMBlockContext(header, bc, author)
  156. vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
  157. defer func() {
  158. ite := vmenv.Interpreter()
  159. vm.EVMInterpreterPool.Put(ite)
  160. vm.EvmPool.Put(vmenv)
  161. }()
  162. return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
  163. }