state_transition.go 6.3 KB

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