state_transition.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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/state"
  22. "github.com/ethereum/go-ethereum/core/vm"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. )
  27. /*
  28. * The State transitioning model
  29. *
  30. * A state transition is a change made when a transaction is applied to the current world state
  31. * The state transitioning model does all all the necessary work to work out a valid new state root.
  32. * 1) Nonce handling
  33. * 2) Pre pay / buy gas of the coinbase (miner)
  34. * 3) Create a new state object if the recipient is \0*32
  35. * 4) Value transfer
  36. * == If contract creation ==
  37. * 4a) Attempt to run transaction data
  38. * 4b) If valid, use result as code for the new state object
  39. * == end ==
  40. * 5) Run Script section
  41. * 6) Derive new state root
  42. */
  43. type StateTransition struct {
  44. gp GasPool
  45. msg Message
  46. gas, gasPrice *big.Int
  47. initialGas *big.Int
  48. value *big.Int
  49. data []byte
  50. state vm.Database
  51. env vm.Environment
  52. }
  53. // Message represents a message sent to a contract.
  54. type Message interface {
  55. From() (common.Address, error)
  56. To() *common.Address
  57. GasPrice() *big.Int
  58. Gas() *big.Int
  59. Value() *big.Int
  60. Nonce() uint64
  61. Data() []byte
  62. }
  63. func MessageCreatesContract(msg Message) bool {
  64. return msg.To() == nil
  65. }
  66. // IntrinsicGas computes the 'intrisic gas' for a message
  67. // with the given data.
  68. func IntrinsicGas(data []byte) *big.Int {
  69. igas := new(big.Int).Set(params.TxGas)
  70. if len(data) > 0 {
  71. var nz int64
  72. for _, byt := range data {
  73. if byt != 0 {
  74. nz++
  75. }
  76. }
  77. m := big.NewInt(nz)
  78. m.Mul(m, params.TxDataNonZeroGas)
  79. igas.Add(igas, m)
  80. m.SetInt64(int64(len(data)) - nz)
  81. m.Mul(m, params.TxDataZeroGas)
  82. igas.Add(igas, m)
  83. }
  84. return igas
  85. }
  86. func ApplyMessage(env vm.Environment, msg Message, gp GasPool) ([]byte, *big.Int, error) {
  87. var st = StateTransition{
  88. gp: gp,
  89. env: env,
  90. msg: msg,
  91. gas: new(big.Int),
  92. gasPrice: msg.GasPrice(),
  93. initialGas: new(big.Int),
  94. value: msg.Value(),
  95. data: msg.Data(),
  96. state: env.Db(),
  97. }
  98. return st.transitionDb()
  99. }
  100. func (self *StateTransition) from() (vm.Account, error) {
  101. f, err := self.msg.From()
  102. if err != nil {
  103. return nil, err
  104. }
  105. if !self.state.Exist(f) {
  106. return self.state.CreateAccount(f), nil
  107. }
  108. return self.state.GetAccount(f), nil
  109. }
  110. func (self *StateTransition) to() vm.Account {
  111. if self.msg == nil {
  112. return nil
  113. }
  114. to := self.msg.To()
  115. if to == nil {
  116. return nil // contract creation
  117. }
  118. if !self.state.Exist(*to) {
  119. return self.state.CreateAccount(*to)
  120. }
  121. return self.state.GetAccount(*to)
  122. }
  123. func (self *StateTransition) useGas(amount *big.Int) error {
  124. if self.gas.Cmp(amount) < 0 {
  125. return vm.OutOfGasError
  126. }
  127. self.gas.Sub(self.gas, amount)
  128. return nil
  129. }
  130. func (self *StateTransition) addGas(amount *big.Int) {
  131. self.gas.Add(self.gas, amount)
  132. }
  133. func (self *StateTransition) buyGas() error {
  134. mgas := self.msg.Gas()
  135. mgval := new(big.Int).Mul(mgas, self.gasPrice)
  136. sender, err := self.from()
  137. if err != nil {
  138. return err
  139. }
  140. if sender.Balance().Cmp(mgval) < 0 {
  141. return fmt.Errorf("insufficient ETH for gas (%x). Req %v, has %v", sender.Address().Bytes()[:4], mgval, sender.Balance())
  142. }
  143. if err = self.gp.SubGas(mgas, self.gasPrice); err != nil {
  144. return err
  145. }
  146. self.addGas(mgas)
  147. self.initialGas.Set(mgas)
  148. sender.SubBalance(mgval)
  149. return nil
  150. }
  151. func (self *StateTransition) preCheck() (err error) {
  152. msg := self.msg
  153. sender, err := self.from()
  154. if err != nil {
  155. return err
  156. }
  157. // Make sure this transaction's nonce is correct
  158. //if sender.Nonce() != msg.Nonce() {
  159. if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
  160. return NonceError(msg.Nonce(), n)
  161. }
  162. // Pre-pay gas / Buy gas of the coinbase account
  163. if err = self.buyGas(); err != nil {
  164. if state.IsGasLimitErr(err) {
  165. return err
  166. }
  167. return InvalidTxError(err)
  168. }
  169. return nil
  170. }
  171. func (self *StateTransition) transitionDb() (ret []byte, usedGas *big.Int, err error) {
  172. if err = self.preCheck(); err != nil {
  173. return
  174. }
  175. msg := self.msg
  176. sender, _ := self.from() // err checked in preCheck
  177. // Pay intrinsic gas
  178. if err = self.useGas(IntrinsicGas(self.data)); err != nil {
  179. return nil, nil, InvalidTxError(err)
  180. }
  181. vmenv := self.env
  182. var addr common.Address
  183. if MessageCreatesContract(msg) {
  184. ret, addr, err = vmenv.Create(sender, self.data, self.gas, self.gasPrice, self.value)
  185. if err == nil {
  186. dataGas := big.NewInt(int64(len(ret)))
  187. dataGas.Mul(dataGas, params.CreateDataGas)
  188. if err := self.useGas(dataGas); err == nil {
  189. self.state.SetCode(addr, ret)
  190. } else {
  191. ret = nil // does not affect consensus but useful for StateTests validations
  192. glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
  193. }
  194. }
  195. glog.V(logger.Core).Infoln("VM create err:", err)
  196. } else {
  197. // Increment the nonce for the next transaction
  198. self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1)
  199. ret, err = vmenv.Call(sender, self.to().Address(), self.data, self.gas, self.gasPrice, self.value)
  200. glog.V(logger.Core).Infoln("VM call err:", err)
  201. }
  202. if err != nil && IsValueTransferErr(err) {
  203. return nil, nil, InvalidTxError(err)
  204. }
  205. // We aren't interested in errors here. Errors returned by the VM are non-consensus errors and therefor shouldn't bubble up
  206. if err != nil {
  207. err = nil
  208. }
  209. if vm.Debug {
  210. vm.StdErrFormat(vmenv.StructLogs())
  211. }
  212. self.refundGas()
  213. self.state.AddBalance(self.env.Coinbase(), new(big.Int).Mul(self.gasUsed(), self.gasPrice))
  214. return ret, self.gasUsed(), err
  215. }
  216. func (self *StateTransition) refundGas() {
  217. sender, _ := self.from() // err already checked
  218. // Return remaining gas
  219. remaining := new(big.Int).Mul(self.gas, self.gasPrice)
  220. sender.AddBalance(remaining)
  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. self.gp.AddGas(self.gas, self.gasPrice)
  226. }
  227. func (self *StateTransition) gasUsed() *big.Int {
  228. return new(big.Int).Sub(self.initialGas, self.gas)
  229. }