github.com/dominant-strategies/go-quai@v0.28.2/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 "fmt" 21 "math" 22 "math/big" 23 24 "github.com/dominant-strategies/go-quai/common" 25 cmath "github.com/dominant-strategies/go-quai/common/math" 26 "github.com/dominant-strategies/go-quai/core/types" 27 "github.com/dominant-strategies/go-quai/core/vm" 28 "github.com/dominant-strategies/go-quai/crypto" 29 "github.com/dominant-strategies/go-quai/params" 30 ) 31 32 var emptyCodeHash = crypto.Keccak256Hash(nil) 33 34 /* 35 The State Transitioning Model 36 37 A state transition is a change made when a transaction is applied to the current world state 38 The state transitioning model does all the necessary work to work out a valid new state root. 39 40 1) Nonce handling 41 2) Pre pay gas 42 3) Create a new state object if the recipient is \0*32 43 4) Value transfer 44 == If contract creation == 45 46 4a) Attempt to run transaction data 47 4b) If valid, use result as code for the new state object 48 49 == end == 50 5) Run Script section 51 6) Derive new state root 52 */ 53 type StateTransition struct { 54 gp *GasPool 55 msg Message 56 gas uint64 57 gasPrice *big.Int 58 gasFeeCap *big.Int 59 gasTipCap *big.Int 60 initialGas uint64 61 value *big.Int 62 data []byte 63 state vm.StateDB 64 evm *vm.EVM 65 } 66 67 // Message represents a message sent to a contract. 68 type Message interface { 69 From() common.Address 70 To() *common.Address 71 72 GasPrice() *big.Int 73 GasFeeCap() *big.Int 74 GasTipCap() *big.Int 75 Gas() uint64 76 Value() *big.Int 77 78 Nonce() uint64 79 CheckNonce() bool 80 Data() []byte 81 AccessList() types.AccessList 82 ETXSender() common.Address 83 Type() byte 84 85 ETXGasLimit() uint64 86 ETXGasPrice() *big.Int 87 ETXGasTip() *big.Int 88 ETXData() []byte 89 ETXAccessList() types.AccessList 90 } 91 92 // ExecutionResult includes all output after executing given evm 93 // message no matter the execution itself is successful or not. 94 type ExecutionResult struct { 95 UsedGas uint64 // Total used gas but include the refunded gas 96 Err error // Any error encountered during the execution(listed in core/vm/errors.go) 97 ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode) 98 Etxs []*types.Transaction // External transactions generated from opETX 99 } 100 101 // Unwrap returns the internal evm error which allows us for further 102 // analysis outside. 103 func (result *ExecutionResult) Unwrap() error { 104 return result.Err 105 } 106 107 // Failed returns the indicator whether the execution is successful or not 108 func (result *ExecutionResult) Failed() bool { return result.Err != nil } 109 110 // Return is a helper function to help caller distinguish between revert reason 111 // and function return. Return returns the data after execution if no error occurs. 112 func (result *ExecutionResult) Return() []byte { 113 if result.Err != nil { 114 return nil 115 } 116 return common.CopyBytes(result.ReturnData) 117 } 118 119 // Revert returns the concrete revert reason if the execution is aborted by `REVERT` 120 // opcode. Note the reason can be nil if no data supplied with revert opcode. 121 func (result *ExecutionResult) Revert() []byte { 122 if result.Err != vm.ErrExecutionReverted { 123 return nil 124 } 125 return common.CopyBytes(result.ReturnData) 126 } 127 128 // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. 129 func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool) (uint64, error) { 130 // Set the starting gas for the raw transaction 131 var gas uint64 132 if isContractCreation { 133 gas = params.TxGasContractCreation 134 } else { 135 gas = params.TxGas 136 } 137 // Bump the required gas by the amount of transactional data 138 if len(data) > 0 { 139 // Zero and non-zero bytes are priced differently 140 var nz uint64 141 for _, byt := range data { 142 if byt != 0 { 143 nz++ 144 } 145 } 146 // Make sure we don't exceed uint64 for all data combinations 147 nonZeroGas := params.TxDataNonZeroGas 148 if (math.MaxUint64-gas)/nonZeroGas < nz { 149 return 0, ErrGasUintOverflow 150 } 151 gas += nz * nonZeroGas 152 153 z := uint64(len(data)) - nz 154 if (math.MaxUint64-gas)/params.TxDataZeroGas < z { 155 return 0, ErrGasUintOverflow 156 } 157 gas += z * params.TxDataZeroGas 158 } 159 if accessList != nil { 160 gas += uint64(len(accessList)) * params.TxAccessListAddressGas 161 gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas 162 } 163 return gas, nil 164 } 165 166 // NewStateTransition initialises and returns a new state transition object. 167 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition { 168 return &StateTransition{ 169 gp: gp, 170 evm: evm, 171 msg: msg, 172 gasPrice: msg.GasPrice(), 173 gasFeeCap: msg.GasFeeCap(), 174 gasTipCap: msg.GasTipCap(), 175 value: msg.Value(), 176 data: msg.Data(), 177 state: evm.StateDB, 178 } 179 } 180 181 // ApplyMessage computes the new state by applying the given message 182 // against the old state within the environment. 183 // 184 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 185 // the gas used (which includes gas refunds) and an error if it failed. An error always 186 // indicates a core error meaning that the message would always fail for that particular 187 // state and would never be accepted within a block. 188 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) { 189 return NewStateTransition(evm, msg, gp).TransitionDb() 190 } 191 192 // to returns the recipient of the message. 193 func (st *StateTransition) to() common.Address { 194 if st.msg == nil || st.msg.To() == nil /* contract creation */ { 195 return common.ZeroAddr 196 } 197 return *st.msg.To() 198 } 199 200 func (st *StateTransition) buyGas() error { 201 mgval := new(big.Int).SetUint64(st.msg.Gas()) 202 mgval = mgval.Mul(mgval, st.gasPrice) 203 balanceCheck := mgval 204 if st.gasFeeCap != nil { 205 balanceCheck = new(big.Int).SetUint64(st.msg.Gas()) 206 balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap) 207 balanceCheck.Add(balanceCheck, st.value) 208 } 209 from, err := st.msg.From().InternalAddress() 210 if err != nil { 211 return err 212 } 213 if have, want := st.state.GetBalance(from), balanceCheck; have.Cmp(want) < 0 { 214 return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want) 215 } 216 if err := st.gp.SubGas(st.msg.Gas()); err != nil { 217 return err 218 } 219 st.gas += st.msg.Gas() 220 221 st.initialGas = st.msg.Gas() 222 st.state.SubBalance(from, mgval) 223 return nil 224 } 225 226 func (st *StateTransition) preCheck() error { 227 from, err := st.msg.From().InternalAddress() 228 if err != nil { 229 return err 230 } 231 // Make sure this transaction's nonce is correct. 232 if st.msg.CheckNonce() { 233 stNonce := st.state.GetNonce(from) 234 if msgNonce := st.msg.Nonce(); stNonce < msgNonce { 235 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh, 236 st.msg.From().Hex(), msgNonce, stNonce) 237 } else if stNonce > msgNonce { 238 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow, 239 st.msg.From().Hex(), msgNonce, stNonce) 240 } 241 } 242 // Make sure the sender is an EOA 243 if codeHash := st.state.GetCodeHash(from); codeHash != emptyCodeHash && codeHash != (common.Hash{}) { 244 return fmt.Errorf("%w: address %v, codehash: %s", ErrSenderNoEOA, 245 st.msg.From().Hex(), codeHash) 246 } 247 // Make sure that transaction gasFeeCap is greater than the baseFee 248 // Skip the checks if gas fields are zero and baseFee was explicitly disabled (eth_call) 249 if !st.evm.Config.NoBaseFee || st.gasFeeCap.BitLen() > 0 || st.gasTipCap.BitLen() > 0 { 250 if l := st.gasFeeCap.BitLen(); l > 256 { 251 return fmt.Errorf("%w: address %v, maxFeePerGas bit length: %d", ErrFeeCapVeryHigh, 252 st.msg.From().Hex(), l) 253 } 254 if l := st.gasTipCap.BitLen(); l > 256 { 255 return fmt.Errorf("%w: address %v, maxPriorityFeePerGas bit length: %d", ErrTipVeryHigh, 256 st.msg.From().Hex(), l) 257 } 258 if st.gasFeeCap.Cmp(st.gasTipCap) < 0 { 259 return fmt.Errorf("%w: address %v, maxPriorityFeePerGas: %s, maxFeePerGas: %s", ErrTipAboveFeeCap, 260 st.msg.From().Hex(), st.gasTipCap, st.gasFeeCap) 261 } 262 // This will panic if baseFee is nil, but basefee presence is verified 263 // as part of header validation. 264 if st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 { 265 return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow, 266 st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee) 267 } 268 } 269 return st.buyGas() 270 } 271 272 // TransitionDb will transition the state by applying the current message and 273 // returning the evm execution result with following fields. 274 // 275 // - used gas: 276 // total gas used (including gas being refunded) 277 // - returndata: 278 // the returned data from evm 279 // - concrete execution error: 280 // various **EVM** error which aborts the execution, 281 // e.g. ErrOutOfGas, ErrExecutionReverted 282 // 283 // However if any consensus issue encountered, return the error directly with 284 // nil evm execution result. 285 func (st *StateTransition) TransitionDb() (*ExecutionResult, error) { 286 // First check this message satisfies all consensus rules before 287 // applying the message. The rules include these clauses 288 // 289 // 1. the nonce of the message caller is correct 290 // 2. caller has enough balance to cover transaction fee(gaslimit * gasprice) 291 // 3. the amount of gas required is available in the block 292 // 4. the purchased gas is enough to cover intrinsic usage 293 // 5. there is no overflow when calculating intrinsic gas 294 // 6. caller has enough balance to cover asset transfer for **topmost** call 295 296 // Check clauses 1-3, buy gas if everything is correct 297 if err := st.preCheck(); err != nil { 298 return nil, err 299 } 300 msg := st.msg 301 sender := vm.AccountRef(msg.From()) 302 contractCreation := msg.To() == nil 303 304 // Check clauses 4-5, subtract intrinsic gas if everything is correct 305 gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation) 306 if err != nil { 307 return nil, err 308 } 309 if st.gas < gas { 310 return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas) 311 } 312 st.gas -= gas 313 314 // Check clause 6 315 if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) { 316 return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()) 317 } 318 319 // Set up the initial access list. 320 rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber) 321 st.state.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList()) 322 323 var ( 324 ret []byte 325 vmerr error // vm errors do not effect consensus and are therefore not assigned to err 326 ) 327 if contractCreation { 328 ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value) 329 } else { 330 // Increment the nonce for the next transaction 331 addr, err := sender.Address().InternalAddress() 332 if err != nil { 333 return nil, err 334 } 335 from, err := msg.From().InternalAddress() 336 if err != nil { 337 return nil, err 338 } 339 st.state.SetNonce(from, st.state.GetNonce(addr)+1) 340 ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value) 341 } 342 343 // At this point, the execution completed, so the ETX cache can be dumped and reset 344 st.evm.ETXCacheLock.Lock() 345 etxs := make([]*types.Transaction, len(st.evm.ETXCache)) 346 copy(etxs, st.evm.ETXCache) 347 st.evm.ETXCache = make([]*types.Transaction, 0) 348 st.evm.ETXCacheLock.Unlock() 349 350 // refunds are capped to gasUsed / 5 351 st.refundGas(params.RefundQuotient) 352 353 effectiveTip := cmath.BigMin(st.gasTipCap, new(big.Int).Sub(st.gasFeeCap, st.evm.Context.BaseFee)) 354 coinbase, err := st.evm.Context.Coinbase.InternalAddress() 355 if err != nil { 356 return nil, err 357 } 358 st.state.AddBalance(coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip)) 359 360 return &ExecutionResult{ 361 UsedGas: st.gasUsed(), 362 Err: vmerr, 363 ReturnData: ret, 364 Etxs: etxs, 365 }, nil 366 } 367 368 func (st *StateTransition) refundGas(refundQuotient uint64) { 369 // Apply refund counter, capped to a refund quotient 370 refund := st.gasUsed() / refundQuotient 371 if refund > st.state.GetRefund() { 372 refund = st.state.GetRefund() 373 } 374 st.gas += refund 375 376 // Return ETH for remaining gas, exchanged at the original rate. 377 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 378 from, err := st.msg.From().InternalAddress() 379 if err != nil { 380 return 381 } 382 st.state.AddBalance(from, remaining) 383 384 // Also return remaining gas to the block gas counter so it is 385 // available for the next transaction. 386 st.gp.AddGas(st.gas) 387 } 388 389 // gasUsed returns the amount of gas used up by the state transition. 390 func (st *StateTransition) gasUsed() uint64 { 391 return st.initialGas - st.gas 392 }