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