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. "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 {
  94. f, _ := self.msg.From()
  95. return self.state.GetOrNewStateObject(f)
  96. }
  97. func (self *StateTransition) To() *state.StateObject {
  98. if self.msg == nil {
  99. return nil
  100. }
  101. to := self.msg.To()
  102. if to == nil {
  103. return nil // contract creation
  104. }
  105. return self.state.GetOrNewStateObject(*to)
  106. }
  107. func (self *StateTransition) UseGas(amount *big.Int) error {
  108. if self.gas.Cmp(amount) < 0 {
  109. return OutOfGasError()
  110. }
  111. self.gas.Sub(self.gas, amount)
  112. return nil
  113. }
  114. func (self *StateTransition) AddGas(amount *big.Int) {
  115. self.gas.Add(self.gas, amount)
  116. }
  117. func (self *StateTransition) BuyGas() error {
  118. var err error
  119. sender := self.From()
  120. if sender.Balance().Cmp(MessageGasValue(self.msg)) < 0 {
  121. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], MessageGasValue(self.msg), sender.Balance())
  122. }
  123. coinbase := self.Coinbase()
  124. err = coinbase.BuyGas(self.msg.Gas(), self.msg.GasPrice())
  125. if err != nil {
  126. return err
  127. }
  128. self.AddGas(self.msg.Gas())
  129. self.initialGas.Set(self.msg.Gas())
  130. sender.SubBalance(MessageGasValue(self.msg))
  131. return nil
  132. }
  133. func (self *StateTransition) preCheck() (err error) {
  134. var (
  135. msg = self.msg
  136. sender = self.From()
  137. )
  138. // Make sure this transaction's nonce is correct
  139. if sender.Nonce() != msg.Nonce() {
  140. return NonceError(msg.Nonce(), sender.Nonce())
  141. }
  142. // Pre-pay gas / Buy gas of the coinbase account
  143. if err = self.BuyGas(); err != nil {
  144. if state.IsGasLimitErr(err) {
  145. return err
  146. }
  147. return InvalidTxError(err)
  148. }
  149. return nil
  150. }
  151. func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
  152. if err = self.preCheck(); err != nil {
  153. return
  154. }
  155. var (
  156. msg = self.msg
  157. sender = self.From()
  158. )
  159. // Pay intrinsic gas
  160. if err = self.UseGas(IntrinsicGas(self.msg)); 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, params.CreateDataGas)
  170. if err := self.UseGas(dataGas); err == nil {
  171. ref.SetCode(ret)
  172. } else {
  173. glog.V(logger.Core).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. }