gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/core/state_transition.go (about) 1 // Copyright 2014 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 "errors" 21 "math" 22 "math/big" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/consensus" 26 "github.com/ethereum/go-ethereum/core/vm" 27 "github.com/ethereum/go-ethereum/log" 28 "github.com/ethereum/go-ethereum/params" 29 ) 30 31 var ( 32 errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas") 33 ) 34 35 /* 36 The State Transitioning Model 37 38 A state transition is a change made when a transaction is applied to the current world state 39 The state transitioning model does all the necessary work to work out a valid new state root. 40 41 1) Nonce handling 42 2) Pre pay gas 43 3) Create a new state object if the recipient is \0*32 44 4) Value transfer 45 == If contract creation == 46 4a) Attempt to run transaction data 47 4b) If valid, use result as code for the new state object 48 == end == 49 5) Run Script section 50 6) Derive new state root 51 */ 52 type StateTransition struct { 53 gp *GasPool 54 msg Message 55 gas uint64 56 gasPrice *big.Int 57 initialGas uint64 58 value *big.Int 59 data []byte 60 state vm.StateDB 61 evm *vm.EVM 62 } 63 64 // Message represents a message sent to a contract. 65 type Message interface { 66 From() common.Address 67 //FromFrontier() (common.Address, error) 68 To() *common.Address 69 70 GasPrice() *big.Int 71 Gas() uint64 72 Value() *big.Int 73 74 Nonce() uint64 75 CheckNonce() bool 76 Data() []byte 77 } 78 79 // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. 80 func IntrinsicGas(data []byte, contractCreation, isHomestead bool, isEIP2028 bool) (uint64, error) { 81 // Set the starting gas for the raw transaction 82 var gas uint64 83 if contractCreation && isHomestead { 84 gas = params.TxGasContractCreation 85 } else { 86 gas = params.TxGas 87 } 88 // Bump the required gas by the amount of transactional data 89 if len(data) > 0 { 90 // Zero and non-zero bytes are priced differently 91 var nz uint64 92 for _, byt := range data { 93 if byt != 0 { 94 nz++ 95 } 96 } 97 // Make sure we don't exceed uint64 for all data combinations 98 nonZeroGas := params.TxDataNonZeroGasFrontier 99 if isEIP2028 { 100 nonZeroGas = params.TxDataNonZeroGasEIP2028 101 } 102 if (math.MaxUint64-gas)/nonZeroGas < nz { 103 return 0, vm.ErrOutOfGas 104 } 105 gas += nz * nonZeroGas 106 107 z := uint64(len(data)) - nz 108 if (math.MaxUint64-gas)/params.TxDataZeroGas < z { 109 return 0, vm.ErrOutOfGas 110 } 111 gas += z * params.TxDataZeroGas 112 } 113 return gas, nil 114 } 115 116 // NewStateTransition initialises and returns a new state transition object. 117 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition { 118 return &StateTransition{ 119 gp: gp, 120 evm: evm, 121 msg: msg, 122 gasPrice: msg.GasPrice(), 123 value: msg.Value(), 124 data: msg.Data(), 125 state: evm.StateDB, 126 } 127 } 128 129 // ApplyMessage computes the new state by applying the given message 130 // against the old state within the environment. 131 // 132 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 133 // the gas used (which includes gas refunds) and an error if it failed. An error always 134 // indicates a core error meaning that the message would always fail for that particular 135 // state and would never be accepted within a block. 136 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) { 137 return NewStateTransition(evm, msg, gp).TransitionDb() 138 } 139 140 // to returns the recipient of the message. 141 func (st *StateTransition) to() common.Address { 142 if st.msg == nil || st.msg.To() == nil /* contract creation */ { 143 return common.Address{} 144 } 145 return *st.msg.To() 146 } 147 148 func (st *StateTransition) useGas(amount uint64) error { 149 if st.gas < amount { 150 return vm.ErrOutOfGas 151 } 152 st.gas -= amount 153 154 return nil 155 } 156 157 func (st *StateTransition) buyGas() error { 158 mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice) 159 if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 { 160 return errInsufficientBalanceForGas 161 } 162 if err := st.gp.SubGas(st.msg.Gas()); err != nil { 163 return err 164 } 165 st.gas += st.msg.Gas() 166 167 st.initialGas = st.msg.Gas() 168 st.state.SubBalance(st.msg.From(), mgval) 169 return nil 170 } 171 172 func (st *StateTransition) preCheck() error { 173 // Make sure this transaction's nonce is correct. 174 if st.msg.CheckNonce() { 175 nonce := st.state.GetNonce(st.msg.From()) 176 if nonce < st.msg.Nonce() { 177 return ErrNonceTooHigh 178 } else if nonce > st.msg.Nonce() { 179 return ErrNonceTooLow 180 } 181 } 182 return st.buyGas() 183 } 184 185 // TransitionDb will transition the state by applying the current message and 186 // returning the result including the used gas. It returns an error if failed. 187 // An error indicates a consensus issue. 188 func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) { 189 if err = st.preCheck(); err != nil { 190 return 191 } 192 msg := st.msg 193 sender := vm.AccountRef(msg.From()) 194 homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber) 195 istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber) 196 contractCreation := msg.To() == nil 197 198 // Pay intrinsic gas 199 gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul) 200 if err != nil { 201 return nil, 0, false, err 202 } 203 if err = st.useGas(gas); err != nil { 204 return nil, 0, false, err 205 } 206 207 var ( 208 evm = st.evm 209 // vm errors do not effect consensus and are therefor 210 // not assigned to err, except for insufficient balance 211 // error. 212 vmerr error 213 ) 214 if contractCreation { 215 ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value) 216 } else { 217 // Increment the nonce for the next transaction 218 st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1) 219 ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value) 220 } 221 if vmerr != nil { 222 log.Debug("VM returned with error", "err", vmerr) 223 // The only possible consensus-error would be if there wasn't 224 // sufficient balance to make the transfer happen. The first 225 // balance transfer may never fail. 226 if vmerr == vm.ErrInsufficientBalance { 227 return nil, 0, false, vmerr 228 } 229 } 230 st.refundGas() 231 232 // consensus engine is parlia 233 if evm.ChainConfig().Parlia != nil { 234 st.state.AddBalance(consensus.SystemAddress, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 235 } else { 236 st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 237 } 238 return ret, st.gasUsed(), vmerr != nil, err 239 } 240 241 func (st *StateTransition) refundGas() { 242 // Apply refund counter, capped to half of the used gas. 243 refund := st.gasUsed() / 2 244 if refund > st.state.GetRefund() { 245 refund = st.state.GetRefund() 246 } 247 st.gas += refund 248 249 // Return ETH for remaining gas, exchanged at the original rate. 250 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 251 st.state.AddBalance(st.msg.From(), remaining) 252 253 // Also return remaining gas to the block gas counter so it is 254 // available for the next transaction. 255 st.gp.AddGas(st.gas) 256 } 257 258 // gasUsed returns the amount of gas used up by the state transition. 259 func (st *StateTransition) gasUsed() uint64 { 260 return st.initialGas - st.gas 261 }