state_transition.go 13 KB

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