state_transition.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/core/vm"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. /*
  27. The State Transitioning Model
  28. A state transition is a change made when a transaction is applied to the current world state
  29. The state transitioning model does all the necessary work to work out a valid new state root.
  30. 1) Nonce handling
  31. 2) Pre pay gas
  32. 3) Create a new state object if the recipient is \0*32
  33. 4) Value transfer
  34. == If contract creation ==
  35. 4a) Attempt to run transaction data
  36. 4b) If valid, use result as code for the new state object
  37. == end ==
  38. 5) Run Script section
  39. 6) Derive new state root
  40. */
  41. type StateTransition struct {
  42. gp *GasPool
  43. msg Message
  44. gas uint64
  45. gasPrice *big.Int
  46. initialGas uint64
  47. value *big.Int
  48. data []byte
  49. state vm.StateDB
  50. evm *vm.EVM
  51. }
  52. // Message represents a message sent to a contract.
  53. type Message interface {
  54. From() common.Address
  55. To() *common.Address
  56. GasPrice() *big.Int
  57. Gas() uint64
  58. Value() *big.Int
  59. Nonce() uint64
  60. CheckNonce() bool
  61. Data() []byte
  62. AccessList() types.AccessList
  63. }
  64. // ExecutionResult includes all output after executing given evm
  65. // message no matter the execution itself is successful or not.
  66. type ExecutionResult struct {
  67. UsedGas uint64 // Total used gas but include the refunded gas
  68. Err error // Any error encountered during the execution(listed in core/vm/errors.go)
  69. ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
  70. }
  71. // Unwrap returns the internal evm error which allows us for further
  72. // analysis outside.
  73. func (result *ExecutionResult) Unwrap() error {
  74. return result.Err
  75. }
  76. // Failed returns the indicator whether the execution is successful or not
  77. func (result *ExecutionResult) Failed() bool { return result.Err != nil }
  78. // Return is a helper function to help caller distinguish between revert reason
  79. // and function return. Return returns the data after execution if no error occurs.
  80. func (result *ExecutionResult) Return() []byte {
  81. if result.Err != nil {
  82. return nil
  83. }
  84. return common.CopyBytes(result.ReturnData)
  85. }
  86. // Revert returns the concrete revert reason if the execution is aborted by `REVERT`
  87. // opcode. Note the reason can be nil if no data supplied with revert opcode.
  88. func (result *ExecutionResult) Revert() []byte {
  89. if result.Err != vm.ErrExecutionReverted {
  90. return nil
  91. }
  92. return common.CopyBytes(result.ReturnData)
  93. }
  94. // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
  95. func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool) (uint64, error) {
  96. // Set the starting gas for the raw transaction
  97. var gas uint64
  98. if isContractCreation && isHomestead {
  99. gas = params.TxGasContractCreation
  100. } else {
  101. gas = params.TxGas
  102. }
  103. // Bump the required gas by the amount of transactional data
  104. if len(data) > 0 {
  105. // Zero and non-zero bytes are priced differently
  106. var nz uint64
  107. for _, byt := range data {
  108. if byt != 0 {
  109. nz++
  110. }
  111. }
  112. // Make sure we don't exceed uint64 for all data combinations
  113. nonZeroGas := params.TxDataNonZeroGasFrontier
  114. if isEIP2028 {
  115. nonZeroGas = params.TxDataNonZeroGasEIP2028
  116. }
  117. if (math.MaxUint64-gas)/nonZeroGas < nz {
  118. return 0, ErrGasUintOverflow
  119. }
  120. gas += nz * nonZeroGas
  121. z := uint64(len(data)) - nz
  122. if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
  123. return 0, ErrGasUintOverflow
  124. }
  125. gas += z * params.TxDataZeroGas
  126. }
  127. if accessList != nil {
  128. gas += uint64(len(accessList)) * params.TxAccessListAddressGas
  129. gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
  130. }
  131. return gas, nil
  132. }
  133. // NewStateTransition initialises and returns a new state transition object.
  134. func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
  135. return &StateTransition{
  136. gp: gp,
  137. evm: evm,
  138. msg: msg,
  139. gasPrice: msg.GasPrice(),
  140. value: msg.Value(),
  141. data: msg.Data(),
  142. state: evm.StateDB,
  143. }
  144. }
  145. // ApplyMessage computes the new state by applying the given message
  146. // against the old state within the environment.
  147. //
  148. // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
  149. // the gas used (which includes gas refunds) and an error if it failed. An error always
  150. // indicates a core error meaning that the message would always fail for that particular
  151. // state and would never be accepted within a block.
  152. func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
  153. return NewStateTransition(evm, msg, gp).TransitionDb()
  154. }
  155. // to returns the recipient of the message.
  156. func (st *StateTransition) to() common.Address {
  157. if st.msg == nil || st.msg.To() == nil /* contract creation */ {
  158. return common.Address{}
  159. }
  160. return *st.msg.To()
  161. }
  162. func (st *StateTransition) buyGas() error {
  163. mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
  164. if have, want := st.state.GetBalance(st.msg.From()), mgval; have.Cmp(want) < 0 {
  165. return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want)
  166. }
  167. if err := st.gp.SubGas(st.msg.Gas()); err != nil {
  168. return err
  169. }
  170. st.gas += st.msg.Gas()
  171. st.initialGas = st.msg.Gas()
  172. st.state.SubBalance(st.msg.From(), mgval)
  173. return nil
  174. }
  175. func (st *StateTransition) preCheck() error {
  176. // Make sure this transaction's nonce is correct.
  177. if st.msg.CheckNonce() {
  178. stNonce := st.state.GetNonce(st.msg.From())
  179. if msgNonce := st.msg.Nonce(); stNonce < msgNonce {
  180. return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh,
  181. st.msg.From().Hex(), msgNonce, stNonce)
  182. } else if stNonce > msgNonce {
  183. return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow,
  184. st.msg.From().Hex(), msgNonce, stNonce)
  185. }
  186. }
  187. return st.buyGas()
  188. }
  189. // TransitionDb will transition the state by applying the current message and
  190. // returning the evm execution result with following fields.
  191. //
  192. // - used gas:
  193. // total gas used (including gas being refunded)
  194. // - returndata:
  195. // the returned data from evm
  196. // - concrete execution error:
  197. // various **EVM** error which aborts the execution,
  198. // e.g. ErrOutOfGas, ErrExecutionReverted
  199. //
  200. // However if any consensus issue encountered, return the error directly with
  201. // nil evm execution result.
  202. func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
  203. // First check this message satisfies all consensus rules before
  204. // applying the message. The rules include these clauses
  205. //
  206. // 1. the nonce of the message caller is correct
  207. // 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
  208. // 3. the amount of gas required is available in the block
  209. // 4. the purchased gas is enough to cover intrinsic usage
  210. // 5. there is no overflow when calculating intrinsic gas
  211. // 6. caller has enough balance to cover asset transfer for **topmost** call
  212. // Check clauses 1-3, buy gas if everything is correct
  213. if err := st.preCheck(); err != nil {
  214. return nil, err
  215. }
  216. msg := st.msg
  217. sender := vm.AccountRef(msg.From())
  218. homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
  219. istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
  220. contractCreation := msg.To() == nil
  221. // Check clauses 4-5, subtract intrinsic gas if everything is correct
  222. gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul)
  223. if err != nil {
  224. return nil, err
  225. }
  226. if st.gas < gas {
  227. return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
  228. }
  229. st.gas -= gas
  230. // Check clause 6
  231. if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
  232. return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
  233. }
  234. // Set up the initial access list.
  235. if st.evm.ChainConfig().IsYoloV3(st.evm.Context.BlockNumber) {
  236. st.state.PrepareAccessList(msg.From(), msg.To(), st.evm.ActivePrecompiles(), msg.AccessList())
  237. }
  238. var (
  239. ret []byte
  240. vmerr error // vm errors do not effect consensus and are therefore not assigned to err
  241. )
  242. if contractCreation {
  243. ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value)
  244. } else {
  245. // Increment the nonce for the next transaction
  246. st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
  247. ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
  248. }
  249. st.refundGas()
  250. st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
  251. return &ExecutionResult{
  252. UsedGas: st.gasUsed(),
  253. Err: vmerr,
  254. ReturnData: ret,
  255. }, nil
  256. }
  257. func (st *StateTransition) refundGas() {
  258. // Apply refund counter, capped to half of the used gas.
  259. refund := st.gasUsed() / 2
  260. if refund > st.state.GetRefund() {
  261. refund = st.state.GetRefund()
  262. }
  263. st.gas += refund
  264. // Return ETH for remaining gas, exchanged at the original rate.
  265. remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
  266. st.state.AddBalance(st.msg.From(), remaining)
  267. // Also return remaining gas to the block gas counter so it is
  268. // available for the next transaction.
  269. st.gp.AddGas(st.gas)
  270. }
  271. // gasUsed returns the amount of gas used up by the state transition.
  272. func (st *StateTransition) gasUsed() uint64 {
  273. return st.initialGas - st.gas
  274. }