state_transition.go 7.9 KB

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