evm.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. package vm
  17. import (
  18. "errors"
  19. "math/big"
  20. "sync/atomic"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/params"
  28. "github.com/ethereum/go-ethereum/trie"
  29. "github.com/holiman/uint256"
  30. )
  31. // note: Quorum, States, and Value Transfer
  32. //
  33. // In Quorum there is a tricky issue in one specific case when there is call from private state to public state:
  34. // * The state db is selected based on the callee (public)
  35. // * With every call there is an associated value transfer -- in our case this is 0
  36. // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state
  37. // * However in our scenario the caller is private
  38. // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage
  39. //
  40. // The solution is to skip this transfer of 0 value under Quorum
  41. // emptyCodeHash is used by create to ensure deployment is disallowed to already
  42. // deployed contract addresses (relevant after the account abstraction).
  43. var emptyCodeHash = crypto.Keccak256Hash(nil)
  44. type (
  45. // CanTransferFunc is the signature of a transfer guard function
  46. CanTransferFunc func(StateDB, common.Address, *big.Int) bool
  47. // TransferFunc is the signature of a transfer function
  48. TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
  49. // GetHashFunc returns the n'th block hash in the blockchain
  50. // and is used by the BLOCKHASH EVM op code.
  51. GetHashFunc func(uint64) common.Hash
  52. )
  53. func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) {
  54. var precompiles map[common.Address]PrecompiledContract
  55. switch {
  56. case evm.chainRules.IsBerlin:
  57. precompiles = PrecompiledContractsBerlin
  58. case evm.chainRules.IsIstanbul:
  59. precompiles = PrecompiledContractsIstanbul
  60. case evm.chainRules.IsByzantium:
  61. precompiles = PrecompiledContractsByzantium
  62. default:
  63. precompiles = PrecompiledContractsHomestead
  64. }
  65. p, ok := precompiles[addr]
  66. return p, ok
  67. }
  68. // Quorum
  69. func (evm *EVM) quorumPrecompile(addr common.Address) (QuorumPrecompiledContract, bool) {
  70. var quorumPrecompiles map[common.Address]QuorumPrecompiledContract
  71. switch {
  72. case evm.chainRules.IsPrivacyPrecompile:
  73. quorumPrecompiles = QuorumPrecompiledContracts
  74. }
  75. p, ok := quorumPrecompiles[addr]
  76. return p, ok
  77. }
  78. // End Quorum
  79. // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
  80. func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
  81. // Quorum
  82. if contract.CodeAddr != nil {
  83. // Using CodeAddr is favour over contract.Address()
  84. // During DelegateCall() CodeAddr is the address of the delegated account
  85. address := *contract.CodeAddr
  86. if _, ok := evm.affectedContracts[address]; !ok {
  87. evm.affectedContracts[address] = MessageCall
  88. }
  89. }
  90. // End Quorum
  91. for _, interpreter := range evm.interpreters {
  92. if interpreter.CanRun(contract.Code) {
  93. if evm.interpreter != interpreter {
  94. // Ensure that the interpreter pointer is set back
  95. // to its current value upon return.
  96. defer func(i Interpreter) {
  97. evm.interpreter = i
  98. }(evm.interpreter)
  99. evm.interpreter = interpreter
  100. }
  101. return interpreter.Run(contract, input, readOnly)
  102. }
  103. }
  104. return nil, errors.New("no compatible interpreter")
  105. }
  106. // BlockContext provides the EVM with auxiliary information. Once provided
  107. // it shouldn't be modified.
  108. type BlockContext struct {
  109. // CanTransfer returns whether the account contains
  110. // sufficient ether to transfer the value
  111. CanTransfer CanTransferFunc
  112. // Transfer transfers ether from one account to the other
  113. Transfer TransferFunc
  114. // GetHash returns the hash corresponding to n
  115. GetHash GetHashFunc
  116. // Block information
  117. Coinbase common.Address // Provides information for COINBASE
  118. GasLimit uint64 // Provides information for GASLIMIT
  119. BlockNumber *big.Int // Provides information for NUMBER
  120. Time *big.Int // Provides information for TIME
  121. Difficulty *big.Int // Provides information for DIFFICULTY
  122. }
  123. // TxContext provides the EVM with information about a transaction.
  124. // All fields can change between transactions.
  125. type TxContext struct {
  126. // Message information
  127. Origin common.Address // Provides information for ORIGIN
  128. GasPrice *big.Int // Provides information for GASPRICE
  129. }
  130. // Quorum
  131. type PublicState StateDB
  132. type PrivateState StateDB
  133. // End Quorum
  134. // EVM is the Ethereum Virtual Machine base object and provides
  135. // the necessary tools to run a contract on the given state with
  136. // the provided context. It should be noted that any error
  137. // generated through any of the calls should be considered a
  138. // revert-state-and-consume-all-gas operation, no checks on
  139. // specific errors should ever be performed. The interpreter makes
  140. // sure that any errors generated are to be considered faulty code.
  141. //
  142. // The EVM should never be reused and is not thread safe.
  143. type EVM struct {
  144. // Context provides auxiliary blockchain related information
  145. Context BlockContext
  146. TxContext
  147. // StateDB gives access to the underlying state
  148. StateDB StateDB
  149. // Depth is the current call stack
  150. depth int
  151. // chainConfig contains information about the current chain
  152. chainConfig *params.ChainConfig
  153. // chain rules contains the chain rules for the current epoch
  154. chainRules params.Rules
  155. // virtual machine configuration options used to initialise the
  156. // evm.
  157. vmConfig Config
  158. // global (to this context) ethereum virtual machine
  159. // used throughout the execution of the tx.
  160. interpreters []Interpreter
  161. interpreter Interpreter
  162. // abort is used to abort the EVM calling operations
  163. // NOTE: must be set atomically
  164. abort int32
  165. // callGasTemp holds the gas available for the current call. This is needed because the
  166. // available gas is calculated in gasCall* according to the 63/64 rule and later
  167. // applied in opCall*.
  168. callGasTemp uint64
  169. // Quorum additions:
  170. publicState PublicState
  171. privateState PrivateState
  172. states [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025
  173. currentStateDepth uint
  174. // This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe
  175. // be simplified). This is set by Quorum when it's inside a Private State -> Public State read.
  176. quorumReadOnly bool
  177. readOnlyDepth uint
  178. // Quorum: these are for privacy enhancements and multitenancy
  179. affectedContracts map[common.Address]AffectedReason // affected contract account address -> type
  180. currentTx *types.Transaction // transaction currently being applied on this EVM
  181. // Quorum: these are for privacy marker transactions
  182. InnerApply func(innerTx *types.Transaction) error //Quorum
  183. InnerPrivateReceipt *types.Receipt //Quorum
  184. }
  185. // AffectedReason defines a type of operation that was applied to a contract.
  186. type AffectedReason byte
  187. const (
  188. _ AffectedReason = iota
  189. Creation AffectedReason = iota
  190. MessageCall
  191. )
  192. // NewEVM returns a new EVM. The returned EVM is not thread safe and should
  193. // only ever be used *once*.
  194. func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb, privateState StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
  195. evm := &EVM{
  196. Context: blockCtx,
  197. TxContext: txCtx,
  198. StateDB: statedb,
  199. vmConfig: vmConfig,
  200. chainConfig: chainConfig,
  201. chainRules: chainConfig.Rules(blockCtx.BlockNumber),
  202. interpreters: make([]Interpreter, 0, 1),
  203. publicState: statedb,
  204. privateState: privateState,
  205. affectedContracts: make(map[common.Address]AffectedReason),
  206. }
  207. if chainConfig.IsEWASM(blockCtx.BlockNumber) {
  208. // to be implemented by EVM-C and Wagon PRs.
  209. // if vmConfig.EWASMInterpreter != "" {
  210. // extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
  211. // path := extIntOpts[0]
  212. // options := []string{}
  213. // if len(extIntOpts) > 1 {
  214. // options = extIntOpts[1..]
  215. // }
  216. // evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
  217. // } else {
  218. // evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
  219. // }
  220. panic("No supported ewasm interpreter yet.")
  221. }
  222. evm.Push(privateState)
  223. // vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
  224. // as we always want to have the built-in EVM as the failover option.
  225. evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
  226. evm.interpreter = evm.interpreters[0]
  227. return evm
  228. }
  229. // Reset resets the EVM with a new transaction context.Reset
  230. // This is not threadsafe and should only be done very cautiously.
  231. func (evm *EVM) Reset(txCtx TxContext, statedb StateDB, privateStateDB StateDB) {
  232. evm.TxContext = txCtx
  233. evm.StateDB = statedb
  234. }
  235. // Cancel cancels any running EVM operation. This may be called concurrently and
  236. // it's safe to be called multiple times.
  237. func (evm *EVM) Cancel() {
  238. atomic.StoreInt32(&evm.abort, 1)
  239. }
  240. // Cancelled returns true if Cancel has been called
  241. func (evm *EVM) Cancelled() bool {
  242. return atomic.LoadInt32(&evm.abort) == 1
  243. }
  244. // Interpreter returns the current interpreter
  245. func (evm *EVM) Interpreter() Interpreter {
  246. return evm.interpreter
  247. }
  248. // Call executes the contract associated with the addr with the given input as
  249. // parameters. It also handles any necessary value transfer required and takes
  250. // the necessary steps to create accounts and reverses the state in case of an
  251. // execution error or failed value transfer.
  252. func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  253. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  254. return nil, gas, nil
  255. }
  256. evm.Push(getDualState(evm, addr))
  257. defer func() { evm.Pop() }()
  258. // Fail if we're trying to execute above the call depth limit
  259. if evm.depth > int(params.CallCreateDepth) {
  260. return nil, gas, ErrDepth
  261. }
  262. // Fail if we're trying to transfer more than the available balance
  263. if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
  264. return nil, gas, ErrInsufficientBalance
  265. }
  266. snapshot := evm.StateDB.Snapshot()
  267. p, isPrecompile := evm.precompile(addr)
  268. qp, isQuorumPrecompile := evm.quorumPrecompile(addr) // Quorum
  269. if !evm.StateDB.Exist(addr) {
  270. if !isPrecompile && !isQuorumPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 {
  271. // Calling a non existing account, don't do anything, but ping the tracer
  272. if evm.vmConfig.Debug && evm.depth == 0 {
  273. evm.vmConfig.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value)
  274. evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
  275. }
  276. return nil, gas, nil
  277. }
  278. // If we are executing the quorum PMT precompile, then don't add it to state.
  279. // (When executing the PMT precompile, we are using private state - adding the account can cause differences in private state root when using with MPS.)
  280. if !isQuorumPrecompile {
  281. evm.StateDB.CreateAccount(addr)
  282. }
  283. }
  284. // Quorum
  285. if evm.ChainConfig().IsQuorum {
  286. // skip transfer if value == 0 (see note: Quorum, States, and Value Transfer)
  287. if value.Sign() != 0 {
  288. if evm.quorumReadOnly {
  289. return nil, gas, ErrReadOnlyValueTransfer
  290. }
  291. evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
  292. }
  293. // End Quorum
  294. } else {
  295. evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
  296. }
  297. // Capture the tracer start/end events in debug mode
  298. if evm.vmConfig.Debug && evm.depth == 0 {
  299. evm.vmConfig.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value)
  300. defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters
  301. evm.vmConfig.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err)
  302. }(gas, time.Now())
  303. }
  304. if isQuorumPrecompile {
  305. ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
  306. } else if isPrecompile {
  307. ret, gas, err = RunPrecompiledContract(p, input, gas)
  308. } else {
  309. // Initialise a new contract and set the code that is to be used by the EVM.
  310. // The contract is a scoped environment for this execution context only.
  311. code := evm.StateDB.GetCode(addr)
  312. addrCopy := addr
  313. // If the account has no code, we can abort here
  314. // The depth-check is already done, and precompiles handled above
  315. contract := NewContract(caller, AccountRef(addrCopy), value, gas)
  316. contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code)
  317. ret, err = run(evm, contract, input, false)
  318. gas = contract.Gas
  319. }
  320. // When an error was returned by the EVM or when setting the creation code
  321. // above we revert to the snapshot and consume any gas remaining. Additionally
  322. // when we're in homestead this also counts for code storage gas errors.
  323. if err != nil {
  324. evm.StateDB.RevertToSnapshot(snapshot)
  325. if err != ErrExecutionReverted {
  326. gas = 0
  327. }
  328. // TODO: consider clearing up unused snapshots:
  329. //} else {
  330. // evm.StateDB.DiscardSnapshot(snapshot)
  331. }
  332. return ret, gas, err
  333. }
  334. // CallCode executes the contract associated with the addr with the given input
  335. // as 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. //
  339. // CallCode differs from Call in the sense that it executes the given address'
  340. // code with the caller as context.
  341. func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  342. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  343. return nil, gas, nil
  344. }
  345. // Quorum
  346. evm.Push(getDualState(evm, addr))
  347. defer func() { evm.Pop() }()
  348. // End Quorum
  349. // Fail if we're trying to execute above the call depth limit
  350. if evm.depth > int(params.CallCreateDepth) {
  351. return nil, gas, ErrDepth
  352. }
  353. // Fail if we're trying to transfer more than the available balance
  354. // Note although it's noop to transfer X ether to caller itself. But
  355. // if caller doesn't have enough balance, it would be an error to allow
  356. // over-charging itself. So the check here is necessary.
  357. if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
  358. return nil, gas, ErrInsufficientBalance
  359. }
  360. var snapshot = evm.StateDB.Snapshot()
  361. // It is allowed to call precompiles, even via delegatecall
  362. if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
  363. ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
  364. } else if p, isPrecompile := evm.precompile(addr); isPrecompile {
  365. ret, gas, err = RunPrecompiledContract(p, input, gas)
  366. } else {
  367. addrCopy := addr
  368. // Initialise a new contract and set the code that is to be used by the EVM.
  369. // The contract is a scoped environment for this execution context only.
  370. contract := NewContract(caller, AccountRef(caller.Address()), value, gas)
  371. contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
  372. ret, err = run(evm, contract, input, false)
  373. gas = contract.Gas
  374. }
  375. if err != nil {
  376. evm.StateDB.RevertToSnapshot(snapshot)
  377. if err != ErrExecutionReverted {
  378. gas = 0
  379. }
  380. }
  381. return ret, gas, err
  382. }
  383. // DelegateCall executes the contract associated with the addr with the given input
  384. // as parameters. It reverses the state in case of an execution error.
  385. //
  386. // DelegateCall differs from CallCode in the sense that it executes the given address'
  387. // code with the caller as context and the caller is set to the caller of the caller.
  388. func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  389. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  390. return nil, gas, nil
  391. }
  392. // Quorum
  393. evm.Push(getDualState(evm, addr))
  394. defer func() { evm.Pop() }()
  395. // End Quorum
  396. // Fail if we're trying to execute above the call depth limit
  397. if evm.depth > int(params.CallCreateDepth) {
  398. return nil, gas, ErrDepth
  399. }
  400. var snapshot = evm.StateDB.Snapshot()
  401. // It is allowed to call precompiles, even via delegatecall
  402. if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
  403. ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
  404. } else if p, isPrecompile := evm.precompile(addr); isPrecompile {
  405. ret, gas, err = RunPrecompiledContract(p, input, gas)
  406. } else {
  407. addrCopy := addr
  408. // Initialise a new contract and make initialise the delegate values
  409. contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate()
  410. contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
  411. ret, err = run(evm, contract, input, false)
  412. gas = contract.Gas
  413. }
  414. if err != nil {
  415. evm.StateDB.RevertToSnapshot(snapshot)
  416. if err != ErrExecutionReverted {
  417. gas = 0
  418. }
  419. }
  420. return ret, gas, err
  421. }
  422. // StaticCall executes the contract associated with the addr with the given input
  423. // as parameters while disallowing any modifications to the state during the call.
  424. // Opcodes that attempt to perform such modifications will result in exceptions
  425. // instead of performing the modifications.
  426. func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  427. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  428. return nil, gas, nil
  429. }
  430. // Fail if we're trying to execute above the call depth limit
  431. if evm.depth > int(params.CallCreateDepth) {
  432. return nil, gas, ErrDepth
  433. }
  434. // Quorum
  435. // use the right state (public or private)
  436. stateDb := getDualState(evm, addr)
  437. // End Quorum
  438. // We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped.
  439. // However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced
  440. // after all empty accounts were deleted, so this is not required. However, if we omit this,
  441. // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json.
  442. // We could change this, but for now it's left for legacy reasons
  443. var snapshot = stateDb.Snapshot()
  444. // We do an AddBalance of zero here, just in order to trigger a touch.
  445. // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
  446. // but is the correct thing to do and matters on other networks, in tests, and potential
  447. // future scenarios
  448. stateDb.AddBalance(addr, big0)
  449. if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
  450. ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
  451. } else if p, isPrecompile := evm.precompile(addr); isPrecompile {
  452. ret, gas, err = RunPrecompiledContract(p, input, gas)
  453. } else {
  454. // At this point, we use a copy of address. If we don't, the go compiler will
  455. // leak the 'contract' to the outer scope, and make allocation for 'contract'
  456. // even if the actual execution ends on RunPrecompiled above.
  457. addrCopy := addr
  458. // Initialise a new contract and set the code that is to be used by the EVM.
  459. // The contract is a scoped environment for this execution context only.
  460. contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas)
  461. contract.SetCallCode(&addrCopy, stateDb.GetCodeHash(addrCopy), stateDb.GetCode(addrCopy))
  462. // When an error was returned by the EVM or when setting the creation code
  463. // above we revert to the snapshot and consume any gas remaining. Additionally
  464. // when we're in Homestead this also counts for code storage gas errors.
  465. ret, err = run(evm, contract, input, true)
  466. gas = contract.Gas
  467. }
  468. if err != nil {
  469. stateDb.RevertToSnapshot(snapshot)
  470. if err != ErrExecutionReverted {
  471. gas = 0
  472. }
  473. }
  474. return ret, gas, err
  475. }
  476. type codeAndHash struct {
  477. code []byte
  478. hash common.Hash
  479. }
  480. func (c *codeAndHash) Hash() common.Hash {
  481. if c.hash == (common.Hash{}) {
  482. c.hash = crypto.Keccak256Hash(c.code)
  483. }
  484. return c.hash
  485. }
  486. // create creates a new contract using code as deployment code.
  487. func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
  488. // Depth check execution. Fail if we're trying to execute above the
  489. // limit.
  490. if evm.depth > int(params.CallCreateDepth) {
  491. return nil, common.Address{}, gas, ErrDepth
  492. }
  493. if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
  494. return nil, common.Address{}, gas, ErrInsufficientBalance
  495. }
  496. // We add this to the access list _before_ taking a snapshot. Even if the creation fails,
  497. // the access-list change should not be rolled back
  498. if evm.chainRules.IsBerlin {
  499. evm.StateDB.AddAddressToAccessList(address)
  500. }
  501. // Quorum
  502. // Get the right state in case of a dual state environment. If a sender
  503. // is a transaction (depth == 0) use the public state to derive the address
  504. // and increment the nonce of the public state. If the sender is a contract
  505. // (depth > 0) use the private state to derive the nonce and increment the
  506. // nonce on the private state only.
  507. //
  508. // If the transaction went to a public contract the private and public state
  509. // are the same.
  510. var creatorStateDb StateDB
  511. if evm.depth > 0 {
  512. creatorStateDb = evm.privateState
  513. } else {
  514. creatorStateDb = evm.publicState
  515. }
  516. nonce := creatorStateDb.GetNonce(caller.Address())
  517. creatorStateDb.SetNonce(caller.Address(), nonce+1)
  518. // Ensure there's no existing contract already at the designated address
  519. contractHash := evm.StateDB.GetCodeHash(address)
  520. if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
  521. return nil, common.Address{}, 0, ErrContractAddressCollision
  522. }
  523. // Create a new account on the state
  524. snapshot := evm.StateDB.Snapshot()
  525. evm.StateDB.CreateAccount(address)
  526. // Quorum
  527. evm.affectedContracts[address] = Creation
  528. // End Quorum
  529. if evm.chainRules.IsEIP158 {
  530. evm.StateDB.SetNonce(address, 1)
  531. }
  532. if evm.currentTx != nil && evm.currentTx.IsPrivate() && evm.currentTx.PrivacyMetadata() != nil {
  533. // for calls (reading contract state) or finding the affected contracts there is no transaction
  534. if evm.currentTx.PrivacyMetadata().PrivacyFlag.IsNotStandardPrivate() {
  535. pm := state.NewStatePrivacyMetadata(common.BytesToEncryptedPayloadHash(evm.currentTx.Data()), evm.currentTx.PrivacyMetadata().PrivacyFlag)
  536. evm.StateDB.SetPrivacyMetadata(address, pm)
  537. log.Trace("Set Privacy Metadata", "key", address, "privacyMetadata", pm)
  538. }
  539. }
  540. if evm.ChainConfig().IsQuorum {
  541. // skip transfer if value == 0 (see note: Quorum, States, and Value Transfer)
  542. if value.Sign() != 0 {
  543. if evm.quorumReadOnly {
  544. return nil, common.Address{}, gas, ErrReadOnlyValueTransfer
  545. }
  546. evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
  547. }
  548. } else {
  549. evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
  550. }
  551. // Initialise a new contract and set the code that is to be used by the EVM.
  552. // The contract is a scoped environment for this execution context only.
  553. contract := NewContract(caller, AccountRef(address), value, gas)
  554. contract.SetCodeOptionalHash(&address, codeAndHash)
  555. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  556. return nil, address, gas, nil
  557. }
  558. if evm.vmConfig.Debug && evm.depth == 0 {
  559. evm.vmConfig.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value)
  560. }
  561. start := time.Now()
  562. ret, err := run(evm, contract, nil, false)
  563. maxCodeSize := evm.ChainConfig().GetMaxCodeSize(evm.Context.BlockNumber)
  564. if maxCodeSize < params.MaxCodeSize {
  565. maxCodeSize = params.MaxCodeSize
  566. }
  567. // Check whether the max code size has been exceeded, assign err if the case.
  568. if err == nil && evm.chainRules.IsEIP158 && len(ret) > maxCodeSize {
  569. err = ErrMaxCodeSizeExceeded
  570. }
  571. // if the contract creation ran successfully and no errors were returned
  572. // calculate the gas required to store the code. If the code could not
  573. // be stored due to not enough gas set an error and let it be handled
  574. // by the error checking condition below.
  575. if err == nil {
  576. createDataGas := uint64(len(ret)) * params.CreateDataGas
  577. if contract.UseGas(createDataGas) {
  578. evm.StateDB.SetCode(address, ret)
  579. } else {
  580. err = ErrCodeStoreOutOfGas
  581. }
  582. }
  583. // When an error was returned by the EVM or when setting the creation code
  584. // above we revert to the snapshot and consume any gas remaining. Additionally
  585. // when we're in homestead this also counts for code storage gas errors.
  586. if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) {
  587. evm.StateDB.RevertToSnapshot(snapshot)
  588. if err != ErrExecutionReverted {
  589. contract.UseGas(contract.Gas)
  590. }
  591. }
  592. if evm.vmConfig.Debug && evm.depth == 0 {
  593. evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
  594. }
  595. return ret, address, contract.Gas, err
  596. }
  597. // Create creates a new contract using code as deployment code.
  598. func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
  599. // Quorum
  600. // Get the right state in case of a dual state environment. If a sender
  601. // is a transaction (depth == 0) use the public state to derive the address
  602. // and increment the nonce of the public state. If the sender is a contract
  603. // (depth > 0) use the private state to derive the nonce and increment the
  604. // nonce on the private state only.
  605. //
  606. // If the transaction went to a public contract the private and public state
  607. // are the same.
  608. var creatorStateDb StateDB
  609. if evm.depth > 0 {
  610. creatorStateDb = evm.privateState
  611. } else {
  612. creatorStateDb = evm.publicState
  613. }
  614. // Ensure there's no existing contract already at the designated address
  615. nonce := creatorStateDb.GetNonce(caller.Address())
  616. contractAddr = crypto.CreateAddress(caller.Address(), nonce)
  617. return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
  618. }
  619. // Create2 creates a new contract using code as deployment code.
  620. //
  621. // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
  622. // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
  623. func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
  624. codeAndHash := &codeAndHash{code: code}
  625. contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes())
  626. return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
  627. }
  628. // ChainConfig returns the environment's chain configuration
  629. func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
  630. // Quorum functions for dual state
  631. func getDualState(evm *EVM, addr common.Address) StateDB {
  632. // priv: (a) -> (b) (private)
  633. // pub: a -> [b] (private -> public)
  634. // priv: (a) -> b (public)
  635. state := evm.StateDB
  636. if evm.PrivateState().Exist(addr) {
  637. state = evm.PrivateState()
  638. } else if evm.PublicState().Exist(addr) {
  639. state = evm.PublicState()
  640. }
  641. return state
  642. }
  643. func (evm *EVM) PublicState() PublicState { return evm.publicState }
  644. func (evm *EVM) PrivateState() PrivateState { return evm.privateState }
  645. func (evm *EVM) SetCurrentTX(tx *types.Transaction) { evm.currentTx = tx }
  646. func (evm *EVM) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
  647. evm.currentTx.SetTxPrivacyMetadata(pm)
  648. }
  649. func (evm *EVM) Push(statedb StateDB) {
  650. // Quorum : the read only depth to be set up only once for the entire
  651. // op code execution. This will be set first time transition from
  652. // private state to public state happens
  653. // statedb will be the state of the contract being called.
  654. // if a private contract is calling a public contract make it readonly.
  655. if !evm.quorumReadOnly && evm.privateState != statedb {
  656. evm.quorumReadOnly = true
  657. evm.readOnlyDepth = evm.currentStateDepth
  658. }
  659. if castedStateDb, ok := statedb.(*state.StateDB); ok {
  660. evm.states[evm.currentStateDepth] = castedStateDb
  661. evm.currentStateDepth++
  662. }
  663. evm.StateDB = statedb
  664. }
  665. func (evm *EVM) Pop() {
  666. evm.currentStateDepth--
  667. if evm.quorumReadOnly && evm.currentStateDepth == evm.readOnlyDepth {
  668. evm.quorumReadOnly = false
  669. }
  670. evm.StateDB = evm.states[evm.currentStateDepth-1]
  671. }
  672. func (evm *EVM) Depth() int { return evm.depth }
  673. // We only need to revert the current state because when we call from private
  674. // public state it's read only, there wouldn't be anything to reset.
  675. // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged
  676. // read only.
  677. func (evm *EVM) RevertToSnapshot(snapshot int) {
  678. evm.StateDB.RevertToSnapshot(snapshot)
  679. }
  680. // Quorum
  681. //
  682. // Returns addresses of contracts which are newly created
  683. func (evm *EVM) CreatedContracts() []common.Address {
  684. addr := make([]common.Address, 0, len(evm.affectedContracts))
  685. for a, t := range evm.affectedContracts {
  686. if t == Creation {
  687. addr = append(addr, a)
  688. }
  689. }
  690. return addr[:]
  691. }
  692. // Quorum
  693. //
  694. // AffectedContracts returns all affected contracts that are the results of
  695. // MessageCall transaction
  696. func (evm *EVM) AffectedContracts() []common.Address {
  697. addr := make([]common.Address, 0, len(evm.affectedContracts))
  698. for a, t := range evm.affectedContracts {
  699. if t == MessageCall {
  700. addr = append(addr, a)
  701. }
  702. }
  703. return addr[:]
  704. }
  705. // Quorum
  706. //
  707. // Return MerkleRoot of all affected contracts (due to both creation and message call)
  708. func (evm *EVM) CalculateMerkleRoot() (common.Hash, error) {
  709. combined := new(trie.Trie)
  710. for addr := range evm.affectedContracts {
  711. data, err := getDualState(evm, addr).GetRLPEncodedStateObject(addr)
  712. if err != nil {
  713. return common.Hash{}, err
  714. }
  715. if err := combined.TryUpdate(addr.Bytes(), data); err != nil {
  716. return common.Hash{}, err
  717. }
  718. }
  719. return combined.Hash(), nil
  720. }