state_transition.go 6.3 KB

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