state_transition.go 6.2 KB

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