state_transition.go 10 KB

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