state_transition.go 9.5 KB

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