state_transition.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "fmt"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/vm"
  22. "github.com/ethereum/go-ethereum/logger"
  23. "github.com/ethereum/go-ethereum/logger/glog"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. /*
  27. The State Transitioning Model
  28. A state transition is a change made when a transaction is applied to the current world state
  29. The state transitioning model does all all the necessary work to work out a valid new state root.
  30. 1) Nonce handling
  31. 2) Pre pay gas
  32. 3) Create a new state object if the recipient is \0*32
  33. 4) Value transfer
  34. == If contract creation ==
  35. 4a) Attempt to run transaction data
  36. 4b) If valid, use result as code for the new state object
  37. == end ==
  38. 5) Run Script section
  39. 6) Derive new state root
  40. */
  41. type StateTransition struct {
  42. gp *GasPool
  43. msg Message
  44. gas, gasPrice *big.Int
  45. initialGas *big.Int
  46. value *big.Int
  47. data []byte
  48. state vm.Database
  49. env vm.Environment
  50. }
  51. // Message represents a message sent to a contract.
  52. type Message interface {
  53. From() (common.Address, error)
  54. To() *common.Address
  55. GasPrice() *big.Int
  56. Gas() *big.Int
  57. Value() *big.Int
  58. Nonce() uint64
  59. Data() []byte
  60. }
  61. func MessageCreatesContract(msg Message) bool {
  62. return msg.To() == nil
  63. }
  64. // IntrinsicGas computes the 'intrisic gas' for a message
  65. // with the given data.
  66. func IntrinsicGas(data []byte) *big.Int {
  67. igas := new(big.Int).Set(params.TxGas)
  68. if len(data) > 0 {
  69. var nz int64
  70. for _, byt := range data {
  71. if byt != 0 {
  72. nz++
  73. }
  74. }
  75. m := big.NewInt(nz)
  76. m.Mul(m, params.TxDataNonZeroGas)
  77. igas.Add(igas, m)
  78. m.SetInt64(int64(len(data)) - nz)
  79. m.Mul(m, params.TxDataZeroGas)
  80. igas.Add(igas, m)
  81. }
  82. return igas
  83. }
  84. func ApplyMessage(env vm.Environment, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
  85. var st = StateTransition{
  86. gp: gp,
  87. env: env,
  88. msg: msg,
  89. gas: new(big.Int),
  90. gasPrice: msg.GasPrice(),
  91. initialGas: new(big.Int),
  92. value: msg.Value(),
  93. data: msg.Data(),
  94. state: env.Db(),
  95. }
  96. return st.transitionDb()
  97. }
  98. func (self *StateTransition) from() (vm.Account, error) {
  99. f, err := self.msg.From()
  100. if err != nil {
  101. return nil, err
  102. }
  103. if !self.state.Exist(f) {
  104. return self.state.CreateAccount(f), nil
  105. }
  106. return self.state.GetAccount(f), nil
  107. }
  108. func (self *StateTransition) to() vm.Account {
  109. if self.msg == nil {
  110. return nil
  111. }
  112. to := self.msg.To()
  113. if to == nil {
  114. return nil // contract creation
  115. }
  116. if !self.state.Exist(*to) {
  117. return self.state.CreateAccount(*to)
  118. }
  119. return self.state.GetAccount(*to)
  120. }
  121. func (self *StateTransition) useGas(amount *big.Int) error {
  122. if self.gas.Cmp(amount) < 0 {
  123. return vm.OutOfGasError
  124. }
  125. self.gas.Sub(self.gas, amount)
  126. return nil
  127. }
  128. func (self *StateTransition) addGas(amount *big.Int) {
  129. self.gas.Add(self.gas, amount)
  130. }
  131. func (self *StateTransition) buyGas() error {
  132. mgas := self.msg.Gas()
  133. mgval := new(big.Int).Mul(mgas, self.gasPrice)
  134. sender, err := self.from()
  135. if err != nil {
  136. return err
  137. }
  138. if sender.Balance().Cmp(mgval) < 0 {
  139. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
  140. }
  141. if err = self.gp.SubGas(mgas); err != nil {
  142. return err
  143. }
  144. self.addGas(mgas)
  145. self.initialGas.Set(mgas)
  146. sender.SubBalance(mgval)
  147. return nil
  148. }
  149. func (self *StateTransition) preCheck() (err error) {
  150. msg := self.msg
  151. sender, err := self.from()
  152. if err != nil {
  153. return err
  154. }
  155. // Make sure this transaction's nonce is correct
  156. //if sender.Nonce() != msg.Nonce() {
  157. if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
  158. return NonceError(msg.Nonce(), n)
  159. }
  160. // Pre-pay gas
  161. if err = self.buyGas(); err != nil {
  162. if IsGasLimitErr(err) {
  163. return err
  164. }
  165. return InvalidTxError(err)
  166. }
  167. return nil
  168. }
  169. func (self *StateTransition) transitionDb() (ret []byte, usedGas *big.Int, err error) {
  170. if err = self.preCheck(); err != nil {
  171. return
  172. }
  173. msg := self.msg
  174. sender, _ := self.from() // err checked in preCheck
  175. // Pay intrinsic gas
  176. if err = self.useGas(IntrinsicGas(self.data)); err != nil {
  177. return nil, nil, InvalidTxError(err)
  178. }
  179. vmenv := self.env
  180. var addr common.Address
  181. if MessageCreatesContract(msg) {
  182. ret, addr, err = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
  183. if err == nil {
  184. dataGas := big.NewInt(int64(len(ret)))
  185. dataGas.Mul(dataGas, params.CreateDataGas)
  186. if err := self.useGas(dataGas); err == nil {
  187. self.state.SetCode(addr, ret)
  188. } else {
  189. ret = nil // does not affect consensus but useful for StateTests validations
  190. glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
  191. }
  192. }
  193. glog.V(logger.Core).Infoln("VM create err:", err)
  194. } else {
  195. // Increment the nonce for the next transaction
  196. self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
  197. ret, err = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.gasPrice, self.value)
  198. glog.V(logger.Core).Infoln("VM call err:", err)
  199. }
  200. if err != nil && IsValueTransferErr(err) {
  201. return nil, nil, InvalidTxError(err)
  202. }
  203. // We aren't interested in errors here. Errors returned by the VM are non-consensus errors and therefor shouldn't bubble up
  204. if err != nil {
  205. err = nil
  206. }
  207. if vm.Debug {
  208. vm.StdErrFormat(vmenv.StructLogs())
  209. }
  210. self.refundGas()
  211. self.state.AddBalance(self.env.Coinbase(), new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  212. return ret, self.gasUsed(), err
  213. }
  214. func (self *StateTransition) refundGas() {
  215. // Return eth for remaining gas to the sender account,
  216. // exchanged at the original rate.
  217. sender, _ := self.from() // err already checked
  218. remaining := new(big.Int).Mul(self.gas, self.gasPrice)
  219. sender.AddBalance(remaining)
  220. // Apply refund counter, capped to half of the used gas.
  221. uhalf := remaining.Div(self.gasUsed(), common.Big2)
  222. refund := common.BigMin(uhalf, self.state.GetRefund())
  223. self.gas.Add(self.gas, refund)
  224. self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice))
  225. // Also return remaining gas to the block gas counter so it is
  226. // available for the next transaction.
  227. self.gp.AddGas(self.gas)
  228. }
  229. func (self *StateTransition) gasUsed() *big.Int {
  230. return new(big.Int).Sub(self.initialGas, self.gas)
  231. }