github.com/Consensys/quorum@v21.1.0+incompatible/core/vm/evm.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 vm 18 19 import ( 20 "fmt" 21 "math/big" 22 "sync/atomic" 23 "time" 24 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/core/state" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/log" 30 "github.com/ethereum/go-ethereum/multitenancy" 31 "github.com/ethereum/go-ethereum/params" 32 "github.com/ethereum/go-ethereum/trie" 33 ) 34 35 // note: Quorum, States, and Value Transfer 36 // 37 // In Quorum there is a tricky issue in one specific case when there is call from private state to public state: 38 // * The state db is selected based on the callee (public) 39 // * With every call there is an associated value transfer -- in our case this is 0 40 // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state 41 // * However in our scenario the caller is private 42 // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage 43 // 44 // The solution is to skip this transfer of 0 value under Quorum 45 46 // emptyCodeHash is used by create to ensure deployment is disallowed to already 47 // deployed contract addresses (relevant after the account abstraction). 48 var emptyCodeHash = crypto.Keccak256Hash(nil) 49 50 type ( 51 // CanTransferFunc is the signature of a transfer guard function 52 CanTransferFunc func(StateDB, common.Address, *big.Int) bool 53 // TransferFunc is the signature of a transfer function 54 TransferFunc func(StateDB, common.Address, common.Address, *big.Int) 55 // GetHashFunc returns the n'th block hash in the blockchain 56 // and is used by the BLOCKHASH EVM op code. 57 GetHashFunc func(uint64) common.Hash 58 ) 59 60 // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter. 61 func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) { 62 if contract.CodeAddr != nil { 63 // Using CodeAddr is favour over contract.Address() 64 // During DelegateCall() CodeAddr is the address of the delegated account 65 address := *contract.CodeAddr 66 // during simulation/eth_call, when contract code is empty, there's no execution hence the 67 // multitenancy check will not happen in captureOperationMode(). 68 // This additional check to ensure we capture this case 69 if evm.SupportsMultitenancy && evm.AuthorizeMessageCallFunc != nil && len(contract.Code) == 0 { 70 return nil, multitenancy.ErrNotAuthorized 71 } 72 if err := evm.captureAffectedContract(address, ModeUnknown); err != nil { 73 return nil, err 74 } 75 // When delegatecall, need to capture the operation mode in the context of contract.Address() 76 // the affected contract is required read only mode 77 if address != contract.Address() { 78 evm.pushAddress(contract.Address()) 79 } else { 80 evm.pushAddress(address) 81 } 82 defer evm.popAddress() 83 precompiles := PrecompiledContractsHomestead 84 if evm.chainRules.IsByzantium { 85 precompiles = PrecompiledContractsByzantium 86 } 87 if evm.chainRules.IsIstanbul { 88 precompiles = PrecompiledContractsIstanbul 89 } 90 if p := precompiles[address]; p != nil { 91 return RunPrecompiledContract(p, input, contract) 92 } 93 } 94 for _, interpreter := range evm.interpreters { 95 if interpreter.CanRun(contract.Code) { 96 if evm.interpreter != interpreter { 97 // Ensure that the interpreter pointer is set back 98 // to its current value upon return. 99 defer func(i Interpreter) { 100 evm.interpreter = i 101 }(evm.interpreter) 102 evm.interpreter = interpreter 103 } 104 return interpreter.Run(contract, input, readOnly) 105 } 106 } 107 return nil, ErrNoCompatibleInterpreter 108 } 109 110 // Context provides the EVM with auxiliary information. Once provided 111 // it shouldn't be modified. 112 type Context struct { 113 // CanTransfer returns whether the account contains 114 // sufficient ether to transfer the value 115 CanTransfer CanTransferFunc 116 // Transfer transfers ether from one account to the other 117 Transfer TransferFunc 118 // GetHash returns the hash corresponding to n 119 GetHash GetHashFunc 120 121 // Message information 122 Origin common.Address // Provides information for ORIGIN 123 GasPrice *big.Int // Provides information for GASPRICE 124 125 // Block information 126 Coinbase common.Address // Provides information for COINBASE 127 GasLimit uint64 // Provides information for GASLIMIT 128 BlockNumber *big.Int // Provides information for NUMBER 129 Time *big.Int // Provides information for TIME 130 Difficulty *big.Int // Provides information for DIFFICULTY 131 132 // Quorum 133 // EVM should consider multitenancy 134 SupportsMultitenancy bool 135 // AuthorizeCreateFunc performs tenancy authorization check for contract creation. 136 // It's only injected during simulation 137 AuthorizeCreateFunc multitenancy.AuthorizeCreateFunc 138 // AuthorizeMessageCallFunc performs tenancy authorization check for message call to a contract. 139 // It's only injected during simulation/eth_call 140 AuthorizeMessageCallFunc multitenancy.AuthorizeMessageCallFunc 141 } 142 143 type PublicState StateDB 144 type PrivateState StateDB 145 146 // EVM is the Ethereum Virtual Machine base object and provides 147 // the necessary tools to run a contract on the given state with 148 // the provided context. It should be noted that any error 149 // generated through any of the calls should be considered a 150 // revert-state-and-consume-all-gas operation, no checks on 151 // specific errors should ever be performed. The interpreter makes 152 // sure that any errors generated are to be considered faulty code. 153 // 154 // The EVM should never be reused and is not thread safe. 155 type EVM struct { 156 // Context provides auxiliary blockchain related information 157 Context 158 // StateDB gives access to the underlying state 159 StateDB StateDB 160 // Depth is the current call stack 161 depth int 162 163 // chainConfig contains information about the current chain 164 chainConfig *params.ChainConfig 165 // chain rules contains the chain rules for the current epoch 166 chainRules params.Rules 167 // virtual machine configuration options used to initialise the 168 // evm. 169 vmConfig Config 170 // global (to this context) ethereum virtual machine 171 // used throughout the execution of the tx. 172 interpreters []Interpreter 173 interpreter Interpreter 174 // abort is used to abort the EVM calling operations 175 // NOTE: must be set atomically 176 abort int32 177 // callGasTemp holds the gas available for the current call. This is needed because the 178 // available gas is calculated in gasCall* according to the 63/64 rule and later 179 // applied in opCall*. 180 callGasTemp uint64 181 182 // Quorum additions: 183 publicState PublicState 184 privateState PrivateState 185 states [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025 186 currentStateDepth uint 187 188 // This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe 189 // be simplified). This is set by Quorum when it's inside a Private State -> Public State read. 190 quorumReadOnly bool 191 readOnlyDepth uint 192 193 // these are for privacy enhancements and multitenancy 194 affectedContracts map[common.Address]*AffectedType // affected contract account address -> type 195 currentTx *types.Transaction // transaction currently being applied on this EVM 196 addressStack []common.Address // store contract addresses being executed 197 // store last error during EVM execution lifecycle. 198 // we use this to bubble up the error instead of "evm: execution revert" error. 199 // use it with care as it's meant for runtime multitenancy check during simulation. 200 lastError error 201 } 202 203 // AffectedType defines attributes indicating how a contract is affected 204 // as the result of the contract code execution in an EVM 205 type AffectedType struct { 206 // reason captures how the contract is affected. 207 // Default to MessageCall and set to Creation if the contract under execution is newly created. 208 reason AffectedReason 209 // mode captures how the state is operated as the result of contract code execution. 210 // The value is cached as an expectation by performing trial of ModeRead and ModeWrite against access token for a contract before execution. 211 // Runtime multitenancy check uses this value to verify if an opcode execution violates the expectation. 212 // At the end of EVM lifecycle, this reflects the actual mode. 213 mode AffectedMode 214 } 215 216 func (t AffectedType) String() string { 217 return fmt.Sprintf("reason=%d,mode=%d", t.reason, t.mode) 218 } 219 220 // AffectedReason defines a type of operation that was applied to a contract. 221 type AffectedReason byte 222 223 const ( 224 _ AffectedReason = iota 225 Creation AffectedReason = iota 226 MessageCall 227 ) 228 229 // AffectedMode defines a mode in which the state is operated as the result of contract code execution. 230 type AffectedMode byte 231 232 const ( 233 // ModeUnknown indicates an auxiliary mode used during initialization of an affected contract 234 ModeUnknown AffectedMode = iota 235 // ModeRead indicates that state has not been modified as the result of contract code execution 236 ModeRead AffectedMode = iota 237 // ModeWrite indicates that state has been modified as the result of contract code execution 238 ModeWrite = ModeRead << 1 239 // ModeUpdated indicates that the affected mode has been setup for multitenancy check. 240 // This is mainly used during simulation and eth_call 241 ModeUpdated = ModeRead << 7 242 ) 243 244 func ModeOf(isWrite bool) AffectedMode { 245 if isWrite { 246 return ModeWrite 247 } 248 return ModeRead 249 } 250 251 func (mode AffectedMode) IsNotAuthorized(actualMode AffectedMode) bool { 252 return mode.Has(ModeUpdated) && !mode.Has(actualMode) 253 } 254 255 func (mode AffectedMode) Update(authorizedRead bool, authorizedWrite bool) AffectedMode { 256 newMode := mode | ModeUpdated 257 if authorizedRead { 258 newMode = newMode | ModeRead 259 } 260 if authorizedWrite { 261 newMode = newMode | ModeWrite 262 } 263 return newMode 264 } 265 266 func (mode AffectedMode) Has(modes ...AffectedMode) bool { 267 expectedMode := ModeUnknown 268 for _, m := range modes { 269 expectedMode = expectedMode | m 270 } 271 return mode&expectedMode == expectedMode 272 } 273 274 // NewEVM returns a new EVM. The returned EVM is not thread safe and should 275 // only ever be used *once*. 276 func NewEVM(ctx Context, statedb, privateState StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM { 277 evm := &EVM{ 278 Context: ctx, 279 StateDB: statedb, 280 vmConfig: vmConfig, 281 chainConfig: chainConfig, 282 chainRules: chainConfig.Rules(ctx.BlockNumber), 283 interpreters: make([]Interpreter, 0, 1), 284 285 publicState: statedb, 286 privateState: privateState, 287 288 affectedContracts: make(map[common.Address]*AffectedType), 289 addressStack: make([]common.Address, 0), 290 } 291 292 if chainConfig.IsEWASM(ctx.BlockNumber) { 293 // to be implemented by EVM-C and Wagon PRs. 294 // if vmConfig.EWASMInterpreter != "" { 295 // extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":") 296 // path := extIntOpts[0] 297 // options := []string{} 298 // if len(extIntOpts) > 1 { 299 // options = extIntOpts[1..] 300 // } 301 // evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options)) 302 // } else { 303 // evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig)) 304 // } 305 panic("No supported ewasm interpreter yet.") 306 } 307 308 evm.Push(privateState) 309 310 // vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here 311 // as we always want to have the built-in EVM as the failover option. 312 evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig)) 313 evm.interpreter = evm.interpreters[0] 314 315 return evm 316 } 317 318 // Cancel cancels any running EVM operation. This may be called concurrently and 319 // it's safe to be called multiple times. 320 func (evm *EVM) Cancel() { 321 atomic.StoreInt32(&evm.abort, 1) 322 } 323 324 // Cancelled returns true if Cancel has been called 325 func (evm *EVM) Cancelled() bool { 326 return atomic.LoadInt32(&evm.abort) == 1 327 } 328 329 // Interpreter returns the current interpreter 330 func (evm *EVM) Interpreter() Interpreter { 331 return evm.interpreter 332 } 333 334 // Call executes the contract associated with the addr with the given input as 335 // parameters. It also handles any necessary value transfer required and takes 336 // the necessary steps to create accounts and reverses the state in case of an 337 // execution error or failed value transfer. 338 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 339 if evm.vmConfig.NoRecursion && evm.depth > 0 { 340 return nil, gas, nil 341 } 342 343 evm.Push(getDualState(evm, addr)) 344 defer func() { evm.Pop() }() 345 346 // Fail if we're trying to execute above the call depth limit 347 if evm.depth > int(params.CallCreateDepth) { 348 return nil, gas, ErrDepth 349 } 350 // Fail if we're trying to transfer more than the available balance 351 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 352 return nil, gas, ErrInsufficientBalance 353 } 354 355 var ( 356 to = AccountRef(addr) 357 snapshot = evm.StateDB.Snapshot() 358 ) 359 if !evm.StateDB.Exist(addr) { 360 precompiles := PrecompiledContractsHomestead 361 if evm.chainRules.IsByzantium { 362 precompiles = PrecompiledContractsByzantium 363 } 364 if evm.chainRules.IsIstanbul { 365 precompiles = PrecompiledContractsIstanbul 366 } 367 if precompiles[addr] == nil && evm.chainRules.IsEIP158 && value.Sign() == 0 { 368 // Calling a non existing account, don't do anything, but ping the tracer 369 if evm.vmConfig.Debug && evm.depth == 0 { 370 evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value) 371 evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil) 372 } 373 return nil, gas, nil 374 } 375 evm.StateDB.CreateAccount(addr) 376 } 377 if evm.ChainConfig().IsQuorum { 378 // skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer) 379 if value.Sign() != 0 { 380 if evm.quorumReadOnly { 381 return nil, gas, ErrReadOnlyValueTransfer 382 } 383 evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value) 384 } 385 } else { 386 evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value) 387 } 388 389 // Initialise a new contract and set the code that is to be used by the EVM. 390 // The contract is a scoped environment for this execution context only. 391 contract := NewContract(caller, to, value, gas) 392 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 393 394 // Even if the account has no code, we need to continue because it might be a precompile 395 start := time.Now() 396 397 // Capture the tracer start/end events in debug mode 398 if evm.vmConfig.Debug && evm.depth == 0 { 399 evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value) 400 401 defer func() { // Lazy evaluation of the parameters 402 evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err) 403 }() 404 } 405 ret, err = run(evm, contract, input, false) 406 407 // When an error was returned by the EVM or when setting the creation code 408 // above we revert to the snapshot and consume any gas remaining. Additionally 409 // when we're in homestead this also counts for code storage gas errors. 410 if err != nil { 411 evm.StateDB.RevertToSnapshot(snapshot) 412 if err != errExecutionReverted { 413 contract.UseGas(contract.Gas) 414 } 415 } 416 return ret, contract.Gas, err 417 } 418 419 // CallCode executes the contract associated with the addr with the given input 420 // as parameters. It also handles any necessary value transfer required and takes 421 // the necessary steps to create accounts and reverses the state in case of an 422 // execution error or failed value transfer. 423 // 424 // CallCode differs from Call in the sense that it executes the given address' 425 // code with the caller as context. 426 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 427 if evm.vmConfig.NoRecursion && evm.depth > 0 { 428 return nil, gas, nil 429 } 430 431 evm.Push(getDualState(evm, addr)) 432 defer func() { evm.Pop() }() 433 434 // Fail if we're trying to execute above the call depth limit 435 if evm.depth > int(params.CallCreateDepth) { 436 return nil, gas, ErrDepth 437 } 438 // Fail if we're trying to transfer more than the available balance 439 if !evm.CanTransfer(evm.StateDB, caller.Address(), value) { 440 return nil, gas, ErrInsufficientBalance 441 } 442 443 var ( 444 snapshot = evm.StateDB.Snapshot() 445 to = AccountRef(caller.Address()) 446 ) 447 // Initialise a new contract and set the code that is to be used by the EVM. 448 // The contract is a scoped environment for this execution context only. 449 contract := NewContract(caller, to, value, gas) 450 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 451 452 ret, err = run(evm, contract, input, false) 453 if err != nil { 454 evm.StateDB.RevertToSnapshot(snapshot) 455 if err != errExecutionReverted { 456 contract.UseGas(contract.Gas) 457 } 458 } 459 return ret, contract.Gas, err 460 } 461 462 // DelegateCall executes the contract associated with the addr with the given input 463 // as parameters. It reverses the state in case of an execution error. 464 // 465 // DelegateCall differs from CallCode in the sense that it executes the given address' 466 // code with the caller as context and the caller is set to the caller of the caller. 467 func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 468 if evm.vmConfig.NoRecursion && evm.depth > 0 { 469 return nil, gas, nil 470 } 471 472 evm.Push(getDualState(evm, addr)) 473 defer func() { evm.Pop() }() 474 475 // Fail if we're trying to execute above the call depth limit 476 if evm.depth > int(params.CallCreateDepth) { 477 return nil, gas, ErrDepth 478 } 479 480 var ( 481 snapshot = evm.StateDB.Snapshot() 482 to = AccountRef(caller.Address()) 483 ) 484 485 // Initialise a new contract and make initialise the delegate values 486 contract := NewContract(caller, to, nil, gas).AsDelegate() 487 contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 488 489 ret, err = run(evm, contract, input, false) 490 if err != nil { 491 evm.StateDB.RevertToSnapshot(snapshot) 492 if err != errExecutionReverted { 493 contract.UseGas(contract.Gas) 494 } 495 } 496 return ret, contract.Gas, err 497 } 498 499 // StaticCall executes the contract associated with the addr with the given input 500 // as parameters while disallowing any modifications to the state during the call. 501 // Opcodes that attempt to perform such modifications will result in exceptions 502 // instead of performing the modifications. 503 func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 504 if evm.vmConfig.NoRecursion && evm.depth > 0 { 505 return nil, gas, nil 506 } 507 // Fail if we're trying to execute above the call depth limit 508 if evm.depth > int(params.CallCreateDepth) { 509 return nil, gas, ErrDepth 510 } 511 512 var ( 513 to = AccountRef(addr) 514 stateDb = getDualState(evm, addr) 515 snapshot = stateDb.Snapshot() 516 ) 517 // Initialise a new contract and set the code that is to be used by the EVM. 518 // The contract is a scoped environment for this execution context only. 519 contract := NewContract(caller, to, new(big.Int), gas) 520 contract.SetCallCode(&addr, stateDb.GetCodeHash(addr), stateDb.GetCode(addr)) 521 522 // We do an AddBalance of zero here, just in order to trigger a touch. 523 // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, 524 // but is the correct thing to do and matters on other networks, in tests, and potential 525 // future scenarios 526 stateDb.AddBalance(addr, bigZero) 527 528 // When an error was returned by the EVM or when setting the creation code 529 // above we revert to the snapshot and consume any gas remaining. Additionally 530 // when we're in Homestead this also counts for code storage gas errors. 531 ret, err = run(evm, contract, input, true) 532 if err != nil { 533 stateDb.RevertToSnapshot(snapshot) 534 if err != errExecutionReverted { 535 contract.UseGas(contract.Gas) 536 } 537 } 538 return ret, contract.Gas, err 539 } 540 541 type codeAndHash struct { 542 code []byte 543 hash common.Hash 544 } 545 546 func (c *codeAndHash) Hash() common.Hash { 547 if c.hash == (common.Hash{}) { 548 c.hash = crypto.Keccak256Hash(c.code) 549 } 550 return c.hash 551 } 552 553 // create creates a new contract using code as deployment code. 554 func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) { 555 // Depth check execution. Fail if we're trying to execute above the 556 // limit. 557 if evm.depth > int(params.CallCreateDepth) { 558 return nil, common.Address{}, gas, ErrDepth 559 } 560 if !evm.CanTransfer(evm.StateDB, caller.Address(), value) { 561 return nil, common.Address{}, gas, ErrInsufficientBalance 562 } 563 564 // Quorum 565 // Get the right state in case of a dual state environment. If a sender 566 // is a transaction (depth == 0) use the public state to derive the address 567 // and increment the nonce of the public state. If the sender is a contract 568 // (depth > 0) use the private state to derive the nonce and increment the 569 // nonce on the private state only. 570 // 571 // If the transaction went to a public contract the private and public state 572 // are the same. 573 var creatorStateDb StateDB 574 if evm.depth > 0 { 575 creatorStateDb = evm.privateState 576 } else { 577 creatorStateDb = evm.publicState 578 } 579 580 nonce := creatorStateDb.GetNonce(caller.Address()) 581 creatorStateDb.SetNonce(caller.Address(), nonce+1) 582 583 // Ensure there's no existing contract already at the designated address 584 contractHash := evm.StateDB.GetCodeHash(address) 585 if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) { 586 return nil, common.Address{}, 0, ErrContractAddressCollision 587 } 588 // Create a new account on the state 589 snapshot := evm.StateDB.Snapshot() 590 if evm.SupportsMultitenancy && evm.AuthorizeCreateFunc != nil { 591 if authorized := evm.AuthorizeCreateFunc(); !authorized { 592 return nil, common.Address{}, gas, multitenancy.ErrNotAuthorized 593 } 594 } 595 evm.StateDB.CreateAccount(address) 596 evm.affectedContracts[address] = newAffectedType(Creation, ModeWrite|ModeRead) 597 if evm.chainRules.IsEIP158 { 598 evm.StateDB.SetNonce(address, 1) 599 } 600 if nil != evm.currentTx && evm.currentTx.IsPrivate() && evm.currentTx.PrivacyMetadata() != nil { 601 // for calls (reading contract state) or finding the affected contracts there is no transaction 602 if evm.currentTx.PrivacyMetadata().PrivacyFlag.IsNotStandardPrivate() { 603 pm := state.NewStatePrivacyMetadata(common.BytesToEncryptedPayloadHash(evm.currentTx.Data()), evm.currentTx.PrivacyMetadata().PrivacyFlag) 604 evm.StateDB.SetPrivacyMetadata(address, pm) 605 log.Trace("Set Privacy Metadata", "key", address, "privacyMetadata", pm) 606 } 607 } 608 if evm.ChainConfig().IsQuorum { 609 // skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer) 610 if value.Sign() != 0 { 611 if evm.quorumReadOnly { 612 return nil, common.Address{}, gas, ErrReadOnlyValueTransfer 613 } 614 evm.Transfer(evm.StateDB, caller.Address(), address, value) 615 } 616 } else { 617 evm.Transfer(evm.StateDB, caller.Address(), address, value) 618 } 619 620 // Initialise a new contract and set the code that is to be used by the EVM. 621 // The contract is a scoped environment for this execution context only. 622 contract := NewContract(caller, AccountRef(address), value, gas) 623 contract.SetCodeOptionalHash(&address, codeAndHash) 624 625 if evm.vmConfig.NoRecursion && evm.depth > 0 { 626 return nil, address, gas, nil 627 } 628 629 if evm.vmConfig.Debug && evm.depth == 0 { 630 evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value) 631 } 632 start := time.Now() 633 634 ret, err := run(evm, contract, nil, false) 635 636 maxCodeSize := evm.ChainConfig().GetMaxCodeSize(evm.BlockNumber) 637 // check whether the max code size has been exceeded, check maxcode size from chain config 638 maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > maxCodeSize 639 // if the contract creation ran successfully and no errors were returned 640 // calculate the gas required to store the code. If the code could not 641 // be stored due to not enough gas set an error and let it be handled 642 // by the error checking condition below. 643 if err == nil && !maxCodeSizeExceeded { 644 createDataGas := uint64(len(ret)) * params.CreateDataGas 645 if contract.UseGas(createDataGas) { 646 evm.StateDB.SetCode(address, ret) 647 } else { 648 err = ErrCodeStoreOutOfGas 649 } 650 } 651 652 // When an error was returned by the EVM or when setting the creation code 653 // above we revert to the snapshot and consume any gas remaining. Additionally 654 // when we're in homestead this also counts for code storage gas errors. 655 if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) { 656 evm.StateDB.RevertToSnapshot(snapshot) 657 if err != errExecutionReverted { 658 contract.UseGas(contract.Gas) 659 } 660 } 661 // Assign err if contract code size exceeds the max while the err is still empty. 662 if maxCodeSizeExceeded && err == nil { 663 err = errMaxCodeSizeExceeded 664 } 665 if evm.vmConfig.Debug && evm.depth == 0 { 666 evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err) 667 } 668 return ret, address, contract.Gas, err 669 670 } 671 672 // Create creates a new contract using code as deployment code. 673 func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 674 // Quorum 675 // Get the right state in case of a dual state environment. If a sender 676 // is a transaction (depth == 0) use the public state to derive the address 677 // and increment the nonce of the public state. If the sender is a contract 678 // (depth > 0) use the private state to derive the nonce and increment the 679 // nonce on the private state only. 680 // 681 // If the transaction went to a public contract the private and public state 682 // are the same. 683 var creatorStateDb StateDB 684 if evm.depth > 0 { 685 creatorStateDb = evm.privateState 686 } else { 687 creatorStateDb = evm.publicState 688 } 689 690 // Ensure there's no existing contract already at the designated address 691 nonce := creatorStateDb.GetNonce(caller.Address()) 692 contractAddr = crypto.CreateAddress(caller.Address(), nonce) 693 return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr) 694 } 695 696 // Create2 creates a new contract using code as deployment code. 697 // 698 // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:] 699 // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. 700 func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 701 codeAndHash := &codeAndHash{code: code} 702 contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes()) 703 return evm.create(caller, codeAndHash, gas, endowment, contractAddr) 704 } 705 706 // ChainConfig returns the environment's chain configuration 707 func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig } 708 709 // Quorum functions for dual state 710 func getDualState(evm *EVM, addr common.Address) StateDB { 711 // priv: (a) -> (b) (private) 712 // pub: a -> [b] (private -> public) 713 // priv: (a) -> b (public) 714 state := evm.StateDB 715 716 if evm.PrivateState().Exist(addr) { 717 state = evm.PrivateState() 718 evm.captureAffectedContract(addr, ModeUnknown) 719 } else if evm.PublicState().Exist(addr) { 720 state = evm.PublicState() 721 } 722 723 return state 724 } 725 726 func (evm *EVM) PublicState() PublicState { return evm.publicState } 727 func (evm *EVM) PrivateState() PrivateState { return evm.privateState } 728 func (evm *EVM) SetCurrentTX(tx *types.Transaction) { evm.currentTx = tx } 729 func (evm *EVM) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) { 730 evm.currentTx.SetTxPrivacyMetadata(pm) 731 } 732 func (evm *EVM) Push(statedb StateDB) { 733 // Quorum : the read only depth to be set up only once for the entire 734 // op code execution. This will be set first time transition from 735 // private state to public state happens 736 // statedb will be the state of the contract being called. 737 // if a private contract is calling a public contract make it readonly. 738 if !evm.quorumReadOnly && evm.privateState != statedb { 739 evm.quorumReadOnly = true 740 evm.readOnlyDepth = evm.currentStateDepth 741 } 742 743 if castedStateDb, ok := statedb.(*state.StateDB); ok { 744 evm.states[evm.currentStateDepth] = castedStateDb 745 evm.currentStateDepth++ 746 } 747 748 evm.StateDB = statedb 749 } 750 func (evm *EVM) Pop() { 751 evm.currentStateDepth-- 752 if evm.quorumReadOnly && evm.currentStateDepth == evm.readOnlyDepth { 753 evm.quorumReadOnly = false 754 } 755 evm.StateDB = evm.states[evm.currentStateDepth-1] 756 } 757 758 func (evm *EVM) Depth() int { return evm.depth } 759 760 // We only need to revert the current state because when we call from private 761 // public state it's read only, there wouldn't be anything to reset. 762 // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged 763 // read only. 764 func (evm *EVM) RevertToSnapshot(snapshot int) { 765 evm.StateDB.RevertToSnapshot(snapshot) 766 } 767 768 // Quorum 769 // 770 // Returns addresses of contracts which are message-called 771 func (evm *EVM) CalledContracts() []common.Address { 772 addr := make([]common.Address, 0, len(evm.affectedContracts)) 773 for a, t := range evm.affectedContracts { 774 if t.reason == MessageCall { 775 addr = append(addr, a) 776 } 777 } 778 return addr[:] 779 } 780 781 // Quorum 782 // 783 // Returns addresses of contracts which are newly created 784 func (evm *EVM) CreatedContracts() []common.Address { 785 addr := make([]common.Address, 0, len(evm.affectedContracts)) 786 for a, t := range evm.affectedContracts { 787 if t.reason == Creation { 788 addr = append(addr, a) 789 } 790 } 791 return addr[:] 792 } 793 794 // Quorum 795 // 796 // pushAddress stores the contract address being affected during EVM execution 797 func (evm *EVM) pushAddress(address common.Address) { 798 evm.addressStack = append(evm.addressStack, address) 799 } 800 801 // Quorum 802 // 803 // popAddress retrieves the affected contract address from the stack 804 func (evm *EVM) popAddress() { 805 l := len(evm.addressStack) 806 if l == 0 { 807 return 808 } 809 evm.addressStack = evm.addressStack[:l-1] 810 } 811 812 // Quorum 813 // 814 // peekAddress retrieves the affected contract address from the top of the stack 815 func (evm *EVM) peekAddress() common.Address { 816 l := len(evm.addressStack) 817 if l == 0 { 818 return common.Address{} 819 } 820 return evm.addressStack[l-1] 821 } 822 823 // Quorum 824 // 825 // captureOperationMode stores the type of operation being applied on the current 826 // affected contract whose address is on top of the stack. 827 // For multitenancy, it checks if the mode is allowed. Also it bubbles up the last error 828 // captured. This helps to avoid "evm: execution revert" generic error 829 func (evm *EVM) captureOperationMode(isWriteOperation bool) error { 830 currentAddress := evm.peekAddress() 831 if (currentAddress == common.Address{}) { 832 return evm.lastError 833 } 834 actualMode := ModeOf(isWriteOperation) 835 if t, ok := evm.affectedContracts[currentAddress]; ok { 836 // perform multitenancy check 837 if evm.enforceMultitenancyCheck() { 838 if t.mode.IsNotAuthorized(actualMode) { 839 log.Trace("Multitenancy check for captureOperationMode()", "address", currentAddress.Hex(), "actual", actualMode, "expect", t.mode) 840 evm.lastError = multitenancy.ErrNotAuthorized 841 } 842 // bubble up the last error 843 if evm.lastError != nil { 844 return evm.lastError 845 } 846 } 847 t.mode = t.mode | actualMode 848 } 849 return nil 850 } 851 852 // Quorum 853 // 854 // captureAffectedContract stores the contract address to the affectedContract list if not yet there. 855 // The affected mode is also updated if required. 856 // Default affected reason is MessageCall. 857 // In simulation/eth_call for multitenancy, it sets the expectation of AffectedMode 858 // to be verified later when an opcode is executed. 859 func (evm *EVM) captureAffectedContract(address common.Address, mode AffectedMode) error { 860 affectedType, found := evm.affectedContracts[address] 861 if !found { 862 affectedType = newAffectedType(MessageCall, mode) 863 evm.affectedContracts[address] = affectedType 864 } 865 if affectedType.mode != ModeUnknown { 866 return nil 867 } 868 if evm.SupportsMultitenancy && evm.AuthorizeMessageCallFunc != nil { 869 authorizedRead, authorizedWrite, err := evm.AuthorizeMessageCallFunc(address) 870 if err != nil { 871 return err 872 } 873 // if we don't authorize either read/write, it's unauthorized access 874 // and we need to inform EVM 875 if !authorizedRead && !authorizedWrite { 876 evm.lastError = multitenancy.ErrNotAuthorized 877 log.Debug("Affected contract not authorized", "address", address.Hex(), "read", authorizedRead, "write", authorizedWrite) 878 return multitenancy.ErrNotAuthorized 879 } 880 oldMode := affectedType.mode 881 affectedType.mode = affectedType.mode.Update(authorizedRead, authorizedWrite) 882 log.Debug("AffectedMode changed", "address", address.Hex(), "old", oldMode, "new", affectedType.mode) 883 } 884 return nil 885 } 886 887 // enforceMultitenancyCheck returns true if EVM is enforced to do multitenancy check 888 // during simulation/eth_call, false otherwise 889 func (evm *EVM) enforceMultitenancyCheck() bool { 890 return evm.AuthorizeCreateFunc != nil || evm.AuthorizeMessageCallFunc != nil 891 } 892 893 // Quorum 894 // 895 // AffecteMode returns the type of operation (read/write) which was applied on the given 896 // contract address. It returns ModeUnknown if the contract is not affected during 897 // the lifecycle of this EVM instance 898 func (evm *EVM) AffectedMode(a common.Address) (AffectedMode, error) { 899 if t, ok := evm.affectedContracts[a]; ok { 900 return t.mode, nil 901 } 902 return ModeUnknown, fmt.Errorf("address not found") 903 } 904 905 func newAffectedType(r AffectedReason, m AffectedMode) *AffectedType { 906 return &AffectedType{ 907 reason: r, 908 mode: m, 909 } 910 } 911 912 // Quorum 913 // 914 // AffectedContracts returns all affected contracts that are the results of 915 // MessageCall transaction 916 func (evm *EVM) AffectedContracts() []common.Address { 917 addr := make([]common.Address, 0, len(evm.affectedContracts)) 918 for a, t := range evm.affectedContracts { 919 if t.reason == MessageCall { 920 addr = append(addr, a) 921 } 922 } 923 return addr[:] 924 } 925 926 // Return MerkleRoot of all affected contracts (due to both creation and message call) 927 func (evm *EVM) CalculateMerkleRoot() (common.Hash, error) { 928 combined := new(trie.Trie) 929 for addr := range evm.affectedContracts { 930 data, err := getDualState(evm, addr).GetRLPEncodedStateObject(addr) 931 if err != nil { 932 return common.Hash{}, err 933 } 934 if err := combined.TryUpdate(addr.Bytes(), data); err != nil { 935 return common.Hash{}, err 936 } 937 } 938 return combined.Hash(), nil 939 }