state_transition.go 6.2 KB

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