state_transition.go 6.3 KB

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