github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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 "fmt" 22 "math" 23 "math/big" 24 25 "github.com/kisexp/xdchain/common" 26 "github.com/kisexp/xdchain/core/state" 27 "github.com/kisexp/xdchain/core/types" 28 "github.com/kisexp/xdchain/core/vm" 29 "github.com/kisexp/xdchain/log" 30 "github.com/kisexp/xdchain/multitenancy" 31 "github.com/kisexp/xdchain/params" 32 "github.com/kisexp/xdchain/private" 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 To() *common.Address 68 69 GasPrice() *big.Int 70 Gas() uint64 71 Value() *big.Int 72 73 Nonce() uint64 74 CheckNonce() bool 75 Data() []byte 76 } 77 78 // ExecutionResult includes all output after executing given evm 79 // message no matter the execution itself is successful or not. 80 type ExecutionResult struct { 81 UsedGas uint64 // Total used gas but include the refunded gas 82 Err error // Any error encountered during the execution(listed in core/vm/errors.go) 83 ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode) 84 } 85 86 // Unwrap returns the internal evm error which allows us for further 87 // analysis outside. 88 func (result *ExecutionResult) Unwrap() error { 89 return result.Err 90 } 91 92 // Failed returns the indicator whether the execution is successful or not 93 func (result *ExecutionResult) Failed() bool { return result.Err != nil } 94 95 // Return is a helper function to help caller distinguish between revert reason 96 // and function return. Return returns the data after execution if no error occurs. 97 func (result *ExecutionResult) Return() []byte { 98 if result.Err != nil { 99 return nil 100 } 101 return common.CopyBytes(result.ReturnData) 102 } 103 104 // Revert returns the concrete revert reason if the execution is aborted by `REVERT` 105 // opcode. Note the reason can be nil if no data supplied with revert opcode. 106 func (result *ExecutionResult) Revert() []byte { 107 if result.Err != vm.ErrExecutionReverted { 108 return nil 109 } 110 return common.CopyBytes(result.ReturnData) 111 } 112 113 // PrivateMessage implements a private message 114 type PrivateMessage interface { 115 Message 116 IsPrivate() bool 117 } 118 119 // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. 120 func IntrinsicGas(data []byte, contractCreation, isHomestead bool, isEIP2028 bool) (uint64, error) { 121 // Set the starting gas for the raw transaction 122 var gas uint64 123 if contractCreation && isHomestead { 124 gas = params.TxGasContractCreation 125 } else { 126 gas = params.TxGas 127 } 128 // Bump the required gas by the amount of transactional data 129 if len(data) > 0 { 130 // Zero and non-zero bytes are priced differently 131 var nz uint64 132 for _, byt := range data { 133 if byt != 0 { 134 nz++ 135 } 136 } 137 // Make sure we don't exceed uint64 for all data combinations 138 nonZeroGas := params.TxDataNonZeroGasFrontier 139 if isEIP2028 { 140 nonZeroGas = params.TxDataNonZeroGasEIP2028 141 } 142 if (math.MaxUint64-gas)/nonZeroGas < nz { 143 return 0, ErrGasUintOverflow 144 } 145 gas += nz * nonZeroGas 146 147 z := uint64(len(data)) - nz 148 if (math.MaxUint64-gas)/params.TxDataZeroGas < z { 149 return 0, ErrGasUintOverflow 150 } 151 gas += z * params.TxDataZeroGas 152 } 153 return gas, nil 154 } 155 156 // NewStateTransition initialises and returns a new state transition object. 157 func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition { 158 return &StateTransition{ 159 gp: gp, 160 evm: evm, 161 msg: msg, 162 gasPrice: msg.GasPrice(), 163 value: msg.Value(), 164 data: msg.Data(), 165 state: evm.PublicState(), 166 } 167 } 168 169 // ApplyMessage computes the new state by applying the given message 170 // against the old state within the environment. 171 // 172 // ApplyMessage returns the bytes returned by any EVM execution (if it took place), 173 // the gas used (which includes gas refunds) and an error if it failed. An error always 174 // indicates a core error meaning that the message would always fail for that particular 175 // state and would never be accepted within a block. 176 177 func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) { 178 return NewStateTransition(evm, msg, gp).TransitionDb() 179 } 180 181 // to returns the recipient of the message. 182 func (st *StateTransition) to() common.Address { 183 if st.msg == nil || st.msg.To() == nil /* contract creation */ { 184 return common.Address{} 185 } 186 return *st.msg.To() 187 } 188 189 func (st *StateTransition) buyGas() error { 190 mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice) 191 if have, want := st.state.GetBalance(st.msg.From()), mgval; have.Cmp(want) < 0 { 192 return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want) 193 } 194 if err := st.gp.SubGas(st.msg.Gas()); err != nil { 195 return err 196 } 197 st.gas += st.msg.Gas() 198 199 st.initialGas = st.msg.Gas() 200 st.state.SubBalance(st.msg.From(), mgval) 201 return nil 202 } 203 204 func (st *StateTransition) preCheck() error { 205 // Make sure this transaction's nonce is correct. 206 if st.msg.CheckNonce() { 207 stNonce := st.state.GetNonce(st.msg.From()) 208 if msgNonce := st.msg.Nonce(); stNonce < msgNonce { 209 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh, 210 st.msg.From().Hex(), msgNonce, stNonce) 211 } else if stNonce > msgNonce { 212 return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow, 213 st.msg.From().Hex(), msgNonce, stNonce) 214 } 215 } 216 return st.buyGas() 217 } 218 219 // TransitionDb will transition the state by applying the current message and 220 // returning the evm execution result with following fields. 221 // 222 // - used gas: 223 // total gas used (including gas being refunded) 224 // - returndata: 225 // the returned data from evm 226 // - concrete execution error: 227 // various **EVM** error which aborts the execution, 228 // e.g. ErrOutOfGas, ErrExecutionReverted 229 // 230 // However if any consensus issue encountered, return the error directly with 231 // nil evm execution result. 232 // 233 // Quorum: 234 // 1. Intrinsic gas is calculated based on the encrypted payload hash 235 // and NOT the actual private payload. 236 // 2. For private transactions, we only deduct intrinsic gas from the gas pool 237 // regardless the current node is party to the transaction or not. 238 // 3. For privacy marker transactions, we only deduct the PMT gas from the gas pool. No gas is deducted 239 // for the internal private transaction, regardless of whether the current node is a party. 240 // 4. With multitenancy support, we enforce the party set in the contract index must contain all 241 // parties from the transaction. This is to detect unauthorized access from a legit proxy contract 242 // to an unauthorized contract. 243 func (st *StateTransition) TransitionDb() (*ExecutionResult, error) { 244 // First check this message satisfies all consensus rules before 245 // applying the message. The rules include these clauses 246 // 247 // 1. the nonce of the message caller is correct 248 // 2. caller has enough balance to cover transaction fee(gaslimit * gasprice) 249 // 3. the amount of gas required is available in the block 250 // 4. the purchased gas is enough to cover intrinsic usage 251 // 5. there is no overflow when calculating intrinsic gas 252 // 6. caller has enough balance to cover asset transfer for **topmost** call 253 254 // Check clauses 1-3, buy gas if everything is correct 255 var err error 256 if err = st.preCheck(); err != nil { 257 return nil, err 258 } 259 msg := st.msg 260 sender := vm.AccountRef(msg.From()) 261 homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber) 262 istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber) 263 contractCreation := msg.To() == nil 264 isQuorum := st.evm.ChainConfig().IsQuorum 265 snapshot := st.evm.StateDB.Snapshot() 266 267 var data []byte 268 isPrivate := false 269 publicState := st.state 270 pmh := newPMH(st) 271 if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() { 272 isPrivate = true 273 pmh.snapshot = snapshot 274 pmh.eph = common.BytesToEncryptedPayloadHash(st.data) 275 _, _, data, pmh.receivedPrivacyMetadata, err = private.P.Receive(pmh.eph) 276 // Increment the public account nonce if: 277 // 1. Tx is private and *not* a participant of the group and either call or create 278 // 2. Tx is private we are part of the group and is a call 279 if err != nil || !contractCreation { 280 publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1) 281 } 282 if err != nil { 283 return &ExecutionResult{ 284 UsedGas: 0, 285 Err: nil, 286 ReturnData: nil, 287 }, nil 288 } 289 290 pmh.hasPrivatePayload = data != nil 291 292 vmErr, consensusErr := pmh.prepare() 293 if consensusErr != nil || vmErr != nil { 294 return &ExecutionResult{ 295 UsedGas: 0, 296 Err: vmErr, 297 ReturnData: nil, 298 }, consensusErr 299 } 300 } else { 301 data = st.data 302 } 303 304 // Pay intrinsic gas. For a private contract this is done using the public hash passed in, 305 // not the private data retrieved above. This is because we need any (participant) validator 306 // node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues. 307 // Check clauses 4-5, subtract intrinsic gas if everything is correct 308 gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul) 309 if err != nil { 310 return nil, err 311 } 312 if st.gas < gas { 313 return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas) 314 } 315 st.gas -= gas 316 317 // Check clause 6 318 if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) { 319 return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()) 320 } 321 var ( 322 leftoverGas uint64 323 evm = st.evm 324 ret []byte 325 // vm errors do not effect consensus and are therefor 326 // not assigned to err, except for insufficient balance 327 // error. 328 vmerr error 329 ) 330 if contractCreation { 331 ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value) 332 } else { 333 // Increment the account nonce only if the transaction isn't private. 334 // If the transaction is private it has already been incremented on 335 // the public state. 336 if !isPrivate { 337 publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1) 338 } 339 var to common.Address 340 if isQuorum { 341 to = *st.msg.To() 342 } else { 343 to = st.to() 344 } 345 //if input is empty for the smart contract call, return 346 if len(data) == 0 && isPrivate { 347 st.refundGas() 348 st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 349 return &ExecutionResult{ 350 UsedGas: 0, 351 Err: nil, 352 ReturnData: nil, 353 }, nil 354 } 355 356 ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value) 357 } 358 if vmerr != nil { 359 log.Info("VM returned with error", "err", vmerr) 360 // The only possible consensus-error would be if there wasn't 361 // sufficient balance to make the transfer happen. The first 362 // balance transfer may never fail. 363 if vmerr == vm.ErrInsufficientBalance { 364 return nil, vmerr 365 } 366 if errors.Is(vmerr, multitenancy.ErrNotAuthorized) { 367 return nil, vmerr 368 } 369 } 370 371 // Quorum - Privacy Enhancements 372 // perform privacy enhancements checks 373 if pmh.mustVerify() { 374 var exitEarly bool 375 exitEarly, err = pmh.verify(vmerr) 376 if exitEarly { 377 return &ExecutionResult{ 378 UsedGas: 0, 379 Err: ErrPrivateContractInteractionVerificationFailed, 380 ReturnData: nil, 381 }, err 382 } 383 } 384 // End Quorum - Privacy Enhancements 385 386 // Pay gas used during contract creation or execution (st.gas tracks remaining gas) 387 // However, if private contract then we don't want to do this else we can get 388 // a mismatch between a (non-participant) minter and (participant) validator, 389 // which can cause a 'BAD BLOCK' crash. 390 if !isPrivate { 391 st.gas = leftoverGas 392 } 393 // End Quorum 394 395 st.refundGas() 396 st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) 397 398 if isPrivate { 399 return &ExecutionResult{ 400 UsedGas: 0, 401 Err: vmerr, 402 ReturnData: ret, 403 }, err 404 } 405 // End Quorum 406 407 return &ExecutionResult{ 408 UsedGas: st.gasUsed(), 409 Err: vmerr, 410 ReturnData: ret, 411 }, nil 412 } 413 414 func (st *StateTransition) refundGas() { 415 // Apply refund counter, capped to half of the used gas. 416 refund := st.gasUsed() / 2 417 if refund > st.state.GetRefund() { 418 refund = st.state.GetRefund() 419 } 420 st.gas += refund 421 422 // Return ETH for remaining gas, exchanged at the original rate. 423 remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) 424 st.state.AddBalance(st.msg.From(), remaining) 425 426 // Also return remaining gas to the block gas counter so it is 427 // available for the next transaction. 428 st.gp.AddGas(st.gas) 429 } 430 431 // gasUsed returns the amount of gas used up by the state transition. 432 func (st *StateTransition) gasUsed() uint64 { 433 return st.initialGas - st.gas 434 } 435 436 // Quorum - Privacy Enhancements - implement the pmcStateTransitionAPI interface 437 func (st *StateTransition) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) { 438 st.evm.SetTxPrivacyMetadata(pm) 439 } 440 func (st *StateTransition) IsPrivacyEnhancementsEnabled() bool { 441 return st.evm.ChainConfig().IsPrivacyEnhancementsEnabled(st.evm.Context.BlockNumber) 442 } 443 func (st *StateTransition) RevertToSnapshot(snapshot int) { 444 st.evm.StateDB.RevertToSnapshot(snapshot) 445 } 446 func (st *StateTransition) GetStatePrivacyMetadata(addr common.Address) (*state.PrivacyMetadata, error) { 447 return st.evm.StateDB.GetPrivacyMetadata(addr) 448 } 449 func (st *StateTransition) CalculateMerkleRoot() (common.Hash, error) { 450 return st.evm.CalculateMerkleRoot() 451 } 452 func (st *StateTransition) AffectedContracts() []common.Address { 453 return st.evm.AffectedContracts() 454 } 455 456 // End Quorum - Privacy Enhancements