github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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/scroll-tech/go-ethereum/common" 25 cmath "github.com/scroll-tech/go-ethereum/common/math" 26 "github.com/scroll-tech/go-ethereum/core/types" 27 "github.com/scroll-tech/go-ethereum/core/vm" 28 "github.com/scroll-tech/go-ethereum/crypto/codehash" 29 "github.com/scroll-tech/go-ethereum/log" 30 "github.com/scroll-tech/go-ethereum/params" 31 ) 32 33 var emptyKeccakCodeHash = codehash.EmptyKeccakCodeHash 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 gasFeeCap *big.Int 58 gasTipCap *big.Int 59 initialGas uint64 60 value *big.Int 61 data []byte 62 state vm.StateDB 63 evm *vm.EVM 64 65 l1DataFee *big.Int 66 } 67 68 // Message represents a message sent to a contract. 69 type Message interface { 70 From() common.Address 71 To() *common.Address 72 73 GasPrice() *big.Int 74 GasFeeCap() *big.Int 75 GasTipCap() *big.Int 76 Gas() uint64 77 Value() *big.Int 78 79 Nonce() uint64 80 IsFake() bool 81 Data() []byte 82 AccessList() types.AccessList 83 IsL1MessageTx() bool 84 } 85 86 // ExecutionResult includes all output after executing given evm 87 // message no matter the execution itself is successful or not. 88 type ExecutionResult struct { 89 L1DataFee *big.Int 90 UsedGas uint64 // Total used gas but include the refunded gas 91 Err error // Any error encountered during the execution(listed in core/vm/errors.go) 92 ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode) 93 } 94 95 // Unwrap returns the internal evm error which allows us for further 96 // analysis outside. 97 func (result *ExecutionResult) Unwrap() error { 98 return result.Err 99 } 100 101 // Failed returns the indicator whether the execution is successful or not 102 func (result *ExecutionResult) Failed() bool { return result.Err != nil } 103 104 // Return is a helper function to help caller distinguish between revert reason 105 // and function return. Return returns the data after execution if no error occurs. 106 func (result *ExecutionResult) Return() []byte { 107 if result.Err != nil { 108 return nil 109 } 110 return common.CopyBytes(result.ReturnData) 111 } 112 113 // Revert returns the concrete revert reason if the execution is aborted by `REVERT` 114 // opcode. Note the reason can be nil if no data supplied with revert opcode. 115 func (result *ExecutionResult) Revert() []byte { 116 if result.Err != vm.ErrExecutionReverted { 117 return nil 118 } 119 return common.CopyBytes(result.ReturnData) 120 } 121 122 // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. 123 func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool, isEIP3860 bool) (uint64, error) { 124 // Set the starting gas for the raw transaction 125 var gas uint64 126 if isContractCreation && isHomestead { 127 gas = params.TxGasContractCreation 128 } else { 129 gas = params.TxGas 130 } 131 dataLen := uint64(len(data)) 132 // Bump the required gas by the amount of transactional data 133 if dataLen > 0 { 134 // Zero and non-zero bytes are priced differently 135 var nz uint64 136 for _, byt := range data { 137 if byt != 0 { 138 nz++ 139 } 140 } 141 // Make sure we don't exceed uint64 for all data combinations 142 nonZeroGas := params.TxDataNonZeroGasFrontier 143 if isEIP2028 { 144 nonZeroGas = params.TxDataNonZeroGasEIP2028 145 } 146 if (math.MaxUint64-gas)/nonZeroGas < nz { 147 return 0, ErrGasUintOverflow 148 } 149 gas += nz * nonZeroGas 150 151 z := dataLen - nz 152 if (math.MaxUint64-gas)/params.TxDataZeroGas < z { 153 return 0, ErrGasUintOverflow 154 } 155 gas += z * params.TxDataZeroGas 156 157 if isContractCreation && isEIP3860 { 158 lenWords := toWordSize(dataLen) 159 if (math.MaxUint64-gas)/params.InitCodeWordGas < lenWords { 160 return 0, ErrGasUintOverflow 161 } 162 gas += lenWords * params.InitCodeWordGas 163 } 164 } 165 if accessList != nil { 166 gas += uint64(len(accessList)) * params.TxAccessListAddressGas 167 gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas 168 } 169 return gas, nil 170 } 171 172 // toWordSize returns the ceiled word size required for init code payment calculation. 173 func toWordSize(size uint64) uint64 { 174 if size > math.MaxUint64-31 { 175 return math.MaxUint64/32 + 1 176 } 177 178 return (size + 31) / 32 179 } 180 181 // NewStateTransition initialises and returns a new state transition object. 182 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool, l1DataFee *big.Int) *StateTransition { 183 return &StateTransition{ 184 gp: gp, 185 evm: evm, 186 msg: msg, 187 gasPrice: msg.GasPrice(), 188 gasFeeCap: msg.GasFeeCap(), 189 gasTipCap: msg.GasTipCap(), 190 value: msg.Value(), 191 data: msg.Data(), 192 state: evm.StateDB, 193 l1DataFee: l1DataFee, 194 } 195 } 196 197 // ApplyMessage computes the new state by applying the given message 198 // against the old state within the environment. 199 // 200 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 201 // the gas used (which includes gas refunds) and an error if it failed. An error always 202 // indicates a core error meaning that the message would always fail for that particular 203 // state and would never be accepted within a block. 204 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool, l1DataFee *big.Int) (*ExecutionResult, error) { 205 return NewStateTransition(evm, msg, gp, l1DataFee).TransitionDb() 206 } 207 208 // to returns the recipient of the message. 209 func (st *StateTransition) to() common.Address { 210 if st.msg == nil || st.msg.To() == nil /* contract creation */ { 211 return common.Address{} 212 } 213 return *st.msg.To() 214 } 215 216 func (st *StateTransition) buyGas() error { 217 mgval := new(big.Int).SetUint64(st.msg.Gas()) 218 mgval = mgval.Mul(mgval, st.gasPrice) 219 220 if st.evm.ChainConfig().Scroll.FeeVaultEnabled() { 221 // should be fine to add st.l1DataFee even without `L1MessageTx` check, since L1MessageTx will come with 0 l1DataFee, 222 // but double check to make sure 223 if !st.msg.IsL1MessageTx() { 224 log.Debug("Adding L1DataFee", "l1DataFee", st.l1DataFee) 225 mgval = mgval.Add(mgval, st.l1DataFee) 226 } 227 } 228 229 balanceCheck := mgval 230 if st.gasFeeCap != nil { 231 balanceCheck = new(big.Int).SetUint64(st.msg.Gas()) 232 balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap) 233 balanceCheck.Add(balanceCheck, st.value) 234 if st.evm.ChainConfig().Scroll.FeeVaultEnabled() { 235 // should be fine to add st.l1DataFee even without `L1MessageTx` check, since L1MessageTx will come with 0 l1DataFee, 236 // but double check to make sure 237 if !st.msg.IsL1MessageTx() { 238 balanceCheck.Add(balanceCheck, st.l1DataFee) 239 } 240 } 241 } 242 if have, want := st.state.GetBalance(st.msg.From()), balanceCheck; have.Cmp(want) < 0 { 243 return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want) 244 } 245 if err := st.gp.SubGas(st.msg.Gas()); err != nil { 246 return err 247 } 248 st.gas += st.msg.Gas() 249 250 st.initialGas = st.msg.Gas() 251 st.state.SubBalance(st.msg.From(), mgval) 252 return nil 253 } 254 255 func (st *StateTransition) preCheck() error { 256 if st.msg.IsL1MessageTx() { 257 // No fee fields to check, no nonce to check, and no need to check if EOA (L1 already verified it for us) 258 // Gas is free, but no refunds! 259 st.gas += st.msg.Gas() 260 st.initialGas = st.msg.Gas() 261 return st.gp.SubGas(st.msg.Gas()) // gas used by deposits may not be used by other txs 262 } 263 264 // Only check transactions that are not fake 265 if !st.msg.IsFake() { 266 // Make sure this transaction's nonce is correct. 267 stNonce := st.state.GetNonce(st.msg.From()) 268 if msgNonce := st.msg.Nonce(); stNonce < msgNonce { 269 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh, 270 st.msg.From().Hex(), msgNonce, stNonce) 271 } else if stNonce > msgNonce { 272 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow, 273 st.msg.From().Hex(), msgNonce, stNonce) 274 } else if stNonce+1 < stNonce { 275 return fmt.Errorf("%w: address %v, nonce: %d", ErrNonceMax, 276 st.msg.From().Hex(), stNonce) 277 } 278 // Make sure the sender is an EOA 279 if codeHash := st.state.GetKeccakCodeHash(st.msg.From()); codeHash != emptyKeccakCodeHash && codeHash != (common.Hash{}) { 280 return fmt.Errorf("%w: address %v, codehash: %s", ErrSenderNoEOA, 281 st.msg.From().Hex(), codeHash) 282 } 283 } 284 // Make sure that transaction gasFeeCap is greater than the baseFee (post london) 285 if st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber) { 286 // Skip the checks if gas fields are zero and baseFee was explicitly disabled (eth_call) 287 if !st.evm.Config.NoBaseFee || st.gasFeeCap.BitLen() > 0 || st.gasTipCap.BitLen() > 0 { 288 if l := st.gasFeeCap.BitLen(); l > 256 { 289 return fmt.Errorf("%w: address %v, maxFeePerGas bit length: %d", ErrFeeCapVeryHigh, 290 st.msg.From().Hex(), l) 291 } 292 if l := st.gasTipCap.BitLen(); l > 256 { 293 return fmt.Errorf("%w: address %v, maxPriorityFeePerGas bit length: %d", ErrTipVeryHigh, 294 st.msg.From().Hex(), l) 295 } 296 if st.gasFeeCap.Cmp(st.gasTipCap) < 0 { 297 return fmt.Errorf("%w: address %v, maxPriorityFeePerGas: %s, maxFeePerGas: %s", ErrTipAboveFeeCap, 298 st.msg.From().Hex(), st.gasTipCap, st.gasFeeCap) 299 } 300 // This will panic if baseFee is nil, but basefee presence is verified 301 // as part of header validation. 302 if st.evm.Context.BaseFee != nil && st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 { 303 return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow, 304 st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee) 305 } 306 if st.evm.Context.BaseFee == nil && st.gasFeeCap.Cmp(big.NewInt(0)) < 0 { 307 return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow, 308 st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee) 309 } 310 } 311 } 312 return st.buyGas() 313 } 314 315 // TransitionDb will transition the state by applying the current message and 316 // returning the evm execution result with following fields. 317 // 318 // - used gas: 319 // total gas used (including gas being refunded) 320 // - returndata: 321 // the returned data from evm 322 // - concrete execution error: 323 // various **EVM** error which aborts the execution, 324 // e.g. ErrOutOfGas, ErrExecutionReverted 325 // 326 // However if any consensus issue encountered, return the error directly with 327 // nil evm execution result. 328 func (st *StateTransition) TransitionDb() (*ExecutionResult, error) { 329 // First check this message satisfies all consensus rules before 330 // applying the message. The rules include these clauses 331 // 332 // 1. the nonce of the message caller is correct 333 // 2. caller has enough balance to cover transaction fee(gaslimit * gasprice) 334 // 3. the amount of gas required is available in the block 335 // 4. the purchased gas is enough to cover intrinsic usage 336 // 5. there is no overflow when calculating intrinsic gas 337 // 6. caller has enough balance to cover asset transfer for **topmost** call 338 339 // Check clauses 1-3, buy gas if everything is correct 340 if err := st.preCheck(); err != nil { 341 return nil, err 342 } 343 msg := st.msg 344 sender := vm.AccountRef(msg.From()) 345 homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber) 346 istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber) 347 shanghai := st.evm.ChainConfig().IsShanghai(st.evm.Context.BlockNumber) 348 london := st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber) 349 contractCreation := msg.To() == nil 350 351 // Check clauses 4-5, subtract intrinsic gas if everything is correct 352 gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul, shanghai) 353 if err != nil { 354 return nil, err 355 } 356 if st.gas < gas { 357 return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas) 358 } 359 st.gas -= gas 360 361 // Check clause 6 362 if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) { 363 return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()) 364 } 365 366 rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber) 367 368 // Check whether the init code size has been exceeded. 369 if rules.IsShanghai && contractCreation && len(st.data) > params.MaxInitCodeSize { 370 return nil, fmt.Errorf("%w: code size %v limit %v", ErrMaxInitCodeSizeExceeded, len(st.data), params.MaxInitCodeSize) 371 } 372 373 // Set up the initial access list. 374 if rules.IsBerlin { 375 st.state.PrepareAccessList(rules, msg.From(), st.evm.Context.Coinbase, msg.To(), vm.ActivePrecompiles(rules), msg.AccessList()) 376 } 377 378 var ( 379 ret []byte 380 vmerr error // vm errors do not effect consensus and are therefore not assigned to err 381 ) 382 if contractCreation { 383 ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value) 384 } else { 385 // Increment the nonce for the next transaction 386 st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1) 387 ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value) 388 } 389 390 // no refunds for l1 messages 391 if st.msg.IsL1MessageTx() { 392 return &ExecutionResult{ 393 L1DataFee: big.NewInt(0), 394 UsedGas: st.gasUsed(), 395 Err: vmerr, 396 ReturnData: ret, 397 }, nil 398 } 399 400 if !london { 401 // Before EIP-3529: refunds were capped to gasUsed / 2 402 st.refundGas(params.RefundQuotient) 403 } else { 404 // After EIP-3529: refunds are capped to gasUsed / 5 405 st.refundGas(params.RefundQuotientEIP3529) 406 } 407 effectiveTip := st.gasPrice 408 if london { 409 if st.evm.Context.BaseFee != nil { 410 effectiveTip = cmath.BigMin(st.gasTipCap, new(big.Int).Sub(st.gasFeeCap, st.evm.Context.BaseFee)) 411 } else { 412 effectiveTip = cmath.BigMin(st.gasTipCap, st.gasFeeCap) 413 } 414 } 415 416 // The L2 Fee is the same as the fee that is charged in the normal geth 417 // codepath. Add the L1DataFee to the L2 fee for the total fee that is sent 418 // to the sequencer. 419 l2Fee := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip) 420 fee := new(big.Int).Add(st.l1DataFee, l2Fee) 421 st.state.AddBalance(st.evm.FeeRecipient(), fee) 422 423 return &ExecutionResult{ 424 L1DataFee: st.l1DataFee, 425 UsedGas: st.gasUsed(), 426 Err: vmerr, 427 ReturnData: ret, 428 }, nil 429 } 430 431 func (st *StateTransition) refundGas(refundQuotient uint64) { 432 // Apply refund counter, capped to a refund quotient 433 refund := st.gasUsed() / refundQuotient 434 if refund > st.state.GetRefund() { 435 refund = st.state.GetRefund() 436 } 437 st.gas += refund 438 439 // Return ETH for remaining gas, exchanged at the original rate. 440 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 441 st.state.AddBalance(st.msg.From(), remaining) 442 443 // Also return remaining gas to the block gas counter so it is 444 // available for the next transaction. 445 st.gp.AddGas(st.gas) 446 } 447 448 // gasUsed returns the amount of gas used up by the state transition. 449 func (st *StateTransition) gasUsed() uint64 { 450 return st.initialGas - st.gas 451 }