Compare commits

...

4 Commits

Author SHA1 Message Date
Omar Abdulla 7f4fadf7b1 Add a cached fs abstraction 2025-08-14 13:12:23 +03:00
Omar f2045db0e9 Add compiler directives to metadata (#139) 2025-08-14 07:38:56 +00:00
Omar 5a11f44673 Misc features/improvements (#138)
* Implement various needed features and improvements

* Reorder the metadata struct

* Format comments
2025-08-13 13:50:06 +00:00
James Wilson 46aea0890d Split reporter and case runner, use channels to pass test reports (#137)
* Use channels to send data to reporting thread and avoid hangs / mutex / duration. Limit max concurrent tasks to avoid too many open files

* More appropriate name for dirver/reporter task fns

* Back to parallelise individual cases, report individual cases, address grumbles

* newline before 'Failures' title in report
2025-08-13 13:10:26 +00:00
18 changed files with 457 additions and 282 deletions
Generated
+1
View File
@@ -4081,6 +4081,7 @@ dependencies = [
"revive-dt-node-interaction",
"revive-dt-report",
"semver 1.0.26",
"serde_json",
"temp-dir",
"tokio",
"tracing",
+1
View File
@@ -36,6 +36,7 @@ serde = { version = "1.0", default-features = false, features = ["derive"] }
serde_json = { version = "1.0", default-features = false, features = [
"arbitrary_precision",
"std",
"unbounded_depth",
] }
sha2 = { version = "0.10.9" }
sp-core = "36.1.0"
@@ -0,0 +1,38 @@
//! Implements a cached file system that allows for files to be read once into memory and then when
//! they're requested to be read again they will be returned from the cache.
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, LazyLock},
};
use anyhow::Result;
use tokio::sync::RwLock;
#[allow(clippy::type_complexity)]
static CACHE: LazyLock<Arc<RwLock<HashMap<PathBuf, Vec<u8>>>>> = LazyLock::new(Default::default);
pub struct CachedFileSystem;
impl CachedFileSystem {
pub async fn read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
let cache_read_lock = CACHE.read().await;
match cache_read_lock.get(path.as_ref()) {
Some(entry) => Ok(entry.clone()),
None => {
drop(cache_read_lock);
let content = std::fs::read(&path)?;
let mut cache_write_lock = CACHE.write().await;
cache_write_lock.insert(path.as_ref().to_path_buf(), content.clone());
Ok(content)
}
}
}
pub async fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
let content = Self::read(path).await?;
String::from_utf8(content).map_err(Into::into)
}
}
+2
View File
@@ -1,3 +1,5 @@
mod cached_file_system;
mod clear_dir;
pub use cached_file_system::*;
pub use clear_dir::*;
+28 -6
View File
@@ -5,7 +5,6 @@
use std::{
collections::HashMap,
fs::read_to_string,
hash::Hash,
path::{Path, PathBuf},
};
@@ -16,7 +15,7 @@ use semver::Version;
use serde::{Deserialize, Serialize};
use revive_common::EVMVersion;
use revive_dt_common::types::VersionOrRequirement;
use revive_dt_common::{fs::CachedFileSystem, types::VersionOrRequirement};
use revive_dt_config::Arguments;
pub mod revive_js;
@@ -55,6 +54,7 @@ pub struct CompilerInput {
pub base_path: Option<PathBuf>,
pub sources: HashMap<PathBuf, String>,
pub libraries: HashMap<PathBuf, HashMap<String, Address>>,
pub revert_string_handling: Option<RevertString>,
}
/// The generic compilation output configuration.
@@ -91,6 +91,7 @@ where
base_path: Default::default(),
sources: Default::default(),
libraries: Default::default(),
revert_string_handling: Default::default(),
},
additional_options: T::Options::default(),
}
@@ -121,10 +122,11 @@ where
self
}
pub fn with_source(mut self, path: impl AsRef<Path>) -> anyhow::Result<Self> {
self.input
.sources
.insert(path.as_ref().to_path_buf(), read_to_string(path.as_ref())?);
pub async fn with_source(mut self, path: impl AsRef<Path>) -> anyhow::Result<Self> {
self.input.sources.insert(
path.as_ref().to_path_buf(),
CachedFileSystem::read_to_string(path.as_ref()).await?,
);
Ok(self)
}
@@ -142,6 +144,14 @@ where
self
}
pub fn with_revert_string_handling(
mut self,
revert_string_handling: impl Into<Option<RevertString>>,
) -> Self {
self.input.revert_string_handling = revert_string_handling.into();
self
}
pub fn with_additional_options(mut self, options: impl Into<T::Options>) -> Self {
self.additional_options = options.into();
self
@@ -160,3 +170,15 @@ where
self.input.clone()
}
}
/// Defines how the compiler should handle revert strings.
#[derive(
Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
pub enum RevertString {
#[default]
Default,
Debug,
Strip,
VerboseDebug,
}
+3
View File
@@ -47,6 +47,9 @@ impl SolidityCompiler for Resolc {
base_path,
sources,
libraries,
// TODO: this is currently not being handled since there is no way to pass it into
// resolc. So, we need to go back to this later once it's supported.
revert_string_handling: _,
}: CompilerInput,
additional_options: Self::Options,
) -> anyhow::Result<CompilerOutput> {
+10
View File
@@ -42,6 +42,7 @@ impl SolidityCompiler for Solc {
base_path,
sources,
libraries,
revert_string_handling,
}: CompilerInput,
_: Self::Options,
) -> anyhow::Result<CompilerOutput> {
@@ -87,6 +88,15 @@ impl SolidityCompiler for Solc {
})
.collect(),
},
debug: revert_string_handling.map(|revert_string_handling| DebuggingSettings {
revert_strings: match revert_string_handling {
crate::RevertString::Default => Some(RevertStrings::Default),
crate::RevertString::Debug => Some(RevertStrings::Debug),
crate::RevertString::Strip => Some(RevertStrings::Strip),
crate::RevertString::VerboseDebug => Some(RevertStrings::VerboseDebug),
},
debug_info: Default::default(),
}),
..Default::default()
},
};
+18 -2
View File
@@ -96,10 +96,19 @@ pub struct Arguments {
#[arg(long, default_value = "1")]
pub number_of_nodes: usize,
/// Determines the amount of threads that will will be used.
#[arg(long, default_value = "12")]
/// Determines the amount of tokio worker threads that will will be used.
#[arg(
long,
default_value_t = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
)]
pub number_of_threads: usize,
/// Determines the amount of concurrent tasks that will be spawned to run tests. Defaults to 10 x the number of nodes.
#[arg(long)]
pub number_concurrent_tasks: Option<usize>,
/// Extract problems back to the test corpus.
#[arg(short, long = "extract-problems")]
pub extract_problems: bool,
@@ -134,6 +143,13 @@ impl Arguments {
panic!("should have a workdir configured")
}
/// Return the number of concurrent tasks to run. This is provided via the
/// `--number-concurrent-tasks` argument, and otherwise defaults to --number-of-nodes * 20.
pub fn number_of_concurrent_tasks(&self) -> usize {
self.number_concurrent_tasks
.unwrap_or(20 * self.number_of_nodes)
}
/// Try to parse `self.account` into a [PrivateKeySigner],
/// panicing on error.
pub fn wallet(&self) -> EthereumWallet {
+1
View File
@@ -30,4 +30,5 @@ tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
semver = { workspace = true }
serde_json = { workspace = true }
temp-dir = { workspace = true }
+9 -4
View File
@@ -11,8 +11,8 @@ use alloy::network::{Ethereum, TransactionBuilder};
use alloy::primitives::U256;
use alloy::rpc::types::TransactionReceipt;
use alloy::rpc::types::trace::geth::{
CallFrame, GethDebugBuiltInTracerType, GethDebugTracerType, GethDebugTracingOptions, GethTrace,
PreStateConfig,
CallFrame, GethDebugBuiltInTracerType, GethDebugTracerConfig, GethDebugTracerType,
GethDebugTracingOptions, GethTrace, PreStateConfig,
};
use alloy::{
primitives::Address,
@@ -263,6 +263,11 @@ where
tracer: Some(GethDebugTracerType::BuiltInTracer(
GethDebugBuiltInTracerType::CallTracer,
)),
tracer_config: GethDebugTracerConfig(serde_json::json! {{
"onlyTopCall": true,
"withLog": false,
"withReturnData": false
}}),
..Default::default()
},
)
@@ -528,7 +533,7 @@ where
) -> anyhow::Result<()> {
let Some(instance) = balance_assertion
.address
.strip_prefix(".address")
.strip_suffix(".address")
.map(ContractInstance::new)
else {
return Ok(());
@@ -588,7 +593,7 @@ where
) -> anyhow::Result<()> {
let Some(instance) = storage_empty_assertion
.address
.strip_prefix(".address")
.strip_suffix(".address")
.map(ContractInstance::new)
else {
return Ok(());
+192 -183
View File
@@ -1,6 +1,6 @@
use std::{
collections::HashMap,
path::Path,
path::{Path, PathBuf},
sync::{Arc, LazyLock},
time::Instant,
};
@@ -18,7 +18,7 @@ use revive_dt_common::iterators::FilesWithExtensionIterator;
use revive_dt_node_interaction::EthereumNode;
use semver::Version;
use temp_dir::TempDir;
use tokio::sync::{Mutex, RwLock};
use tokio::sync::{Mutex, RwLock, mpsc};
use tracing::{Instrument, Level};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
@@ -41,20 +41,33 @@ use revive_dt_report::reporter::{Report, Span};
static TEMP_DIR: LazyLock<TempDir> = LazyLock::new(|| TempDir::new().unwrap());
type CompilationCache<'a> = Arc<
type CompilationCache = Arc<
RwLock<
HashMap<
(&'a Path, SolcMode, TestingPlatform),
(PathBuf, SolcMode, TestingPlatform),
Arc<Mutex<Option<Arc<(Version, CompilerOutput)>>>>,
>,
>,
>;
/// this represents a single "test"; a mode, path and collection of cases.
#[derive(Clone)]
struct Test {
metadata: Metadata,
path: PathBuf,
mode: SolcMode,
case_idx: usize,
case: Case,
}
/// This represents the results that we gather from running test cases.
type CaseResult = Result<usize, anyhow::Error>;
fn main() -> anyhow::Result<()> {
let args = init_cli()?;
let body = async {
for (corpus, tests) in collect_corpora(&args)? {
for (corpus, tests) in collect_corpora(&args).await? {
let span = Span::new(corpus, args.clone())?;
match &args.compile_only {
Some(platform) => compile_corpus(&args, &tests, platform, span).await,
@@ -104,13 +117,13 @@ fn init_cli() -> anyhow::Result<Arguments> {
Ok(args)
}
fn collect_corpora(args: &Arguments) -> anyhow::Result<HashMap<Corpus, Vec<MetadataFile>>> {
async 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();
let tests = corpus.enumerate_tests().await;
tracing::info!("corpus '{}' contains {} tests", &corpus.name, tests.len());
corpora.insert(corpus, tests);
}
@@ -120,7 +133,7 @@ fn collect_corpora(args: &Arguments) -> anyhow::Result<HashMap<Corpus, Vec<Metad
async fn run_driver<L, F>(
args: &Arguments,
tests: &[MetadataFile],
metadata_files: &[MetadataFile],
span: Span,
) -> anyhow::Result<()>
where
@@ -129,10 +142,25 @@ where
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)?;
let (report_tx, report_rx) = mpsc::unbounded_channel::<(Test, CaseResult)>();
let test_cases = tests
let tests = prepare_tests::<L, F>(metadata_files);
let driver_task = start_driver_task::<L, F>(args, tests, span, report_tx).await?;
let status_reporter_task = start_reporter_task(report_rx);
tokio::join!(status_reporter_task, driver_task);
Ok(())
}
fn prepare_tests<L, F>(metadata_files: &[MetadataFile]) -> impl Iterator<Item = Test>
where
L: Platform,
F: Platform,
L::Blockchain: revive_dt_node::Node + Send + Sync + 'static,
F::Blockchain: revive_dt_node::Node + Send + Sync + 'static,
{
metadata_files
.iter()
.flat_map(
|MetadataFile {
@@ -198,188 +226,159 @@ where
}
None => true,
})
.collect::<Vec<_>>();
let metadata_case_status = Arc::new(RwLock::new(test_cases.iter().fold(
HashMap::<_, HashMap<_, _>>::new(),
|mut map, (path, _, case_idx, case, solc_mode)| {
map.entry((path.to_path_buf(), solc_mode.clone()))
.or_default()
.insert((CaseIdx::new(*case_idx), case.name.clone()), None::<bool>);
map
},
)));
let status_reporter_task = {
let metadata_case_status = metadata_case_status.clone();
let start = Instant::now();
async move {
const GREEN: &str = "\x1B[32m";
const RED: &str = "\x1B[31m";
const RESET: &str = "\x1B[0m";
let mut entries_to_delete = Vec::new();
let mut number_of_successes = 0;
let mut number_of_failures = 0;
loop {
let metadata_case_status_read = metadata_case_status.read().await;
if metadata_case_status_read.is_empty() {
break;
}
for ((metadata_file_path, solc_mode), case_status) in
metadata_case_status_read.iter()
{
if case_status.values().any(|value| value.is_none()) {
continue;
}
let contains_failures = case_status
.values()
.any(|value| value.is_some_and(|value| !value));
if !contains_failures {
eprintln!(
"{}Succeeded:{} {} - {:?}",
GREEN,
RESET,
metadata_file_path.display(),
solc_mode
)
} else {
eprintln!(
"{}Failed:{} {} - {:?}",
RED,
RESET,
metadata_file_path.display(),
solc_mode
)
};
number_of_successes += case_status
.values()
.filter(|value| value.is_some_and(|value| value))
.count();
number_of_failures += case_status
.values()
.filter(|value| value.is_some_and(|value| !value))
.count();
let mut case_status = case_status
.iter()
.map(|((case_idx, case_name), case_status)| {
(case_idx.into_inner(), case_name, case_status.unwrap())
})
.collect::<Vec<_>>();
case_status.sort_by(|a, b| a.0.cmp(&b.0));
for (case_idx, case_name, case_status) in case_status.into_iter() {
if case_status {
eprintln!(
" {GREEN}Case Succeeded:{RESET} {} - Case Idx: {case_idx}",
case_name
.as_ref()
.map(|string| string.as_str())
.unwrap_or("Unnamed case")
)
} else {
eprintln!(
" {RED}Case Failed:{RESET} {} - Case Idx: {case_idx}",
case_name
.as_ref()
.map(|string| string.as_str())
.unwrap_or("Unnamed case")
)
};
}
eprintln!();
entries_to_delete.push((metadata_file_path.clone(), solc_mode.clone()));
}
drop(metadata_case_status_read);
let mut metadata_case_status_write = metadata_case_status.write().await;
for entry in entries_to_delete.drain(..) {
metadata_case_status_write.remove(&entry);
}
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
.map(|(metadata_file_path, metadata, case_idx, case, solc_mode)| {
Test {
metadata: metadata.clone(),
path: metadata_file_path.to_path_buf(),
mode: solc_mode,
case_idx,
case: case.clone(),
}
})
}
let elapsed = start.elapsed();
eprintln!(
"{GREEN}{}{RESET} cases succeeded, {RED}{}{RESET} cases failed in {} seconds",
number_of_successes,
number_of_failures,
elapsed.as_secs()
);
}
};
async fn start_driver_task<L, F>(
args: &Arguments,
tests: impl Iterator<Item = Test>,
span: Span,
report_tx: mpsc::UnboundedSender<(Test, CaseResult)>,
) -> anyhow::Result<impl Future<Output = ()>>
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 = Arc::new(NodePool::<L::Blockchain>::new(args).await?);
let follower_nodes = Arc::new(NodePool::<F::Blockchain>::new(args).await?);
let compilation_cache = Arc::new(RwLock::new(HashMap::new()));
let driver_task = futures::stream::iter(test_cases).for_each_concurrent(
None,
|(metadata_file_path, metadata, case_idx, case, solc_mode)| {
let number_concurrent_tasks = args.number_of_concurrent_tasks();
Ok(futures::stream::iter(tests).for_each_concurrent(
// We want to limit the concurrent tasks here because:
//
// 1. We don't want to overwhelm the nodes with too many requests, leading to responses timing out.
// 2. We don't want to open too many files at once, leading to the OS running out of file descriptors.
//
// By default, we allow maximum of 10 ongoing requests per node in order to limit (1), and assume that
// this number will automatically be low enough to address (2). The user can override this.
Some(number_concurrent_tasks),
move |test| {
let leader_nodes = leader_nodes.clone();
let follower_nodes = follower_nodes.clone();
let compilation_cache = compilation_cache.clone();
let leader_node = leader_nodes.round_robbin();
let follower_node = follower_nodes.round_robbin();
let tracing_span = tracing::span!(
Level::INFO,
"Running driver",
metadata_file_path = %metadata_file_path.display(),
case_idx = case_idx,
solc_mode = ?solc_mode,
);
let metadata_case_status = metadata_case_status.clone();
let report_tx = report_tx.clone();
async move {
let leader_node = leader_nodes.round_robbin();
let follower_node = follower_nodes.round_robbin();
let tracing_span = tracing::span!(
Level::INFO,
"Running driver",
metadata_file_path = %test.path.display(),
case_idx = ?test.case_idx,
solc_mode = ?test.mode,
);
let result = handle_case_driver::<L, F>(
metadata_file_path.as_path(),
metadata,
case_idx.into(),
case,
solc_mode.clone(),
&test.path,
&test.metadata,
test.case_idx.into(),
&test.case,
test.mode.clone(),
args,
compilation_cache.clone(),
leader_node,
follower_node,
span,
)
.instrument(tracing_span)
.await;
let mut metadata_case_status = metadata_case_status.write().await;
match result {
Ok(inputs_executed) => {
tracing::info!(inputs_executed, "Execution succeeded");
metadata_case_status
.entry((metadata_file_path.clone(), solc_mode))
.or_default()
.insert((CaseIdx::new(case_idx), case.name.clone()), Some(true));
}
Err(error) => {
metadata_case_status
.entry((metadata_file_path.clone(), solc_mode))
.or_default()
.insert((CaseIdx::new(case_idx), case.name.clone()), Some(false));
tracing::error!(%error, "Execution failed")
}
}
tracing::info!("Execution completed");
report_tx
.send((test, result))
.expect("Failed to send report");
}
.instrument(tracing_span)
},
))
}
async fn start_reporter_task(mut report_rx: mpsc::UnboundedReceiver<(Test, CaseResult)>) {
let start = Instant::now();
const GREEN: &str = "\x1B[32m";
const RED: &str = "\x1B[31m";
const COLOUR_RESET: &str = "\x1B[0m";
const BOLD: &str = "\x1B[1m";
const BOLD_RESET: &str = "\x1B[22m";
let mut number_of_successes = 0;
let mut number_of_failures = 0;
let mut failures = vec![];
// Wait for reports to come from our test runner. When the channel closes, this ends.
while let Some((test, case_result)) = report_rx.recv().await {
let case_name = test.case.name.as_deref().unwrap_or("unnamed_case");
let case_idx = test.case_idx;
let test_path = test.path.display();
let test_mode = test.mode.clone();
match case_result {
Ok(_inputs) => {
number_of_successes += 1;
eprintln!(
"{GREEN}Case Succeeded:{COLOUR_RESET} {test_path} -> {case_name}:{case_idx} (mode: {test_mode:?})"
);
}
Err(err) => {
number_of_failures += 1;
eprintln!(
"{RED}Case Failed:{COLOUR_RESET} {test_path} -> {case_name}:{case_idx} (mode: {test_mode:?})"
);
failures.push((test, err));
}
}
}
eprintln!();
let elapsed = start.elapsed();
// Now, log the failures with more complete errors at the bottom, like `cargo test` does, so
// that we don't have to scroll through the entire output to find them.
if !failures.is_empty() {
eprintln!("{BOLD}Failures:{BOLD_RESET}\n");
for failure in failures {
let (test, err) = failure;
let case_name = test.case.name.as_deref().unwrap_or("unnamed_case");
let case_idx = test.case_idx;
let test_path = test.path.display();
let test_mode = test.mode.clone();
eprintln!(
"---- {RED}Case Failed:{COLOUR_RESET} {test_path} -> {case_name}:{case_idx} (mode: {test_mode:?}) ----\n\n{err}\n"
);
}
}
// Summary at the end.
eprintln!(
"{} cases: {GREEN}{number_of_successes}{COLOUR_RESET} cases succeeded, {RED}{number_of_failures}{COLOUR_RESET} cases failed in {} seconds",
number_of_successes + number_of_failures,
elapsed.as_secs()
);
tokio::join!(status_reporter_task, driver_task);
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn handle_case_driver<'a, L, F>(
metadata_file_path: &'a Path,
metadata: &'a Metadata,
async fn handle_case_driver<L, F>(
metadata_file_path: &Path,
metadata: &Metadata,
case_idx: CaseIdx,
case: &Case,
mode: SolcMode,
config: &Arguments,
compilation_cache: CompilationCache<'a>,
compilation_cache: CompilationCache,
leader_node: &L::Blockchain,
follower_node: &F::Blockchain,
_: Span,
@@ -520,11 +519,9 @@ where
);
let Some(leader_library_address) = leader_receipt.contract_address else {
tracing::error!("Contract deployment transaction didn't return an address");
anyhow::bail!("Contract deployment didn't return an address");
};
let Some(follower_library_address) = follower_receipt.contract_address else {
tracing::error!("Contract deployment transaction didn't return an address");
anyhow::bail!("Contract deployment didn't return an address");
};
@@ -554,8 +551,16 @@ where
.any(|(code, _)| !code.chars().all(|char| char.is_ascii_hexdigit()));
let (leader_compiled_contracts, follower_compiled_contracts) =
if metadata_file_contains_libraries && compiled_contracts_require_linking {
let leader_key = (metadata_file_path, mode.clone(), L::config_id());
let follower_key = (metadata_file_path, mode.clone(), L::config_id());
let leader_key = (
metadata_file_path.to_path_buf(),
mode.clone(),
L::config_id(),
);
let follower_key = (
metadata_file_path.to_path_buf(),
mode.clone(),
F::config_id(),
);
{
let mut cache = compilation_cache.write().await;
cache.remove(&leader_key);
@@ -609,15 +614,19 @@ where
driver.execute().await
}
async fn get_or_build_contracts<'a, P: Platform>(
metadata: &'a Metadata,
metadata_file_path: &'a Path,
async fn get_or_build_contracts<P: Platform>(
metadata: &Metadata,
metadata_file_path: &Path,
mode: SolcMode,
config: &Arguments,
compilation_cache: CompilationCache<'a>,
compilation_cache: CompilationCache,
deployed_libraries: &HashMap<ContractInstance, (Address, JsonAbi)>,
) -> anyhow::Result<Arc<(Version, CompilerOutput)>> {
let key = (metadata_file_path, mode.clone(), P::config_id());
let key = (
metadata_file_path.to_path_buf(),
mode.clone(),
P::config_id(),
);
if let Some(compilation_artifact) = compilation_cache.read().await.get(&key).cloned() {
let mut compilation_artifact = compilation_artifact.lock().await;
match *compilation_artifact {
@@ -684,12 +693,12 @@ async fn compile_contracts<P: Platform>(
"Compiling contracts"
);
let compiler = Compiler::<P::Compiler>::new()
let mut compiler = Compiler::<P::Compiler>::new()
.with_allow_path(metadata.directory()?)
.with_optimization(mode.solc_optimize());
let mut compiler = metadata
.files_to_compile()?
.try_fold(compiler, |compiler, path| compiler.with_source(&path))?;
for path in metadata.files_to_compile()? {
compiler = compiler.with_source(path).await?;
}
for (library_instance, (library_address, _)) in deployed_libraries.iter() {
let library_ident = &metadata
.contracts
+6
View File
@@ -11,16 +11,22 @@ use crate::{
pub struct Case {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modes: Option<Vec<Mode>>,
#[serde(rename = "inputs")]
pub steps: Vec<Step>,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expected: Option<Expected>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ignore: Option<bool>,
}
+6 -6
View File
@@ -39,9 +39,9 @@ impl Corpus {
}
/// Scan the corpus base directory and return all tests found.
pub fn enumerate_tests(&self) -> Vec<MetadataFile> {
pub async fn enumerate_tests(&self) -> Vec<MetadataFile> {
let mut tests = Vec::new();
collect_metadata(&self.path, &mut tests);
collect_metadata(&self.path, &mut tests).await;
tests
}
}
@@ -52,7 +52,7 @@ impl Corpus {
/// Found tests are inserted into `tests`.
///
/// `path` is expected to be a directory.
pub fn collect_metadata(path: &Path, tests: &mut Vec<MetadataFile>) {
pub async fn collect_metadata(path: &Path, tests: &mut Vec<MetadataFile>) {
if path.is_dir() {
let dir_entry = match std::fs::read_dir(path) {
Ok(dir_entry) => dir_entry,
@@ -73,12 +73,12 @@ pub fn collect_metadata(path: &Path, tests: &mut Vec<MetadataFile>) {
let path = entry.path();
if path.is_dir() {
collect_metadata(&path, tests);
Box::pin(collect_metadata(&path, tests)).await;
continue;
}
if path.is_file() {
if let Some(metadata) = MetadataFile::try_from_file(&path) {
if let Some(metadata) = MetadataFile::try_from_file(&path).await {
tests.push(metadata)
}
}
@@ -89,7 +89,7 @@ pub fn collect_metadata(path: &Path, tests: &mut Vec<MetadataFile>) {
return;
};
if extension.eq_ignore_ascii_case("sol") || extension.eq_ignore_ascii_case("json") {
if let Some(metadata) = MetadataFile::try_from_file(path) {
if let Some(metadata) = MetadataFile::try_from_file(path).await {
tests.push(metadata)
}
} else {
+30 -11
View File
@@ -3,6 +3,7 @@ use std::collections::HashMap;
use alloy::{
eips::BlockNumberOrTag,
hex::ToHexExt,
json_abi::Function,
network::TransactionBuilder,
primitives::{Address, Bytes, U256},
rpc::types::TransactionRequest,
@@ -36,19 +37,27 @@ pub enum Step {
pub struct Input {
#[serde(default = "Input::default_caller")]
pub caller: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default = "Input::default_instance")]
pub instance: ContractInstance,
pub method: Method,
#[serde(default)]
pub calldata: Calldata,
#[serde(skip_serializing_if = "Option::is_none")]
pub expected: Option<Expected>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<EtherValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub storage: Option<HashMap<String, Calldata>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub variable_assignments: Option<VariableAssignments>,
}
@@ -271,17 +280,27 @@ impl Input {
// 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.
// Overloads are handled by providing the full function signature in the "function
// name".
// 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.signature().starts_with(function_name))
.ok_or_else(|| {
anyhow::anyhow!(
"Function with name {:?} not found in ABI for the instance {:?}",
function_name,
&self.instance
)
})?;
let selector = if function_name.contains('(') && function_name.contains(')') {
Function::parse(function_name)
.context(
"Failed to parse the provided function name into a function signature",
)?
.selector()
} else {
abi.functions()
.find(|function| function.signature().starts_with(function_name))
.ok_or_else(|| {
anyhow::anyhow!(
"Function with name {:?} not found in ABI for the instance {:?}",
function_name,
&self.instance
)
})?
.selector()
};
tracing::trace!("Functions found for instance: {}", self.instance.as_ref());
@@ -297,7 +316,7 @@ impl Input {
// 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 + self.calldata.size_requirement());
calldata.extend(function.selector().0);
calldata.extend(selector.0);
self.calldata
.calldata_into_slice(&mut calldata, resolver, context)
.await?;
+64 -21
View File
@@ -2,7 +2,6 @@ use std::{
cmp::Ordering,
collections::BTreeMap,
fmt::Display,
fs::{File, read_to_string},
ops::Deref,
path::{Path, PathBuf},
str::FromStr,
@@ -11,7 +10,9 @@ use std::{
use serde::{Deserialize, Serialize};
use revive_common::EVMVersion;
use revive_dt_common::{iterators::FilesWithExtensionIterator, macros::define_wrapper_type};
use revive_dt_common::{
fs::CachedFileSystem, iterators::FilesWithExtensionIterator, macros::define_wrapper_type,
};
use crate::{
case::Case,
@@ -29,8 +30,8 @@ pub struct MetadataFile {
}
impl MetadataFile {
pub fn try_from_file(path: &Path) -> Option<Self> {
Metadata::try_from_file(path).map(|metadata| Self {
pub async fn try_from_file(path: &Path) -> Option<Self> {
Metadata::try_from_file(path).await.map(|metadata| Self {
path: path.to_owned(),
content: metadata,
})
@@ -47,25 +48,40 @@ impl Deref for MetadataFile {
#[derive(Debug, Default, Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct Metadata {
/// A comment on the test case that's added for human-readability.
#[serde(skip_serializing_if = "Option::is_none")]
pub targets: Option<Vec<String>>,
pub cases: Vec<Case>,
#[serde(skip_serializing_if = "Option::is_none")]
pub contracts: Option<BTreeMap<ContractInstance, ContractPathAndIdent>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub libraries: Option<BTreeMap<PathBuf, BTreeMap<ContractIdent, ContractInstance>>>,
pub comment: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ignore: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub targets: Option<Vec<String>>,
pub cases: Vec<Case>,
#[serde(skip_serializing_if = "Option::is_none")]
pub contracts: Option<BTreeMap<ContractInstance, ContractPathAndIdent>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub libraries: Option<BTreeMap<PathBuf, BTreeMap<ContractIdent, ContractInstance>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modes: Option<Vec<Mode>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub file_path: Option<PathBuf>,
/// This field specifies an EVM version requirement that the test case has
/// where the test might be run of the evm version of the nodes match the
/// evm version specified here.
/// This field specifies an EVM version requirement that the test case has where the test might
/// be run of the evm version of the nodes match the evm version specified here.
#[serde(skip_serializing_if = "Option::is_none")]
pub required_evm_version: Option<EvmVersionRequirement>,
/// A set of compilation directives that will be passed to the compiler whenever the contracts for
/// the test are being compiled. Note that this differs from the [`Mode`]s in that a [`Mode`] is
/// just a filter for when a test can run whereas this is an instruction to the compiler.
#[serde(skip_serializing_if = "Option::is_none")]
pub compiler_directives: Option<CompilationDirectives>,
}
impl Metadata {
@@ -136,7 +152,7 @@ impl Metadata {
///
/// # Panics
/// Expects the supplied `path` to be a file.
pub fn try_from_file(path: &Path) -> Option<Self> {
pub async fn try_from_file(path: &Path) -> Option<Self> {
assert!(path.is_file(), "not a file: {}", path.display());
let Some(file_extension) = path.extension() else {
@@ -145,19 +161,20 @@ impl Metadata {
};
if file_extension == METADATA_FILE_EXTENSION {
return Self::try_from_json(path);
return Self::try_from_json(path).await;
}
if file_extension == SOLIDITY_CASE_FILE_EXTENSION {
return Self::try_from_solidity(path);
return Self::try_from_solidity(path).await;
}
tracing::debug!("ignoring invalid corpus file: {}", path.display());
None
}
fn try_from_json(path: &Path) -> Option<Self> {
let file = File::open(path)
async fn try_from_json(path: &Path) -> Option<Self> {
let content = CachedFileSystem::read(path)
.await
.inspect_err(|error| {
tracing::error!(
"opening JSON test metadata file '{}' error: {error}",
@@ -166,7 +183,7 @@ impl Metadata {
})
.ok()?;
match serde_json::from_reader::<_, Metadata>(file) {
match serde_json::from_slice::<Metadata>(content.as_slice()) {
Ok(mut metadata) => {
metadata.file_path = Some(path.to_path_buf());
Some(metadata)
@@ -181,8 +198,9 @@ impl Metadata {
}
}
fn try_from_solidity(path: &Path) -> Option<Self> {
let spec = read_to_string(path)
async fn try_from_solidity(path: &Path) -> Option<Self> {
let spec = CachedFileSystem::read_to_string(path)
.await
.inspect_err(|error| {
tracing::error!(
"opening JSON test metadata file '{}' error: {error}",
@@ -481,6 +499,31 @@ impl From<EvmVersionRequirement> for String {
}
}
/// A set of compilation directives that will be passed to the compiler whenever the contracts for
/// the test are being compiled. Note that this differs from the [`Mode`]s in that a [`Mode`] is
/// just a filter for when a test can run whereas this is an instruction to the compiler.
/// Defines how the compiler should handle revert strings.
#[derive(
Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
pub struct CompilationDirectives {
/// Defines how the revert strings should be handled.
pub revert_string_handling: Option<RevertString>,
}
/// Defines how the compiler should handle revert strings.
#[derive(
Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum RevertString {
#[default]
Default,
Debug,
Strip,
VerboseDebug,
}
#[cfg(test)]
mod test {
use super::*;
+23 -23
View File
@@ -92,7 +92,7 @@ impl GethNode {
const TRACE_POLLING_DURATION: Duration = Duration::from_secs(60);
/// Create the node directory and call `geth init` to configure the genesis.
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
fn init(&mut self, genesis: String) -> anyhow::Result<&mut Self> {
let _ = clear_directory(&self.base_directory);
let _ = clear_directory(&self.logs_directory);
@@ -142,7 +142,7 @@ impl GethNode {
/// Spawn the go-ethereum node child process.
///
/// [Instance::init] must be called prior.
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", 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:
@@ -200,7 +200,7 @@ impl GethNode {
/// 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))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
fn wait_ready(&mut self) -> anyhow::Result<&mut Self> {
let start_time = Instant::now();
@@ -269,7 +269,7 @@ impl GethNode {
}
impl EthereumNode for GethNode {
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn execute_transaction(
&self,
transaction: TransactionRequest,
@@ -325,7 +325,7 @@ impl EthereumNode for GethNode {
.await
}
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn trace_transaction(
&self,
transaction: &TransactionReceipt,
@@ -358,7 +358,7 @@ impl EthereumNode for GethNode {
.await
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn state_diff(&self, transaction: &TransactionReceipt) -> anyhow::Result<DiffMode> {
let trace_options = GethDebugTracingOptions::prestate_tracer(PreStateConfig {
diff_mode: Some(true),
@@ -375,7 +375,7 @@ impl EthereumNode for GethNode {
}
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn balance_of(&self, address: Address) -> anyhow::Result<U256> {
self.provider()
.await?
@@ -384,7 +384,7 @@ impl EthereumNode for GethNode {
.map_err(Into::into)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn latest_state_proof(
&self,
address: Address,
@@ -400,7 +400,7 @@ impl EthereumNode for GethNode {
}
impl ResolverApi for GethNode {
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn chain_id(&self) -> anyhow::Result<alloy::primitives::ChainId> {
self.provider()
.await?
@@ -409,7 +409,7 @@ impl ResolverApi for GethNode {
.map_err(Into::into)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn transaction_gas_price(&self, tx_hash: &TxHash) -> anyhow::Result<u128> {
self.provider()
.await?
@@ -419,7 +419,7 @@ impl ResolverApi for GethNode {
.map(|receipt| receipt.effective_gas_price)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_gas_limit(&self, number: BlockNumberOrTag) -> anyhow::Result<u128> {
self.provider()
.await?
@@ -429,7 +429,7 @@ impl ResolverApi for GethNode {
.map(|block| block.header.gas_limit as _)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_coinbase(&self, number: BlockNumberOrTag) -> anyhow::Result<Address> {
self.provider()
.await?
@@ -439,7 +439,7 @@ impl ResolverApi for GethNode {
.map(|block| block.header.beneficiary)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_difficulty(&self, number: BlockNumberOrTag) -> anyhow::Result<U256> {
self.provider()
.await?
@@ -449,7 +449,7 @@ impl ResolverApi for GethNode {
.map(|block| U256::from_be_bytes(block.header.mix_hash.0))
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_base_fee(&self, number: BlockNumberOrTag) -> anyhow::Result<u64> {
self.provider()
.await?
@@ -464,7 +464,7 @@ impl ResolverApi for GethNode {
})
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_hash(&self, number: BlockNumberOrTag) -> anyhow::Result<BlockHash> {
self.provider()
.await?
@@ -474,7 +474,7 @@ impl ResolverApi for GethNode {
.map(|block| block.header.hash)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn block_timestamp(&self, number: BlockNumberOrTag) -> anyhow::Result<BlockTimestamp> {
self.provider()
.await?
@@ -484,7 +484,7 @@ impl ResolverApi for GethNode {
.map(|block| block.header.timestamp)
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
async fn last_block_number(&self) -> anyhow::Result<BlockNumber> {
self.provider()
.await?
@@ -527,12 +527,12 @@ impl Node for GethNode {
}
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", 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))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
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() {
@@ -554,13 +554,13 @@ impl Node for GethNode {
Ok(())
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
fn spawn(&mut self, genesis: String) -> anyhow::Result<()> {
self.init(genesis)?.spawn_process()?;
Ok(())
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id), err)]
fn version(&self) -> anyhow::Result<String> {
let output = Command::new(&self.geth)
.arg("--version")
@@ -573,7 +573,7 @@ impl Node for GethNode {
Ok(String::from_utf8_lossy(&output).into())
}
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
fn matches_target(&self, targets: Option<&[String]>) -> bool {
match targets {
None => true,
@@ -587,7 +587,7 @@ impl Node for GethNode {
}
impl Drop for GethNode {
#[tracing::instrument(skip_all, fields(geth_node_id = self.id))]
#[tracing::instrument(level = "info", skip_all, fields(geth_node_id = self.id))]
fn drop(&mut self) {
self.shutdown().expect("Failed to shutdown")
}
+20 -20
View File
@@ -160,7 +160,7 @@ impl KitchensinkNode {
Ok(self)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
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;
@@ -258,7 +258,7 @@ impl KitchensinkNode {
Ok(())
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
fn extract_balance_from_genesis_file(
&self,
genesis: &Genesis,
@@ -307,7 +307,7 @@ impl KitchensinkNode {
}
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
pub fn eth_rpc_version(&self) -> anyhow::Result<String> {
let output = Command::new(&self.eth_proxy_binary)
.arg("--version")
@@ -382,7 +382,7 @@ impl KitchensinkNode {
}
impl EthereumNode for KitchensinkNode {
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn execute_transaction(
&self,
transaction: alloy::rpc::types::TransactionRequest,
@@ -399,7 +399,7 @@ impl EthereumNode for KitchensinkNode {
Ok(receipt)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn trace_transaction(
&self,
transaction: &TransactionReceipt,
@@ -413,7 +413,7 @@ impl EthereumNode for KitchensinkNode {
.await?)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn state_diff(&self, transaction: &TransactionReceipt) -> anyhow::Result<DiffMode> {
let trace_options = GethDebugTracingOptions::prestate_tracer(PreStateConfig {
diff_mode: Some(true),
@@ -430,7 +430,7 @@ impl EthereumNode for KitchensinkNode {
}
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn balance_of(&self, address: Address) -> anyhow::Result<U256> {
self.provider()
.await?
@@ -439,7 +439,7 @@ impl EthereumNode for KitchensinkNode {
.map_err(Into::into)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn latest_state_proof(
&self,
address: Address,
@@ -455,7 +455,7 @@ impl EthereumNode for KitchensinkNode {
}
impl ResolverApi for KitchensinkNode {
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn chain_id(&self) -> anyhow::Result<alloy::primitives::ChainId> {
self.provider()
.await?
@@ -464,7 +464,7 @@ impl ResolverApi for KitchensinkNode {
.map_err(Into::into)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn transaction_gas_price(&self, tx_hash: &TxHash) -> anyhow::Result<u128> {
self.provider()
.await?
@@ -474,7 +474,7 @@ impl ResolverApi for KitchensinkNode {
.map(|receipt| receipt.effective_gas_price)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_gas_limit(&self, number: BlockNumberOrTag) -> anyhow::Result<u128> {
self.provider()
.await?
@@ -484,7 +484,7 @@ impl ResolverApi for KitchensinkNode {
.map(|block| block.header.gas_limit as _)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_coinbase(&self, number: BlockNumberOrTag) -> anyhow::Result<Address> {
self.provider()
.await?
@@ -494,7 +494,7 @@ impl ResolverApi for KitchensinkNode {
.map(|block| block.header.beneficiary)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_difficulty(&self, number: BlockNumberOrTag) -> anyhow::Result<U256> {
self.provider()
.await?
@@ -504,7 +504,7 @@ impl ResolverApi for KitchensinkNode {
.map(|block| U256::from_be_bytes(block.header.mix_hash.0))
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_base_fee(&self, number: BlockNumberOrTag) -> anyhow::Result<u64> {
self.provider()
.await?
@@ -519,7 +519,7 @@ impl ResolverApi for KitchensinkNode {
})
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_hash(&self, number: BlockNumberOrTag) -> anyhow::Result<BlockHash> {
self.provider()
.await?
@@ -529,7 +529,7 @@ impl ResolverApi for KitchensinkNode {
.map(|block| block.header.hash)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn block_timestamp(&self, number: BlockNumberOrTag) -> anyhow::Result<BlockTimestamp> {
self.provider()
.await?
@@ -539,7 +539,7 @@ impl ResolverApi for KitchensinkNode {
.map(|block| block.header.timestamp)
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
async fn last_block_number(&self) -> anyhow::Result<BlockNumber> {
self.provider()
.await?
@@ -587,7 +587,7 @@ impl Node for KitchensinkNode {
self.rpc_url.clone()
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
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() {
@@ -614,12 +614,12 @@ impl Node for KitchensinkNode {
Ok(())
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
fn spawn(&mut self, genesis: String) -> anyhow::Result<()> {
self.init(&genesis)?.spawn_process()
}
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id))]
#[tracing::instrument(skip_all, fields(kitchensink_node_id = self.id), err)]
fn version(&self) -> anyhow::Result<String> {
let output = Command::new(&self.substrate_binary)
.arg("--version")
+5 -6
View File
@@ -1,12 +1,12 @@
//! 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_common::fs::CachedFileSystem;
use revive_dt_config::Arguments;
use crate::Node;
@@ -23,12 +23,11 @@ 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> {
pub async fn new(config: &Arguments) -> anyhow::Result<Self> {
let nodes = config.number_of_nodes;
let genesis = read_to_string(&config.genesis_file).context(format!(
"can not read genesis file: {}",
config.genesis_file.display()
))?;
let genesis = CachedFileSystem::read_to_string(&config.genesis_file)
.await
.context("Failed to read genesis file")?;
let mut handles = Vec::with_capacity(nodes);
for _ in 0..nodes {