state_transition.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/params"
  10. )
  11. const tryJit = false
  12. var ()
  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. func MessageGasValue(msg Message) *big.Int {
  58. return new(big.Int).Mul(msg.Gas(), msg.GasPrice())
  59. }
  60. func ApplyMessage(env vm.Environment, msg Message, coinbase *state.StateObject) ([]byte, *big.Int, error) {
  61. return NewStateTransition(env, msg, coinbase).transitionState()
  62. }
  63. func NewStateTransition(env vm.Environment, msg Message, coinbase *state.StateObject) *StateTransition {
  64. return &StateTransition{
  65. coinbase: coinbase.Address(),
  66. env: env,
  67. msg: msg,
  68. gas: new(big.Int),
  69. gasPrice: new(big.Int).Set(msg.GasPrice()),
  70. initialGas: new(big.Int),
  71. value: msg.Value(),
  72. data: msg.Data(),
  73. state: env.State(),
  74. cb: coinbase,
  75. }
  76. }
  77. func (self *StateTransition) Coinbase() *state.StateObject {
  78. return self.state.GetOrNewStateObject(self.coinbase)
  79. }
  80. func (self *StateTransition) From() *state.StateObject {
  81. f, _ := self.msg.From()
  82. return self.state.GetOrNewStateObject(f)
  83. }
  84. func (self *StateTransition) To() *state.StateObject {
  85. if self.msg == nil {
  86. return nil
  87. }
  88. to := self.msg.To()
  89. if to == nil {
  90. return nil // contract creation
  91. }
  92. return self.state.GetOrNewStateObject(*to)
  93. }
  94. func (self *StateTransition) UseGas(amount *big.Int) error {
  95. if self.gas.Cmp(amount) < 0 {
  96. return OutOfGasError()
  97. }
  98. self.gas.Sub(self.gas, amount)
  99. return nil
  100. }
  101. func (self *StateTransition) AddGas(amount *big.Int) {
  102. self.gas.Add(self.gas, amount)
  103. }
  104. func (self *StateTransition) BuyGas() error {
  105. var err error
  106. sender := self.From()
  107. if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
  108. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], MessageGasValue(self.msg), sender.Balance())
  109. }
  110. coinbase := self.Coinbase()
  111. err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
  112. if err != nil {
  113. return err
  114. }
  115. self.AddGas(self.msg.Gas())
  116. self.initialGas.Set(self.msg.Gas())
  117. sender.SubBalance(MessageGasValue(self.msg))
  118. return nil
  119. }
  120. func (self *StateTransition) preCheck() (err error) {
  121. var (
  122. msg = self.msg
  123. sender = self.From()
  124. )
  125. // Make sure this transaction's nonce is correct
  126. if sender.Nonce() != msg.Nonce() {
  127. return NonceError(msg.Nonce(), sender.Nonce())
  128. }
  129. // Pre-pay gas / Buy gas of the coinbase account
  130. if err = self.BuyGas(); err != nil {
  131. if state.IsGasLimitErr(err) {
  132. return err
  133. }
  134. return InvalidTxError(err)
  135. }
  136. return nil
  137. }
  138. func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
  139. // statelogger.Debugf("(~) %x\n", self.msg.Hash())
  140. // XXX Transactions after this point are considered valid.
  141. if err = self.preCheck(); err != nil {
  142. return
  143. }
  144. var (
  145. msg = self.msg
  146. sender = self.From()
  147. )
  148. // Transaction gas
  149. if err = self.UseGas(params.TxGas); err != nil {
  150. return nil, nil, InvalidTxError(err)
  151. }
  152. // Pay data gas
  153. dgas := new(big.Int)
  154. for _, byt := range self.data {
  155. if byt != 0 {
  156. dgas.Add(dgas, params.TxDataNonZeroGas)
  157. } else {
  158. dgas.Add(dgas, params.TxDataZeroGas)
  159. }
  160. }
  161. if err = self.UseGas(dgas); err != nil {
  162. return nil, nil, InvalidTxError(err)
  163. }
  164. vmenv := self.env
  165. var ref vm.ContextRef
  166. if MessageCreatesContract(msg) {
  167. ret, err, ref = vmenv.Create(sender, self.msg.Data(), self.gas, self.gasPrice, self.value)
  168. if err == nil {
  169. dataGas := big.NewInt(int64(len(ret)))
  170. dataGas.Mul(dataGas, params.CreateDataGas)
  171. if err := self.UseGas(dataGas); err == nil {
  172. ref.SetCode(ret)
  173. } else {
  174. statelogger.Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
  175. }
  176. }
  177. } else {
  178. // Increment the nonce for the next transaction
  179. self.state.SetNonce(sender.Address(), sender.Nonce()+1)
  180. ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
  181. }
  182. if err != nil && IsValueTransferErr(err) {
  183. return nil, nil, InvalidTxError(err)
  184. }
  185. self.refundGas()
  186. self.state.AddBalance(self.coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  187. return ret, self.gasUsed(), err
  188. }
  189. func (self *StateTransition) refundGas() {
  190. coinbase, sender := self.Coinbase(), self.From()
  191. // Return remaining gas
  192. remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice())
  193. sender.AddBalance(remaining)
  194. uhalf := new(big.Int).Div(self.gasUsed(), common.Big2)
  195. for addr, ref := range self.state.Refunds() {
  196. refund := common.BigMin(uhalf, ref)
  197. self.gas.Add(self.gas, refund)
  198. self.state.AddBalance(common.StringToAddress(addr), refund.Mul(refund, self.msg.GasPrice()))
  199. }
  200. coinbase.RefundGas(self.gas, self.msg.GasPrice())
  201. }
  202. func (self *StateTransition) gasUsed() *big.Int {
  203. return new(big.Int).Sub(self.initialGas, self.gas)
  204. }
  205. // Converts an message in to a state object
  206. func makeContract(msg Message, state *state.StateDB) *state.StateObject {
  207. faddr, _ := msg.From()
  208. addr := crypto.CreateAddress(faddr, msg.Nonce())
  209. contract := state.GetOrNewStateObject(addr)
  210. contract.SetInitCode(msg.Data())
  211. return contract
  212. }