github.com/bencicandrej/quorum@v2.2.6-0.20190909091323-878cab86f711+incompatible/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 // 192 // Quorum: 193 // 1. Intrinsic gas is calculated based on the encrypted payload hash 194 // and NOT the actual private payload 195 // 2. For private transactions, we only deduct intrinsic gas from the gas pool 196 // regardless the current node is party to the transaction or not 197 func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) { 198 if err = st.preCheck(); err != nil { 199 return 200 } 201 msg := st.msg 202 sender := vm.AccountRef(msg.From()) 203 homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber) 204 contractCreation := msg.To() == nil 205 isQuorum := st.evm.ChainConfig().IsQuorum 206 207 var data []byte 208 isPrivate := false 209 publicState := st.state 210 if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() { 211 isPrivate = true 212 data, err = private.P.Receive(st.data) 213 // Increment the public account nonce if: 214 // 1. Tx is private and *not* a participant of the group and either call or create 215 // 2. Tx is private we are part of the group and is a call 216 if err != nil || !contractCreation { 217 publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1) 218 } 219 220 if err != nil { 221 return nil, 0, false, nil 222 } 223 } else { 224 data = st.data 225 } 226 227 // Pay intrinsic gas. For a private contract this is done using the public hash passed in, 228 // not the private data retrieved above. This is because we need any (participant) validator 229 // node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues. 230 gas, err := IntrinsicGas(st.data, contractCreation, homestead) 231 if err != nil { 232 return nil, 0, false, err 233 } 234 if err = st.useGas(gas); err != nil { 235 return nil, 0, false, err 236 } 237 238 var ( 239 leftoverGas uint64 240 evm = st.evm 241 // vm errors do not effect consensus and are therefor 242 // not assigned to err, except for insufficient balance 243 // error. 244 vmerr error 245 ) 246 if contractCreation { 247 ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value) 248 } else { 249 // Increment the account nonce only if the transaction isn't private. 250 // If the transaction is private it has already been incremented on 251 // the public state. 252 if !isPrivate { 253 publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1) 254 } 255 var to common.Address 256 if isQuorum { 257 to = *st.msg.To() 258 } else { 259 to = st.to() 260 } 261 //if input is empty for the smart contract call, return 262 if len(data) == 0 && isPrivate { 263 st.refundGas() 264 st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 265 return nil, 0, false, nil 266 } 267 268 ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value) 269 } 270 if vmerr != nil { 271 log.Info("VM returned with error", "err", vmerr) 272 // The only possible consensus-error would be if there wasn't 273 // sufficient balance to make the transfer happen. The first 274 // balance transfer may never fail. 275 if vmerr == vm.ErrInsufficientBalance { 276 return nil, 0, false, vmerr 277 } 278 } 279 280 // Pay gas used during contract creation or execution (st.gas tracks remaining gas) 281 // However, if private contract then we don't want to do this else we can get 282 // a mismatch between a (non-participant) minter and (participant) validator, 283 // which can cause a 'BAD BLOCK' crash. 284 if !isPrivate { 285 st.gas = leftoverGas 286 } 287 288 st.refundGas() 289 st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 290 291 if isPrivate { 292 return ret, 0, vmerr != nil, err 293 } 294 return ret, st.gasUsed(), vmerr != nil, err 295 } 296 297 func (st *StateTransition) refundGas() { 298 // Apply refund counter, capped to half of the used gas. 299 refund := st.gasUsed() / 2 300 if refund > st.state.GetRefund() { 301 refund = st.state.GetRefund() 302 } 303 st.gas += refund 304 305 // Return ETH for remaining gas, exchanged at the original rate. 306 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 307 st.state.AddBalance(st.msg.From(), remaining) 308 309 // Also return remaining gas to the block gas counter so it is 310 // available for the next transaction. 311 st.gp.AddGas(st.gas) 312 } 313 314 // gasUsed returns the amount of gas used up by the state transition. 315 func (st *StateTransition) gasUsed() uint64 { 316 return st.initialGas - st.gas 317 }