state_transition.go 7.8 KB

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