state_transition.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. "errors"
  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/log"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. var (
  27. errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
  28. )
  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. initialGas uint64
  50. value *big.Int
  51. data []byte
  52. state vm.StateDB
  53. evm *vm.EVM
  54. }
  55. // Message represents a message sent to a contract.
  56. type Message interface {
  57. From() common.Address
  58. //FromFrontier() (common.Address, error)
  59. To() *common.Address
  60. GasPrice() *big.Int
  61. Gas() uint64
  62. Value() *big.Int
  63. Nonce() uint64
  64. CheckNonce() bool
  65. Data() []byte
  66. }
  67. // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
  68. func IntrinsicGas(data []byte, contractCreation, isHomestead bool, isEIP2028 bool) (uint64, error) {
  69. // Set the starting gas for the raw transaction
  70. var gas uint64
  71. if contractCreation && isHomestead {
  72. gas = params.TxGasContractCreation
  73. } else {
  74. gas = params.TxGas
  75. }
  76. // Bump the required gas by the amount of transactional data
  77. if len(data) > 0 {
  78. // Zero and non-zero bytes are priced differently
  79. var nz uint64
  80. for _, byt := range data {
  81. if byt != 0 {
  82. nz++
  83. }
  84. }
  85. // Make sure we don't exceed uint64 for all data combinations
  86. nonZeroGas := params.TxDataNonZeroGasFrontier
  87. if isEIP2028 {
  88. nonZeroGas = params.TxDataNonZeroGasEIP2028
  89. }
  90. if (math.MaxUint64-gas)/nonZeroGas < nz {
  91. return 0, vm.ErrOutOfGas
  92. }
  93. gas += nz * nonZeroGas
  94. z := uint64(len(data)) - nz
  95. if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
  96. return 0, vm.ErrOutOfGas
  97. }
  98. gas += z * params.TxDataZeroGas
  99. }
  100. return gas, nil
  101. }
  102. // NewStateTransition initialises and returns a new state transition object.
  103. func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
  104. return &StateTransition{
  105. gp: gp,
  106. evm: evm,
  107. msg: msg,
  108. gasPrice: msg.GasPrice(),
  109. value: msg.Value(),
  110. data: msg.Data(),
  111. state: evm.StateDB,
  112. }
  113. }
  114. // ApplyMessage computes the new state by applying the given message
  115. // against the old state within the environment.
  116. //
  117. // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
  118. // the gas used (which includes gas refunds) and an error if it failed. An error always
  119. // indicates a core error meaning that the message would always fail for that particular
  120. // state and would never be accepted within a block.
  121. func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) {
  122. return NewStateTransition(evm, msg, gp).TransitionDb()
  123. }
  124. // to returns the recipient of the message.
  125. func (st *StateTransition) to() common.Address {
  126. if st.msg == nil || st.msg.To() == nil /* contract creation */ {
  127. return common.Address{}
  128. }
  129. return *st.msg.To()
  130. }
  131. func (st *StateTransition) useGas(amount uint64) error {
  132. if st.gas < amount {
  133. return vm.ErrOutOfGas
  134. }
  135. st.gas -= amount
  136. return nil
  137. }
  138. func (st *StateTransition) buyGas() error {
  139. mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
  140. if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
  141. return errInsufficientBalanceForGas
  142. }
  143. if err := st.gp.SubGas(st.msg.Gas()); err != nil {
  144. return err
  145. }
  146. st.gas += st.msg.Gas()
  147. st.initialGas = st.msg.Gas()
  148. st.state.SubBalance(st.msg.From(), mgval)
  149. return nil
  150. }
  151. func (st *StateTransition) preCheck() error {
  152. // Make sure this transaction's nonce is correct.
  153. if st.msg.CheckNonce() {
  154. nonce := st.state.GetNonce(st.msg.From())
  155. if nonce < st.msg.Nonce() {
  156. return ErrNonceTooHigh
  157. } else if nonce > st.msg.Nonce() {
  158. return ErrNonceTooLow
  159. }
  160. }
  161. return st.buyGas()
  162. }
  163. // TransitionDb will transition the state by applying the current message and
  164. // returning the result including the used gas. It returns an error if failed.
  165. // An error indicates a consensus issue.
  166. func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
  167. if err = st.preCheck(); err != nil {
  168. return
  169. }
  170. msg := st.msg
  171. sender := vm.AccountRef(msg.From())
  172. homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
  173. istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber)
  174. contractCreation := msg.To() == nil
  175. // Pay intrinsic gas
  176. gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul)
  177. if err != nil {
  178. return nil, 0, false, err
  179. }
  180. if err = st.useGas(gas); err != nil {
  181. return nil, 0, false, err
  182. }
  183. var (
  184. evm = st.evm
  185. // vm errors do not effect consensus and are therefor
  186. // not assigned to err, except for insufficient balance
  187. // error.
  188. vmerr error
  189. )
  190. if contractCreation {
  191. ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
  192. } else {
  193. // Increment the nonce for the next transaction
  194. st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
  195. ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value)
  196. }
  197. if vmerr != nil {
  198. log.Debug("VM returned with error", "err", vmerr)
  199. // The only possible consensus-error would be if there wasn't
  200. // sufficient balance to make the transfer happen. The first
  201. // balance transfer may never fail.
  202. if vmerr == vm.ErrInsufficientBalance {
  203. return nil, 0, false, vmerr
  204. }
  205. }
  206. st.refundGas()
  207. st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
  208. return ret, st.gasUsed(), vmerr != nil, err
  209. }
  210. func (st *StateTransition) refundGas() {
  211. // Apply refund counter, capped to half of the used gas.
  212. refund := st.gasUsed() / 2
  213. if refund > st.state.GetRefund() {
  214. refund = st.state.GetRefund()
  215. }
  216. st.gas += refund
  217. // Return ETH for remaining gas, exchanged at the original rate.
  218. remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
  219. st.state.AddBalance(st.msg.From(), remaining)
  220. // Also return remaining gas to the block gas counter so it is
  221. // available for the next transaction.
  222. st.gp.AddGas(st.gas)
  223. }
  224. // gasUsed returns the amount of gas used up by the state transition.
  225. func (st *StateTransition) gasUsed() uint64 {
  226. return st.initialGas - st.gas
  227. }