state_transition.go 6.3 KB

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