state_transition.go 7.2 KB

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