state_transition.go 6.8 KB

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