Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brave-owls-toggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nomicfoundation/edr": minor
---

Added `Provider::setIncludeCallTraces` method to change which call traces are collected for subsequent requests
10 changes: 10 additions & 0 deletions crates/edr_napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ export declare class Provider {
* `false` to disable this.
*/
setVerboseTracing(verboseTracing: boolean): Promise<void>
/**
* Sets which transactions' call traces the `traces()` and `callTraces()`
* of later responses include. Requests handled after the returned promise
* resolves use the new value.
*
* Traces that are not included are never collected. Consumers that read
* traces conditionally can keep this at `IncludeTraces.None` while
* nothing reads them, and avoid the collection cost.
*/
setIncludeCallTraces(includeCallTraces: IncludeTraces): Promise<void>
}

export declare class ProviderFactory {}
Expand Down
7 changes: 7 additions & 0 deletions crates/edr_napi/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,11 @@ impl SyncProvider for MockProvider {
fn set_verbose_tracing(&self, _enabled: bool) -> napi::Result<()> {
Ok(())
}

fn set_include_call_traces(
&self,
_include_call_traces: edr_solidity::config::IncludeTraces,
) -> napi::Result<()> {
Ok(())
}
}
27 changes: 24 additions & 3 deletions crates/edr_napi/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use self::factory::ProviderFactory;
use self::response::{call_trace_external_mem_size, GcResponse, Response};
use crate::{
async_deallocator::AsyncDeallocatorSender, call_override::CallOverrideCallback,
contract_decoder::ContractDecoder, gc::gc_tracked,
contract_decoder::ContractDecoder, gc::gc_tracked, solidity_tests::config::IncludeTraces,
};

/// A JSON-RPC provider for Ethereum.
Expand All @@ -39,8 +39,9 @@ pub struct Provider {
/// enabled.
record_stack: StackSnapshotType,
/// What a response reports to V8 for each call trace arena it carries.
/// Follows the recorded stack snapshots, which
/// [`Self::set_verbose_tracing`] changes.
/// Follows the stack snapshots recorded while call traces are included,
/// which [`Self::set_verbose_tracing`] changes. Responses carry no arenas
/// otherwise.
call_trace_external_mem_size: AtomicI64,
#[cfg(feature = "scenarios")]
scenario_file: Option<Arc<napi::tokio::sync::Mutex<napi::tokio::fs::File>>>,
Expand Down Expand Up @@ -318,6 +319,26 @@ impl Provider {
.await
.map_err(|error| napi::Error::new(Status::GenericFailure, error.to_string()))?
}

/// Sets which transactions' call traces the `traces()` and `callTraces()`
/// of later responses include. Requests handled after the returned promise
/// resolves use the new value.
///
/// Traces that are not included are never collected. Consumers that read
/// traces conditionally can keep this at `IncludeTraces.None` while
/// nothing reads them, and avoid the collection cost.
#[napi(catch_unwind)]
pub async fn set_include_call_traces(
&self,
include_call_traces: IncludeTraces,
) -> napi::Result<()> {
let provider = self.provider.clone();

self.runtime
.spawn_blocking(move || provider.set_include_call_traces(include_call_traces.into()))
.await
.map_err(|error| napi::Error::new(Status::GenericFailure, error.to_string()))?
}
}

