From 8119ca3891362f574aa4d8e6030fb212f239d0e9 Mon Sep 17 00:00:00 2001 From: Rodrigo Quelhas Date: Thu, 2 May 2024 17:49:13 +0100 Subject: [PATCH] feat: support transient storage (EIP-1153) --- Cargo.lock | 8 ++--- Cargo.toml | 2 +- frame/evm/src/runner/stack.rs | 13 ++++++++ ts-tests/contracts/eip1153.sol | 57 ++++++++++++++++++++++++++++++++++ ts-tests/tests/test-eip1153.ts | 54 ++++++++++++++++++++++++++++++++ ts-tests/truffle-config.js | 2 +- 6 files changed, 130 insertions(+), 6 deletions(-) create mode 100644 ts-tests/contracts/eip1153.sol create mode 100644 ts-tests/tests/test-eip1153.ts diff --git a/Cargo.lock b/Cargo.lock index afa83a1edf..5178b2280a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2291,7 +2291,7 @@ dependencies = [ [[package]] name = "evm" version = "0.41.1" -source = "git+https://github.com/moonbeam-foundation/evm?branch=moonbeam-polkadot-v1.7.2#d8991ec727ad0fb64fe9957a3cd307387a6701e4" +source = "git+https://github.com/moonbeam-foundation/evm?branch=v0.4.1-eip1153#f04b630487f63335cc95e33a66be2d83cae2bb70" dependencies = [ "auto_impl", "environmental", @@ -2311,7 +2311,7 @@ dependencies = [ [[package]] name = "evm-core" version = "0.41.0" -source = "git+https://github.com/moonbeam-foundation/evm?branch=moonbeam-polkadot-v1.7.2#d8991ec727ad0fb64fe9957a3cd307387a6701e4" +source = "git+https://github.com/moonbeam-foundation/evm?branch=v0.4.1-eip1153#f04b630487f63335cc95e33a66be2d83cae2bb70" dependencies = [ "parity-scale-codec", "primitive-types", @@ -2322,7 +2322,7 @@ dependencies = [ [[package]] name = "evm-gasometer" version = "0.41.0" -source = "git+https://github.com/moonbeam-foundation/evm?branch=moonbeam-polkadot-v1.7.2#d8991ec727ad0fb64fe9957a3cd307387a6701e4" +source = "git+https://github.com/moonbeam-foundation/evm?branch=v0.4.1-eip1153#f04b630487f63335cc95e33a66be2d83cae2bb70" dependencies = [ "environmental", "evm-core", @@ -2333,7 +2333,7 @@ dependencies = [ [[package]] name = "evm-runtime" version = "0.41.0" -source = "git+https://github.com/moonbeam-foundation/evm?branch=moonbeam-polkadot-v1.7.2#d8991ec727ad0fb64fe9957a3cd307387a6701e4" +source = "git+https://github.com/moonbeam-foundation/evm?branch=v0.4.1-eip1153#f04b630487f63335cc95e33a66be2d83cae2bb70" dependencies = [ "auto_impl", "environmental", diff --git a/Cargo.toml b/Cargo.toml index 6b7583e787..d02dbd13af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ derive_more = "0.99" environmental = { version = "1.1.4", default-features = false } ethereum = { version = "0.15.0", default-features = false } ethereum-types = { version = "0.14.1", default-features = false } -evm = { git = "https://github.com/moonbeam-foundation/evm", branch = "moonbeam-polkadot-v1.7.2", default-features = false } +evm = { git = "https://github.com/moonbeam-foundation/evm", branch = "v0.4.1-eip1153", default-features = false } futures = "0.3.30" hash-db = { version = "0.16.0", default-features = false } hex = { version = "0.4.3", default-features = false, features = ["alloc"] } diff --git a/frame/evm/src/runner/stack.rs b/frame/evm/src/runner/stack.rs index b252c95c08..8b0a792b5b 100644 --- a/frame/evm/src/runner/stack.rs +++ b/frame/evm/src/runner/stack.rs @@ -725,6 +725,7 @@ pub struct SubstrateStackState<'vicinity, 'config, T> { vicinity: &'vicinity Vicinity, substate: SubstrateStackSubstate<'config>, original_storage: BTreeMap<(H160, H256), H256>, + transient_storage: BTreeMap<(H160, H256), H256>, recorded: Recorded, weight_info: Option, storage_meter: Option, @@ -750,6 +751,7 @@ impl<'vicinity, 'config, T: Config> SubstrateStackState<'vicinity, 'config, T> { }, _marker: PhantomData, original_storage: BTreeMap::new(), + transient_storage: BTreeMap::new(), recorded: Default::default(), weight_info, storage_meter, @@ -844,6 +846,13 @@ where >::get(address, index) } + fn transient_storage(&self, address: H160, index: H256) -> H256 { + self.transient_storage + .get(&(address, index)) + .copied() + .unwrap_or_default() + } + fn original_storage(&self, address: H160, index: H256) -> Option { Some( self.original_storage @@ -930,6 +939,10 @@ where } } + fn set_transient_storage(&mut self, address: H160, key: H256, value: H256) { + self.transient_storage.insert((address, key), value); + } + fn reset_storage(&mut self, address: H160) { #[allow(deprecated)] let _ = >::remove_prefix(address, None); diff --git a/ts-tests/contracts/eip1153.sol b/ts-tests/contracts/eip1153.sol new file mode 100644 index 0000000000..92ec078f21 --- /dev/null +++ b/ts-tests/contracts/eip1153.sol @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +contract ReentrancyProtected { + // A constant key for the reentrancy guard stored in Transient Storage. + // This acts as a unique identifier for the reentrancy lock. + bytes32 constant REENTRANCY_GUARD = keccak256("REENTRANCY_GUARD"); + + // Modifier to prevent reentrant calls. + // It checks if the reentrancy guard is set (indicating an ongoing execution) + // and sets the guard before proceeding with the function execution. + // After the function executes, it resets the guard to allow future calls. + modifier nonReentrant() { + // Ensure the guard is not set (i.e., no ongoing execution). + require(tload(REENTRANCY_GUARD) == 0, "Reentrant call detected."); + + // Set the guard to block reentrant calls. + tstore(REENTRANCY_GUARD, 1); + + _; // Execute the function body. + + // Reset the guard after execution to allow future calls. + tstore(REENTRANCY_GUARD, 0); + } + + // Uses inline assembly to access the Transient Storage's tstore operation. + function tstore(bytes32 location, uint value) private { + assembly { + tstore(location, value) + } + } + + // Uses inline assembly to access the Transient Storage's tload operation. + // Returns the value stored at the given location. + function tload(bytes32 location) private returns (uint value) { + assembly { + value := tload(location) + } + } + + function nonReentrantMethod() public nonReentrant() { + (bool success, bytes memory result) = msg.sender.call(""); + if (!success) { + assembly { + revert(add(32, result), mload(result)) + } + } + } + + function test() external { + this.nonReentrantMethod(); + } + + receive() external payable { + this.nonReentrantMethod(); + } +} \ No newline at end of file diff --git a/ts-tests/tests/test-eip1153.ts b/ts-tests/tests/test-eip1153.ts new file mode 100644 index 0000000000..ef6fbe2151 --- /dev/null +++ b/ts-tests/tests/test-eip1153.ts @@ -0,0 +1,54 @@ +import { expect, use as chaiUse } from "chai"; +import chaiAsPromised from "chai-as-promised"; +import { AbiItem } from "web3-utils"; + +import ReentrancyProtected from "../build/contracts/ReentrancyProtected.json"; +import { GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./config"; +import { createAndFinalizeBlock, customRequest, describeWithFrontier } from "./util"; + +chaiUse(chaiAsPromised); + +describeWithFrontier("Frontier RPC (EIP-1153)", (context) => { + const TEST_CONTRACT_BYTECODE = ReentrancyProtected.bytecode; + const TEST_CONTRACT_ABI = ReentrancyProtected.abi as AbiItem[]; + let contract_address: string = null; + + // Those test are ordered. In general this should be avoided, but due to the time it takes + // to spin up a frontier node, it saves a lot of time. + + before("create the contract", async function () { + this.timeout(15000); + const tx = await context.web3.eth.accounts.signTransaction( + { + from: GENESIS_ACCOUNT, + data: TEST_CONTRACT_BYTECODE, + value: "0x00", + gasPrice: "0x3B9ACA00", + gas: "0x100000", + }, + GENESIS_ACCOUNT_PRIVATE_KEY + ); + await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); + await createAndFinalizeBlock(context.web3); + + const receipt = await context.web3.eth.getTransactionReceipt(tx.transactionHash); + contract_address = receipt.contractAddress; + }); + + it("should detect reentrant call and revert", async function () { + const contract = new context.web3.eth.Contract(TEST_CONTRACT_ABI, contract_address, { + from: GENESIS_ACCOUNT, + gasPrice: "0x3B9ACA00" + }); + + try { + await contract.methods.test().call(); + } catch (error) { + return expect(error.message).to.be.eq( + "Returned error: VM Exception while processing transaction: revert Reentrant call detected." + ); + } + + expect.fail("Expected the contract call to fail"); + }); +}); diff --git a/ts-tests/truffle-config.js b/ts-tests/truffle-config.js index 3a2b265974..16e922a0f7 100644 --- a/ts-tests/truffle-config.js +++ b/ts-tests/truffle-config.js @@ -85,7 +85,7 @@ module.exports = { // Configure your compilers compilers: { solc: { - version: "0.8.2", // Fetch exact version from solc-bin (default: truffle's version) + version: "0.8.25", // Fetch exact version from solc-bin (default: truffle's version) docker: true, // Use "0.5.1" you've installed locally with docker (default: false) // settings: { // See the solidity docs for advice about optimization and evmVersion // optimizer: {