state_transition.go 7.6 KB

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