gc_tracked! {
Expand Down
29 changes: 25 additions & 4 deletions crates/edr_napi/test/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,8 @@ describe("Provider", () => {
assert.deepEqual(steps[3].stack, [1n, 2n, 3n]);
});

async function pushThreeAndStopStacks(
provider: Provider
): Promise<bigint[][]> {
const responseObject = await provider.handleRequest(
function sendPushThreeAndStop(provider: Provider): Promise<Response> {
return provider.handleRequest(
JSON.stringify({
id: 1,
jsonrpc: "2.0",
Expand All @@ -263,6 +261,12 @@ describe("Provider", () => {
],
})
);
}

async function pushThreeAndStopStacks(
provider: Provider
): Promise<bigint[][]> {
const responseObject = await sendPushThreeAndStop(provider);

const rawTraces = responseObject.traces();
assert.lengthOf(rawTraces, 1);
Expand Down Expand Up @@ -311,6 +315,23 @@ describe("Provider", () => {
assert.deepEqual(await pushThreeAndStopStacks(provider), TOP_OF_STACK);
});

it("should follow setIncludeCallTraces for subsequent requests", async function () {
const provider = await createGenericProvider(context, {
genesisState: fundedGenesisState(),
observability: {
recordStack: StackSnapshotType.Top,
},
});

assert.lengthOf((await sendPushThreeAndStop(provider)).traces(), 0);

await provider.setIncludeCallTraces(IncludeTraces.All);
assert.deepEqual(await pushThreeAndStopStacks(provider), TOP_OF_STACK);

await provider.setIncludeCallTraces(IncludeTraces.None);
assert.lengthOf((await sendPushThreeAndStop(provider)).traces(), 0);
});

it("should include the top of the stack across nested call frames", async function () {
const provider = await createGenericProvider(context, {
...tracingProviderOverrides,
Expand Down
10 changes: 10 additions & 0 deletions crates/edr_napi_core/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{str::FromStr as _, sync::Arc};

use edr_provider::{time::TimeSinceEpoch, InvalidRequestReason, SyncCallOverride};
use edr_rpc_client::jsonrpc;
use edr_solidity::config::IncludeTraces;

pub use self::config::{Config, ConfigOption};
use crate::spec::{Response, SyncNapiSpec};
Expand Down Expand Up @@ -34,6 +35,10 @@ pub trait SyncProvider: Send + Sync {

/// Set the verbose tracing flag to the provided value.
fn set_verbose_tracing(&self, enabled: bool) -> napi::Result<()>;

/// Sets which transactions' call traces are included in responses, for
/// requests handled from this point on.
fn set_include_call_traces(&self, include_call_traces: IncludeTraces) -> napi::Result<()>;
}

impl<ChainSpecT: SyncNapiSpec<TimerT>, TimerT: Clone + TimeSinceEpoch> SyncProvider
Expand Down Expand Up @@ -72,6 +77,11 @@ impl<ChainSpecT: SyncNapiSpec<TimerT>, TimerT: Clone + TimeSinceEpoch> SyncProvi
edr_provider::Provider::set_verbose_tracing(self, enabled)
.map_err(|error| napi::Error::new(napi::Status::GenericFailure, error.to_string()))
}

fn set_include_call_traces(&self, include_call_traces: IncludeTraces) -> napi::Result<()> {
edr_provider::Provider::set_include_call_traces(self, include_call_traces)
.map_err(|error| napi::Error::new(napi::Status::GenericFailure, error.to_string()))
}
}

/// Constructs the JSON-RPC error response for a request that failed to
Expand Down
5 changes: 5 additions & 0 deletions crates/edr_provider/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,11 @@ where
self.observability.verbose_raw_tracing = verbose_tracing;
}

/// Sets which transactions' call traces responses include.
pub fn set_include_call_traces(&mut self, include_call_traces: IncludeTraces) {
self.observability.include_call_traces = include_call_traces;
}

pub fn stop_impersonating_account(&mut self, address: Address) -> bool {
self.impersonated_accounts.remove(&address)
}
Expand Down
12 changes: 12 additions & 0 deletions crates/edr_provider/src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::{
use crossbeam_channel::{Receiver, Sender};
use edr_chain_spec::TransactionValidation;
use edr_chain_spec_provider::ProviderChainSpec;
use edr_solidity::config::IncludeTraces;
use edr_transaction::{IsEip155, IsEip4844, TransactionMut, TransactionType};

use crate::{
Expand Down Expand Up @@ -90,6 +91,11 @@ pub(crate) enum Message<ChainSpecT: ProviderChainSpec> {
},
/// Set whether traces include the full stack and memory.
SetVerboseTracing { enabled: bool, ack: Sender<()> },
/// Set which transactions' call traces responses include.
SetIncludeCallTraces {
include_call_traces: IncludeTraces,
ack: Sender<()>,
},
/// Log a failed request deserialization through the provider's logger.
/// Not acknowledged, so a caller on the JS main thread is never blocked.
LogFailedDeserialization {
Expand Down Expand Up @@ -172,6 +178,12 @@ pub(crate) fn run<ChainSpecT, TimerT>(
// Ignore the error: the caller may have stopped waiting.
let _ = ack.send(());
}
Ok(Message::SetIncludeCallTraces { include_call_traces, ack }) => {
data.set_include_call_traces(include_call_traces);

// Ignore the error: the caller may have stopped waiting.
let _ = ack.send(());
}
Ok(Message::LogFailedDeserialization { method_name, error }) => {
if let Err(error) = data
.logger_mut()
Expand Down
58 changes: 53 additions & 5 deletions crates/edr_provider/src/observability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ pub struct ObservabilityConfig {
pub include_call_traces: IncludeTraces,
pub on_collected_coverage_fn: Option<Box<dyn SyncOnCollectedCoverageCallback>>,
pub on_collected_gas_report_fn: Option<Box<dyn SyncOnCollectedGasReportCallback>>,
/// How much of the stack each recorded step carries.
/// How much of the stack each recorded step carries while call traces are
/// included.
pub record_stack: StackSnapshotType,
/// Records the full stack and memory while enabled. `record_stack` keeps
/// its configured value meanwhile.
Expand All @@ -59,18 +60,33 @@ pub struct ObservabilityConfig {

impl ObservabilityConfig {
/// Whether recorded steps carry a memory snapshot.
///
/// Never while call traces are excluded from responses. Only
/// `Response::traces()` reads step snapshots, and it only has call traces
/// to read when they are included.
pub fn records_memory(&self) -> bool {
self.verbose_raw_tracing
self.includes_call_traces() && self.verbose_raw_tracing
}

/// How much of the stack recorded steps carry.
///
/// Nothing while call traces are excluded from responses, for the same
/// reason as [`Self::records_memory`].
pub fn recorded_stack(&self) -> StackSnapshotType {
recorded_stack(self.record_stack, self.verbose_raw_tracing)
if self.includes_call_traces() {
recorded_stack(self.record_stack, self.verbose_raw_tracing)
} else {
StackSnapshotType::None
}
}

fn includes_call_traces(&self) -> bool {
!matches!(self.include_call_traces, IncludeTraces::None)
}
}

/// How much of the stack recorded steps carry, given the configured amount and
/// whether verbose raw tracing is enabled.
/// How much of the stack recorded steps carry while call traces are included,
/// given the configured amount and whether verbose raw tracing is enabled.
pub const fn recorded_stack(
record_stack: StackSnapshotType,
verbose_raw_tracing: bool,
Expand Down Expand Up @@ -455,3 +471,35 @@ pub(crate) fn observe_execution<
include_call_traces,
})
}

#[cfg(test)]
mod tests {
use super::*;

fn config_recording_everything(include_call_traces: IncludeTraces) -> ObservabilityConfig {
ObservabilityConfig {
include_call_traces,
record_stack: StackSnapshotType::Top,
verbose_raw_tracing: true,
..ObservabilityConfig::default()
}
}

#[test]
fn records_no_snapshots_while_call_traces_are_excluded() {
let config = config_recording_everything(IncludeTraces::None);

assert!(!config.records_memory());
assert_eq!(config.recorded_stack(), StackSnapshotType::None);
}

#[test]
fn records_snapshots_while_call_traces_are_included() {
for include_call_traces in [IncludeTraces::Failing, IncludeTraces::All] {
let config = config_recording_everything(include_call_traces);

assert!(config.records_memory());
assert_eq!(config.recorded_stack(), StackSnapshotType::Full);
}
}
}
16 changes: 15 additions & 1 deletion crates/edr_provider/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{marker::PhantomData, sync::Arc};

use crossbeam_channel::{bounded, unbounded, RecvError, Sender};
use edr_chain_spec::{ProtocolHardforkChainSpec, TransactionValidation};
use edr_solidity::contract_decoder::ContractDecoder;
use edr_solidity::{config::IncludeTraces, contract_decoder::ContractDecoder};
use edr_transaction::{IsEip155, IsEip4844, TransactionMut, TransactionType};
use edr_utils_sync::CancellableThread;
use parking_lot::RwLock;
Expand Down Expand Up @@ -105,6 +105,20 @@ impl<ChainSpecT: SyncProviderSpec<TimerT>, TimerT: Clone + TimeSinceEpoch>
let _ = self.send_message(Message::SetVerboseTracing { enabled, ack });
})
}

/// Sets which transactions' call traces are included in responses, for
/// requests handled from this point on.
pub fn set_include_call_traces(
&self,
include_call_traces: IncludeTraces,
) -> Result<(), ProviderErrorForChainSpec<ChainSpecT>> {
Self::wait_for_reply(|ack| {
let _ = self.send_message(Message::SetIncludeCallTraces {
include_call_traces,
ack,
});
})
}
}

impl<
Expand Down
Loading
Loading