state_transition.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. "fmt"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/vm"
  22. "github.com/ethereum/go-ethereum/logger"
  23. "github.com/ethereum/go-ethereum/logger/glog"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. var (
  27. Big0 = big.NewInt(0)
  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, gasPrice *big.Int
  48. initialGas *big.Int
  49. value *big.Int
  50. data []byte
  51. state vm.StateDB
  52. env *vm.Environment
  53. }
  54. // Message represents a message sent to a contract.
  55. type Message interface {
  56. From() common.Address
  57. //FromFrontier() (common.Address, error)
  58. To() *common.Address
  59. GasPrice() *big.Int
  60. Gas() *big.Int
  61. Value() *big.Int
  62. Nonce() uint64
  63. CheckNonce() bool
  64. Data() []byte
  65. }
  66. func MessageCreatesContract(msg Message) bool {
  67. return msg.To() == nil
  68. }
  69. // IntrinsicGas computes the 'intrinsic gas' for a message
  70. // with the given data.
  71. func IntrinsicGas(data []byte, contractCreation, homestead bool) *big.Int {
  72. igas := new(big.Int)
  73. if contractCreation && homestead {
  74. igas.Set(params.TxGasContractCreation)
  75. } else {
  76. igas.Set(params.TxGas)
  77. }
  78. if len(data) > 0 {
  79. var nz int64
  80. for _, byt := range data {
  81. if byt != 0 {
  82. nz++
  83. }
  84. }
  85. m := big.NewInt(nz)
  86. m.Mul(m, params.TxDataNonZeroGas)
  87. igas.Add(igas, m)
  88. m.SetInt64(int64(len(data)) - nz)
  89. m.Mul(m, params.TxDataZeroGas)
  90. igas.Add(igas, m)
  91. }
  92. return igas
  93. }
  94. // NewStateTransition initialises and returns a new state transition object.
  95. func NewStateTransition(env *vm.Environment, msg Message, gp *GasPool) *StateTransition {
  96. return &StateTransition{
  97. gp: gp,
  98. env: env,
  99. msg: msg,
  100. gas: new(big.Int),
  101. gasPrice: msg.GasPrice(),
  102. initialGas: new(big.Int),
  103. value: msg.Value(),
  104. data: msg.Data(),
  105. state: env.StateDB,
  106. }
  107. }
  108. // ApplyMessage computes the new state by applying the given message
  109. // against the old state within the environment.
  110. //
  111. // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
  112. // the gas used (which includes gas refunds) and an error if it failed. An error always
  113. // indicates a core error meaning that the message would always fail for that particular
  114. // state and would never be accepted within a block.
  115. func ApplyMessage(env *vm.Environment, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
  116. st := NewStateTransition(env, msg, gp)
  117. ret, _, gasUsed, err := st.TransitionDb()
  118. return ret, gasUsed, err
  119. }
  120. func (self *StateTransition) from() vm.Account {
  121. f := self.msg.From()
  122. if !self.state.Exist(f) {
  123. return self.state.CreateAccount(f)
  124. }
  125. return self.state.GetAccount(f)
  126. }
  127. func (self *StateTransition) to() vm.Account {
  128. if self.msg == nil {
  129. return nil
  130. }
  131. to := self.msg.To()
  132. if to == nil {
  133. return nil // contract creation
  134. }
  135. if !self.state.Exist(*to) {
  136. return self.state.CreateAccount(*to)
  137. }
  138. return self.state.GetAccount(*to)
  139. }
  140. func (self *StateTransition) useGas(amount *big.Int) error {
  141. if self.gas.Cmp(amount) < 0 {
  142. return vm.OutOfGasError
  143. }
  144. self.gas.Sub(self.gas, amount)
  145. return nil
  146. }
  147. func (self *StateTransition) addGas(amount *big.Int) {
  148. self.gas.Add(self.gas, amount)
  149. }
  150. func (self *StateTransition) buyGas() error {
  151. mgas := self.msg.Gas()
  152. mgval := new(big.Int).Mul(mgas, self.gasPrice)
  153. sender := self.from()
  154. if sender.Balance().Cmp(mgval) < 0 {
  155. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
  156. }
  157. if err := self.gp.SubGas(mgas); err != nil {
  158. return err
  159. }
  160. self.addGas(mgas)
  161. self.initialGas.Set(mgas)
  162. sender.SubBalance(mgval)
  163. return nil
  164. }
  165. func (self *StateTransition) preCheck() (err error) {
  166. msg := self.msg
  167. sender := self.from()
  168. // Make sure this transaction's nonce is correct
  169. if msg.CheckNonce() {
  170. if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
  171. return NonceError(msg.Nonce(), n)
  172. }
  173. }
  174. // Pre-pay gas
  175. if err = self.buyGas(); err != nil {
  176. if IsGasLimitErr(err) {
  177. return err
  178. }
  179. return InvalidTxError(err)
  180. }
  181. return nil
  182. }
  183. // TransitionDb will move the state by applying the message against the given environment.
  184. func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
  185. if err = self.preCheck(); err != nil {
  186. return
  187. }
  188. msg := self.msg
  189. sender := self.from() // err checked in preCheck
  190. homestead := self.env.ChainConfig().IsHomestead(self.env.BlockNumber)
  191. contractCreation := MessageCreatesContract(msg)
  192. // Pay intrinsic gas
  193. if err = self.useGas(IntrinsicGas(self.data, contractCreation, homestead)); err != nil {
  194. return nil, nil, nil, InvalidTxError(err)
  195. }
  196. var (
  197. vmenv = self.env
  198. // vm errors do not effect consensus and are therefor
  199. // not assigned to err, except for insufficient balance
  200. // error.
  201. vmerr error
  202. )
  203. if contractCreation {
  204. ret, _, vmerr = vmenv.Create(sender, self.data, self.gas, self.value)
  205. if homestead && err == vm.CodeStoreOutOfGasError {
  206. self.gas = Big0
  207. }
  208. } else {
  209. // Increment the nonce for the next transaction
  210. self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
  211. ret, vmerr = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.value)
  212. }
  213. if vmerr != nil {
  214. glog.V(logger.Core).Infoln("vm returned with error:", err)
  215. // The only possible consensus-error would be if there wasn't
  216. // sufficient balance to make the transfer happen. The first
  217. // balance transfer may never fail.
  218. if vmerr == vm.ErrInsufficientBalance {
  219. return nil, nil, nil, InvalidTxError(vmerr)
  220. }
  221. }
  222. requiredGas = new(big.Int).Set(self.gasUsed())
  223. self.refundGas()
  224. self.state.AddBalance(self.env.Coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  225. return ret, requiredGas, self.gasUsed(), err
  226. }
  227. func (self *StateTransition) refundGas() {
  228. // Return eth for remaining gas to the sender account,
  229. // exchanged at the original rate.
  230. sender := self.from() // err already checked
  231. remaining := new(big.Int).Mul(self.gas, self.gasPrice)
  232. sender.AddBalance(remaining)
  233. // Apply refund counter, capped to half of the used gas.
  234. uhalf := remaining.Div(self.gasUsed(), common.Big2)
  235. refund := common.BigMin(uhalf, self.state.GetRefund())
  236. self.gas.Add(self.gas, refund)
  237. self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
  238. // Also return remaining gas to the block gas counter so it is
  239. // available for the next transaction.
  240. self.gp.AddGas(self.gas)
  241. }
  242. func (self *StateTransition) gasUsed() *big.Int {
  243. return new(big.Int).Sub(self.initialGas, self.gas)
  244. }