github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/core/state_transition.go (about) 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 17 package core 18 19 import ( 20 "errors" 21 "math/big" 22 23 "github.com/ethereum/go-ethereum/common" 24 "github.com/ethereum/go-ethereum/common/math" 25 "github.com/ethereum/go-ethereum/core/vm" 26 "github.com/ethereum/go-ethereum/log" 27 "github.com/ethereum/go-ethereum/params" 28 ) 29 30 var ( 31 Big0 = big.NewInt(0) 32 errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas") 33 ) 34 35 /* 36 The State Transitioning Model 37 38 A state transition is a change made when a transaction is applied to the current world state 39 The state transitioning model does all all the necessary work to work out a valid new state root. 40 41 1) Nonce handling 42 2) Pre pay gas 43 3) Create a new state object if the recipient is \0*32 44 4) Value transfer 45 == If contract creation == 46 4a) Attempt to run transaction data 47 4b) If valid, use result as code for the new state object 48 == end == 49 5) Run Script section 50 6) Derive new state root 51 */ 52 type StateTransition struct { 53 gp *GasPool 54 msg Message 55 gas uint64 56 gasPrice *big.Int 57 initialGas *big.Int 58 value *big.Int 59 data []byte 60 state vm.StateDB 61 62 evm *vm.EVM 63 } 64 65 // Message represents a message sent to a contract. 66 type Message interface { 67 From() common.Address 68 //FromFrontier() (common.Address, error) 69 To() *common.Address 70 71 GasPrice() *big.Int 72 Gas() *big.Int 73 Value() *big.Int 74 75 Nonce() uint64 76 CheckNonce() bool 77 Data() []byte 78 } 79 80 func MessageCreatesContract(msg Message) bool { 81 return msg.To() == nil 82 } 83 84 // IntrinsicGas computes the 'intrinsic gas' for a message 85 // with the given data. 86 // 87 // TODO convert to uint64 88 func IntrinsicGas(data []byte, contractCreation, homestead bool) *big.Int { 89 igas := new(big.Int) 90 if contractCreation && homestead { 91 igas.SetUint64(params.TxGasContractCreation) 92 } else { 93 igas.SetUint64(params.TxGas) 94 } 95 if len(data) > 0 { 96 var nz int64 97 for _, byt := range data { 98 if byt != 0 { 99 nz++ 100 } 101 } 102 m := big.NewInt(nz) 103 m.Mul(m, new(big.Int).SetUint64(params.TxDataNonZeroGas)) 104 igas.Add(igas, m) 105 m.SetInt64(int64(len(data)) - nz) 106 m.Mul(m, new(big.Int).SetUint64(params.TxDataZeroGas)) 107 igas.Add(igas, m) 108 } 109 return igas 110 } 111 112 // NewStateTransition initialises and returns a new state transition object. 113 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition { 114 return &StateTransition{ 115 gp: gp, 116 evm: evm, 117 msg: msg, 118 gasPrice: msg.GasPrice(), 119 initialGas: new(big.Int), 120 value: msg.Value(), 121 data: msg.Data(), 122 state: evm.StateDB, 123 } 124 } 125 126 // ApplyMessage computes the new state by applying the given message 127 // against the old state within the environment. 128 // 129 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 130 // the gas used (which includes gas refunds) and an error if it failed. An error always 131 // indicates a core error meaning that the message would always fail for that particular 132 // state and would never be accepted within a block. 133 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, error) { 134 st := NewStateTransition(evm, msg, gp) 135 136 ret, _, gasUsed, err := st.TransitionDb() 137 return ret, gasUsed, err 138 } 139 140 func (self *StateTransition) from() vm.AccountRef { 141 f := self.msg.From() 142 if !self.state.Exist(f) { 143 self.state.CreateAccount(f) 144 } 145 return vm.AccountRef(f) 146 } 147 148 func (self *StateTransition) to() vm.AccountRef { 149 if self.msg == nil { 150 return vm.AccountRef{} 151 } 152 to := self.msg.To() 153 if to == nil { 154 return vm.AccountRef{} // contract creation 155 } 156 157 reference := vm.AccountRef(*to) 158 if !self.state.Exist(*to) { 159 self.state.CreateAccount(*to) 160 } 161 return reference 162 } 163 164 func (self *StateTransition) useGas(amount uint64) error { 165 if self.gas < amount { 166 return vm.ErrOutOfGas 167 } 168 self.gas -= amount 169 170 return nil 171 } 172 173 func (self *StateTransition) buyGas() error { 174 mgas := self.msg.Gas() 175 if mgas.BitLen() > 64 { 176 return vm.ErrOutOfGas 177 } 178 179 mgval := new(big.Int).Mul(mgas, self.gasPrice) 180 181 var ( 182 state = self.state 183 sender = self.from() 184 ) 185 if state.GetBalance(sender.Address()).Cmp(mgval) < 0 { 186 return errInsufficientBalanceForGas 187 } 188 if err := self.gp.SubGas(mgas); err != nil { 189 return err 190 } 191 self.gas += mgas.Uint64() 192 193 self.initialGas.Set(mgas) 194 state.SubBalance(sender.Address(), mgval) 195 return nil 196 } 197 198 func (self *StateTransition) preCheck() (err error) { 199 msg := self.msg 200 sender := self.from() 201 202 // Make sure this transaction's nonce is correct 203 if msg.CheckNonce() { 204 if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() { 205 return NonceError(msg.Nonce(), n) 206 } 207 } 208 209 // Pre-pay gas 210 if err = self.buyGas(); err != nil { 211 if IsGasLimitErr(err) { 212 return err 213 } 214 return InvalidTxError(err) 215 } 216 217 return nil 218 } 219 220 // TransitionDb will transition the state by applying the current message and returning the result 221 // including the required gas for the operation as well as the used gas. It returns an error if it 222 // failed. An error indicates a consensus issue. 223 func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) { 224 if err = self.preCheck(); err != nil { 225 return 226 } 227 msg := self.msg 228 sender := self.from() // err checked in preCheck 229 230 homestead := self.evm.ChainConfig().IsHomestead(self.evm.BlockNumber) 231 contractCreation := MessageCreatesContract(msg) 232 // Pay intrinsic gas 233 // TODO convert to uint64 234 intrinsicGas := IntrinsicGas(self.data, contractCreation, homestead) 235 if intrinsicGas.BitLen() > 64 { 236 return nil, nil, nil, InvalidTxError(vm.ErrOutOfGas) 237 } 238 239 if err = self.useGas(intrinsicGas.Uint64()); err != nil { 240 return nil, nil, nil, InvalidTxError(err) 241 } 242 243 var ( 244 evm = self.evm 245 // vm errors do not effect consensus and are therefor 246 // not assigned to err, except for insufficient balance 247 // error. 248 vmerr error 249 ) 250 if contractCreation { 251 ret, _, self.gas, vmerr = evm.Create(sender, self.data, self.gas, self.value) 252 } else { 253 // Increment the nonce for the next transaction 254 self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1) 255 ret, self.gas, vmerr = evm.Call(sender, self.to().Address(), self.data, self.gas, self.value) 256 } 257 if vmerr != nil { 258 log.Debug("VM returned with error", "err", err) 259 // The only possible consensus-error would be if there wasn't 260 // sufficient balance to make the transfer happen. The first 261 // balance transfer may never fail. 262 if vmerr == vm.ErrInsufficientBalance { 263 return nil, nil, nil, InvalidTxError(vmerr) 264 } 265 } 266 267 requiredGas = new(big.Int).Set(self.gasUsed()) 268 269 self.refundGas() 270 self.state.AddBalance(self.evm.Coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice)) 271 272 return ret, requiredGas, self.gasUsed(), err 273 } 274 275 func (self *StateTransition) refundGas() { 276 // Return eth for remaining gas to the sender account, 277 // exchanged at the original rate. 278 sender := self.from() // err already checked 279 remaining := new(big.Int).Mul(new(big.Int).SetUint64(self.gas), self.gasPrice) 280 self.state.AddBalance(sender.Address(), remaining) 281 282 // Apply refund counter, capped to half of the used gas. 283 uhalf := remaining.Div(self.gasUsed(), common.Big2) 284 refund := math.BigMin(uhalf, self.state.GetRefund()) 285 self.gas += refund.Uint64() 286 287 self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice)) 288 289 // Also return remaining gas to the block gas counter so it is 290 // available for the next transaction. 291 self.gp.AddGas(new(big.Int).SetUint64(self.gas)) 292 } 293 294 func (self *StateTransition) gasUsed() *big.Int { 295 return new(big.Int).Sub(self.initialGas, new(big.Int).SetUint64(self.gas)) 296 }