state_transition.go 8.1 KB

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