state_transition.go 8.0 KB

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