state_transition.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. 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/state"
  22. "github.com/ethereum/go-ethereum/core/vm"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. )
  27. /*
  28. * The State transitioning model
  29. *
  30. * A state transition is a change made when a transaction is applied to the current world state
  31. * The state transitioning model does all all the necessary work to work out a valid new state root.
  32. * 1) Nonce handling
  33. * 2) Pre pay / buy gas of the coinbase (miner)
  34. * 3) Create a new state object if the recipient is \0*32
  35. * 4) Value transfer
  36. * == If contract creation ==
  37. * 4a) Attempt to run transaction data
  38. * 4b) If valid, use result as code for the new state object
  39. * == end ==
  40. * 5) Run Script section
  41. * 6) Derive new state root
  42. */
  43. type StateTransition struct {
  44. coinbase common.Address
  45. msg Message
  46. gas, gasPrice *big.Int
  47. initialGas *big.Int
  48. value *big.Int
  49. data []byte
  50. state *state.StateDB
  51. cb, rec, sen *state.StateObject
  52. env vm.Environment
  53. }
  54. // Message represents a message sent to a contract.
  55. type Message interface {
  56. From() (common.Address, error)
  57. To() *common.Address
  58. GasPrice() *big.Int
  59. Gas() *big.Int
  60. Value() *big.Int
  61. Nonce() uint64
  62. Data() []byte
  63. }
  64. func MessageCreatesContract(msg Message) bool {
  65. return msg.To() == nil
  66. }
  67. // IntrinsicGas computes the 'intrisic gas' for a message
  68. // with the given data.
  69. func IntrinsicGas(data []byte) *big.Int {
  70. igas := new(big.Int).Set(params.TxGas)
  71. if len(data) > 0 {
  72. var nz int64
  73. for _, byt := range data {
  74. if byt != 0 {
  75. nz++
  76. }
  77. }
  78. m := big.NewInt(nz)
  79. m.Mul(m, params.TxDataNonZeroGas)
  80. igas.Add(igas, m)
  81. m.SetInt64(int64(len(data)) - nz)
  82. m.Mul(m, params.TxDataZeroGas)
  83. igas.Add(igas, m)
  84. }
  85. return igas
  86. }
  87. func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
  88. return NewStateTransition(env, msg, coinbase).transitionState()
  89. }
  90. func NewStateTransition(env vm.Environment, msg Message, coinbase *state.StateObject) *StateTransition {
  91. return &StateTransition{
  92. coinbase: coinbase.Address(),
  93. env: env,
  94. msg: msg,
  95. gas: new(big.Int),
  96. gasPrice: msg.GasPrice(),
  97. initialGas: new(big.Int),
  98. value: msg.Value(),
  99. data: msg.Data(),
  100. state: env.State(),
  101. cb: coinbase,
  102. }
  103. }
  104. func (self *StateTransition) Coinbase() *state.StateObject {
  105. return self.state.GetOrNewStateObject(self.coinbase)
  106. }
  107. func (self *StateTransition) From() (*state.StateObject, error) {
  108. f, err := self.msg.From()
  109. if err != nil {
  110. return nil, err
  111. }
  112. return self.state.GetOrNewStateObject(f), nil
  113. }
  114. func (self *StateTransition) To() *state.StateObject {
  115. if self.msg == nil {
  116. return nil
  117. }
  118. to := self.msg.To()
  119. if to == nil {
  120. return nil // contract creation
  121. }
  122. return self.state.GetOrNewStateObject(*to)
  123. }
  124. func (self *StateTransition) UseGas(amount *big.Int) error {
  125. if self.gas.Cmp(amount) < 0 {
  126. return vm.OutOfGasError
  127. }
  128. self.gas.Sub(self.gas, amount)
  129. return nil
  130. }
  131. func (self *StateTransition) AddGas(amount *big.Int) {
  132. self.gas.Add(self.gas, amount)
  133. }
  134. func (self *StateTransition) BuyGas() error {
  135. mgas := self.msg.Gas()
  136. mgval := new(big.Int).Mul(mgas, self.gasPrice)
  137. sender, err := self.From()
  138. if err != nil {
  139. return err
  140. }
  141. if sender.Balance().Cmp(mgval) < 0 {
  142. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
  143. }
  144. if err = self.Coinbase().SubGas(mgas, self.gasPrice); err != nil {
  145. return err
  146. }
  147. self.AddGas(mgas)
  148. self.initialGas.Set(mgas)
  149. sender.SubBalance(mgval)
  150. return nil
  151. }
  152. func (self *StateTransition) preCheck() (err error) {
  153. msg := self.msg
  154. sender, err := self.From()
  155. if err != nil {
  156. return err
  157. }
  158. // Make sure this transaction's nonce is correct
  159. if sender.Nonce() != msg.Nonce() {
  160. return NonceError(msg.Nonce(), sender.Nonce())
  161. }
  162. // Pre-pay gas / Buy gas of the coinbase account
  163. if err = self.BuyGas(); err != nil {
  164. if state.IsGasLimitErr(err) {
  165. return err
  166. }
  167. return InvalidTxError(err)
  168. }
  169. return nil
  170. }
  171. func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
  172. if err = self.preCheck(); err != nil {
  173. return
  174. }
  175. msg := self.msg
  176. sender, _ := self.From() // err checked in preCheck
  177. // Pay intrinsic gas
  178. if err = self.UseGas(IntrinsicGas(self.data)); err != nil {
  179. return nil, nil, InvalidTxError(err)
  180. }
  181. vmenv := self.env
  182. var ref vm.ContextRef
  183. if MessageCreatesContract(msg) {
  184. ret, err, ref = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
  185. if err == nil {
  186. dataGas := big.NewInt(int64(len(ret)))
  187. dataGas.Mul(dataGas, params.CreateDataGas)
  188. if err := self.UseGas(dataGas); err == nil {
  189. ref.SetCode(ret)
  190. } else {
  191. ret = nil // does not affect consensus but useful for StateTests validations
  192. glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
  193. }
  194. }
  195. glog.V(logger.Core).Infoln("VM create err:", err)
  196. } else {
  197. // Increment the nonce for the next transaction
  198. self.state.SetNonce(sender.Address(), sender.Nonce()+1)
  199. ret, err = vmenv.Call(sender, self.To().Address(), self.data, self.gas, self.gasPrice, self.value)
  200. glog.V(logger.Core).Infoln("VM call err:", err)
  201. }
  202. if err != nil && IsValueTransferErr(err) {
  203. return nil, nil, InvalidTxError(err)
  204. }
  205. // We aren't interested in errors here. Errors returned by the VM are non-consensus errors and therefor shouldn't bubble up
  206. if err != nil {
  207. err = nil
  208. }
  209. if vm.Debug {
  210. vm.StdErrFormat(vmenv.StructLogs())
  211. }
  212. self.refundGas()
  213. self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  214. return ret, self.gasUsed(), err
  215. }
  216. func (self *StateTransition) refundGas() {
  217. coinbase := self.Coinbase()
  218. sender, _ := self.From() // err already checked
  219. // Return remaining gas
  220. remaining := new(big.Int).Mul(self.gas, self.gasPrice)
  221. sender.AddBalance(remaining)
  222. uhalf := remaining.Div(self.gasUsed(), common.Big2)
  223. refund := common.BigMin(uhalf, self.state.Refunds())
  224. self.gas.Add(self.gas, refund)
  225. self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
  226. coinbase.AddGas(self.gas, self.gasPrice)
  227. }
  228. func (self *StateTransition) gasUsed() *big.Int {
  229. return new(big.Int).Sub(self.initialGas, self.gas)
  230. }