state_transition.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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.Database
  52. env vm.Environment
  53. }
  54. // Message represents a message sent to a contract.
  55. type Message interface {
  56. From() (common.Address, error)
  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.Db(),
  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, error) {
  121. var (
  122. f common.Address
  123. err error
  124. )
  125. if self.env.RuleSet().IsHomestead(self.env.BlockNumber()) {
  126. f, err = self.msg.From()
  127. } else {
  128. f, err = self.msg.FromFrontier()
  129. }
  130. if err != nil {
  131. return nil, err
  132. }
  133. if !self.state.Exist(f) {
  134. return self.state.CreateAccount(f), nil
  135. }
  136. return self.state.GetAccount(f), nil
  137. }
  138. func (self *StateTransition) to() vm.Account {
  139. if self.msg == nil {
  140. return nil
  141. }
  142. to := self.msg.To()
  143. if to == nil {
  144. return nil // contract creation
  145. }
  146. if !self.state.Exist(*to) {
  147. return self.state.CreateAccount(*to)
  148. }
  149. return self.state.GetAccount(*to)
  150. }
  151. func (self *StateTransition) useGas(amount *big.Int) error {
  152. if self.gas.Cmp(amount) < 0 {
  153. return vm.OutOfGasError
  154. }
  155. self.gas.Sub(self.gas, amount)
  156. return nil
  157. }
  158. func (self *StateTransition) addGas(amount *big.Int) {
  159. self.gas.Add(self.gas, amount)
  160. }
  161. func (self *StateTransition) buyGas() error {
  162. mgas := self.msg.Gas()
  163. mgval := new(big.Int).Mul(mgas, self.gasPrice)
  164. sender, err := self.from()
  165. if err != nil {
  166. return err
  167. }
  168. if sender.Balance().Cmp(mgval) < 0 {
  169. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
  170. }
  171. if err = self.gp.SubGas(mgas); err != nil {
  172. return err
  173. }
  174. self.addGas(mgas)
  175. self.initialGas.Set(mgas)
  176. sender.SubBalance(mgval)
  177. return nil
  178. }
  179. func (self *StateTransition) preCheck() (err error) {
  180. msg := self.msg
  181. sender, err := self.from()
  182. if err != nil {
  183. return err
  184. }
  185. // Make sure this transaction's nonce is correct
  186. if msg.CheckNonce() {
  187. if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
  188. return NonceError(msg.Nonce(), n)
  189. }
  190. }
  191. // Pre-pay gas
  192. if err = self.buyGas(); err != nil {
  193. if IsGasLimitErr(err) {
  194. return err
  195. }
  196. return InvalidTxError(err)
  197. }
  198. return nil
  199. }
  200. // TransitionDb will move the state by applying the message against the given environment.
  201. func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
  202. if err = self.preCheck(); err != nil {
  203. return
  204. }
  205. msg := self.msg
  206. sender, _ := self.from() // err checked in preCheck
  207. homestead := self.env.RuleSet().IsHomestead(self.env.BlockNumber())
  208. contractCreation := MessageCreatesContract(msg)
  209. // Pay intrinsic gas
  210. if err = self.useGas(IntrinsicGas(self.data, contractCreation, homestead)); err != nil {
  211. return nil, nil, nil, InvalidTxError(err)
  212. }
  213. vmenv := self.env
  214. //var addr common.Address
  215. if contractCreation {
  216. ret, _, err = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
  217. if homestead && err == vm.CodeStoreOutOfGasError {
  218. self.gas = Big0
  219. }
  220. if err != nil {
  221. ret = nil
  222. glog.V(logger.Core).Infoln("VM create err:", err)
  223. }
  224. } else {
  225. // Increment the nonce for the next transaction
  226. self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
  227. ret, err = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.gasPrice, self.value)
  228. if err != nil {
  229. glog.V(logger.Core).Infoln("VM call err:", err)
  230. }
  231. }
  232. if err != nil && IsValueTransferErr(err) {
  233. return nil, nil, nil, InvalidTxError(err)
  234. }
  235. // We aren't interested in errors here. Errors returned by the VM are non-consensus errors and therefor shouldn't bubble up
  236. if err != nil {
  237. err = nil
  238. }
  239. requiredGas = new(big.Int).Set(self.gasUsed())
  240. self.refundGas()
  241. self.state.AddBalance(self.env.Coinbase(), new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  242. return ret, requiredGas, self.gasUsed(), err
  243. }
  244. func (self *StateTransition) refundGas() {
  245. // Return eth for remaining gas to the sender account,
  246. // exchanged at the original rate.
  247. sender, _ := self.from() // err already checked
  248. remaining := new(big.Int).Mul(self.gas, self.gasPrice)
  249. sender.AddBalance(remaining)
  250. // Apply refund counter, capped to half of the used gas.
  251. uhalf := remaining.Div(self.gasUsed(), common.Big2)
  252. refund := common.BigMin(uhalf, self.state.GetRefund())
  253. self.gas.Add(self.gas, refund)
  254. self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
  255. // Also return remaining gas to the block gas counter so it is
  256. // available for the next transaction.
  257. self.gp.AddGas(self.gas)
  258. }
  259. func (self *StateTransition) gasUsed() *big.Int {
  260. return new(big.Int).Sub(self.initialGas, self.gas)
  261. }