state_transition.go 9.1 KB

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