mirror of
https://github.com/pezkuwichain/revive-differential-tests.git
synced 2026-04-22 09:08:02 +00:00
Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 83c20b1be3 | |||
| 075c8235a7 | |||
| 3e99d1c2a5 | |||
| 4e234aa1bd | |||
| b204de5484 | |||
| 43e0d0e592 | |||
| 5eb3a0e1b5 | |||
| 772bd217c3 | |||
| 2373872230 | |||
| e3723e780a | |||
| 0513a4befb | |||
| de7c7d6703 | |||
| 3a537c2812 | |||
| 4ab79ed97e | |||
| ee97b62e70 | |||
| e9b5a06aec | |||
| 534170db6f | |||
| 090b56c46a | |||
| 547563e718 | |||
| c8eb8cf7b0 | |||
| 3b26e1e1d6 | |||
| 1bc20d088f | |||
| 10bfaed461 | |||
| 399f7820cd | |||
| ae1174febe | |||
| 38b42560ec | |||
| 8009f5880c | |||
| c590fa7bfd |
@@ -0,0 +1,147 @@
|
||||
name: Test workflow
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
types: [opened, synchronize]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
cache-polkadot:
|
||||
name: Build and cache Polkadot binaries on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-24.04, macos-14]
|
||||
|
||||
steps:
|
||||
- name: Checkout repo and submodules
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Install dependencies (Linux)
|
||||
if: matrix.os == 'ubuntu-24.04'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler clang libclang-dev
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rustup component add rust-src
|
||||
|
||||
- name: Install dependencies (macOS)
|
||||
if: matrix.os == 'macos-14'
|
||||
run: |
|
||||
brew install protobuf
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rustup component add rust-src
|
||||
|
||||
- name: Cache binaries
|
||||
id: cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/bin/substrate-node
|
||||
~/.cargo/bin/eth-rpc
|
||||
key: polkadot-binaries-${{ matrix.os }}-${{ hashFiles('polkadot-sdk/.git') }}
|
||||
|
||||
- name: Build substrate-node
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd polkadot-sdk
|
||||
cargo install --locked --force --profile=production --path substrate/bin/node/cli --bin substrate-node --features cli
|
||||
|
||||
- name: Build eth-rpc
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd polkadot-sdk
|
||||
cargo install --path substrate/frame/revive/rpc --bin eth-rpc
|
||||
|
||||
ci:
|
||||
name: CI on ${{ matrix.os }}
|
||||
needs: cache-polkadot
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-24.04, macos-14]
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Restore binaries from cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/bin/substrate-node
|
||||
~/.cargo/bin/eth-rpc
|
||||
key: polkadot-binaries-${{ matrix.os }}-${{ hashFiles('polkadot-sdk/.git') }}
|
||||
|
||||
- name: Setup Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
rustflags: ""
|
||||
|
||||
- name: Add wasm32 target
|
||||
run: |
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rustup component add rust-src
|
||||
|
||||
- name: Install Geth on Ubuntu
|
||||
if: matrix.os == 'ubuntu-24.04'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler
|
||||
|
||||
# We were facing some issues in CI with the 1.16.* versions of geth, and specifically on
|
||||
# Ubuntu. Eventually, we found out that the last version of geth that worked in our CI was
|
||||
# version 1.15.11. Thus, this is the version that we want to use in CI. The PPA sadly does
|
||||
# not have historic versions of Geth and therefore we need to resort to downloading pre
|
||||
# built binaries for Geth and the surrounding tools which is what the following parts of
|
||||
# the script do.
|
||||
|
||||
sudo apt-get install -y wget ca-certificates tar
|
||||
ARCH=$(uname -m)
|
||||
if [ "$ARCH" = "x86_64" ]; then
|
||||
URL="https://gethstore.blob.core.windows.net/builds/geth-alltools-linux-amd64-1.15.11-36b2371c.tar.gz"
|
||||
elif [ "$ARCH" = "aarch64" ]; then
|
||||
URL="https://gethstore.blob.core.windows.net/builds/geth-alltools-linux-arm64-1.15.11-36b2371c.tar.gz"
|
||||
else
|
||||
echo "Unsupported architecture: $ARCH"
|
||||
exit 1
|
||||
fi
|
||||
wget -qO- "$URL" | sudo tar xz -C /usr/local/bin --strip-components=1
|
||||
geth --version
|
||||
|
||||
- name: Install Geth on macOS
|
||||
if: matrix.os == 'macos-14'
|
||||
run: |
|
||||
brew tap ethereum/ethereum
|
||||
brew install ethereum protobuf
|
||||
|
||||
- name: Machete
|
||||
uses: bnjbvr/cargo-machete@v0.7.1
|
||||
|
||||
- name: Format
|
||||
run: make format
|
||||
|
||||
- name: Clippy
|
||||
run: make clippy
|
||||
|
||||
- name: Check substrate-node version
|
||||
run: substrate-node --version
|
||||
|
||||
- name: Check eth-rpc version
|
||||
run: eth-rpc --version
|
||||
|
||||
- name: Test cargo workspace
|
||||
run: make test
|
||||
@@ -0,0 +1,9 @@
|
||||
/target
|
||||
.vscode/
|
||||
.DS_Store
|
||||
node_modules
|
||||
/*.json
|
||||
|
||||
# We do not want to commit any log files that we produce from running the code locally so this is
|
||||
# added to the .gitignore file.
|
||||
*.log
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "polkadot-sdk"]
|
||||
path = polkadot-sdk
|
||||
url = https://github.com/paritytech/polkadot-sdk.git
|
||||
Generated
+6315
File diff suppressed because it is too large
Load Diff
+79
@@ -0,0 +1,79 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2024"
|
||||
repository = "https://github.com/paritytech/revive-differential-testing.git"
|
||||
rust-version = "1.85.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
revive-dt-compiler = { version = "0.1.0", path = "crates/compiler" }
|
||||
revive-dt-config = { version = "0.1.0", path = "crates/config" }
|
||||
revive-dt-core = { version = "0.1.0", path = "crates/core" }
|
||||
revive-dt-format = { version = "0.1.0", path = "crates/format" }
|
||||
revive-dt-node = { version = "0.1.0", path = "crates/node" }
|
||||
revive-dt-node-interaction = { version = "0.1.0", path = "crates/node-interaction" }
|
||||
revive-dt-node-pool = { version = "0.1.0", path = "crates/node-pool" }
|
||||
revive-dt-report = { version = "0.1.0", path = "crates/report" }
|
||||
revive-dt-solc-binaries = { version = "0.1.0", path = "crates/solc-binaries" }
|
||||
|
||||
alloy-primitives = "1.2.1"
|
||||
alloy-sol-types = "1.2.1"
|
||||
anyhow = "1.0"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
hex = "0.4.3"
|
||||
reqwest = { version = "0.12.15", features = ["blocking", "json"] }
|
||||
once_cell = "1.21"
|
||||
rayon = { version = "1.10" }
|
||||
semver = { version = "1.0", features = ["serde"] }
|
||||
serde = { version = "1.0", default-features = false, features = ["derive"] }
|
||||
serde_json = { version = "1.0", default-features = false, features = [
|
||||
"arbitrary_precision",
|
||||
"std",
|
||||
] }
|
||||
sha2 = { version = "0.10.9" }
|
||||
sp-core = "36.1.0"
|
||||
sp-runtime = "41.1.0"
|
||||
temp-dir = { version = "0.1.16" }
|
||||
tempfile = "3.3"
|
||||
tokio = { version = "1", default-features = false, features = [
|
||||
"rt-multi-thread",
|
||||
] }
|
||||
uuid = { version = "1.8", features = ["v4"] }
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = { version = "0.3.19", default-features = false, features = [
|
||||
"fmt",
|
||||
"json",
|
||||
"env-filter",
|
||||
] }
|
||||
|
||||
# revive compiler
|
||||
revive-solc-json-interface = { git = "https://github.com/paritytech/revive", rev = "3389865af7c3ff6f29a586d82157e8bc573c1a8e" }
|
||||
revive-common = { git = "https://github.com/paritytech/revive", rev = "3389865af7c3ff6f29a586d82157e8bc573c1a8e" }
|
||||
revive-differential = { git = "https://github.com/paritytech/revive", rev = "3389865af7c3ff6f29a586d82157e8bc573c1a8e" }
|
||||
|
||||
[workspace.dependencies.alloy]
|
||||
version = "1.0"
|
||||
default-features = false
|
||||
features = [
|
||||
"json-abi",
|
||||
"providers",
|
||||
"provider-ipc",
|
||||
"provider-debug-api",
|
||||
"reqwest",
|
||||
"rpc-types",
|
||||
"signer-local",
|
||||
"std",
|
||||
"network",
|
||||
"serde",
|
||||
"rpc-types-eth",
|
||||
]
|
||||
|
||||
[profile.bench]
|
||||
inherits = "release"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
@@ -0,0 +1,15 @@
|
||||
.PHONY: format clippy test machete
|
||||
|
||||
format:
|
||||
cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
cargo clippy --all-features --workspace -- --deny warnings
|
||||
|
||||
machete:
|
||||
cargo install cargo-machete
|
||||
cargo machete crates
|
||||
|
||||
test: format clippy machete
|
||||
cargo test --workspace -- --nocapture
|
||||
|
||||
@@ -1,2 +1,34 @@
|
||||
# revive-differential-tests
|
||||
revive differential testing framework
|
||||
|
||||
The revive differential testing framework allows to define smart contract tests in a declarative manner in order to compile and execute them against different Ethereum-compatible blockchain implmentations. This is useful to:
|
||||
- Analyze observable differences in contract compilation and execution across different blockchain implementations, including contract storage, account balances, transaction output and emitted events on a per-transaction base.
|
||||
- Collect and compare benchmark metrics such as code size, gas usage or transaction throughput per seconds (TPS) of different blockchain implementations.
|
||||
- Ensure reproducible contract builds across multiple compiler implementations or multiple host platforms.
|
||||
- Implement end-to-end regression tests for Ethereum-compatible smart contract stacks.
|
||||
|
||||
# Declarative test format
|
||||
|
||||
For now, the format used to write tests is the [matter-labs era compiler format](https://github.com/matter-labs/era-compiler-tests?tab=readme-ov-file#matter-labs-simplecomplex-format). This allows us to re-use many tests from their corpora.
|
||||
|
||||
# The `retester` utility
|
||||
|
||||
The `retester` helper utilty is used to run the tests. To get an idea of what `retester` can do, please consults its command line help:
|
||||
|
||||
```
|
||||
cargo run -p revive-dt-core -- --help
|
||||
```
|
||||
|
||||
For example, to run the [complex Solidity tests](https://github.com/matter-labs/era-compiler-tests/tree/main/solidity/complex), define a corpus structure as follows:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ML Solidity Complex",
|
||||
"path": "/path/to/era-compiler-tests/solidity/complex"
|
||||
}
|
||||
```
|
||||
|
||||
Assuming this to be saved in a `ml-solidity-complex.json` file, the following command will try to compile and execute the tests found inside the corpus:
|
||||
|
||||
```bash
|
||||
RUST_LOG=debug cargo r --release -p revive-dt-core -- --corpus ml-solidity-complex.json
|
||||
```
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "revive-dt-compiler"
|
||||
description = "Library for compiling Solidity contracts to EVM and PVM"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
revive-solc-json-interface = { workspace = true }
|
||||
revive-dt-config = { workspace = true }
|
||||
revive-dt-solc-binaries = { workspace = true }
|
||||
revive-common = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,169 @@
|
||||
//! This crate provides compiler helpers for all supported Solidity targets:
|
||||
//! - Ethereum solc compiler
|
||||
//! - Polkadot revive resolc compiler
|
||||
//! - Polkadot revive Wasm compiler
|
||||
|
||||
use std::{
|
||||
fs::read_to_string,
|
||||
hash::Hash,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use revive_dt_config::Arguments;
|
||||
|
||||
use revive_common::EVMVersion;
|
||||
use revive_solc_json_interface::{
|
||||
SolcStandardJsonInput, SolcStandardJsonInputLanguage, SolcStandardJsonInputSettings,
|
||||
SolcStandardJsonInputSettingsOptimizer, SolcStandardJsonInputSettingsSelection,
|
||||
SolcStandardJsonOutput,
|
||||
};
|
||||
use semver::Version;
|
||||
|
||||
pub mod revive_js;
|
||||
pub mod revive_resolc;
|
||||
pub mod solc;
|
||||
|
||||
/// A common interface for all supported Solidity compilers.
|
||||
pub trait SolidityCompiler {
|
||||
/// Extra options specific to the compiler.
|
||||
type Options: Default + PartialEq + Eq + Hash;
|
||||
|
||||
/// The low-level compiler interface.
|
||||
fn build(
|
||||
&self,
|
||||
input: CompilerInput<Self::Options>,
|
||||
) -> anyhow::Result<CompilerOutput<Self::Options>>;
|
||||
|
||||
fn new(solc_executable: PathBuf) -> Self;
|
||||
|
||||
fn get_compiler_executable(config: &Arguments, version: Version) -> anyhow::Result<PathBuf>;
|
||||
}
|
||||
|
||||
/// The generic compilation input configuration.
|
||||
#[derive(Debug)]
|
||||
pub struct CompilerInput<T: PartialEq + Eq + Hash> {
|
||||
pub extra_options: T,
|
||||
pub input: SolcStandardJsonInput,
|
||||
}
|
||||
|
||||
/// The generic compilation output configuration.
|
||||
pub struct CompilerOutput<T: PartialEq + Eq + Hash> {
|
||||
/// The solc standard JSON input.
|
||||
pub input: CompilerInput<T>,
|
||||
/// The produced solc standard JSON output.
|
||||
pub output: SolcStandardJsonOutput,
|
||||
/// The error message in case the compiler returns abnormally.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl<T> PartialEq for CompilerInput<T>
|
||||
where
|
||||
T: PartialEq + Eq + Hash,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let self_input = serde_json::to_vec(&self.input).unwrap_or_default();
|
||||
let other_input = serde_json::to_vec(&self.input).unwrap_or_default();
|
||||
self.extra_options.eq(&other.extra_options) && self_input == other_input
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Eq for CompilerInput<T> where T: PartialEq + Eq + Hash {}
|
||||
|
||||
impl<T> Hash for CompilerInput<T>
|
||||
where
|
||||
T: PartialEq + Eq + Hash,
|
||||
{
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.extra_options.hash(state);
|
||||
state.write(&serde_json::to_vec(&self.input).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
/// A generic builder style interface for configuring all compiler options.
|
||||
pub struct Compiler<T: SolidityCompiler> {
|
||||
input: SolcStandardJsonInput,
|
||||
extra_options: T::Options,
|
||||
allow_paths: Vec<String>,
|
||||
base_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Compiler<solc::Solc> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Compiler<T>
|
||||
where
|
||||
T: SolidityCompiler,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
input: SolcStandardJsonInput {
|
||||
language: SolcStandardJsonInputLanguage::Solidity,
|
||||
sources: Default::default(),
|
||||
settings: SolcStandardJsonInputSettings::new(
|
||||
None,
|
||||
Default::default(),
|
||||
None,
|
||||
SolcStandardJsonInputSettingsSelection::new_required(),
|
||||
SolcStandardJsonInputSettingsOptimizer::new(
|
||||
false,
|
||||
None,
|
||||
&Version::new(0, 0, 0),
|
||||
false,
|
||||
),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
},
|
||||
extra_options: Default::default(),
|
||||
allow_paths: Default::default(),
|
||||
base_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn solc_optimizer(mut self, enabled: bool) -> Self {
|
||||
self.input.settings.optimizer.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_source(mut self, path: &Path) -> anyhow::Result<Self> {
|
||||
self.input
|
||||
.sources
|
||||
.insert(path.display().to_string(), read_to_string(path)?.into());
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn evm_version(mut self, evm_version: EVMVersion) -> Self {
|
||||
self.input.settings.evm_version = Some(evm_version);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn extra_options(mut self, extra_options: T::Options) -> Self {
|
||||
self.extra_options = extra_options;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn allow_path(mut self, path: String) -> Self {
|
||||
self.allow_paths.push(path);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn base_path(mut self, base_path: String) -> Self {
|
||||
self.base_path = Some(base_path);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn try_build(self, solc_path: PathBuf) -> anyhow::Result<CompilerOutput<T::Options>> {
|
||||
T::new(solc_path).build(CompilerInput {
|
||||
extra_options: self.extra_options,
|
||||
input: self.input,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the compiler JSON input.
|
||||
pub fn input(&self) -> SolcStandardJsonInput {
|
||||
self.input.clone()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
//! Implements the [crate::SolidityCompiler] trait with revive Wasm for
|
||||
//! compiling contracts to PVM bytecode (via Wasm).
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Implements the [SolidityCompiler] trait with `resolc` for
|
||||
//! compiling contracts to PolkaVM (PVM) bytecode.
|
||||
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use crate::{CompilerInput, CompilerOutput, SolidityCompiler};
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_solc_json_interface::SolcStandardJsonOutput;
|
||||
|
||||
/// A wrapper around the `resolc` binary, emitting PVM-compatible bytecode.
|
||||
pub struct Resolc {
|
||||
/// Path to the `resolc` executable
|
||||
resolc_path: PathBuf,
|
||||
}
|
||||
|
||||
impl SolidityCompiler for Resolc {
|
||||
type Options = Vec<String>;
|
||||
|
||||
fn build(
|
||||
&self,
|
||||
input: CompilerInput<Self::Options>,
|
||||
) -> anyhow::Result<CompilerOutput<Self::Options>> {
|
||||
let mut child = Command::new(&self.resolc_path)
|
||||
.arg("--standard-json")
|
||||
.args(&input.extra_options)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
let stdin_pipe = child.stdin.as_mut().expect("stdin must be piped");
|
||||
serde_json::to_writer(stdin_pipe, &input.input)?;
|
||||
|
||||
let json_in = serde_json::to_string_pretty(&input.input)?;
|
||||
|
||||
let output = child.wait_with_output()?;
|
||||
let stdout = output.stdout;
|
||||
let stderr = output.stderr;
|
||||
|
||||
if !output.status.success() {
|
||||
let message = String::from_utf8_lossy(&stderr);
|
||||
tracing::error!(
|
||||
"resolc failed exit={} stderr={} JSON-in={} ",
|
||||
output.status,
|
||||
&message,
|
||||
json_in,
|
||||
);
|
||||
return Ok(CompilerOutput {
|
||||
input,
|
||||
output: Default::default(),
|
||||
error: Some(message.into()),
|
||||
});
|
||||
}
|
||||
|
||||
let parsed: SolcStandardJsonOutput = serde_json::from_slice(&stdout).map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"failed to parse resolc JSON output: {e}\nstderr: {}",
|
||||
String::from_utf8_lossy(&stderr)
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(CompilerOutput {
|
||||
input,
|
||||
output: parsed,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn new(resolc_path: PathBuf) -> Self {
|
||||
Resolc { resolc_path }
|
||||
}
|
||||
|
||||
fn get_compiler_executable(
|
||||
config: &Arguments,
|
||||
_version: semver::Version,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
if !config.resolc.as_os_str().is_empty() {
|
||||
return Ok(config.resolc.clone());
|
||||
}
|
||||
|
||||
Ok(PathBuf::from("resolc"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Implements the [SolidityCompiler] trait with solc for
|
||||
//! compiling contracts to EVM bytecode.
|
||||
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use crate::{CompilerInput, CompilerOutput, SolidityCompiler};
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_dt_solc_binaries::download_solc;
|
||||
|
||||
pub struct Solc {
|
||||
solc_path: PathBuf,
|
||||
}
|
||||
|
||||
impl SolidityCompiler for Solc {
|
||||
type Options = ();
|
||||
|
||||
fn build(
|
||||
&self,
|
||||
input: CompilerInput<Self::Options>,
|
||||
) -> anyhow::Result<CompilerOutput<Self::Options>> {
|
||||
let mut child = Command::new(&self.solc_path)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.arg("--standard-json")
|
||||
.spawn()?;
|
||||
|
||||
let stdin = child.stdin.as_mut().expect("should be piped");
|
||||
serde_json::to_writer(stdin, &input.input)?;
|
||||
let output = child.wait_with_output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
let message = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("solc failed exit={} stderr={}", output.status, &message);
|
||||
return Ok(CompilerOutput {
|
||||
input,
|
||||
output: Default::default(),
|
||||
error: Some(message.into()),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(CompilerOutput {
|
||||
input,
|
||||
output: serde_json::from_slice(&output.stdout)?,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn new(solc_path: PathBuf) -> Self {
|
||||
Self { solc_path }
|
||||
}
|
||||
|
||||
fn get_compiler_executable(
|
||||
config: &Arguments,
|
||||
version: semver::Version,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let path = download_solc(config.directory(), version, config.wasm)?;
|
||||
Ok(path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "revive-dt-config"
|
||||
description = "global configuration for the revive differential tester"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
alloy = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
temp-dir = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! The global configuration used across all revive differential testing crates.
|
||||
|
||||
use std::{
|
||||
fmt::Display,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use alloy::{network::EthereumWallet, signers::local::PrivateKeySigner};
|
||||
use clap::{Parser, ValueEnum};
|
||||
use semver::Version;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use temp_dir::TempDir;
|
||||
|
||||
#[derive(Debug, Parser, Clone, Serialize, Deserialize)]
|
||||
#[command(name = "retester")]
|
||||
pub struct Arguments {
|
||||
/// The `solc` version to use if the test didn't specify it explicitly.
|
||||
#[arg(long = "solc", short, default_value = "0.8.29")]
|
||||
pub solc: Version,
|
||||
|
||||
/// Use the Wasm compiler versions.
|
||||
#[arg(long = "wasm")]
|
||||
pub wasm: bool,
|
||||
|
||||
/// The path to the `resolc` executable to be tested.
|
||||
///
|
||||
/// By default it uses the `resolc` binary found in `$PATH`.
|
||||
///
|
||||
/// If `--wasm` is set, this should point to the resolc Wasm ile.
|
||||
#[arg(long = "resolc", short, default_value = "resolc")]
|
||||
pub resolc: PathBuf,
|
||||
|
||||
/// A list of test corpus JSON files to be tested.
|
||||
#[arg(long = "corpus", short)]
|
||||
pub corpus: Vec<PathBuf>,
|
||||
|
||||
/// A place to store temporary artifacts during test execution.
|
||||
///
|
||||
/// Creates a temporary dir if not specified.
|
||||
#[arg(long = "workdir", short)]
|
||||
pub working_directory: Option<PathBuf>,
|
||||
|
||||
/// Add a tempdir manually if `working_directory` was not given.
|
||||
///
|
||||
/// We attach it here because [TempDir] prunes itself on drop.
|
||||
#[clap(skip)]
|
||||
#[serde(skip)]
|
||||
pub temp_dir: Option<&'static TempDir>,
|
||||
|
||||
/// The path to the `geth` executable.
|
||||
///
|
||||
/// By default it uses `geth` binary found in `$PATH`.
|
||||
#[arg(short, long = "geth", default_value = "geth")]
|
||||
pub geth: PathBuf,
|
||||
|
||||
/// The maximum time in milliseconds to wait for geth to start.
|
||||
#[arg(long = "geth-start-timeout", default_value = "2000")]
|
||||
pub geth_start_timeout: u64,
|
||||
|
||||
/// The test network chain ID.
|
||||
#[arg(short, long = "network-id", default_value = "420420420")]
|
||||
pub network_id: u64,
|
||||
|
||||
/// Configure nodes according to this genesis.json file.
|
||||
#[arg(long = "genesis", default_value = "genesis.json")]
|
||||
pub genesis_file: PathBuf,
|
||||
|
||||
/// The signing account private key.
|
||||
#[arg(
|
||||
short,
|
||||
long = "account",
|
||||
default_value = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
|
||||
)]
|
||||
pub account: String,
|
||||
|
||||
/// The differential testing leader node implementation.
|
||||
#[arg(short, long = "leader", default_value = "geth")]
|
||||
pub leader: TestingPlatform,
|
||||
|
||||
/// The differential testing follower node implementation.
|
||||
#[arg(short, long = "follower", default_value = "kitchensink")]
|
||||
pub follower: TestingPlatform,
|
||||
|
||||
/// Only compile against this testing platform (doesn't execute the tests).
|
||||
#[arg(long = "compile-only")]
|
||||
pub compile_only: Option<TestingPlatform>,
|
||||
|
||||
/// Determines the amount of tests that are executed in parallel.
|
||||
#[arg(long = "workers", default_value = "12")]
|
||||
pub workers: usize,
|
||||
|
||||
/// Extract problems back to the test corpus.
|
||||
#[arg(short, long = "extract-problems")]
|
||||
pub extract_problems: bool,
|
||||
|
||||
/// The path to the `kitchensink` executable.
|
||||
///
|
||||
/// By default it uses `substrate-node` binary found in `$PATH`.
|
||||
#[arg(short, long = "kitchensink", default_value = "substrate-node")]
|
||||
pub kitchensink: PathBuf,
|
||||
|
||||
/// The path to the `eth_proxy` executable.
|
||||
///
|
||||
/// By default it uses `eth-rpc` binary found in `$PATH`.
|
||||
#[arg(short = 'p', long = "eth_proxy", default_value = "eth-rpc")]
|
||||
pub eth_proxy: PathBuf,
|
||||
}
|
||||
|
||||
impl Arguments {
|
||||
/// Return the configured working directory with the following precedence:
|
||||
/// 1. `self.working_directory` if it was provided.
|
||||
/// 2. `self.temp_dir` if it it was provided
|
||||
/// 3. Panic.
|
||||
pub fn directory(&self) -> &Path {
|
||||
if let Some(path) = &self.working_directory {
|
||||
return path.as_path();
|
||||
}
|
||||
|
||||
if let Some(temp_dir) = &self.temp_dir {
|
||||
return temp_dir.path();
|
||||
}
|
||||
|
||||
panic!("should have a workdir configured")
|
||||
}
|
||||
|
||||
/// Try to parse `self.account` into a [PrivateKeySigner],
|
||||
/// panicing on error.
|
||||
pub fn wallet(&self) -> EthereumWallet {
|
||||
let signer = self
|
||||
.account
|
||||
.parse::<PrivateKeySigner>()
|
||||
.unwrap_or_else(|error| {
|
||||
panic!("private key '{}' parsing error: {error}", self.account);
|
||||
});
|
||||
EthereumWallet::new(signer)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Arguments {
|
||||
fn default() -> Self {
|
||||
Arguments::parse_from(["retester"])
|
||||
}
|
||||
}
|
||||
|
||||
/// The Solidity compatible node implementation.
|
||||
///
|
||||
/// This describes the solutions to be tested against on a high level.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, ValueEnum, Serialize, Deserialize)]
|
||||
#[clap(rename_all = "lower")]
|
||||
pub enum TestingPlatform {
|
||||
/// The go-ethereum reference full node EVM implementation.
|
||||
Geth,
|
||||
/// The kitchensink runtime provides the PolkaVM (PVM) based node implentation.
|
||||
Kitchensink,
|
||||
}
|
||||
|
||||
impl Display for TestingPlatform {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Geth => f.write_str("geth"),
|
||||
Self::Kitchensink => f.write_str("revive"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "revive-dt-core"
|
||||
description = "revive differential testing core utility"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "retester"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
revive-dt-compiler = { workspace = true }
|
||||
revive-dt-config = { workspace = true }
|
||||
revive-dt-format = { workspace = true }
|
||||
revive-dt-node = { workspace = true }
|
||||
revive-dt-node-interaction = { workspace = true }
|
||||
revive-dt-report = { workspace = true }
|
||||
|
||||
alloy = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
revive-solc-json-interface = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
temp-dir = { workspace = true }
|
||||
@@ -0,0 +1,478 @@
|
||||
//! The test driver handles the compilation and execution of the test cases.
|
||||
|
||||
use alloy::json_abi::JsonAbi;
|
||||
use alloy::network::TransactionBuilder;
|
||||
use alloy::rpc::types::TransactionReceipt;
|
||||
use alloy::rpc::types::trace::geth::GethTrace;
|
||||
use alloy::{
|
||||
primitives::{Address, map::HashMap},
|
||||
rpc::types::{
|
||||
TransactionRequest,
|
||||
trace::geth::{AccountState, DiffMode},
|
||||
},
|
||||
};
|
||||
use revive_dt_compiler::{Compiler, CompilerInput, SolidityCompiler};
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_dt_format::{input::Input, metadata::Metadata, mode::SolcMode};
|
||||
use revive_dt_node_interaction::EthereumNode;
|
||||
use revive_dt_report::reporter::{CompilationTask, Report, Span};
|
||||
use revive_solc_json_interface::SolcStandardJsonOutput;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap as StdHashMap;
|
||||
use tracing::Level;
|
||||
|
||||
use crate::Platform;
|
||||
|
||||
type Contracts<T> = HashMap<
|
||||
CompilerInput<<<T as Platform>::Compiler as SolidityCompiler>::Options>,
|
||||
SolcStandardJsonOutput,
|
||||
>;
|
||||
|
||||
pub struct State<'a, T: Platform> {
|
||||
config: &'a Arguments,
|
||||
span: Span,
|
||||
contracts: Contracts<T>,
|
||||
deployed_contracts: StdHashMap<String, Address>,
|
||||
deployed_abis: StdHashMap<String, JsonAbi>,
|
||||
}
|
||||
|
||||
impl<'a, T> State<'a, T>
|
||||
where
|
||||
T: Platform,
|
||||
{
|
||||
pub fn new(config: &'a Arguments, span: Span) -> Self {
|
||||
Self {
|
||||
config,
|
||||
span,
|
||||
contracts: Default::default(),
|
||||
deployed_contracts: Default::default(),
|
||||
deployed_abis: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a copy of the current span.
|
||||
fn span(&self) -> Span {
|
||||
self.span
|
||||
}
|
||||
|
||||
pub fn build_contracts(&mut self, mode: &SolcMode, metadata: &Metadata) -> anyhow::Result<()> {
|
||||
let mut span = self.span();
|
||||
span.next_metadata(
|
||||
metadata
|
||||
.file_path
|
||||
.as_ref()
|
||||
.expect("metadata should have been read from a file")
|
||||
.clone(),
|
||||
);
|
||||
|
||||
let Some(version) = mode.last_patch_version(&self.config.solc) else {
|
||||
anyhow::bail!("unsupported solc version: {:?}", &mode.solc_version);
|
||||
};
|
||||
|
||||
let mut compiler = Compiler::<T::Compiler>::new()
|
||||
.base_path(metadata.directory()?.display().to_string())
|
||||
.solc_optimizer(mode.solc_optimize());
|
||||
|
||||
for (file, _contract) in metadata.contract_sources()?.values() {
|
||||
tracing::debug!("contract source {}", file.display());
|
||||
compiler = compiler.with_source(file)?;
|
||||
}
|
||||
|
||||
let mut task = CompilationTask {
|
||||
json_input: compiler.input(),
|
||||
json_output: None,
|
||||
mode: mode.clone(),
|
||||
compiler_version: format!("{}", &version),
|
||||
error: None,
|
||||
};
|
||||
|
||||
let compiler_path = T::Compiler::get_compiler_executable(self.config, version)?;
|
||||
match compiler.try_build(compiler_path) {
|
||||
Ok(output) => {
|
||||
task.json_output = Some(output.output.clone());
|
||||
task.error = output.error;
|
||||
self.contracts.insert(output.input, output.output);
|
||||
|
||||
if let Some(last_output) = self.contracts.values().last() {
|
||||
if let Some(contracts) = &last_output.contracts {
|
||||
for (file, contracts_map) in contracts {
|
||||
for contract_name in contracts_map.keys() {
|
||||
tracing::debug!(
|
||||
"Compiled contract: {contract_name} from file: {file}"
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("Compiled contracts field is None");
|
||||
}
|
||||
}
|
||||
|
||||
Report::compilation(span, T::config_id(), task);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to compile contract: {:?}", error.to_string());
|
||||
task.error = Some(error.to_string());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute_input(
|
||||
&mut self,
|
||||
input: &Input,
|
||||
node: &T::Blockchain,
|
||||
) -> anyhow::Result<(TransactionReceipt, GethTrace, DiffMode)> {
|
||||
tracing::trace!("Calling execute_input for input: {input:?}");
|
||||
|
||||
let nonce = node.fetch_add_nonce(input.caller)?;
|
||||
|
||||
tracing::debug!(
|
||||
"Nonce calculated on the execute contract, calculated nonce {}, for contract {}, having address {} on node: {}",
|
||||
&nonce,
|
||||
&input.instance,
|
||||
&input.caller,
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
|
||||
let tx =
|
||||
match input.legacy_transaction(nonce, &self.deployed_contracts, &self.deployed_abis) {
|
||||
Ok(tx) => {
|
||||
tracing::debug!("Legacy transaction data: {tx:#?}");
|
||||
tx
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to construct legacy transaction: {err:?}");
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
tracing::trace!("Executing transaction for input: {input:?}");
|
||||
|
||||
let receipt = match node.execute_transaction(tx) {
|
||||
Ok(receipt) => receipt,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
"Failed to execute transaction when executing the contract: {}, {:?}",
|
||||
&input.instance,
|
||||
err
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
tracing::trace!(
|
||||
"Transaction receipt for executed contract: {} - {:?}",
|
||||
&input.instance,
|
||||
receipt,
|
||||
);
|
||||
|
||||
let trace = node.trace_transaction(receipt.clone())?;
|
||||
tracing::trace!(
|
||||
"Trace result for contract: {} - {:?}",
|
||||
&input.instance,
|
||||
trace
|
||||
);
|
||||
|
||||
let diff = node.state_diff(receipt.clone())?;
|
||||
|
||||
Ok((receipt, trace, diff))
|
||||
}
|
||||
|
||||
pub fn deploy_contracts(&mut self, input: &Input, node: &T::Blockchain) -> anyhow::Result<()> {
|
||||
tracing::debug!(
|
||||
"Deploying contracts {}, having address {} on node: {}",
|
||||
&input.instance,
|
||||
&input.caller,
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
for output in self.contracts.values() {
|
||||
let Some(contract_map) = &output.contracts else {
|
||||
tracing::debug!(
|
||||
"No contracts in output — skipping deployment for this input {}",
|
||||
&input.instance
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
for contracts in contract_map.values() {
|
||||
for (contract_name, contract) in contracts {
|
||||
let tracing_span = tracing::info_span!("Deploying contract", contract_name);
|
||||
let _guard = tracing_span.enter();
|
||||
|
||||
tracing::debug!(
|
||||
"Contract name is: {:?} and the input name is: {:?}",
|
||||
&contract_name,
|
||||
&input.instance
|
||||
);
|
||||
|
||||
let bytecode = contract
|
||||
.evm
|
||||
.as_ref()
|
||||
.and_then(|evm| evm.bytecode.as_ref())
|
||||
.map(|b| b.object.clone());
|
||||
|
||||
let Some(code) = bytecode else {
|
||||
tracing::error!("no bytecode for contract {contract_name}");
|
||||
continue;
|
||||
};
|
||||
|
||||
let nonce = node.fetch_add_nonce(input.caller)?;
|
||||
|
||||
tracing::debug!(
|
||||
"Calculated nonce {}, for contract {}, having address {} on node: {}",
|
||||
&nonce,
|
||||
&input.instance,
|
||||
&input.caller,
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
|
||||
// We are using alloy for building and submitting the transactions and it will
|
||||
// automatically fill in all of the missing fields from the provider that we
|
||||
// are using.
|
||||
let code = alloy::hex::decode(&code)?;
|
||||
let tx = TransactionRequest::default()
|
||||
.nonce(nonce)
|
||||
.from(input.caller)
|
||||
.with_deploy_code(code);
|
||||
|
||||
let receipt = match node.execute_transaction(tx) {
|
||||
Ok(receipt) => receipt,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
"Failed to execute transaction when deploying the contract on node : {:?}, {:?}, {:?}",
|
||||
std::any::type_name::<T>(),
|
||||
&contract_name,
|
||||
err
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
tracing::debug!(
|
||||
"Deployment tx sent for {} with nonce {} → tx hash: {:?}, on node: {:?}",
|
||||
contract_name,
|
||||
nonce,
|
||||
receipt.transaction_hash,
|
||||
std::any::type_name::<T>(),
|
||||
);
|
||||
|
||||
tracing::trace!(
|
||||
"Deployed transaction receipt for contract: {} - {:?}, on node: {:?}",
|
||||
&contract_name,
|
||||
receipt,
|
||||
std::any::type_name::<T>(),
|
||||
);
|
||||
|
||||
let Some(address) = receipt.contract_address else {
|
||||
tracing::error!(
|
||||
"contract {contract_name} deployment did not return an address"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
self.deployed_contracts
|
||||
.insert(contract_name.clone(), address);
|
||||
tracing::trace!(
|
||||
"deployed contract `{}` at {:?}, on node {:?}",
|
||||
contract_name,
|
||||
address,
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
|
||||
if let Some(Value::String(metadata_json_str)) = &contract.metadata {
|
||||
tracing::trace!(
|
||||
"metadata found for contract {contract_name}, {metadata_json_str}"
|
||||
);
|
||||
|
||||
match serde_json::from_str::<serde_json::Value>(metadata_json_str) {
|
||||
Ok(metadata_json) => {
|
||||
if let Some(abi_value) =
|
||||
metadata_json.get("output").and_then(|o| o.get("abi"))
|
||||
{
|
||||
match serde_json::from_value::<JsonAbi>(abi_value.clone()) {
|
||||
Ok(parsed_abi) => {
|
||||
tracing::trace!(
|
||||
"ABI found in metadata for contract {}",
|
||||
&contract_name
|
||||
);
|
||||
self.deployed_abis
|
||||
.insert(contract_name.clone(), parsed_abi);
|
||||
}
|
||||
Err(err) => {
|
||||
anyhow::bail!(
|
||||
"Failed to parse ABI from metadata for contract {}: {}",
|
||||
contract_name,
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
anyhow::bail!(
|
||||
"No ABI found in metadata for contract {}",
|
||||
contract_name
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
anyhow::bail!(
|
||||
"Failed to parse metadata JSON string for contract {}: {}",
|
||||
contract_name,
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
anyhow::bail!("No metadata found for contract {}", contract_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!("Available contracts: {:?}", self.deployed_contracts.keys());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Driver<'a, Leader: Platform, Follower: Platform> {
|
||||
metadata: &'a Metadata,
|
||||
config: &'a Arguments,
|
||||
leader_node: &'a Leader::Blockchain,
|
||||
follower_node: &'a Follower::Blockchain,
|
||||
}
|
||||
|
||||
impl<'a, L, F> Driver<'a, L, F>
|
||||
where
|
||||
L: Platform,
|
||||
F: Platform,
|
||||
{
|
||||
pub fn new(
|
||||
metadata: &'a Metadata,
|
||||
config: &'a Arguments,
|
||||
leader_node: &'a L::Blockchain,
|
||||
follower_node: &'a F::Blockchain,
|
||||
) -> Driver<'a, L, F> {
|
||||
Self {
|
||||
metadata,
|
||||
config,
|
||||
leader_node,
|
||||
follower_node,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trace_diff_mode(label: &str, diff: &DiffMode) {
|
||||
tracing::trace!("{label} - PRE STATE:");
|
||||
for (addr, state) in &diff.pre {
|
||||
Self::trace_account_state(" [pre]", addr, state);
|
||||
}
|
||||
|
||||
tracing::trace!("{label} - POST STATE:");
|
||||
for (addr, state) in &diff.post {
|
||||
Self::trace_account_state(" [post]", addr, state);
|
||||
}
|
||||
}
|
||||
|
||||
fn trace_account_state(prefix: &str, addr: &Address, state: &AccountState) {
|
||||
tracing::trace!("{prefix} 0x{addr:x}");
|
||||
|
||||
if let Some(balance) = &state.balance {
|
||||
tracing::trace!("{prefix} balance: {balance}");
|
||||
}
|
||||
if let Some(nonce) = &state.nonce {
|
||||
tracing::trace!("{prefix} nonce: {nonce}");
|
||||
}
|
||||
if let Some(code) = &state.code {
|
||||
tracing::trace!("{prefix} code: {code}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, span: Span) -> anyhow::Result<()> {
|
||||
for mode in self.metadata.solc_modes() {
|
||||
let mut leader_state = State::<L>::new(self.config, span);
|
||||
leader_state.build_contracts(&mode, self.metadata)?;
|
||||
|
||||
let mut follower_state = State::<F>::new(self.config, span);
|
||||
follower_state.build_contracts(&mode, self.metadata)?;
|
||||
|
||||
for (case_idx, case) in self.metadata.cases.iter().enumerate() {
|
||||
// Creating a tracing span to know which case within the metadata is being executed
|
||||
// and which one we're getting logs for.
|
||||
let tracing_span = tracing::span!(
|
||||
Level::INFO,
|
||||
"Executing case",
|
||||
case = case.name,
|
||||
case_idx = case_idx
|
||||
);
|
||||
let _guard = tracing_span.enter();
|
||||
|
||||
for input in &case.inputs {
|
||||
tracing::debug!("Starting deploying contract {}", &input.instance);
|
||||
if let Err(err) = leader_state.deploy_contracts(input, self.leader_node) {
|
||||
tracing::error!("Leader deployment failed for {}: {err}", input.instance);
|
||||
continue;
|
||||
} else {
|
||||
tracing::debug!("Leader deployment succeeded for {}", &input.instance);
|
||||
}
|
||||
|
||||
if let Err(err) = follower_state.deploy_contracts(input, self.follower_node) {
|
||||
tracing::error!("Follower deployment failed for {}: {err}", input.instance);
|
||||
continue;
|
||||
} else {
|
||||
tracing::debug!("Follower deployment succeeded for {}", &input.instance);
|
||||
}
|
||||
|
||||
tracing::debug!("Starting executing contract {}", &input.instance);
|
||||
|
||||
let (leader_receipt, _, leader_diff) =
|
||||
match leader_state.execute_input(input, self.leader_node) {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
"Leader execution failed for {}: {err}",
|
||||
input.instance
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let (follower_receipt, _, follower_diff) =
|
||||
match follower_state.execute_input(input, self.follower_node) {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
"Follower execution failed for {}: {err}",
|
||||
input.instance
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if leader_diff == follower_diff {
|
||||
tracing::debug!("State diffs match between leader and follower.");
|
||||
} else {
|
||||
tracing::debug!("State diffs mismatch between leader and follower.");
|
||||
Self::trace_diff_mode("Leader", &leader_diff);
|
||||
Self::trace_diff_mode("Follower", &follower_diff);
|
||||
}
|
||||
|
||||
if leader_receipt.logs() != follower_receipt.logs() {
|
||||
tracing::debug!("Log/event mismatch between leader and follower.");
|
||||
tracing::trace!("Leader logs: {:?}", leader_receipt.logs());
|
||||
tracing::trace!("Follower logs: {:?}", follower_receipt.logs());
|
||||
}
|
||||
|
||||
if leader_receipt.status() != follower_receipt.status() {
|
||||
tracing::debug!(
|
||||
"Mismatch in status: leader = {}, follower = {}",
|
||||
leader_receipt.status(),
|
||||
follower_receipt.status()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! The revive differential testing core library.
|
||||
//!
|
||||
//! This crate defines the testing configuration and
|
||||
//! provides a helper utilty to execute tests.
|
||||
|
||||
use revive_dt_compiler::{SolidityCompiler, revive_resolc, solc};
|
||||
use revive_dt_config::TestingPlatform;
|
||||
use revive_dt_node::{geth, kitchensink::KitchensinkNode};
|
||||
use revive_dt_node_interaction::EthereumNode;
|
||||
|
||||
pub mod driver;
|
||||
|
||||
/// One platform can be tested differentially against another.
|
||||
///
|
||||
/// For this we need a blockchain node implementation and a compiler.
|
||||
pub trait Platform {
|
||||
type Blockchain: EthereumNode;
|
||||
type Compiler: SolidityCompiler;
|
||||
|
||||
/// Returns the matching [TestingPlatform] of the [revive_dt_config::Arguments].
|
||||
fn config_id() -> TestingPlatform;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Geth;
|
||||
|
||||
impl Platform for Geth {
|
||||
type Blockchain = geth::Instance;
|
||||
type Compiler = solc::Solc;
|
||||
|
||||
fn config_id() -> TestingPlatform {
|
||||
TestingPlatform::Geth
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Kitchensink;
|
||||
|
||||
impl Platform for Kitchensink {
|
||||
type Blockchain = KitchensinkNode;
|
||||
type Compiler = revive_resolc::Resolc;
|
||||
|
||||
fn config_id() -> TestingPlatform {
|
||||
TestingPlatform::Kitchensink
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use std::{collections::HashMap, sync::LazyLock};
|
||||
|
||||
use clap::Parser;
|
||||
use rayon::{ThreadPoolBuilder, prelude::*};
|
||||
|
||||
use revive_dt_config::*;
|
||||
use revive_dt_core::{
|
||||
Geth, Kitchensink, Platform,
|
||||
driver::{Driver, State},
|
||||
};
|
||||
use revive_dt_format::{corpus::Corpus, metadata::MetadataFile};
|
||||
use revive_dt_node::pool::NodePool;
|
||||
use revive_dt_report::reporter::{Report, Span};
|
||||
use temp_dir::TempDir;
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::{EnvFilter, FmtSubscriber, fmt::format::FmtSpan};
|
||||
|
||||
static TEMP_DIR: LazyLock<TempDir> = LazyLock::new(|| TempDir::new().unwrap());
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let args = init_cli()?;
|
||||
|
||||
for (corpus, tests) in collect_corpora(&args)? {
|
||||
let span = Span::new(corpus, args.clone())?;
|
||||
|
||||
match &args.compile_only {
|
||||
Some(platform) => compile_corpus(&args, &tests, platform, span),
|
||||
None => execute_corpus(&args, &tests, span)?,
|
||||
}
|
||||
|
||||
Report::save()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_cli() -> anyhow::Result<Arguments> {
|
||||
let subscriber = FmtSubscriber::builder()
|
||||
.with_thread_ids(true)
|
||||
.with_thread_names(true)
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
|
||||
.pretty()
|
||||
.finish();
|
||||
tracing::subscriber::set_global_default(subscriber)?;
|
||||
|
||||
let mut args = Arguments::parse();
|
||||
|
||||
if args.corpus.is_empty() {
|
||||
anyhow::bail!("no test corpus specified");
|
||||
}
|
||||
|
||||
match args.working_directory.as_ref() {
|
||||
Some(dir) => {
|
||||
if !dir.exists() {
|
||||
anyhow::bail!("workdir {} does not exist", dir.display());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
args.temp_dir = Some(&TEMP_DIR);
|
||||
}
|
||||
}
|
||||
tracing::info!("workdir: {}", args.directory().display());
|
||||
|
||||
ThreadPoolBuilder::new()
|
||||
.num_threads(args.workers)
|
||||
.build_global()?;
|
||||
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
fn collect_corpora(args: &Arguments) -> anyhow::Result<HashMap<Corpus, Vec<MetadataFile>>> {
|
||||
let mut corpora = HashMap::new();
|
||||
|
||||
for path in &args.corpus {
|
||||
let corpus = Corpus::try_from_path(path)?;
|
||||
tracing::info!("found corpus: {}", path.display());
|
||||
let tests = corpus.enumerate_tests();
|
||||
tracing::info!("corpus '{}' contains {} tests", &corpus.name, tests.len());
|
||||
corpora.insert(corpus, tests);
|
||||
}
|
||||
|
||||
Ok(corpora)
|
||||
}
|
||||
|
||||
fn run_driver<L, F>(args: &Arguments, tests: &[MetadataFile], span: Span) -> anyhow::Result<()>
|
||||
where
|
||||
L: Platform,
|
||||
F: Platform,
|
||||
L::Blockchain: revive_dt_node::Node + Send + Sync + 'static,
|
||||
F::Blockchain: revive_dt_node::Node + Send + Sync + 'static,
|
||||
{
|
||||
let leader_nodes = NodePool::<L::Blockchain>::new(args)?;
|
||||
let follower_nodes = NodePool::<F::Blockchain>::new(args)?;
|
||||
|
||||
tests.par_iter().for_each(
|
||||
|MetadataFile {
|
||||
content: metadata,
|
||||
path: metadata_file_path,
|
||||
}| {
|
||||
// Starting a new tracing span for this metadata file. This allows our logs to be clear
|
||||
// about which metadata file the logs belong to. We can add other information into this
|
||||
// as well to be able to associate the logs with the correct metadata file and case
|
||||
// that's being executed.
|
||||
let tracing_span = tracing::span!(
|
||||
Level::INFO,
|
||||
"Running driver",
|
||||
metadata_file_path = metadata_file_path.display().to_string(),
|
||||
);
|
||||
let _guard = tracing_span.enter();
|
||||
|
||||
let mut driver = Driver::<L, F>::new(
|
||||
metadata,
|
||||
args,
|
||||
leader_nodes.round_robbin(),
|
||||
follower_nodes.round_robbin(),
|
||||
);
|
||||
|
||||
match driver.execute(span) {
|
||||
Ok(_) => {
|
||||
tracing::info!(
|
||||
"metadata {} success",
|
||||
metadata.directory().as_ref().unwrap().display()
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
"metadata {} failure: {error:?}",
|
||||
metadata.file_path.as_ref().unwrap().display()
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn execute_corpus(args: &Arguments, tests: &[MetadataFile], span: Span) -> anyhow::Result<()> {
|
||||
match (&args.leader, &args.follower) {
|
||||
(TestingPlatform::Geth, TestingPlatform::Kitchensink) => {
|
||||
run_driver::<Geth, Kitchensink>(args, tests, span)?
|
||||
}
|
||||
(TestingPlatform::Geth, TestingPlatform::Geth) => {
|
||||
run_driver::<Geth, Geth>(args, tests, span)?
|
||||
}
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_corpus(
|
||||
config: &Arguments,
|
||||
tests: &[MetadataFile],
|
||||
platform: &TestingPlatform,
|
||||
span: Span,
|
||||
) {
|
||||
tests.par_iter().for_each(|metadata| {
|
||||
for mode in &metadata.solc_modes() {
|
||||
match platform {
|
||||
TestingPlatform::Geth => {
|
||||
let mut state = State::<Geth>::new(config, span);
|
||||
let _ = state.build_contracts(mode, metadata);
|
||||
}
|
||||
TestingPlatform::Kitchensink => {
|
||||
let mut state = State::<Kitchensink>::new(config, span);
|
||||
let _ = state.build_contracts(mode, metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "revive-dt-format"
|
||||
description = "declarative test definition format"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
alloy = { workspace = true }
|
||||
alloy-primitives = { workspace = true }
|
||||
alloy-sol-types = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,12 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{input::Input, mode::Mode};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct Case {
|
||||
pub name: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
pub modes: Option<Vec<Mode>>,
|
||||
pub inputs: Vec<Input>,
|
||||
pub group: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::metadata::MetadataFile;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq, Hash)]
|
||||
pub struct Corpus {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl Corpus {
|
||||
/// Try to read and parse the corpus definition file at given `path`.
|
||||
pub fn try_from_path(path: &Path) -> anyhow::Result<Self> {
|
||||
let file = File::open(path)?;
|
||||
Ok(serde_json::from_reader(file)?)
|
||||
}
|
||||
|
||||
/// Scan the corpus base directory and return all tests found.
|
||||
pub fn enumerate_tests(&self) -> Vec<MetadataFile> {
|
||||
let mut tests = Vec::new();
|
||||
collect_metadata(&self.path, &mut tests);
|
||||
tests
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively walks `path` and parses any JSON or Solidity file into a test
|
||||
/// definition [Metadata].
|
||||
///
|
||||
/// Found tests are inserted into `tests`.
|
||||
///
|
||||
/// `path` is expected to be a directory.
|
||||
pub fn collect_metadata(path: &Path, tests: &mut Vec<MetadataFile>) {
|
||||
let dir_entry = match std::fs::read_dir(path) {
|
||||
Ok(dir_entry) => dir_entry,
|
||||
Err(error) => {
|
||||
tracing::error!("failed to read dir '{}': {error}", path.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for entry in dir_entry {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(error) => {
|
||||
tracing::error!("error reading dir entry: {error}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_metadata(&path, tests);
|
||||
continue;
|
||||
}
|
||||
|
||||
if path.is_file() {
|
||||
if let Some(metadata) = MetadataFile::try_from_file(&path) {
|
||||
tests.push(metadata)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use alloy::{
|
||||
json_abi::JsonAbi,
|
||||
network::TransactionBuilder,
|
||||
primitives::{Address, Bytes, U256},
|
||||
rpc::types::TransactionRequest,
|
||||
};
|
||||
use semver::VersionReq;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
|
||||
pub struct Input {
|
||||
#[serde(default = "default_caller")]
|
||||
pub caller: Address,
|
||||
pub comment: Option<String>,
|
||||
#[serde(default = "default_instance")]
|
||||
pub instance: String,
|
||||
pub method: Method,
|
||||
pub calldata: Option<Calldata>,
|
||||
pub expected: Option<Expected>,
|
||||
pub value: Option<String>,
|
||||
pub storage: Option<HashMap<String, Calldata>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
|
||||
#[serde(untagged)]
|
||||
pub enum Expected {
|
||||
Calldata(Calldata),
|
||||
Expected(ExpectedOutput),
|
||||
ExpectedMany(Vec<ExpectedOutput>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
|
||||
pub struct ExpectedOutput {
|
||||
compiler_version: Option<VersionReq>,
|
||||
return_data: Option<Calldata>,
|
||||
events: Option<Value>,
|
||||
exception: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
|
||||
#[serde(untagged)]
|
||||
pub enum Calldata {
|
||||
Single(String),
|
||||
Compound(Vec<String>),
|
||||
}
|
||||
|
||||
/// Specify how the contract is called.
|
||||
#[derive(Debug, Default, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub enum Method {
|
||||
/// Initiate a deploy transaction, calling contracts constructor.
|
||||
///
|
||||
/// Indicated by `#deployer`.
|
||||
#[serde(rename = "#deployer")]
|
||||
Deployer,
|
||||
|
||||
/// Does not calculate and insert a function selector.
|
||||
///
|
||||
/// Indicated by `#fallback`.
|
||||
#[default]
|
||||
#[serde(rename = "#fallback")]
|
||||
Fallback,
|
||||
|
||||
/// Call the public function with the given name.
|
||||
#[serde(untagged)]
|
||||
FunctionName(String),
|
||||
}
|
||||
|
||||
impl Input {
|
||||
fn instance_to_address(
|
||||
&self,
|
||||
instance: &str,
|
||||
deployed_contracts: &HashMap<String, Address>,
|
||||
) -> anyhow::Result<Address> {
|
||||
deployed_contracts
|
||||
.get(instance)
|
||||
.copied()
|
||||
.ok_or_else(|| anyhow::anyhow!("instance {instance} not deployed"))
|
||||
}
|
||||
|
||||
pub fn encoded_input(
|
||||
&self,
|
||||
deployed_abis: &HashMap<String, JsonAbi>,
|
||||
deployed_contracts: &HashMap<String, Address>,
|
||||
) -> anyhow::Result<Bytes> {
|
||||
let Method::FunctionName(ref function_name) = self.method else {
|
||||
return Ok(Bytes::default()); // fallback or deployer — no input
|
||||
};
|
||||
|
||||
let abi = deployed_abis
|
||||
.get(&self.instance)
|
||||
.ok_or_else(|| anyhow::anyhow!("ABI for instance '{}' not found", &self.instance))?;
|
||||
|
||||
tracing::trace!("ABI found for instance: {}", &self.instance);
|
||||
|
||||
// We follow the same logic that's implemented in the matter-labs-tester where they resolve
|
||||
// the function name into a function selector and they assume that he function doesn't have
|
||||
// any existing overloads.
|
||||
// https://github.com/matter-labs/era-compiler-tester/blob/1dfa7d07cba0734ca97e24704f12dd57f6990c2c/compiler_tester/src/test/case/input/mod.rs#L158-L190
|
||||
let function = abi
|
||||
.functions()
|
||||
.find(|function| function.name.starts_with(function_name))
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"Function with name {:?} not found in ABI for the instance {:?}",
|
||||
function_name,
|
||||
&self.instance
|
||||
)
|
||||
})?;
|
||||
|
||||
tracing::trace!("Functions found for instance: {}", &self.instance);
|
||||
|
||||
let calldata_args = match &self.calldata {
|
||||
Some(Calldata::Compound(args)) => args,
|
||||
_ => anyhow::bail!("Expected compound calldata for function call"),
|
||||
};
|
||||
|
||||
if calldata_args.len() != function.inputs.len() {
|
||||
anyhow::bail!(
|
||||
"Function expects {} args, but got {}",
|
||||
function.inputs.len(),
|
||||
calldata_args.len()
|
||||
);
|
||||
}
|
||||
|
||||
tracing::trace!(
|
||||
"Starting encoding ABI's parameters for instance: {}",
|
||||
&self.instance
|
||||
);
|
||||
|
||||
// Allocating a vector that we will be using for the calldata. The vector size will be:
|
||||
// 4 bytes for the function selector.
|
||||
// function.inputs.len() * 32 bytes for the arguments (each argument is a U256).
|
||||
//
|
||||
// We're using indices in the following code in order to avoid the need for us to allocate
|
||||
// a new buffer for each one of the resolved arguments.
|
||||
let mut calldata = Vec::<u8>::with_capacity(4 + calldata_args.len() * 32);
|
||||
calldata.extend(function.selector().0);
|
||||
|
||||
for (arg_idx, arg) in calldata_args.iter().enumerate() {
|
||||
match resolve_argument(arg, deployed_contracts) {
|
||||
Ok(resolved) => {
|
||||
calldata.extend(resolved.to_be_bytes::<32>());
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(arg, arg_idx, ?error, "Failed to resolve argument");
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(calldata.into())
|
||||
}
|
||||
|
||||
/// Parse this input into a legacy transaction.
|
||||
pub fn legacy_transaction(
|
||||
&self,
|
||||
nonce: u64,
|
||||
deployed_contracts: &HashMap<String, Address>,
|
||||
deployed_abis: &HashMap<String, JsonAbi>,
|
||||
) -> anyhow::Result<TransactionRequest> {
|
||||
let input_data = self.encoded_input(deployed_abis, deployed_contracts)?;
|
||||
let transaction_request = TransactionRequest::default().nonce(nonce);
|
||||
match self.method {
|
||||
Method::Deployer => Ok(transaction_request.with_deploy_code(input_data)),
|
||||
_ => Ok(transaction_request
|
||||
.to(self.instance_to_address(&self.instance, deployed_contracts)?)
|
||||
.input(input_data.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_instance() -> String {
|
||||
"Test".to_string()
|
||||
}
|
||||
|
||||
fn default_caller() -> Address {
|
||||
"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1".parse().unwrap()
|
||||
}
|
||||
|
||||
/// This function takes in the string calldata argument provided in the JSON input and resolves it
|
||||
/// into a [`U256`] which is later used to construct the calldata.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// This piece of code is taken from the matter-labs-tester repository which is licensed under MIT
|
||||
/// or Apache. The original source code can be found here:
|
||||
/// https://github.com/matter-labs/era-compiler-tester/blob/0ed598a27f6eceee7008deab3ff2311075a2ec69/compiler_tester/src/test/case/input/value.rs#L43-L146
|
||||
fn resolve_argument(
|
||||
value: &str,
|
||||
deployed_contracts: &HashMap<String, Address>,
|
||||
) -> anyhow::Result<U256> {
|
||||
if let Some(instance) = value.strip_suffix(".address") {
|
||||
Ok(U256::from_be_slice(
|
||||
deployed_contracts
|
||||
.get(instance)
|
||||
.ok_or_else(|| anyhow::anyhow!("Instance `{}` not found", instance))?
|
||||
.as_ref(),
|
||||
))
|
||||
} else if let Some(value) = value.strip_prefix('-') {
|
||||
let value = U256::from_str_radix(value, 10)
|
||||
.map_err(|error| anyhow::anyhow!("Invalid decimal literal after `-`: {}", error))?;
|
||||
if value > U256::ONE << 255u8 {
|
||||
anyhow::bail!("Decimal literal after `-` is too big");
|
||||
}
|
||||
let value = value
|
||||
.checked_sub(U256::ONE)
|
||||
.ok_or_else(|| anyhow::anyhow!("`-0` is invalid literal"))?;
|
||||
Ok(U256::MAX.checked_sub(value).expect("Always valid"))
|
||||
} else if let Some(value) = value.strip_prefix("0x") {
|
||||
Ok(U256::from_str_radix(value, 16)
|
||||
.map_err(|error| anyhow::anyhow!("Invalid hexadecimal literal: {}", error))?)
|
||||
} else {
|
||||
// TODO: This is a set of "variables" that we need to be able to resolve to be fully in
|
||||
// compliance with the matter labs tester but we currently do not resolve them. We need to
|
||||
// add logic that does their resolution in the future, perhaps through some kind of system
|
||||
// context API that we pass down to the resolution function that allows it to make calls to
|
||||
// the node to perform these resolutions.
|
||||
let is_unsupported = [
|
||||
"$CHAIN_ID",
|
||||
"$GAS_LIMIT",
|
||||
"$COINBASE",
|
||||
"$DIFFICULTY",
|
||||
"$BLOCK_HASH",
|
||||
"$BLOCK_TIMESTAMP",
|
||||
]
|
||||
.iter()
|
||||
.any(|var| value.starts_with(var));
|
||||
|
||||
if is_unsupported {
|
||||
tracing::error!(value, "Unsupported variable used");
|
||||
anyhow::bail!("Encountered {value} which is currently unsupported by the framework");
|
||||
} else {
|
||||
Ok(U256::from_str_radix(value, 10)
|
||||
.map_err(|error| anyhow::anyhow!("Invalid decimal literal: {}", error))?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
use alloy::json_abi::JsonAbi;
|
||||
use alloy_primitives::address;
|
||||
use alloy_sol_types::SolValue;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn test_encoded_input_uint256() {
|
||||
let raw_metadata = r#"
|
||||
[
|
||||
{
|
||||
"inputs": [{"name": "value", "type": "uint256"}],
|
||||
"name": "store",
|
||||
"outputs": [],
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
}
|
||||
]
|
||||
"#;
|
||||
|
||||
let parsed_abi: JsonAbi = serde_json::from_str(raw_metadata).unwrap();
|
||||
let selector = parsed_abi
|
||||
.function("store")
|
||||
.unwrap()
|
||||
.first()
|
||||
.unwrap()
|
||||
.selector()
|
||||
.0;
|
||||
|
||||
let input = Input {
|
||||
instance: "Contract".to_string(),
|
||||
method: Method::FunctionName("store".to_owned()),
|
||||
calldata: Some(Calldata::Compound(vec!["42".into()])),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut deployed_abis = HashMap::new();
|
||||
deployed_abis.insert("Contract".to_string(), parsed_abi);
|
||||
let deployed_contracts = HashMap::new();
|
||||
|
||||
let encoded = input
|
||||
.encoded_input(&deployed_abis, &deployed_contracts)
|
||||
.unwrap();
|
||||
assert!(encoded.0.starts_with(&selector));
|
||||
|
||||
type T = (u64,);
|
||||
let decoded: T = T::abi_decode(&encoded.0[4..]).unwrap();
|
||||
assert_eq!(decoded.0, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encoded_input_address() {
|
||||
let raw_abi = r#"[
|
||||
{
|
||||
"inputs": [{"name": "recipient", "type": "address"}],
|
||||
"name": "send",
|
||||
"outputs": [],
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
}
|
||||
]"#;
|
||||
|
||||
let parsed_abi: JsonAbi = serde_json::from_str(raw_abi).unwrap();
|
||||
let selector = parsed_abi
|
||||
.function("send")
|
||||
.unwrap()
|
||||
.first()
|
||||
.unwrap()
|
||||
.selector()
|
||||
.0;
|
||||
|
||||
let input: Input = Input {
|
||||
instance: "Contract".to_string(),
|
||||
method: Method::FunctionName("send".to_owned()),
|
||||
calldata: Some(Calldata::Compound(vec![
|
||||
"0x1000000000000000000000000000000000000001".to_string(),
|
||||
])),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut abis = HashMap::new();
|
||||
abis.insert("Contract".to_string(), parsed_abi);
|
||||
let contracts = HashMap::new();
|
||||
|
||||
let encoded = input.encoded_input(&abis, &contracts).unwrap();
|
||||
assert!(encoded.0.starts_with(&selector));
|
||||
|
||||
type T = (alloy_primitives::Address,);
|
||||
let decoded: T = T::abi_decode(&encoded.0[4..]).unwrap();
|
||||
assert_eq!(
|
||||
decoded.0,
|
||||
address!("0x1000000000000000000000000000000000000001")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! The revive differential tests case format.
|
||||
|
||||
pub mod case;
|
||||
pub mod corpus;
|
||||
pub mod input;
|
||||
pub mod metadata;
|
||||
pub mod mode;
|
||||
@@ -0,0 +1,198 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs::{File, read_to_string},
|
||||
ops::Deref,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
case::Case,
|
||||
mode::{Mode, SolcMode},
|
||||
};
|
||||
|
||||
pub const METADATA_FILE_EXTENSION: &str = "json";
|
||||
pub const SOLIDITY_CASE_FILE_EXTENSION: &str = "sol";
|
||||
pub const SOLIDITY_CASE_COMMENT_MARKER: &str = "//!";
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct MetadataFile {
|
||||
pub path: PathBuf,
|
||||
pub content: Metadata,
|
||||
}
|
||||
|
||||
impl MetadataFile {
|
||||
pub fn try_from_file(path: &Path) -> Option<Self> {
|
||||
Metadata::try_from_file(path).map(|metadata| Self {
|
||||
path: path.to_owned(),
|
||||
content: metadata,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for MetadataFile {
|
||||
type Target = Metadata;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.content
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct Metadata {
|
||||
pub cases: Vec<Case>,
|
||||
pub contracts: Option<BTreeMap<String, String>>,
|
||||
pub libraries: Option<BTreeMap<String, BTreeMap<String, String>>>,
|
||||
pub ignore: Option<bool>,
|
||||
pub modes: Option<Vec<Mode>>,
|
||||
pub file_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
/// Returns the solc modes of this metadata, inserting a default mode if not present.
|
||||
pub fn solc_modes(&self) -> Vec<SolcMode> {
|
||||
self.modes
|
||||
.to_owned()
|
||||
.unwrap_or_else(|| vec![Mode::Solidity(Default::default())])
|
||||
.iter()
|
||||
.filter_map(|mode| match mode {
|
||||
Mode::Solidity(solc_mode) => Some(solc_mode),
|
||||
Mode::Unknown(mode) => {
|
||||
tracing::debug!("compiler: ignoring unknown mode '{mode}'");
|
||||
None
|
||||
}
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the base directory of this metadata.
|
||||
pub fn directory(&self) -> anyhow::Result<PathBuf> {
|
||||
Ok(self
|
||||
.file_path
|
||||
.as_ref()
|
||||
.and_then(|path| path.parent())
|
||||
.ok_or_else(|| anyhow::anyhow!("metadata invalid file path: {:?}", self.file_path))?
|
||||
.to_path_buf())
|
||||
}
|
||||
|
||||
/// Extract the contract sources.
|
||||
///
|
||||
/// Returns a mapping of contract IDs to their source path and contract name.
|
||||
pub fn contract_sources(&self) -> anyhow::Result<BTreeMap<String, (PathBuf, String)>> {
|
||||
let directory = self.directory()?;
|
||||
let mut sources = BTreeMap::new();
|
||||
let Some(contracts) = &self.contracts else {
|
||||
return Ok(sources);
|
||||
};
|
||||
|
||||
for (id, contract) in contracts {
|
||||
// TODO: broken if a colon is in the dir name..
|
||||
let mut parts = contract.split(':');
|
||||
let (Some(file_name), Some(contract_name)) = (parts.next(), parts.next()) else {
|
||||
anyhow::bail!("metadata contains invalid contract: {contract}");
|
||||
};
|
||||
let file = directory.to_path_buf().join(file_name);
|
||||
if !file.is_file() {
|
||||
anyhow::bail!("contract {id} is not a file: {}", file.display());
|
||||
}
|
||||
|
||||
sources.insert(id.clone(), (file, contract_name.to_string()));
|
||||
}
|
||||
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
/// Try to parse the test metadata struct from the given file at `path`.
|
||||
///
|
||||
/// Returns `None` if `path` didn't contain a test metadata or case definition.
|
||||
///
|
||||
/// # Panics
|
||||
/// Expects the supplied `path` to be a file.
|
||||
pub fn try_from_file(path: &Path) -> Option<Self> {
|
||||
assert!(path.is_file(), "not a file: {}", path.display());
|
||||
|
||||
let Some(file_extension) = path.extension() else {
|
||||
tracing::debug!("skipping corpus file: {}", path.display());
|
||||
return None;
|
||||
};
|
||||
|
||||
if file_extension == METADATA_FILE_EXTENSION {
|
||||
return Self::try_from_json(path);
|
||||
}
|
||||
|
||||
if file_extension == SOLIDITY_CASE_FILE_EXTENSION {
|
||||
return Self::try_from_solidity(path);
|
||||
}
|
||||
|
||||
tracing::debug!("ignoring invalid corpus file: {}", path.display());
|
||||
None
|
||||
}
|
||||
|
||||
fn try_from_json(path: &Path) -> Option<Self> {
|
||||
let file = File::open(path)
|
||||
.inspect_err(|error| {
|
||||
tracing::error!(
|
||||
"opening JSON test metadata file '{}' error: {error}",
|
||||
path.display()
|
||||
);
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
match serde_json::from_reader::<_, Metadata>(file) {
|
||||
Ok(mut metadata) => {
|
||||
metadata.file_path = Some(path.to_path_buf());
|
||||
Some(metadata)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
"parsing JSON test metadata file '{}' error: {error}",
|
||||
path.display()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_from_solidity(path: &Path) -> Option<Self> {
|
||||
let spec = read_to_string(path)
|
||||
.inspect_err(|error| {
|
||||
tracing::error!(
|
||||
"opening JSON test metadata file '{}' error: {error}",
|
||||
path.display()
|
||||
);
|
||||
})
|
||||
.ok()?
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(SOLIDITY_CASE_COMMENT_MARKER))
|
||||
.fold(String::new(), |mut buf, string| {
|
||||
buf.push_str(string);
|
||||
buf
|
||||
});
|
||||
|
||||
if spec.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
match serde_json::from_str::<Self>(&spec) {
|
||||
Ok(mut metadata) => {
|
||||
metadata.file_path = Some(path.to_path_buf());
|
||||
let name = path
|
||||
.file_name()
|
||||
.expect("this should be the path to a Solidity file")
|
||||
.to_str()
|
||||
.expect("the file name should be valid UTF-8k");
|
||||
metadata.contracts = Some([(String::from("Test"), format!("{name}:Test"))].into());
|
||||
Some(metadata)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
"parsing Solidity test metadata file '{}' error: '{error}' from data: {spec}",
|
||||
path.display()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
use semver::Version;
|
||||
use serde::de::Deserializer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Specifies the compilation mode of the test artifact.
|
||||
#[derive(Hash, Debug, Clone, Eq, PartialEq)]
|
||||
pub enum Mode {
|
||||
Solidity(SolcMode),
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// Specify Solidity specific compiler options.
|
||||
#[derive(Hash, Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SolcMode {
|
||||
pub solc_version: Option<semver::VersionReq>,
|
||||
solc_optimize: Option<bool>,
|
||||
pub llvm_optimizer_settings: Vec<String>,
|
||||
}
|
||||
|
||||
impl SolcMode {
|
||||
/// Try to parse a mode string into a solc mode.
|
||||
/// Returns `None` if the string wasn't a solc YUL mode string.
|
||||
///
|
||||
/// The mode string is expected to start with the `Y` ID (YUL ID),
|
||||
/// optionally followed by `+` or `-` for the solc optimizer settings.
|
||||
///
|
||||
/// Options can be separated by a whitespace contain the following
|
||||
/// - A solc `SemVer version requirement` string
|
||||
/// - One or more `-OX` where X is a supposed to be an LLVM opt mode
|
||||
pub fn parse_from_mode_string(mode_string: &str) -> Option<Self> {
|
||||
let mut result = Self::default();
|
||||
|
||||
let mut parts = mode_string.trim().split(" ");
|
||||
|
||||
match parts.next()? {
|
||||
"Y" => {}
|
||||
"Y+" => result.solc_optimize = Some(true),
|
||||
"Y-" => result.solc_optimize = Some(false),
|
||||
_ => return None,
|
||||
}
|
||||
|
||||
for part in parts {
|
||||
if let Ok(solc_version) = semver::VersionReq::parse(part) {
|
||||
result.solc_version = Some(solc_version);
|
||||
continue;
|
||||
}
|
||||
if let Some(level) = part.strip_prefix("-O") {
|
||||
result.llvm_optimizer_settings.push(level.to_string());
|
||||
continue;
|
||||
}
|
||||
panic!("the YUL mode string {mode_string} failed to parse, invalid part: {part}")
|
||||
}
|
||||
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// Returns whether to enable the solc optimizer.
|
||||
pub fn solc_optimize(&self) -> bool {
|
||||
self.solc_optimize.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Calculate the latest matching solc patch version. Returns:
|
||||
/// - `latest_supported` if no version request was specified.
|
||||
/// - A matching version with the same minor version as `latest_supported`, if any.
|
||||
/// - `None` if no minor version of the `latest_supported` version matches.
|
||||
pub fn last_patch_version(&self, latest_supported: &Version) -> Option<Version> {
|
||||
let Some(version_req) = self.solc_version.as_ref() else {
|
||||
return Some(latest_supported.to_owned());
|
||||
};
|
||||
|
||||
// lgtm
|
||||
for patch in (0..latest_supported.patch + 1).rev() {
|
||||
let version = Version::new(0, latest_supported.minor, patch);
|
||||
if version_req.matches(&version) {
|
||||
return Some(version);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Mode {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let mode_string = String::deserialize(deserializer)?;
|
||||
|
||||
if let Some(solc_mode) = SolcMode::parse_from_mode_string(&mode_string) {
|
||||
return Ok(Self::Solidity(solc_mode));
|
||||
}
|
||||
|
||||
Ok(Self::Unknown(mode_string))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "revive-dt-node-interaction"
|
||||
description = "send and trace transactions to nodes"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
alloy = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,29 @@
|
||||
//! This crate implements all node interactions.
|
||||
|
||||
use alloy::primitives::Address;
|
||||
use alloy::rpc::types::trace::geth::{DiffMode, GethTrace};
|
||||
use alloy::rpc::types::{TransactionReceipt, TransactionRequest};
|
||||
use tokio_runtime::TO_TOKIO;
|
||||
|
||||
pub mod nonce;
|
||||
mod tokio_runtime;
|
||||
pub mod trace;
|
||||
pub mod transaction;
|
||||
|
||||
/// An interface for all interactions with Ethereum compatible nodes.
|
||||
pub trait EthereumNode {
|
||||
/// Execute the [TransactionRequest] and return a [TransactionReceipt].
|
||||
fn execute_transaction(
|
||||
&self,
|
||||
transaction: TransactionRequest,
|
||||
) -> anyhow::Result<TransactionReceipt>;
|
||||
|
||||
/// Trace the transaction in the [TransactionReceipt] and return a [GethTrace].
|
||||
fn trace_transaction(&self, transaction: TransactionReceipt) -> anyhow::Result<GethTrace>;
|
||||
|
||||
/// Returns the state diff of the transaction hash in the [TransactionReceipt].
|
||||
fn state_diff(&self, transaction: TransactionReceipt) -> anyhow::Result<DiffMode>;
|
||||
|
||||
/// Returns the next available nonce for the given [Address].
|
||||
fn fetch_add_nonce(&self, address: Address) -> anyhow::Result<u64>;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use alloy::{
|
||||
primitives::Address,
|
||||
providers::{Provider, ProviderBuilder},
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::{TO_TOKIO, tokio_runtime::AsyncNodeInteraction};
|
||||
|
||||
pub type Task = Pin<Box<dyn Future<Output = anyhow::Result<u64>> + Send>>;
|
||||
|
||||
pub(crate) struct Nonce {
|
||||
sender: oneshot::Sender<anyhow::Result<u64>>,
|
||||
task: Task,
|
||||
}
|
||||
|
||||
impl AsyncNodeInteraction for Nonce {
|
||||
type Output = anyhow::Result<u64>;
|
||||
|
||||
fn split(
|
||||
self,
|
||||
) -> (
|
||||
std::pin::Pin<Box<dyn Future<Output = Self::Output> + Send>>,
|
||||
oneshot::Sender<Self::Output>,
|
||||
) {
|
||||
(self.task, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
/// This is like `trace_transaction`, just for nonces.
|
||||
pub fn fetch_onchain_nonce(
|
||||
connection: String,
|
||||
wallet: alloy::network::EthereumWallet,
|
||||
address: Address,
|
||||
) -> anyhow::Result<u64> {
|
||||
let sender = TO_TOKIO.lock().unwrap().nonce_sender.clone();
|
||||
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let task: Task = Box::pin(async move {
|
||||
let provider = ProviderBuilder::new()
|
||||
.wallet(wallet)
|
||||
.connect(&connection)
|
||||
.await?;
|
||||
let onchain = provider.get_transaction_count(address).await?;
|
||||
Ok(onchain)
|
||||
});
|
||||
|
||||
sender
|
||||
.blocking_send(Nonce { task, sender: tx })
|
||||
.expect("not in async context");
|
||||
|
||||
rx.blocking_recv()
|
||||
.unwrap_or_else(|err| anyhow::bail!("nonce fetch failed: {err}"))
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! The alloy crate __requires__ a tokio runtime.
|
||||
//! We contain any async rust right here.
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::spawn;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::task::JoinError;
|
||||
|
||||
use crate::nonce::Nonce;
|
||||
use crate::trace::Trace;
|
||||
use crate::transaction::Transaction;
|
||||
|
||||
pub(crate) static TO_TOKIO: Lazy<Mutex<TokioRuntime>> =
|
||||
Lazy::new(|| Mutex::new(TokioRuntime::spawn()));
|
||||
|
||||
/// Common interface for executing async node interactions from a non-async context.
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) trait AsyncNodeInteraction: Send + 'static {
|
||||
type Output: Send;
|
||||
|
||||
//// Returns the task and the output sender.
|
||||
fn split(
|
||||
self,
|
||||
) -> (
|
||||
Pin<Box<dyn Future<Output = Self::Output> + Send>>,
|
||||
oneshot::Sender<Self::Output>,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) struct TokioRuntime {
|
||||
pub(crate) transaction_sender: mpsc::Sender<Transaction>,
|
||||
pub(crate) trace_sender: mpsc::Sender<Trace>,
|
||||
pub(crate) nonce_sender: mpsc::Sender<Nonce>,
|
||||
}
|
||||
|
||||
impl TokioRuntime {
|
||||
fn spawn() -> Self {
|
||||
let rt = Runtime::new().expect("should be able to create the tokio runtime");
|
||||
let (transaction_sender, transaction_receiver) = mpsc::channel::<Transaction>(1024);
|
||||
let (trace_sender, trace_receiver) = mpsc::channel::<Trace>(1024);
|
||||
let (nonce_sender, nonce_receiver) = mpsc::channel::<Nonce>(1024);
|
||||
|
||||
thread::spawn(move || {
|
||||
rt.block_on(async move {
|
||||
let transaction_task = spawn(interaction::<Transaction>(transaction_receiver));
|
||||
let trace_task = spawn(interaction::<Trace>(trace_receiver));
|
||||
let nonce_task = spawn(interaction::<Nonce>(nonce_receiver));
|
||||
|
||||
if let Err(error) = transaction_task.await {
|
||||
tracing::error!("tokio transaction task failed: {error}");
|
||||
}
|
||||
if let Err(error) = trace_task.await {
|
||||
tracing::error!("tokio trace transaction task failed: {error}");
|
||||
}
|
||||
if let Err(error) = nonce_task.await {
|
||||
tracing::error!("tokio nonce task failed: {error}");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Self {
|
||||
transaction_sender,
|
||||
trace_sender,
|
||||
nonce_sender,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn interaction<T>(mut receiver: mpsc::Receiver<T>) -> Result<(), JoinError>
|
||||
where
|
||||
T: AsyncNodeInteraction,
|
||||
{
|
||||
while let Some(task) = receiver.recv().await {
|
||||
spawn(async move {
|
||||
let (task, sender) = task.split();
|
||||
sender
|
||||
.send(task.await)
|
||||
.unwrap_or_else(|_| panic!("failed to send task output"));
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Trace transactions in a sync context.
|
||||
|
||||
use std::pin::Pin;
|
||||
|
||||
use alloy::rpc::types::trace::geth::GethTrace;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::TO_TOKIO;
|
||||
use crate::tokio_runtime::AsyncNodeInteraction;
|
||||
|
||||
pub type Task = Pin<Box<dyn Future<Output = anyhow::Result<GethTrace>> + Send>>;
|
||||
|
||||
pub(crate) struct Trace {
|
||||
sender: oneshot::Sender<anyhow::Result<GethTrace>>,
|
||||
task: Task,
|
||||
}
|
||||
|
||||
impl AsyncNodeInteraction for Trace {
|
||||
type Output = anyhow::Result<GethTrace>;
|
||||
|
||||
fn split(
|
||||
self,
|
||||
) -> (
|
||||
std::pin::Pin<Box<dyn Future<Output = Self::Output> + Send>>,
|
||||
oneshot::Sender<Self::Output>,
|
||||
) {
|
||||
(self.task, self.sender)
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute some [Task] that return a [GethTrace] result.
|
||||
pub fn trace_transaction(task: Task) -> anyhow::Result<GethTrace> {
|
||||
let task_sender = TO_TOKIO.lock().unwrap().trace_sender.clone();
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
|
||||
task_sender
|
||||
.blocking_send(Trace { task, sender })
|
||||
.expect("we are not calling this from an async context");
|
||||
|
||||
receiver
|
||||
.blocking_recv()
|
||||
.unwrap_or_else(|error| anyhow::bail!("no trace received: {error}"))
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Execute transactions in a sync context.
|
||||
|
||||
use std::pin::Pin;
|
||||
|
||||
use alloy::rpc::types::TransactionReceipt;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::TO_TOKIO;
|
||||
use crate::tokio_runtime::AsyncNodeInteraction;
|
||||
|
||||
pub type Task = Pin<Box<dyn Future<Output = anyhow::Result<TransactionReceipt>> + Send>>;
|
||||
|
||||
pub(crate) struct Transaction {
|
||||
receipt_sender: oneshot::Sender<anyhow::Result<TransactionReceipt>>,
|
||||
task: Task,
|
||||
}
|
||||
|
||||
impl AsyncNodeInteraction for Transaction {
|
||||
type Output = anyhow::Result<TransactionReceipt>;
|
||||
|
||||
fn split(
|
||||
self,
|
||||
) -> (
|
||||
Pin<Box<dyn Future<Output = Self::Output> + Send>>,
|
||||
oneshot::Sender<Self::Output>,
|
||||
) {
|
||||
(self.task, self.receipt_sender)
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute some [Task] that returns a [TransactionReceipt].
|
||||
pub fn execute_transaction(task: Task) -> anyhow::Result<TransactionReceipt> {
|
||||
let request_sender = TO_TOKIO.lock().unwrap().transaction_sender.clone();
|
||||
let (receipt_sender, receipt_receiver) = oneshot::channel();
|
||||
|
||||
request_sender
|
||||
.blocking_send(Transaction {
|
||||
receipt_sender,
|
||||
task,
|
||||
})
|
||||
.expect("we are not calling this from an async context");
|
||||
|
||||
receipt_receiver
|
||||
.blocking_recv()
|
||||
.unwrap_or_else(|error| anyhow::bail!("no receipt received: {error}"))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "revive-dt-node"
|
||||
description = "abstraction over blockchain nodes"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
alloy = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
revive-dt-node-interaction = { workspace = true }
|
||||
revive-dt-config = { workspace = true }
|
||||
|
||||
serde_json = { workspace = true }
|
||||
|
||||
sp-core = { workspace = true }
|
||||
sp-runtime = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
temp-dir = { workspace = true }
|
||||
@@ -0,0 +1,459 @@
|
||||
//! The go-ethereum node implementation.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions, create_dir_all, remove_dir_all},
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicU32, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use alloy::{
|
||||
network::EthereumWallet,
|
||||
primitives::Address,
|
||||
providers::{Provider, ProviderBuilder, ext::DebugApi},
|
||||
rpc::types::{
|
||||
TransactionReceipt, TransactionRequest,
|
||||
trace::geth::{DiffMode, GethDebugTracingOptions, PreStateConfig, PreStateFrame},
|
||||
},
|
||||
};
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_dt_node_interaction::{
|
||||
EthereumNode, nonce::fetch_onchain_nonce, trace::trace_transaction,
|
||||
transaction::execute_transaction,
|
||||
};
|
||||
use tracing::Level;
|
||||
|
||||
use crate::Node;
|
||||
|
||||
static NODE_COUNT: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// The go-ethereum node instance implementation.
|
||||
///
|
||||
/// Implements helpers to initialize, spawn and wait the node.
|
||||
///
|
||||
/// Assumes dev mode and IPC only (`P2P`, `http`` etc. are kept disabled).
|
||||
///
|
||||
/// Prunes the child process and the base directory on drop.
|
||||
#[derive(Debug)]
|
||||
pub struct Instance {
|
||||
connection_string: String,
|
||||
base_directory: PathBuf,
|
||||
data_directory: PathBuf,
|
||||
logs_directory: PathBuf,
|
||||
geth: PathBuf,
|
||||
id: u32,
|
||||
handle: Option<Child>,
|
||||
network_id: u64,
|
||||
start_timeout: u64,
|
||||
wallet: EthereumWallet,
|
||||
nonces: Mutex<HashMap<Address, u64>>,
|
||||
/// This vector stores [`File`] objects that we use for logging which we want to flush when the
|
||||
/// node object is dropped. We do not store them in a structured fashion at the moment (in
|
||||
/// separate fields) as the logic that we need to apply to them is all the same regardless of
|
||||
/// what it belongs to, we just want to flush them on [`Drop`] of the node.
|
||||
logs_file_to_flush: Vec<File>,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
const BASE_DIRECTORY: &str = "geth";
|
||||
const DATA_DIRECTORY: &str = "data";
|
||||
const LOGS_DIRECTORY: &str = "logs";
|
||||
|
||||
const IPC_FILE: &str = "geth.ipc";
|
||||
const GENESIS_JSON_FILE: &str = "genesis.json";
|
||||
|
||||
const READY_MARKER: &str = "IPC endpoint opened";
|
||||
const ERROR_MARKER: &str = "Fatal:";
|
||||
|
||||
const GETH_STDOUT_LOG_FILE_NAME: &str = "node_stdout.log";
|
||||
const GETH_STDERR_LOG_FILE_NAME: &str = "node_stderr.log";
|
||||
|
||||
/// Create the node directory and call `geth init` to configure the genesis.
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn init(&mut self, genesis: String) -> anyhow::Result<&mut Self> {
|
||||
create_dir_all(&self.base_directory)?;
|
||||
create_dir_all(&self.logs_directory)?;
|
||||
|
||||
let genesis_path = self.base_directory.join(Self::GENESIS_JSON_FILE);
|
||||
File::create(&genesis_path)?.write_all(genesis.as_bytes())?;
|
||||
|
||||
let mut child = Command::new(&self.geth)
|
||||
.arg("init")
|
||||
.arg("--datadir")
|
||||
.arg(&self.data_directory)
|
||||
.arg(genesis_path)
|
||||
.stderr(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.spawn()?;
|
||||
|
||||
let mut stderr = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.expect("should be piped")
|
||||
.read_to_string(&mut stderr)?;
|
||||
|
||||
if !child.wait()?.success() {
|
||||
anyhow::bail!("failed to initialize geth node #{:?}: {stderr}", &self.id);
|
||||
}
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Spawn the go-ethereum node child process.
|
||||
///
|
||||
/// [Instance::init] must be called prior.
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn spawn_process(&mut self) -> anyhow::Result<&mut Self> {
|
||||
// This is the `OpenOptions` that we wish to use for all of the log files that we will be
|
||||
// opening in this method. We need to construct it in this way to:
|
||||
// 1. Be consistent
|
||||
// 2. Less verbose and more dry
|
||||
// 3. Because the builder pattern uses mutable references so we need to get around that.
|
||||
let open_options = {
|
||||
let mut options = OpenOptions::new();
|
||||
options.create(true).truncate(true).write(true);
|
||||
options
|
||||
};
|
||||
|
||||
let stdout_logs_file = open_options
|
||||
.clone()
|
||||
.open(self.geth_stdout_log_file_path())?;
|
||||
let stderr_logs_file = open_options.open(self.geth_stderr_log_file_path())?;
|
||||
self.handle = Command::new(&self.geth)
|
||||
.arg("--dev")
|
||||
.arg("--datadir")
|
||||
.arg(&self.data_directory)
|
||||
.arg("--ipcpath")
|
||||
.arg(&self.connection_string)
|
||||
.arg("--networkid")
|
||||
.arg(self.network_id.to_string())
|
||||
.arg("--nodiscover")
|
||||
.arg("--maxpeers")
|
||||
.arg("0")
|
||||
.stderr(stderr_logs_file.try_clone()?)
|
||||
.stdout(stdout_logs_file.try_clone()?)
|
||||
.spawn()?
|
||||
.into();
|
||||
|
||||
if let Err(error) = self.wait_ready() {
|
||||
tracing::error!(?error, "Failed to start geth, shutting down gracefully");
|
||||
self.shutdown()?;
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
self.logs_file_to_flush
|
||||
.extend([stderr_logs_file, stdout_logs_file]);
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Wait for the g-ethereum node child process getting ready.
|
||||
///
|
||||
/// [Instance::spawn_process] must be called priorly.
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn wait_ready(&mut self) -> anyhow::Result<&mut Self> {
|
||||
let start_time = Instant::now();
|
||||
|
||||
let logs_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(false)
|
||||
.append(false)
|
||||
.truncate(false)
|
||||
.open(self.geth_stderr_log_file_path())?;
|
||||
|
||||
let maximum_wait_time = Duration::from_millis(self.start_timeout);
|
||||
let mut stderr = BufReader::new(logs_file).lines();
|
||||
loop {
|
||||
if let Some(Ok(line)) = stderr.next() {
|
||||
if line.contains(Self::ERROR_MARKER) {
|
||||
anyhow::bail!("Failed to start geth {line}");
|
||||
}
|
||||
if line.contains(Self::READY_MARKER) {
|
||||
return Ok(self);
|
||||
}
|
||||
}
|
||||
if Instant::now().duration_since(start_time) > maximum_wait_time {
|
||||
anyhow::bail!("Timeout in starting geth");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id), level = Level::TRACE)]
|
||||
fn geth_stdout_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory.join(Self::GETH_STDOUT_LOG_FILE_NAME)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id), level = Level::TRACE)]
|
||||
fn geth_stderr_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory.join(Self::GETH_STDERR_LOG_FILE_NAME)
|
||||
}
|
||||
}
|
||||
|
||||
impl EthereumNode for Instance {
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn execute_transaction(
|
||||
&self,
|
||||
transaction: TransactionRequest,
|
||||
) -> anyhow::Result<alloy::rpc::types::TransactionReceipt> {
|
||||
let connection_string = self.connection_string();
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
execute_transaction(Box::pin(async move {
|
||||
let outer_span = tracing::debug_span!("Submitting transaction", ?transaction,);
|
||||
let _outer_guard = outer_span.enter();
|
||||
|
||||
let provider = ProviderBuilder::new()
|
||||
.wallet(wallet)
|
||||
.connect(&connection_string)
|
||||
.await?;
|
||||
|
||||
let pending_transaction = provider.send_transaction(transaction).await?;
|
||||
let transaction_hash = pending_transaction.tx_hash();
|
||||
|
||||
let span = tracing::info_span!("Awaiting transaction receipt", ?transaction_hash);
|
||||
let _guard = span.enter();
|
||||
|
||||
// The following is a fix for the "transaction indexing is in progress" error that we
|
||||
// used to get. You can find more information on this in the following GH issue in geth
|
||||
// https://github.com/ethereum/go-ethereum/issues/28877. To summarize what's going on,
|
||||
// before we can get the receipt of the transaction it needs to have been indexed by the
|
||||
// node's indexer. Just because the transaction has been confirmed it doesn't mean that
|
||||
// it has been indexed. When we call alloy's `get_receipt` it checks if the transaction
|
||||
// was confirmed. If it has been, then it will call `eth_getTransactionReceipt` method
|
||||
// which _might_ return the above error if the tx has not yet been indexed yet. So, we
|
||||
// need to implement a retry mechanism for the receipt to keep retrying to get it until
|
||||
// it eventually works, but we only do that if the error we get back is the "transaction
|
||||
// indexing is in progress" error or if the receipt is None.
|
||||
//
|
||||
// At the moment we do not allow for the 60 seconds to be modified and we take it as
|
||||
// being an implementation detail that's invisible to anything outside of this module.
|
||||
//
|
||||
// We allow a total of 60 retries for getting the receipt with one second between each
|
||||
// retry and the next which means that we allow for a total of 60 seconds of waiting
|
||||
// before we consider that we're unable to get the transaction receipt.
|
||||
let mut retries = 0;
|
||||
loop {
|
||||
match provider.get_transaction_receipt(*transaction_hash).await {
|
||||
Ok(Some(receipt)) => {
|
||||
tracing::info!("Obtained the transaction receipt");
|
||||
break Ok(receipt);
|
||||
}
|
||||
Ok(None) => {
|
||||
if retries == 60 {
|
||||
tracing::error!(
|
||||
"Polled for transaction receipt for 60 seconds but failed to get it"
|
||||
);
|
||||
break Err(anyhow::anyhow!("Failed to get the transaction receipt"));
|
||||
} else {
|
||||
tracing::trace!(
|
||||
retries,
|
||||
"Sleeping for 1 second and trying to get the receipt again"
|
||||
);
|
||||
retries += 1;
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let error_string = error.to_string();
|
||||
if error_string.contains("transaction indexing is in progress") {
|
||||
if retries == 60 {
|
||||
tracing::error!(
|
||||
"Polled for transaction receipt for 60 seconds but failed to get it"
|
||||
);
|
||||
break Err(error.into());
|
||||
} else {
|
||||
tracing::trace!(
|
||||
retries,
|
||||
"Sleeping for 1 second and trying to get the receipt again"
|
||||
);
|
||||
retries += 1;
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
break Err(error.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn trace_transaction(
|
||||
&self,
|
||||
transaction: TransactionReceipt,
|
||||
) -> anyhow::Result<alloy::rpc::types::trace::geth::GethTrace> {
|
||||
let connection_string = self.connection_string();
|
||||
let trace_options = GethDebugTracingOptions::prestate_tracer(PreStateConfig {
|
||||
diff_mode: Some(true),
|
||||
disable_code: None,
|
||||
disable_storage: None,
|
||||
});
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
trace_transaction(Box::pin(async move {
|
||||
Ok(ProviderBuilder::new()
|
||||
.wallet(wallet)
|
||||
.connect(&connection_string)
|
||||
.await?
|
||||
.debug_trace_transaction(transaction.transaction_hash, trace_options)
|
||||
.await?)
|
||||
}))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn state_diff(
|
||||
&self,
|
||||
transaction: alloy::rpc::types::TransactionReceipt,
|
||||
) -> anyhow::Result<DiffMode> {
|
||||
match self
|
||||
.trace_transaction(transaction)?
|
||||
.try_into_pre_state_frame()?
|
||||
{
|
||||
PreStateFrame::Diff(diff) => Ok(diff),
|
||||
_ => anyhow::bail!("expected a diff mode trace"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn fetch_add_nonce(&self, address: Address) -> anyhow::Result<u64> {
|
||||
let connection_string = self.connection_string.clone();
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
let onchain_nonce = fetch_onchain_nonce(connection_string, wallet, address)?;
|
||||
|
||||
let mut nonces = self.nonces.lock().unwrap();
|
||||
let current = nonces.entry(address).or_insert(onchain_nonce);
|
||||
let value = *current;
|
||||
*current += 1;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for Instance {
|
||||
fn new(config: &Arguments) -> Self {
|
||||
let geth_directory = config.directory().join(Self::BASE_DIRECTORY);
|
||||
let id = NODE_COUNT.fetch_add(1, Ordering::SeqCst);
|
||||
let base_directory = geth_directory.join(id.to_string());
|
||||
|
||||
Self {
|
||||
connection_string: base_directory.join(Self::IPC_FILE).display().to_string(),
|
||||
data_directory: base_directory.join(Self::DATA_DIRECTORY),
|
||||
logs_directory: base_directory.join(Self::LOGS_DIRECTORY),
|
||||
base_directory,
|
||||
geth: config.geth.clone(),
|
||||
id,
|
||||
handle: None,
|
||||
network_id: config.network_id,
|
||||
start_timeout: config.geth_start_timeout,
|
||||
wallet: config.wallet(),
|
||||
nonces: Mutex::new(HashMap::new()),
|
||||
// We know that we only need to be storing 2 files so we can specify that when creating
|
||||
// the vector. It's the stdout and stderr of the geth node.
|
||||
logs_file_to_flush: Vec::with_capacity(2),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn connection_string(&self) -> String {
|
||||
self.connection_string.clone()
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn shutdown(&mut self) -> anyhow::Result<()> {
|
||||
// Terminate the processes in a graceful manner to allow for the output to be flushed.
|
||||
if let Some(mut child) = self.handle.take() {
|
||||
child
|
||||
.kill()
|
||||
.map_err(|error| anyhow::anyhow!("Failed to kill the geth process: {error:?}"))?;
|
||||
}
|
||||
|
||||
// Flushing the files that we're using for keeping the logs before shutdown.
|
||||
for file in self.logs_file_to_flush.iter_mut() {
|
||||
file.flush()?
|
||||
}
|
||||
|
||||
// Remove the node's database so that subsequent runs do not run on the same database. We
|
||||
// ignore the error just in case the directory didn't exist in the first place and therefore
|
||||
// there's nothing to be deleted.
|
||||
let _ = remove_dir_all(self.base_directory.join(Self::DATA_DIRECTORY));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn spawn(&mut self, genesis: String) -> anyhow::Result<()> {
|
||||
self.init(genesis)?.spawn_process()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn version(&self) -> anyhow::Result<String> {
|
||||
let output = Command::new(&self.geth)
|
||||
.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?
|
||||
.wait_with_output()?
|
||||
.stdout;
|
||||
Ok(String::from_utf8_lossy(&output).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Instance {
|
||||
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
|
||||
fn drop(&mut self) {
|
||||
self.shutdown().expect("Failed to shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use revive_dt_config::Arguments;
|
||||
use temp_dir::TempDir;
|
||||
|
||||
use crate::{GENESIS_JSON, Node};
|
||||
|
||||
use super::Instance;
|
||||
|
||||
fn test_config() -> (Arguments, TempDir) {
|
||||
let mut config = Arguments::default();
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
config.working_directory = temp_dir.path().to_path_buf().into();
|
||||
|
||||
(config, temp_dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_works() {
|
||||
Instance::new(&test_config().0)
|
||||
.init(GENESIS_JSON.to_string())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_works() {
|
||||
Instance::new(&test_config().0)
|
||||
.spawn(GENESIS_JSON.to_string())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_works() {
|
||||
let version = Instance::new(&test_config().0).version().unwrap();
|
||||
assert!(
|
||||
version.starts_with("geth version"),
|
||||
"expected version string, got: '{version}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions, create_dir_all, remove_dir_all},
|
||||
io::{BufRead, Write},
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Command, Stdio},
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicU32, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use alloy::{
|
||||
hex,
|
||||
network::EthereumWallet,
|
||||
primitives::Address,
|
||||
providers::{Provider, ProviderBuilder, ext::DebugApi},
|
||||
rpc::types::{
|
||||
TransactionReceipt,
|
||||
trace::geth::{DiffMode, GethDebugTracingOptions, PreStateConfig, PreStateFrame},
|
||||
},
|
||||
};
|
||||
use serde_json::{Value as JsonValue, json};
|
||||
use sp_core::crypto::Ss58Codec;
|
||||
use sp_runtime::AccountId32;
|
||||
use tracing::Level;
|
||||
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_dt_node_interaction::{
|
||||
EthereumNode, nonce::fetch_onchain_nonce, trace::trace_transaction,
|
||||
transaction::execute_transaction,
|
||||
};
|
||||
|
||||
use crate::Node;
|
||||
|
||||
static NODE_COUNT: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct KitchensinkNode {
|
||||
id: u32,
|
||||
substrate_binary: PathBuf,
|
||||
eth_proxy_binary: PathBuf,
|
||||
rpc_url: String,
|
||||
wallet: EthereumWallet,
|
||||
base_directory: PathBuf,
|
||||
logs_directory: PathBuf,
|
||||
process_substrate: Option<Child>,
|
||||
process_proxy: Option<Child>,
|
||||
nonces: Mutex<HashMap<Address, u64>>,
|
||||
/// This vector stores [`File`] objects that we use for logging which we want to flush when the
|
||||
/// node object is dropped. We do not store them in a structured fashion at the moment (in
|
||||
/// separate fields) as the logic that we need to apply to them is all the same regardless of
|
||||
/// what it belongs to, we just want to flush them on [`Drop`] of the node.
|
||||
logs_file_to_flush: Vec<File>,
|
||||
}
|
||||
|
||||
impl KitchensinkNode {
|
||||
const BASE_DIRECTORY: &str = "kitchensink";
|
||||
const LOGS_DIRECTORY: &str = "logs";
|
||||
const DATA_DIRECTORY: &str = "chains";
|
||||
|
||||
const SUBSTRATE_READY_MARKER: &str = "Running JSON-RPC server";
|
||||
const ETH_PROXY_READY_MARKER: &str = "Running JSON-RPC server";
|
||||
const CHAIN_SPEC_JSON_FILE: &str = "template_chainspec.json";
|
||||
const BASE_SUBSTRATE_RPC_PORT: u16 = 9944;
|
||||
const BASE_PROXY_RPC_PORT: u16 = 8545;
|
||||
|
||||
const SUBSTRATE_LOG_ENV: &str = "error,evm=debug,sc_rpc_server=info,runtime::revive=debug";
|
||||
const PROXY_LOG_ENV: &str = "info,eth-rpc=debug";
|
||||
|
||||
const KITCHENSINK_STDOUT_LOG_FILE_NAME: &str = "node_stdout.log";
|
||||
const KITCHENSINK_STDERR_LOG_FILE_NAME: &str = "node_stderr.log";
|
||||
|
||||
const PROXY_STDOUT_LOG_FILE_NAME: &str = "proxy_stdout.log";
|
||||
const PROXY_STDERR_LOG_FILE_NAME: &str = "proxy_stderr.log";
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn init(&mut self, genesis: &str) -> anyhow::Result<&mut Self> {
|
||||
create_dir_all(&self.base_directory)?;
|
||||
create_dir_all(&self.logs_directory)?;
|
||||
|
||||
let template_chainspec_path = self.base_directory.join(Self::CHAIN_SPEC_JSON_FILE);
|
||||
|
||||
// Note: we do not pipe the logs of this process to a separate file since this is just a
|
||||
// once-off export of the default chain spec and not part of the long-running node process.
|
||||
let output = Command::new(&self.substrate_binary)
|
||||
.arg("export-chain-spec")
|
||||
.arg("--chain")
|
||||
.arg("dev")
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"substrate-node export-chain-spec failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
let content = String::from_utf8(output.stdout)?;
|
||||
let mut chainspec_json: JsonValue = serde_json::from_str(&content)?;
|
||||
|
||||
let existing_chainspec_balances =
|
||||
chainspec_json["genesis"]["runtimeGenesis"]["patch"]["balances"]["balances"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut merged_balances: Vec<(String, u128)> = existing_chainspec_balances
|
||||
.into_iter()
|
||||
.filter_map(|val| {
|
||||
if let Some(arr) = val.as_array() {
|
||||
if arr.len() == 2 {
|
||||
let account = arr[0].as_str()?.to_string();
|
||||
let balance = arr[1].as_f64()? as u128;
|
||||
return Some((account, balance));
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect();
|
||||
let mut eth_balances = self.extract_balance_from_genesis_file(genesis)?;
|
||||
merged_balances.append(&mut eth_balances);
|
||||
|
||||
chainspec_json["genesis"]["runtimeGenesis"]["patch"]["balances"]["balances"] =
|
||||
json!(merged_balances);
|
||||
|
||||
serde_json::to_writer_pretty(
|
||||
std::fs::File::create(&template_chainspec_path)?,
|
||||
&chainspec_json,
|
||||
)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn spawn_process(&mut self) -> anyhow::Result<()> {
|
||||
let substrate_rpc_port = Self::BASE_SUBSTRATE_RPC_PORT + self.id as u16;
|
||||
let proxy_rpc_port = Self::BASE_PROXY_RPC_PORT + self.id as u16;
|
||||
|
||||
self.rpc_url = format!("http://127.0.0.1:{proxy_rpc_port}");
|
||||
|
||||
let chainspec_path = self.base_directory.join(Self::CHAIN_SPEC_JSON_FILE);
|
||||
|
||||
// This is the `OpenOptions` that we wish to use for all of the log files that we will be
|
||||
// opening in this method. We need to construct it in this way to:
|
||||
// 1. Be consistent
|
||||
// 2. Less verbose and more dry
|
||||
// 3. Because the builder pattern uses mutable references so we need to get around that.
|
||||
let open_options = {
|
||||
let mut options = OpenOptions::new();
|
||||
options.create(true).truncate(true).write(true);
|
||||
options
|
||||
};
|
||||
|
||||
// Start Substrate node
|
||||
let kitchensink_stdout_logs_file = open_options
|
||||
.clone()
|
||||
.open(self.kitchensink_stdout_log_file_path())?;
|
||||
let kitchensink_stderr_logs_file = open_options
|
||||
.clone()
|
||||
.open(self.kitchensink_stderr_log_file_path())?;
|
||||
self.process_substrate = Command::new(&self.substrate_binary)
|
||||
.arg("--chain")
|
||||
.arg(chainspec_path)
|
||||
.arg("--base-path")
|
||||
.arg(&self.base_directory)
|
||||
.arg("--rpc-port")
|
||||
.arg(substrate_rpc_port.to_string())
|
||||
.arg("--name")
|
||||
.arg(format!("revive-kitchensink-{}", self.id))
|
||||
.arg("--force-authoring")
|
||||
.arg("--rpc-methods")
|
||||
.arg("Unsafe")
|
||||
.arg("--rpc-cors")
|
||||
.arg("all")
|
||||
.env("RUST_LOG", Self::SUBSTRATE_LOG_ENV)
|
||||
.stdout(kitchensink_stdout_logs_file.try_clone()?)
|
||||
.stderr(kitchensink_stderr_logs_file.try_clone()?)
|
||||
.spawn()?
|
||||
.into();
|
||||
|
||||
// Give the node a moment to boot
|
||||
if let Err(error) = Self::wait_ready(
|
||||
self.kitchensink_stderr_log_file_path().as_path(),
|
||||
Self::SUBSTRATE_READY_MARKER,
|
||||
Duration::from_secs(30),
|
||||
) {
|
||||
tracing::error!(
|
||||
?error,
|
||||
"Failed to start substrate, shutting down gracefully"
|
||||
);
|
||||
self.shutdown()?;
|
||||
return Err(error);
|
||||
};
|
||||
|
||||
let eth_proxy_stdout_logs_file = open_options
|
||||
.clone()
|
||||
.open(self.proxy_stdout_log_file_path())?;
|
||||
let eth_proxy_stderr_logs_file = open_options.open(self.proxy_stderr_log_file_path())?;
|
||||
self.process_proxy = Command::new(&self.eth_proxy_binary)
|
||||
.arg("--dev")
|
||||
.arg("--rpc-port")
|
||||
.arg(proxy_rpc_port.to_string())
|
||||
.arg("--node-rpc-url")
|
||||
.arg(format!("ws://127.0.0.1:{substrate_rpc_port}"))
|
||||
.env("RUST_LOG", Self::PROXY_LOG_ENV)
|
||||
.stdout(eth_proxy_stdout_logs_file.try_clone()?)
|
||||
.stderr(eth_proxy_stderr_logs_file.try_clone()?)
|
||||
.spawn()?
|
||||
.into();
|
||||
|
||||
if let Err(error) = Self::wait_ready(
|
||||
self.proxy_stderr_log_file_path().as_path(),
|
||||
Self::ETH_PROXY_READY_MARKER,
|
||||
Duration::from_secs(30),
|
||||
) {
|
||||
tracing::error!(?error, "Failed to start proxy, shutting down gracefully");
|
||||
self.shutdown()?;
|
||||
return Err(error);
|
||||
};
|
||||
|
||||
self.logs_file_to_flush.extend([
|
||||
kitchensink_stdout_logs_file,
|
||||
kitchensink_stderr_logs_file,
|
||||
eth_proxy_stdout_logs_file,
|
||||
eth_proxy_stderr_logs_file,
|
||||
]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn extract_balance_from_genesis_file(
|
||||
&self,
|
||||
genesis_str: &str,
|
||||
) -> anyhow::Result<Vec<(String, u128)>> {
|
||||
let genesis_json: JsonValue = serde_json::from_str(genesis_str)?;
|
||||
let alloc = genesis_json
|
||||
.get("alloc")
|
||||
.and_then(|a| a.as_object())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'alloc' in genesis"))?;
|
||||
|
||||
let mut balances = Vec::new();
|
||||
for (eth_addr, obj) in alloc.iter() {
|
||||
let balance_str = obj.get("balance").and_then(|b| b.as_str()).unwrap_or("0");
|
||||
let balance = if balance_str.starts_with("0x") {
|
||||
u128::from_str_radix(balance_str.trim_start_matches("0x"), 16)?
|
||||
} else {
|
||||
balance_str.parse::<u128>()?
|
||||
};
|
||||
let substrate_addr = Self::eth_to_substrate_address(eth_addr)?;
|
||||
balances.push((substrate_addr.clone(), balance));
|
||||
}
|
||||
Ok(balances)
|
||||
}
|
||||
|
||||
fn eth_to_substrate_address(eth_addr: &str) -> anyhow::Result<String> {
|
||||
let eth_bytes = hex::decode(eth_addr.trim_start_matches("0x"))?;
|
||||
if eth_bytes.len() != 20 {
|
||||
anyhow::bail!(
|
||||
"Invalid Ethereum address length: expected 20 bytes, got {}",
|
||||
eth_bytes.len()
|
||||
);
|
||||
}
|
||||
|
||||
let mut padded = [0xEEu8; 32];
|
||||
padded[..20].copy_from_slice(ð_bytes);
|
||||
|
||||
let account_id = AccountId32::from(padded);
|
||||
Ok(account_id.to_ss58check())
|
||||
}
|
||||
|
||||
fn wait_ready(logs_file_path: &Path, marker: &str, timeout: Duration) -> anyhow::Result<()> {
|
||||
let start_time = std::time::Instant::now();
|
||||
let logs_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(false)
|
||||
.append(false)
|
||||
.truncate(false)
|
||||
.open(logs_file_path)?;
|
||||
|
||||
let mut lines = std::io::BufReader::new(logs_file).lines();
|
||||
loop {
|
||||
if let Some(Ok(line)) = lines.next() {
|
||||
if line.contains(marker) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if start_time.elapsed() > timeout {
|
||||
anyhow::bail!("Timeout waiting for process readiness: {marker}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
pub fn eth_rpc_version(&self) -> anyhow::Result<String> {
|
||||
let output = Command::new(&self.eth_proxy_binary)
|
||||
.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?
|
||||
.wait_with_output()?
|
||||
.stdout;
|
||||
Ok(String::from_utf8_lossy(&output).trim().to_string())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), level = Level::TRACE)]
|
||||
fn kitchensink_stdout_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory
|
||||
.join(Self::KITCHENSINK_STDOUT_LOG_FILE_NAME)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), level = Level::TRACE)]
|
||||
fn kitchensink_stderr_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory
|
||||
.join(Self::KITCHENSINK_STDERR_LOG_FILE_NAME)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), level = Level::TRACE)]
|
||||
fn proxy_stdout_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory.join(Self::PROXY_STDOUT_LOG_FILE_NAME)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), level = Level::TRACE)]
|
||||
fn proxy_stderr_log_file_path(&self) -> PathBuf {
|
||||
self.logs_directory.join(Self::PROXY_STDERR_LOG_FILE_NAME)
|
||||
}
|
||||
}
|
||||
|
||||
impl EthereumNode for KitchensinkNode {
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn execute_transaction(
|
||||
&self,
|
||||
transaction: alloy::rpc::types::TransactionRequest,
|
||||
) -> anyhow::Result<TransactionReceipt> {
|
||||
let url = self.rpc_url.clone();
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
tracing::debug!("Submitting transaction: {transaction:#?}");
|
||||
|
||||
tracing::info!("Submitting tx to kitchensink");
|
||||
let receipt = execute_transaction(Box::pin(async move {
|
||||
Ok(ProviderBuilder::new()
|
||||
.wallet(wallet)
|
||||
.connect(&url)
|
||||
.await?
|
||||
.send_transaction(transaction)
|
||||
.await?
|
||||
.get_receipt()
|
||||
.await?)
|
||||
}));
|
||||
tracing::info!(?receipt, "Submitted tx to kitchensink");
|
||||
receipt
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn trace_transaction(
|
||||
&self,
|
||||
transaction: TransactionReceipt,
|
||||
) -> anyhow::Result<alloy::rpc::types::trace::geth::GethTrace> {
|
||||
let url = self.rpc_url.clone();
|
||||
let trace_options = GethDebugTracingOptions::prestate_tracer(PreStateConfig {
|
||||
diff_mode: Some(true),
|
||||
disable_code: None,
|
||||
disable_storage: None,
|
||||
});
|
||||
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
trace_transaction(Box::pin(async move {
|
||||
Ok(ProviderBuilder::new()
|
||||
.wallet(wallet)
|
||||
.connect(&url)
|
||||
.await?
|
||||
.debug_trace_transaction(transaction.transaction_hash, trace_options)
|
||||
.await?)
|
||||
}))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn state_diff(&self, transaction: TransactionReceipt) -> anyhow::Result<DiffMode> {
|
||||
match self
|
||||
.trace_transaction(transaction)?
|
||||
.try_into_pre_state_frame()?
|
||||
{
|
||||
PreStateFrame::Diff(diff) => Ok(diff),
|
||||
_ => anyhow::bail!("expected a diff mode trace"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn fetch_add_nonce(&self, address: Address) -> anyhow::Result<u64> {
|
||||
let url = self.rpc_url.clone();
|
||||
let wallet = self.wallet.clone();
|
||||
|
||||
let onchain_nonce = fetch_onchain_nonce(url, wallet, address)?;
|
||||
|
||||
let mut nonces = self.nonces.lock().unwrap();
|
||||
let current = nonces.entry(address).or_insert(onchain_nonce);
|
||||
let value = *current;
|
||||
*current += 1;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for KitchensinkNode {
|
||||
fn new(config: &Arguments) -> Self {
|
||||
let kitchensink_directory = config.directory().join(Self::BASE_DIRECTORY);
|
||||
let id = NODE_COUNT.fetch_add(1, Ordering::SeqCst);
|
||||
let base_directory = kitchensink_directory.join(id.to_string());
|
||||
let logs_directory = base_directory.join(Self::LOGS_DIRECTORY);
|
||||
|
||||
Self {
|
||||
id,
|
||||
substrate_binary: config.kitchensink.clone(),
|
||||
eth_proxy_binary: config.eth_proxy.clone(),
|
||||
rpc_url: String::new(),
|
||||
wallet: config.wallet(),
|
||||
base_directory,
|
||||
logs_directory,
|
||||
process_substrate: None,
|
||||
process_proxy: None,
|
||||
nonces: Mutex::new(HashMap::new()),
|
||||
// We know that we only need to be storing 4 files so we can specify that when creating
|
||||
// the vector. It's the stdout and stderr of the substrate-node and the eth-rpc.
|
||||
logs_file_to_flush: Vec::with_capacity(4),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn connection_string(&self) -> String {
|
||||
self.rpc_url.clone()
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn shutdown(&mut self) -> anyhow::Result<()> {
|
||||
// Terminate the processes in a graceful manner to allow for the output to be flushed.
|
||||
if let Some(mut child) = self.process_proxy.take() {
|
||||
child
|
||||
.kill()
|
||||
.map_err(|error| anyhow::anyhow!("Failed to kill the proxy process: {error:?}"))?;
|
||||
}
|
||||
if let Some(mut child) = self.process_substrate.take() {
|
||||
child.kill().map_err(|error| {
|
||||
anyhow::anyhow!("Failed to kill the substrate process: {error:?}")
|
||||
})?;
|
||||
}
|
||||
|
||||
// Flushing the files that we're using for keeping the logs before shutdown.
|
||||
for file in self.logs_file_to_flush.iter_mut() {
|
||||
file.flush()?
|
||||
}
|
||||
|
||||
// Remove the node's database so that subsequent runs do not run on the same database. We
|
||||
// ignore the error just in case the directory didn't exist in the first place and therefore
|
||||
// there's nothing to be deleted.
|
||||
let _ = remove_dir_all(self.base_directory.join(Self::DATA_DIRECTORY));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn spawn(&mut self, genesis: String) -> anyhow::Result<()> {
|
||||
self.init(&genesis)?.spawn_process()
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn version(&self) -> anyhow::Result<String> {
|
||||
let output = Command::new(&self.substrate_binary)
|
||||
.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?
|
||||
.wait_with_output()?
|
||||
.stdout;
|
||||
Ok(String::from_utf8_lossy(&output).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KitchensinkNode {
|
||||
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
|
||||
fn drop(&mut self) {
|
||||
self.shutdown().expect("Failed to shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use revive_dt_config::Arguments;
|
||||
use std::path::PathBuf;
|
||||
use temp_dir::TempDir;
|
||||
|
||||
use std::fs;
|
||||
|
||||
use super::KitchensinkNode;
|
||||
use crate::{GENESIS_JSON, Node};
|
||||
|
||||
fn test_config() -> (Arguments, TempDir) {
|
||||
let mut config = Arguments::default();
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
|
||||
config.working_directory = temp_dir.path().to_path_buf().into();
|
||||
|
||||
config.kitchensink = PathBuf::from("substrate-node");
|
||||
config.eth_proxy = PathBuf::from("eth-rpc");
|
||||
|
||||
(config, temp_dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_init_generates_chainspec_with_balances() {
|
||||
let genesis_content = r#"
|
||||
{
|
||||
"alloc": {
|
||||
"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1": {
|
||||
"balance": "1000000000000000000"
|
||||
},
|
||||
"Ab8483F64d9C6d1EcF9b849Ae677dD3315835cb2": {
|
||||
"balance": "2000000000000000000"
|
||||
}
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
let mut dummy_node = KitchensinkNode::new(&test_config().0);
|
||||
|
||||
// Call `init()`
|
||||
dummy_node.init(genesis_content).expect("init failed");
|
||||
|
||||
// Check that the patched chainspec file was generated
|
||||
let final_chainspec_path = dummy_node
|
||||
.base_directory
|
||||
.join(KitchensinkNode::CHAIN_SPEC_JSON_FILE);
|
||||
assert!(final_chainspec_path.exists(), "Chainspec file should exist");
|
||||
|
||||
let contents = fs::read_to_string(&final_chainspec_path).expect("Failed to read chainspec");
|
||||
|
||||
// Validate that the Substrate addresses derived from the Ethereum addresses are in the file
|
||||
let first_eth_addr =
|
||||
KitchensinkNode::eth_to_substrate_address("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")
|
||||
.unwrap();
|
||||
let second_eth_addr =
|
||||
KitchensinkNode::eth_to_substrate_address("Ab8483F64d9C6d1EcF9b849Ae677dD3315835cb2")
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
contents.contains(&first_eth_addr),
|
||||
"Chainspec should contain Substrate address for first Ethereum account"
|
||||
);
|
||||
assert!(
|
||||
contents.contains(&second_eth_addr),
|
||||
"Chainspec should contain Substrate address for second Ethereum account"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_genesis_alloc() {
|
||||
// Create test genesis file
|
||||
let genesis_json = r#"
|
||||
{
|
||||
"alloc": {
|
||||
"0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1": { "balance": "1000000000000000000" },
|
||||
"0x0000000000000000000000000000000000000000": { "balance": "0xDE0B6B3A7640000" },
|
||||
"0xffffffffffffffffffffffffffffffffffffffff": { "balance": "123456789" }
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
let node = KitchensinkNode::new(&test_config().0);
|
||||
|
||||
let result = node
|
||||
.extract_balance_from_genesis_file(genesis_json)
|
||||
.unwrap();
|
||||
|
||||
let result_map: std::collections::HashMap<_, _> = result.into_iter().collect();
|
||||
|
||||
assert_eq!(
|
||||
result_map.get("5FLneRcWAfk3X3tg6PuGyLNGAquPAZez5gpqvyuf3yUK8VaV"),
|
||||
Some(&1_000_000_000_000_000_000u128)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result_map.get("5C4hrfjw9DjXZTzV3MwzrrAr9P1MLDHajjSidz9bR544LEq1"),
|
||||
Some(&1_000_000_000_000_000_000u128)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result_map.get("5HrN7fHLXWcFiXPwwtq2EkSGns9eMmoUQnbVKweNz3VVr6N4"),
|
||||
Some(&123_456_789u128)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_eth_to_substrate_mappings() {
|
||||
let eth_addresses = vec![
|
||||
"0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1",
|
||||
"0xffffffffffffffffffffffffffffffffffffffff",
|
||||
"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1",
|
||||
];
|
||||
|
||||
for eth_addr in eth_addresses {
|
||||
let ss58 = KitchensinkNode::eth_to_substrate_address(eth_addr).unwrap();
|
||||
|
||||
println!("Ethereum: {eth_addr} -> Substrate SS58: {ss58}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_eth_to_substrate_address() {
|
||||
let cases = vec![
|
||||
(
|
||||
"0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1",
|
||||
"5FLneRcWAfk3X3tg6PuGyLNGAquPAZez5gpqvyuf3yUK8VaV",
|
||||
),
|
||||
(
|
||||
"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1",
|
||||
"5FLneRcWAfk3X3tg6PuGyLNGAquPAZez5gpqvyuf3yUK8VaV",
|
||||
),
|
||||
(
|
||||
"0x0000000000000000000000000000000000000000",
|
||||
"5C4hrfjw9DjXZTzV3MwzrrAr9P1MLDHajjSidz9bR544LEq1",
|
||||
),
|
||||
(
|
||||
"0xffffffffffffffffffffffffffffffffffffffff",
|
||||
"5HrN7fHLXWcFiXPwwtq2EkSGns9eMmoUQnbVKweNz3VVr6N4",
|
||||
),
|
||||
];
|
||||
|
||||
for (eth_addr, expected_ss58) in cases {
|
||||
let result = KitchensinkNode::eth_to_substrate_address(eth_addr).unwrap();
|
||||
assert_eq!(
|
||||
result, expected_ss58,
|
||||
"Mismatch for Ethereum address {eth_addr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_works() {
|
||||
let (config, _temp_dir) = test_config();
|
||||
|
||||
let mut node = KitchensinkNode::new(&config);
|
||||
node.spawn(GENESIS_JSON.to_string()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_works() {
|
||||
let (config, _temp_dir) = test_config();
|
||||
|
||||
let node = KitchensinkNode::new(&config);
|
||||
let version = node.version().unwrap();
|
||||
|
||||
assert!(
|
||||
version.starts_with("substrate-node"),
|
||||
"Expected substrate-node version string, got: {version}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eth_rpc_version_works() {
|
||||
let (config, _temp_dir) = test_config();
|
||||
|
||||
let node = KitchensinkNode::new(&config);
|
||||
let version = node.eth_rpc_version().unwrap();
|
||||
|
||||
assert!(
|
||||
version.starts_with("pallet-revive-eth-rpc"),
|
||||
"Expected eth-rpc version string, got: {version}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! This crate implements the testing nodes.
|
||||
|
||||
use revive_dt_config::Arguments;
|
||||
use revive_dt_node_interaction::EthereumNode;
|
||||
|
||||
pub mod geth;
|
||||
pub mod kitchensink;
|
||||
pub mod pool;
|
||||
|
||||
/// The default genesis configuration.
|
||||
pub const GENESIS_JSON: &str = include_str!("../../../genesis.json");
|
||||
|
||||
/// An abstract interface for testing nodes.
|
||||
pub trait Node: EthereumNode {
|
||||
/// Create a new uninitialized instance.
|
||||
fn new(config: &Arguments) -> Self;
|
||||
|
||||
/// Spawns a node configured according to the genesis json.
|
||||
///
|
||||
/// Blocking until it's ready to accept transactions.
|
||||
fn spawn(&mut self, genesis: String) -> anyhow::Result<()>;
|
||||
|
||||
/// Prune the node instance and related data.
|
||||
///
|
||||
/// Blocking until it's completely stopped.
|
||||
fn shutdown(&mut self) -> anyhow::Result<()>;
|
||||
|
||||
/// Returns the nodes connection string.
|
||||
fn connection_string(&self) -> String;
|
||||
|
||||
/// Returns the node version.
|
||||
fn version(&self) -> anyhow::Result<String>;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! This crate implements concurrent handling of testing node.
|
||||
|
||||
use std::{
|
||||
fs::read_to_string,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
thread,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use revive_dt_config::Arguments;
|
||||
|
||||
use crate::Node;
|
||||
|
||||
/// The node pool starts one or more [Node] which then can be accessed
|
||||
/// in a round robbin fasion.
|
||||
pub struct NodePool<T> {
|
||||
next: AtomicUsize,
|
||||
nodes: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> NodePool<T>
|
||||
where
|
||||
T: Node + Send + 'static,
|
||||
{
|
||||
/// Create a new Pool. This will start as many nodes as there are workers in `config`.
|
||||
pub fn new(config: &Arguments) -> anyhow::Result<Self> {
|
||||
let nodes = config.workers;
|
||||
let genesis = read_to_string(&config.genesis_file).context(format!(
|
||||
"can not read genesis file: {}",
|
||||
config.genesis_file.display()
|
||||
))?;
|
||||
|
||||
let mut handles = Vec::with_capacity(nodes);
|
||||
for _ in 0..nodes {
|
||||
let config = config.clone();
|
||||
let genesis = genesis.clone();
|
||||
handles.push(thread::spawn(move || spawn_node::<T>(&config, genesis)));
|
||||
}
|
||||
|
||||
let mut nodes = Vec::with_capacity(nodes);
|
||||
for handle in handles {
|
||||
nodes.push(
|
||||
handle
|
||||
.join()
|
||||
.map_err(|error| anyhow::anyhow!("failed to spawn node: {:?}", error))?
|
||||
.map_err(|error| anyhow::anyhow!("node failed to spawn: {error}"))?,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
nodes,
|
||||
next: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Get a handle to the next node.
|
||||
pub fn round_robbin(&self) -> &T {
|
||||
let current = self.next.fetch_add(1, Ordering::SeqCst) % self.nodes.len();
|
||||
self.nodes.get(current).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_node<T: Node + Send>(args: &Arguments, genesis: String) -> anyhow::Result<T> {
|
||||
let mut node = T::new(args);
|
||||
tracing::info!("starting node: {}", node.connection_string());
|
||||
node.spawn(genesis)?;
|
||||
Ok(node)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "revive-dt-report"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
revive-dt-config = { workspace = true }
|
||||
revive-dt-format = { workspace = true }
|
||||
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
revive-solc-json-interface = { workspace = true }
|
||||
@@ -0,0 +1,94 @@
|
||||
//! The report analyzer enriches the raw report data.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::reporter::CompilationTask;
|
||||
|
||||
/// Provides insights into how well the compilers perform.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, PartialOrd)]
|
||||
pub struct CompilerStatistics {
|
||||
/// The sum of contracts observed.
|
||||
pub n_contracts: usize,
|
||||
/// The mean size of compiled contracts.
|
||||
pub mean_code_size: usize,
|
||||
/// The mean size of the optimized YUL IR.
|
||||
pub mean_yul_size: usize,
|
||||
/// Is a proxy because the YUL also containes a lot of comments.
|
||||
pub yul_to_bytecode_size_ratio: f32,
|
||||
}
|
||||
|
||||
impl CompilerStatistics {
|
||||
/// Cumulatively update the statistics with the next compiler task.
|
||||
pub fn sample(&mut self, compilation_task: &CompilationTask) {
|
||||
let Some(output) = &compilation_task.json_output else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(contracts) = &output.contracts else {
|
||||
return;
|
||||
};
|
||||
|
||||
for (_solidity, contracts) in contracts.iter() {
|
||||
for (_name, contract) in contracts.iter() {
|
||||
let Some(evm) = &contract.evm else {
|
||||
continue;
|
||||
};
|
||||
let Some(deploy_code) = &evm.deployed_bytecode else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// The EVM bytecode can be unlinked and thus is not necessarily a decodable hex
|
||||
// string; for our statistics this is a good enough approximation.
|
||||
let bytecode_size = deploy_code.object.len() / 2;
|
||||
|
||||
let yul_size = contract
|
||||
.ir_optimized
|
||||
.as_ref()
|
||||
.expect("if the contract has a deploy code it should also have the opimized IR")
|
||||
.len();
|
||||
|
||||
self.update_sizes(bytecode_size, yul_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the size statistics cumulatively.
|
||||
fn update_sizes(&mut self, bytecode_size: usize, yul_size: usize) {
|
||||
let n_previous = self.n_contracts;
|
||||
let n_current = self.n_contracts + 1;
|
||||
|
||||
self.n_contracts = n_current;
|
||||
|
||||
self.mean_code_size = (n_previous * self.mean_code_size + bytecode_size) / n_current;
|
||||
self.mean_yul_size = (n_previous * self.mean_yul_size + yul_size) / n_current;
|
||||
|
||||
if self.mean_code_size > 0 {
|
||||
self.yul_to_bytecode_size_ratio =
|
||||
self.mean_yul_size as f32 / self.mean_code_size as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::CompilerStatistics;
|
||||
|
||||
#[test]
|
||||
fn compiler_statistics() {
|
||||
let mut received = CompilerStatistics::default();
|
||||
received.update_sizes(0, 0);
|
||||
received.update_sizes(3, 37);
|
||||
received.update_sizes(123, 456);
|
||||
|
||||
let mean_code_size = 41; // rounding error from integer truncation
|
||||
let mean_yul_size = 164;
|
||||
let expected = CompilerStatistics {
|
||||
n_contracts: 3,
|
||||
mean_code_size,
|
||||
mean_yul_size,
|
||||
yul_to_bytecode_size_ratio: mean_yul_size as f32 / mean_code_size as f32,
|
||||
};
|
||||
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! The revive differential tests reporting facility.
|
||||
|
||||
pub mod analyzer;
|
||||
pub mod reporter;
|
||||
@@ -0,0 +1,243 @@
|
||||
//! The reporter is the central place observing test execution by collecting data.
|
||||
//!
|
||||
//! The data collected gives useful insights into the outcome of the test run
|
||||
//! and helps identifying and reproducing failing cases.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File, create_dir_all},
|
||||
path::PathBuf,
|
||||
sync::{Mutex, OnceLock},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use revive_dt_config::{Arguments, TestingPlatform};
|
||||
use revive_dt_format::{corpus::Corpus, mode::SolcMode};
|
||||
use revive_solc_json_interface::{SolcStandardJsonInput, SolcStandardJsonOutput};
|
||||
|
||||
use crate::analyzer::CompilerStatistics;
|
||||
|
||||
pub(crate) static REPORTER: OnceLock<Mutex<Report>> = OnceLock::new();
|
||||
|
||||
/// The `Report` datastructure stores all relevant inforamtion required for generating reports.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Report {
|
||||
/// The configuration used during the test.
|
||||
pub config: Arguments,
|
||||
/// The observed test corpora.
|
||||
pub corpora: Vec<Corpus>,
|
||||
/// The observed test definitions.
|
||||
pub metadata_files: Vec<PathBuf>,
|
||||
/// The observed compilation results.
|
||||
pub compiler_results: HashMap<TestingPlatform, Vec<CompilationResult>>,
|
||||
/// The observed compilation statistics.
|
||||
pub compiler_statistics: HashMap<TestingPlatform, CompilerStatistics>,
|
||||
/// The file name this is serialized to.
|
||||
#[serde(skip)]
|
||||
directory: PathBuf,
|
||||
}
|
||||
|
||||
/// Contains a compiled contract.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CompilationTask {
|
||||
/// The observed compiler input.
|
||||
pub json_input: SolcStandardJsonInput,
|
||||
/// The observed compiler output.
|
||||
pub json_output: Option<SolcStandardJsonOutput>,
|
||||
/// The observed compiler mode.
|
||||
pub mode: SolcMode,
|
||||
/// The observed compiler version.
|
||||
pub compiler_version: String,
|
||||
/// The observed error, if any.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Represents a report about a compilation task.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CompilationResult {
|
||||
/// The observed compilation task.
|
||||
pub compilation_task: CompilationTask,
|
||||
/// The linked span.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// The [Span] struct indicates the context of what is being reported.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
pub struct Span {
|
||||
/// The corpus index this belongs to.
|
||||
corpus: usize,
|
||||
/// The metadata file this belongs to.
|
||||
metadata_file: usize,
|
||||
/// The index of the case definition this belongs to.
|
||||
case: usize,
|
||||
/// The index of the case input this belongs to.
|
||||
input: usize,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// The file name where this report will be written to.
|
||||
pub const FILE_NAME: &str = "report.json";
|
||||
|
||||
/// The [Span] is expected to initialize the reporter by providing the config.
|
||||
const INITIALIZED_VIA_SPAN: &str = "requires a Span which initializes the reporter";
|
||||
|
||||
/// Create a new [Report].
|
||||
fn new(config: Arguments) -> anyhow::Result<Self> {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
|
||||
let directory = config.directory().join("report").join(format!("{now}"));
|
||||
if !directory.exists() {
|
||||
create_dir_all(&directory)?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
directory,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Add a compilation task to the report.
|
||||
pub fn compilation(span: Span, platform: TestingPlatform, compilation_task: CompilationTask) {
|
||||
let mut report = REPORTER
|
||||
.get()
|
||||
.expect(Report::INITIALIZED_VIA_SPAN)
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
report
|
||||
.compiler_statistics
|
||||
.entry(platform)
|
||||
.or_default()
|
||||
.sample(&compilation_task);
|
||||
|
||||
report
|
||||
.compiler_results
|
||||
.entry(platform)
|
||||
.or_default()
|
||||
.push(CompilationResult {
|
||||
compilation_task,
|
||||
span,
|
||||
});
|
||||
}
|
||||
|
||||
/// Write the report to disk.
|
||||
pub fn save() -> anyhow::Result<()> {
|
||||
let Some(reporter) = REPORTER.get() else {
|
||||
return Ok(());
|
||||
};
|
||||
let report = reporter.lock().unwrap();
|
||||
|
||||
if let Err(error) = report.write_to_file() {
|
||||
anyhow::bail!("can not write report: {error}");
|
||||
}
|
||||
|
||||
if report.config.extract_problems {
|
||||
if let Err(error) = report.save_compiler_problems() {
|
||||
anyhow::bail!("can not write compiler problems: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write compiler problems to disk for later debugging.
|
||||
pub fn save_compiler_problems(&self) -> anyhow::Result<()> {
|
||||
for (platform, results) in self.compiler_results.iter() {
|
||||
for result in results {
|
||||
// ignore if there were no errors
|
||||
if result.compilation_task.error.is_none()
|
||||
&& result
|
||||
.compilation_task
|
||||
.json_output
|
||||
.as_ref()
|
||||
.and_then(|output| output.errors.as_ref())
|
||||
.map(|errors| errors.is_empty())
|
||||
.unwrap_or(true)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = &self.metadata_files[result.span.metadata_file]
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join(format!("{platform}_errors"));
|
||||
if !path.exists() {
|
||||
create_dir_all(path)?;
|
||||
}
|
||||
|
||||
if let Some(error) = result.compilation_task.error.as_ref() {
|
||||
fs::write(path.join("compiler_error.txt"), error)?;
|
||||
}
|
||||
|
||||
if let Some(errors) = result.compilation_task.json_output.as_ref() {
|
||||
let file = File::create(path.join("compiler_output.txt"))?;
|
||||
serde_json::to_writer_pretty(file, &errors)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_to_file(&self) -> anyhow::Result<()> {
|
||||
let path = self.directory.join(Self::FILE_NAME);
|
||||
|
||||
let file = File::create(&path).context(path.display().to_string())?;
|
||||
serde_json::to_writer_pretty(file, &self)?;
|
||||
|
||||
tracing::info!("report written to: {}", path.display());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Span {
|
||||
/// Create a new [Span] with case and input index at 0.
|
||||
///
|
||||
/// Initializes the reporting facility on the first call.
|
||||
pub fn new(corpus: Corpus, config: Arguments) -> anyhow::Result<Self> {
|
||||
let report = Mutex::new(Report::new(config)?);
|
||||
let mut reporter = REPORTER.get_or_init(|| report).lock().unwrap();
|
||||
reporter.corpora.push(corpus);
|
||||
|
||||
Ok(Self {
|
||||
corpus: reporter.corpora.len() - 1,
|
||||
metadata_file: 0,
|
||||
case: 0,
|
||||
input: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Advance to the next metadata file: Resets the case input index to 0.
|
||||
pub fn next_metadata(&mut self, metadata_file: PathBuf) {
|
||||
let mut reporter = REPORTER
|
||||
.get()
|
||||
.expect(Report::INITIALIZED_VIA_SPAN)
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
reporter.metadata_files.push(metadata_file);
|
||||
|
||||
self.metadata_file = reporter.metadata_files.len() - 1;
|
||||
self.case = 0;
|
||||
self.input = 0;
|
||||
}
|
||||
|
||||
/// Advance to the next case: Increas the case index by one and resets the input index to 0.
|
||||
pub fn next_case(&mut self) {
|
||||
self.case += 1;
|
||||
self.input = 0;
|
||||
}
|
||||
|
||||
/// Advance to the next input.
|
||||
pub fn next_input(&mut self) {
|
||||
self.input += 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "revive-dt-solc-binaries"
|
||||
description = "Download and cache solc binaries"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Helper for caching the solc binaries.
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::{File, create_dir_all},
|
||||
io::{BufWriter, Write},
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
sync::{LazyLock, Mutex},
|
||||
};
|
||||
|
||||
use crate::download::GHDownloader;
|
||||
|
||||
pub const SOLC_CACHE_DIRECTORY: &str = "solc";
|
||||
pub(crate) static SOLC_CACHER: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(Default::default);
|
||||
|
||||
pub(crate) fn get_or_download(
|
||||
working_directory: &Path,
|
||||
downloader: &GHDownloader,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let target_directory = working_directory
|
||||
.join(SOLC_CACHE_DIRECTORY)
|
||||
.join(downloader.version.to_string());
|
||||
let target_file = target_directory.join(downloader.target);
|
||||
|
||||
let mut cache = SOLC_CACHER.lock().unwrap();
|
||||
if cache.contains(&target_file) {
|
||||
tracing::debug!("using cached solc: {}", target_file.display());
|
||||
return Ok(target_file);
|
||||
}
|
||||
|
||||
create_dir_all(target_directory)?;
|
||||
download_to_file(&target_file, downloader)?;
|
||||
cache.insert(target_file.clone());
|
||||
|
||||
Ok(target_file)
|
||||
}
|
||||
|
||||
fn download_to_file(path: &Path, downloader: &GHDownloader) -> anyhow::Result<()> {
|
||||
tracing::info!("caching file: {}", path.display());
|
||||
|
||||
let Ok(file) = File::create_new(path) else {
|
||||
tracing::debug!("cache file already exists: {}", path.display());
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut permissions = file.metadata()?.permissions();
|
||||
permissions.set_mode(permissions.mode() | 0o111);
|
||||
file.set_permissions(permissions)?;
|
||||
}
|
||||
|
||||
let mut file = BufWriter::new(file);
|
||||
file.write_all(&downloader.download()?)?;
|
||||
file.flush()?;
|
||||
drop(file);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
std::process::Command::new("xattr")
|
||||
.arg("-d")
|
||||
.arg("com.apple.quarantine")
|
||||
.arg(path)
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()?
|
||||
.wait()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! This module downloads solc binaries.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{LazyLock, Mutex},
|
||||
};
|
||||
|
||||
use semver::Version;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::list::List;
|
||||
|
||||
pub static LIST_CACHE: LazyLock<Mutex<HashMap<&'static str, List>>> =
|
||||
LazyLock::new(Default::default);
|
||||
|
||||
impl List {
|
||||
pub const LINUX_URL: &str = "https://binaries.soliditylang.org/linux-amd64/list.json";
|
||||
pub const WINDOWS_URL: &str = "https://binaries.soliditylang.org/windows-amd64/list.json";
|
||||
pub const MACOSX_URL: &str = "https://binaries.soliditylang.org/macosx-amd64/list.json";
|
||||
pub const WASM_URL: &str = "https://binaries.soliditylang.org/wasm/list.json";
|
||||
|
||||
/// Try to downloads the list from the given URL.
|
||||
///
|
||||
/// Caches the list retrieved from the `url` into [LIST_CACHE],
|
||||
/// subsequent calls with the same `url` will return the cached list.
|
||||
pub fn download(url: &'static str) -> anyhow::Result<Self> {
|
||||
if let Some(list) = LIST_CACHE.lock().unwrap().get(url) {
|
||||
return Ok(list.clone());
|
||||
}
|
||||
|
||||
let body: List = reqwest::blocking::get(url)?.json()?;
|
||||
|
||||
LIST_CACHE.lock().unwrap().insert(url, body.clone());
|
||||
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
/// Download solc binaries from GitHub releases (IPFS links aren't reliable).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GHDownloader {
|
||||
pub version: Version,
|
||||
pub target: &'static str,
|
||||
pub list: &'static str,
|
||||
}
|
||||
|
||||
impl GHDownloader {
|
||||
pub const BASE_URL: &str = "https://github.com/ethereum/solidity/releases/download";
|
||||
|
||||
pub const LINUX_NAME: &str = "solc-static-linux";
|
||||
pub const MACOSX_NAME: &str = "solc-macos";
|
||||
pub const WINDOWS_NAME: &str = "solc-windows.exe";
|
||||
pub const WASM_NAME: &str = "soljson.js";
|
||||
|
||||
fn new(version: Version, target: &'static str, list: &'static str) -> Self {
|
||||
Self {
|
||||
version,
|
||||
target,
|
||||
list,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn linux(version: Version) -> Self {
|
||||
Self::new(version, Self::LINUX_NAME, List::LINUX_URL)
|
||||
}
|
||||
|
||||
pub fn macosx(version: Version) -> Self {
|
||||
Self::new(version, Self::MACOSX_NAME, List::MACOSX_URL)
|
||||
}
|
||||
|
||||
pub fn windows(version: Version) -> Self {
|
||||
Self::new(version, Self::WINDOWS_NAME, List::WINDOWS_URL)
|
||||
}
|
||||
|
||||
pub fn wasm(version: Version) -> Self {
|
||||
Self::new(version, Self::WASM_NAME, List::WASM_URL)
|
||||
}
|
||||
|
||||
/// Returns the download link.
|
||||
pub fn url(&self) -> String {
|
||||
format!("{}/v{}/{}", Self::BASE_URL, &self.version, &self.target)
|
||||
}
|
||||
|
||||
/// Download the solc binary.
|
||||
///
|
||||
/// Errors out if the download fails or the digest of the downloaded file
|
||||
/// mismatches the expected digest from the release [List].
|
||||
pub fn download(&self) -> anyhow::Result<Vec<u8>> {
|
||||
tracing::info!("downloading solc: {self:?}");
|
||||
let expected_digest = List::download(self.list)?
|
||||
.builds
|
||||
.iter()
|
||||
.find(|build| build.version == self.version)
|
||||
.ok_or_else(|| anyhow::anyhow!("solc v{} not found builds", self.version))
|
||||
.map(|b| b.sha256.strip_prefix("0x").unwrap_or(&b.sha256).to_string())?;
|
||||
|
||||
let file = reqwest::blocking::get(self.url())?.bytes()?.to_vec();
|
||||
|
||||
if hex::encode(Sha256::digest(&file)) != expected_digest {
|
||||
anyhow::bail!("sha256 mismatch for solc version {}", self.version);
|
||||
}
|
||||
|
||||
Ok(file)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{download::GHDownloader, list::List};
|
||||
|
||||
#[test]
|
||||
fn try_get_windows() {
|
||||
let version = List::download(List::WINDOWS_URL)
|
||||
.unwrap()
|
||||
.latest_release
|
||||
.into();
|
||||
GHDownloader::windows(version).download().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_get_macosx() {
|
||||
let version = List::download(List::MACOSX_URL)
|
||||
.unwrap()
|
||||
.latest_release
|
||||
.into();
|
||||
GHDownloader::macosx(version).download().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_get_linux() {
|
||||
let version = List::download(List::LINUX_URL)
|
||||
.unwrap()
|
||||
.latest_release
|
||||
.into();
|
||||
GHDownloader::linux(version).download().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_get_wasm() {
|
||||
let version = List::download(List::WASM_URL)
|
||||
.unwrap()
|
||||
.latest_release
|
||||
.into();
|
||||
GHDownloader::wasm(version).download().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! This crates provides serializable Rust type definitions for the [solc binary lists][0]
|
||||
//! and download helpers.
|
||||
//!
|
||||
//! [0]: https://binaries.soliditylang.org
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cache::get_or_download;
|
||||
use download::GHDownloader;
|
||||
use semver::Version;
|
||||
|
||||
pub mod cache;
|
||||
pub mod download;
|
||||
pub mod list;
|
||||
|
||||
/// Downloads the solc binary for Wasm is `wasm` is set, otherwise for
|
||||
/// the target platform.
|
||||
///
|
||||
/// Subsequent calls for the same version will use a cached artifact
|
||||
/// and not download it again.
|
||||
pub fn download_solc(
|
||||
cache_directory: &Path,
|
||||
version: Version,
|
||||
wasm: bool,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let downloader = if wasm {
|
||||
GHDownloader::wasm(version)
|
||||
} else if cfg!(target_os = "linux") {
|
||||
GHDownloader::linux(version)
|
||||
} else if cfg!(target_os = "macos") {
|
||||
GHDownloader::macosx(version)
|
||||
} else if cfg!(target_os = "windows") {
|
||||
GHDownloader::windows(version)
|
||||
} else {
|
||||
unimplemented!()
|
||||
};
|
||||
|
||||
get_or_download(cache_directory, &downloader)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Rust type definitions for the solc binary lists.
|
||||
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use semver::Version;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct List {
|
||||
pub builds: Vec<Build>,
|
||||
pub releases: HashMap<Version, String>,
|
||||
#[serde(rename = "latestRelease")]
|
||||
pub latest_release: Version,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct Build {
|
||||
pub path: PathBuf,
|
||||
pub version: Version,
|
||||
pub build: String,
|
||||
#[serde(rename = "longVersion")]
|
||||
pub long_version: String,
|
||||
pub keccak256: String,
|
||||
pub sha256: String,
|
||||
pub urls: Vec<String>,
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"config": {
|
||||
"chainId": 420420420,
|
||||
"homesteadBlock": 0,
|
||||
"eip150Block": 0,
|
||||
"eip155Block": 0,
|
||||
"eip158Block": 0,
|
||||
"byzantiumBlock": 0,
|
||||
"constantinopleBlock": 0,
|
||||
"petersburgBlock": 0,
|
||||
"istanbulBlock": 0,
|
||||
"berlinBlock": 0,
|
||||
"londonBlock": 0,
|
||||
"arrowGlacierBlock": 0,
|
||||
"grayGlacierBlock": 0,
|
||||
"shanghaiTime": 0,
|
||||
"cancunTime": 0,
|
||||
"terminalTotalDifficulty": 0,
|
||||
"terminalTotalDifficultyPassed": true,
|
||||
"blobSchedule": {
|
||||
"cancun": {
|
||||
"target": 3,
|
||||
"max": 6,
|
||||
"baseFeeUpdateFraction": 3338477
|
||||
}
|
||||
}
|
||||
},
|
||||
"coinbase": "0xffffffffffffffffffffffffffffffffffffffff",
|
||||
"difficulty": "0x00",
|
||||
"extraData": "",
|
||||
"gasLimit": "0xffffffff",
|
||||
"nonce": "0x0000000000000042",
|
||||
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"timestamp": "0x00",
|
||||
"alloc": {
|
||||
"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1": {
|
||||
"balance": "1000000000000000000"
|
||||
}
|
||||
}
|
||||
}
|
||||
Submodule
+1
Submodule polkadot-sdk added at dc3d0e5ab7
Reference in New Issue
Block a user