state_transition.go 7.1 KB

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