state_transition.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. func (st *StateTransition) from() vm.AccountRef {
  121. f := st.msg.From()
  122. if !st.state.Exist(f) {
  123. st.state.CreateAccount(f)
  124. }
  125. return vm.AccountRef(f)
  126. }
  127. func (st *StateTransition) to() vm.AccountRef {
  128. if st.msg == nil {
  129. return vm.AccountRef{}
  130. }
  131. to := st.msg.To()
  132. if to == nil {
  133. return vm.AccountRef{} // contract creation
  134. }
  135. reference := vm.AccountRef(*to)
  136. if !st.state.Exist(*to) {
  137. st.state.CreateAccount(*to)
  138. }
  139. return reference
  140. }
  141. func (st *StateTransition) useGas(amount uint64) error {
  142. if st.gas < amount {
  143. return vm.ErrOutOfGas
  144. }
  145. st.gas -= amount
  146. return nil
  147. }
  148. func (st *StateTransition) buyGas() error {
  149. var (
  150. state = st.state
  151. sender = st.from()
  152. )
  153. mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
  154. if state.GetBalance(sender.Address()).Cmp(mgval) < 0 {
  155. return errInsufficientBalanceForGas
  156. }
  157. if err := st.gp.SubGas(st.msg.Gas()); err != nil {
  158. return err
  159. }
  160. st.gas += st.msg.Gas()
  161. st.initialGas = st.msg.Gas()
  162. state.SubBalance(sender.Address(), mgval)
  163. return nil
  164. }
  165. func (st *StateTransition) preCheck() error {
  166. msg := st.msg
  167. sender := st.from()
  168. // Make sure this transaction's nonce is correct
  169. if msg.CheckNonce() {
  170. nonce := st.state.GetNonce(sender.Address())
  171. if nonce < msg.Nonce() {
  172. return ErrNonceTooHigh
  173. } else if nonce > msg.Nonce() {
  174. return ErrNonceTooLow
  175. }
  176. }
  177. return st.buyGas()
  178. }
  179. // TransitionDb will transition the state by applying the current message and
  180. // returning the result including the the used gas. It returns an error if it
  181. // failed. An error indicates a consensus issue.
  182. func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
  183. if err = st.preCheck(); err != nil {
  184. return
  185. }
  186. msg := st.msg
  187. sender := st.from() // err checked in preCheck
  188. homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
  189. contractCreation := msg.To() == nil
  190. // Pay intrinsic gas
  191. gas, err := IntrinsicGas(st.data, contractCreation, homestead)
  192. if err = st.useGas(gas); err != nil {
  193. return nil, 0, false, err
  194. }
  195. var (
  196. evm = st.evm
  197. // vm errors do not effect consensus and are therefor
  198. // not assigned to err, except for insufficient balance
  199. // error.
  200. vmerr error
  201. )
  202. if contractCreation {
  203. ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
  204. } else {
  205. // Increment the nonce for the next transaction
  206. st.state.SetNonce(sender.Address(), st.state.GetNonce(sender.Address())+1)
  207. ret, st.gas, vmerr = evm.Call(sender, st.to().Address(), st.data, st.gas, st.value)
  208. }
  209. if vmerr != nil {
  210. log.Debug("VM returned with error", "err", vmerr)
  211. // The only possible consensus-error would be if there wasn't
  212. // sufficient balance to make the transfer happen. The first
  213. // balance transfer may never fail.
  214. if vmerr == vm.ErrInsufficientBalance {
  215. return nil, 0, false, vmerr
  216. }
  217. }
  218. st.refundGas()
  219. st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
  220. return ret, st.gasUsed(), vmerr != nil, err
  221. }
  222. func (st *StateTransition) refundGas() {
  223. // Apply refund counter, capped to half of the used gas.
  224. refund := st.gasUsed() / 2
  225. if refund > st.state.GetRefund() {
  226. refund = st.state.GetRefund()
  227. }
  228. st.gas += refund
  229. // Return ETH for remaining gas, exchanged at the original rate.
  230. sender := st.from()
  231. remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
  232. st.state.AddBalance(sender.Address(), remaining)
  233. // Also return remaining gas to the block gas counter so it is
  234. // available for the next transaction.
  235. st.gp.AddGas(st.gas)
  236. }
  237. // gasUsed returns the amount of gas used up by the state transition.
  238. func (st *StateTransition) gasUsed() uint64 {
  239. return st.initialGas - st.gas
  240. }