state_transition.go 8.0 KB

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