github.com/zjj1991/quorum@v0.0.0-20190524123704-ae4b0a1e1a19/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" 22 "math/big" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/core/vm" 26 "github.com/ethereum/go-ethereum/log" 27 "github.com/ethereum/go-ethereum/params" 28 "github.com/ethereum/go-ethereum/private" 29 ) 30 31 var ( 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 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 uint64 58 value *big.Int 59 data []byte 60 state vm.StateDB 61 evm *vm.EVM 62 } 63 64 // Message represents a message sent to a contract. 65 type Message interface { 66 From() common.Address 67 //FromFrontier() (common.Address, error) 68 To() *common.Address 69 70 GasPrice() *big.Int 71 Gas() uint64 72 Value() *big.Int 73 74 Nonce() uint64 75 CheckNonce() bool 76 Data() []byte 77 } 78 79 // PrivateMessage implements a private message 80 type PrivateMessage interface { 81 Message 82 IsPrivate() bool 83 } 84 85 // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. 86 func IntrinsicGas(data []byte, contractCreation, homestead bool) (uint64, error) { 87 // Set the starting gas for the raw transaction 88 var gas uint64 89 if contractCreation && homestead { 90 gas = params.TxGasContractCreation 91 } else { 92 gas = params.TxGas 93 } 94 // Bump the required gas by the amount of transactional data 95 if len(data) > 0 { 96 // Zero and non-zero bytes are priced differently 97 var nz uint64 98 for _, byt := range data { 99 if byt != 0 { 100 nz++ 101 } 102 } 103 // Make sure we don't exceed uint64 for all data combinations 104 if (math.MaxUint64-gas)/params.TxDataNonZeroGas < nz { 105 return 0, vm.ErrOutOfGas 106 } 107 gas += nz * params.TxDataNonZeroGas 108 109 z := uint64(len(data)) - nz 110 if (math.MaxUint64-gas)/params.TxDataZeroGas < z { 111 return 0, vm.ErrOutOfGas 112 } 113 gas += z * params.TxDataZeroGas 114 } 115 return gas, nil 116 } 117 118 // NewStateTransition initialises and returns a new state transition object. 119 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition { 120 return &StateTransition{ 121 gp: gp, 122 evm: evm, 123 msg: msg, 124 gasPrice: msg.GasPrice(), 125 value: msg.Value(), 126 data: msg.Data(), 127 state: evm.PublicState(), 128 } 129 } 130 131 // ApplyMessage computes the new state by applying the given message 132 // against the old state within the environment. 133 // 134 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 135 // the gas used (which includes gas refunds) and an error if it failed. An error always 136 // indicates a core error meaning that the message would always fail for that particular 137 // state and would never be accepted within a block. 138 139 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) { 140 return NewStateTransition(evm, msg, gp).TransitionDb() 141 } 142 143 // to returns the recipient of the message. 144 func (st *StateTransition) to() common.Address { 145 if st.msg == nil || st.msg.To() == nil /* contract creation */ { 146 return common.Address{} 147 } 148 return *st.msg.To() 149 } 150 151 func (st *StateTransition) useGas(amount uint64) error { 152 if st.gas < amount { 153 return vm.ErrOutOfGas 154 } 155 st.gas -= amount 156 157 return nil 158 } 159 160 func (st *StateTransition) buyGas() error { 161 mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice) 162 if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 { 163 return errInsufficientBalanceForGas 164 } 165 if err := st.gp.SubGas(st.msg.Gas()); err != nil { 166 return err 167 } 168 st.gas += st.msg.Gas() 169 170 st.initialGas = st.msg.Gas() 171 st.state.SubBalance(st.msg.From(), mgval) 172 return nil 173 } 174 175 func (st *StateTransition) preCheck() error { 176 // Make sure this transaction's nonce is correct. 177 if st.msg.CheckNonce() { 178 nonce := st.state.GetNonce(st.msg.From()) 179 if nonce < st.msg.Nonce() { 180 return ErrNonceTooHigh 181 } else if nonce > st.msg.Nonce() { 182 return ErrNonceTooLow 183 } 184 } 185 return st.buyGas() 186 } 187 188 // TransitionDb will transition the state by applying the current message and 189 // returning the result including the used gas. It returns an error if failed. 190 // An error indicates a consensus issue. 191 func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) { 192 if err = st.preCheck(); err != nil { 193 return 194 } 195 msg := st.msg 196 sender := vm.AccountRef(msg.From()) 197 homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber) 198 contractCreation := msg.To() == nil 199 isQuorum := st.evm.ChainConfig().IsQuorum 200 201 var data []byte 202 isPrivate := false 203 publicState := st.state 204 if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() { 205 isPrivate = true 206 data, err = private.P.Receive(st.data) 207 // Increment the public account nonce if: 208 // 1. Tx is private and *not* a participant of the group and either call or create 209 // 2. Tx is private we are part of the group and is a call 210 if err != nil || !contractCreation { 211 publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1) 212 } 213 214 if err != nil { 215 return nil, 0, false, nil 216 } 217 } else { 218 data = st.data 219 } 220 221 // Pay intrinsic gas. For a private contract this is done using the public hash passed in, 222 // not the private data retrieved above. This is because we need any (participant) validator 223 // node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues. 224 gas, err := IntrinsicGas(st.data, contractCreation, homestead) 225 if err != nil { 226 return nil, 0, false, err 227 } 228 if err = st.useGas(gas); err != nil { 229 return nil, 0, false, err 230 } 231 232 var ( 233 leftoverGas uint64 234 evm = st.evm 235 // vm errors do not effect consensus and are therefor 236 // not assigned to err, except for insufficient balance 237 // error. 238 vmerr error 239 ) 240 if contractCreation { 241 ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value) 242 } else { 243 // Increment the account nonce only if the transaction isn't private. 244 // If the transaction is private it has already been incremented on 245 // the public state. 246 if !isPrivate { 247 publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1) 248 } 249 var to common.Address 250 if isQuorum { 251 to = *st.msg.To() 252 } else { 253 to = st.to() 254 } 255 //if input is empty for the smart contract call, return 256 if len(data) == 0 && isPrivate { 257 return nil, 0, false, nil 258 } 259 260 ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value) 261 } 262 if vmerr != nil { 263 log.Info("VM returned with error", "err", vmerr) 264 // The only possible consensus-error would be if there wasn't 265 // sufficient balance to make the transfer happen. The first 266 // balance transfer may never fail. 267 if vmerr == vm.ErrInsufficientBalance { 268 return nil, 0, false, vmerr 269 } 270 } 271 272 // Pay gas used during contract creation or execution (st.gas tracks remaining gas) 273 // However, if private contract then we don't want to do this else we can get 274 // a mismatch between a (non-participant) minter and (participant) validator, 275 // which can cause a 'BAD BLOCK' crash. 276 if !isPrivate { 277 st.gas = leftoverGas 278 } 279 280 st.refundGas() 281 st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 282 283 if isPrivate { 284 return ret, 0, vmerr != nil, err 285 } 286 return ret, st.gasUsed(), vmerr != nil, err 287 } 288 289 func (st *StateTransition) refundGas() { 290 // Apply refund counter, capped to half of the used gas. 291 refund := st.gasUsed() / 2 292 if refund > st.state.GetRefund() { 293 refund = st.state.GetRefund() 294 } 295 st.gas += refund 296 297 // Return ETH for remaining gas, exchanged at the original rate. 298 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 299 st.state.AddBalance(st.msg.From(), remaining) 300 301 // Also return remaining gas to the block gas counter so it is 302 // available for the next transaction. 303 st.gp.AddGas(st.gas) 304 } 305 306 // gasUsed returns the amount of gas used up by the state transition. 307 func (st *StateTransition) gasUsed() uint64 { 308 return st.initialGas - st.gas 309 }