Skip to content

Commit f7defa3

Browse files
committed
refactor: attach host block header to SimEnv
1 parent 3e98b2e commit f7defa3

File tree

9 files changed

+204
-129
lines changed

9 files changed

+204
-129
lines changed

bin/builder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ async fn main() -> eyre::Result<()> {
2222
let constants = SignetSystemConstants::pecorino();
2323

2424
// Spawn the EnvTask
25-
let env_task = config.env_task();
25+
let env_task = config.env_task().await;
2626
let (block_env, env_jh) = env_task.spawn();
2727

2828
// Spawn the cache system

src/config.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{
33
tasks::{
44
block::cfg::SignetCfgEnv,
55
cache::{BundlePoller, CacheSystem, CacheTask, TxPoller},
6-
env::EnvTask,
6+
env::{EnvTask, SimEnv},
77
},
88
};
99
use alloy::{
@@ -29,7 +29,6 @@ use init4_bin_base::{
2929
use signet_zenith::Zenith;
3030
use std::borrow::Cow;
3131
use tokio::sync::watch;
32-
use trevm::revm::context::BlockEnv;
3332

3433
/// Type alias for the provider used to simulate against rollup state.
3534
pub type RuProvider = RootProvider<Ethereum>;
@@ -246,17 +245,19 @@ impl BuilderConfig {
246245
}
247246

248247
/// Create an [`EnvTask`] using this config.
249-
pub fn env_task(&self) -> EnvTask {
250-
let provider = self.connect_ru_provider();
251-
EnvTask::new(self.clone(), provider)
248+
pub async fn env_task(&self) -> EnvTask {
249+
let ru_provider = self.connect_ru_provider();
250+
let host_provider =
251+
self.connect_host_provider().await.expect("failed to configure host provider");
252+
EnvTask::new(self.clone(), ru_provider, host_provider)
252253
}
253254

254255
/// Spawn a new [`CacheSystem`] using this config. This contains the
255256
/// joinhandles for [`TxPoller`] and [`BundlePoller`] and [`CacheTask`], as
256257
/// well as the [`SimCache`] and the block env watcher.
257258
///
258259
/// [`SimCache`]: signet_sim::SimCache
259-
pub fn spawn_cache_system(&self, block_env: watch::Receiver<Option<BlockEnv>>) -> CacheSystem {
260+
pub fn spawn_cache_system(&self, block_env: watch::Receiver<Option<SimEnv>>) -> CacheSystem {
260261
// Tx Poller pulls transactions from the cache
261262
let tx_poller = TxPoller::new(self);
262263
let (tx_receiver, tx_poller) = tx_poller.spawn();

src/tasks/block/sim.rs

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
//! `block.rs` contains the Simulator and everything that wires it into an
22
//! actor that handles the simulation of a stream of bundles and transactions
33
//! and turns them into valid Pecorino blocks for network submission.
4-
use crate::config::{BuilderConfig, RuProvider};
5-
use alloy::{eips::BlockId, network::Ethereum, providers::Provider};
4+
use crate::{
5+
config::{BuilderConfig, RuProvider},
6+
tasks::env::SimEnv,
7+
};
8+
use alloy::{
9+
eips::BlockId,
10+
network::Ethereum,
11+
providers::Provider,
12+
};
613
use init4_bin_base::{
714
deps::tracing::{debug, error},
815
utils::calc::SlotCalculator,
916
};
1017
use signet_sim::{BlockBuild, BuiltBlock, SimCache};
1118
use signet_types::constants::SignetSystemConstants;
19+
use tracing::info;
1220
use std::time::{Duration, Instant};
1321
use tokio::{
1422
sync::{
@@ -35,7 +43,7 @@ pub struct Simulator {
3543
/// A provider that cannot sign transactions, used for interacting with the rollup.
3644
pub ru_provider: RuProvider,
3745
/// The block configuration environment on which to simulate
38-
pub block_env: watch::Receiver<Option<BlockEnv>>,
46+
pub sim_env: watch::Receiver<Option<SimEnv>>,
3947
}
4048

4149
/// SimResult bundles a BuiltBlock to the BlockEnv it was simulated against.
@@ -44,7 +52,7 @@ pub struct SimResult {
4452
/// The block built with the successfully simulated transactions
4553
pub block: BuiltBlock,
4654
/// The block environment the transactions were simulated against.
47-
pub env: BlockEnv,
55+
pub env: SimEnv,
4856
}
4957

5058
impl Simulator {
@@ -62,9 +70,9 @@ impl Simulator {
6270
pub fn new(
6371
config: &BuilderConfig,
6472
ru_provider: RuProvider,
65-
block_env: watch::Receiver<Option<BlockEnv>>,
73+
sim_env: watch::Receiver<Option<SimEnv>>,
6674
) -> Self {
67-
Self { config: config.clone(), ru_provider, block_env }
75+
Self { config: config.clone(), ru_provider, sim_env }
6876
}
6977

7078
/// Get the slot calculator.
@@ -74,6 +82,10 @@ impl Simulator {
7482

7583
/// Handles building a single block.
7684
///
85+
/// Builds a block in the block environment with items from the simulation cache
86+
/// against the database state. When the `finish_by` deadline is reached, it
87+
/// stops simulating and returns the block.
88+
///
7789
/// # Arguments
7890
///
7991
/// - `constants`: The system constants for the rollup.
@@ -93,7 +105,6 @@ impl Simulator {
93105
) -> eyre::Result<BuiltBlock> {
94106
debug!(
95107
block_number = block_env.number,
96-
?finish_by,
97108
tx_count = sim_items.len(),
98109
"starting block build",
99110
);
@@ -114,15 +125,15 @@ impl Simulator {
114125
let built_block = block_build.build().await;
115126
debug!(
116127
tx_count = built_block.tx_count(),
117-
block_number = ?built_block.block_number(),
128+
block_number = built_block.block_number(),
118129
"block simulation completed",
119130
);
120131

121132
Ok(built_block)
122133
}
123134

124-
/// Spawns the simulator task, which handles the setup and sets the deadline
125-
/// for the each round of simulation.
135+
/// Spawns the simulator task, which ticks along the simulation loop
136+
/// as it receives block environments.
126137
///
127138
/// # Arguments
128139
///
@@ -144,14 +155,16 @@ impl Simulator {
144155
tokio::spawn(async move { self.run_simulator(constants, cache, submit_sender).await })
145156
}
146157

147-
/// Continuously runs the block simulation and submission loop.
158+
/// This function runs indefinitely, waiting for the block environment to be set and checking
159+
/// if the current slot is valid before building a block and sending it along for to the submit channel.
148160
///
149-
/// This function clones the simulation cache, calculates a deadline for block building,
150-
/// attempts to build a block using the latest cache and constants, and submits the built
151-
/// block through the provided channel. If an error occurs during block building or submission,
152-
/// it logs the error and continues the loop.
153-
///
154-
/// This function runs indefinitely and never returns.
161+
/// If it is authorized for the current slot, then the simulator task
162+
/// - clones the simulation cache,
163+
/// - calculates a deadline for block building,
164+
/// - attempts to build a block using the latest cache and constants,
165+
/// - then submits the built block through the provided channel.
166+
///
167+
/// If an error occurs during block building or submission, it logs the error and continues the loop.
155168
///
156169
/// # Arguments
157170
///
@@ -166,19 +179,23 @@ impl Simulator {
166179
) {
167180
loop {
168181
// Wait for the block environment to be set
169-
if self.block_env.changed().await.is_err() {
170-
error!("block_env channel closed");
182+
if self.sim_env.changed().await.is_err() {
183+
error!("block_env channel closed - shutting down simulator task");
171184
return;
172185
}
186+
let Some(sim_env) = self.sim_env.borrow_and_update().clone() else { return };
187+
info!(block_number = sim_env.signet.number, "new block environment received");
173188

174-
let Some(block_env) = self.block_env.borrow_and_update().clone() else { return };
175-
189+
// Calculate the deadline for this block simulation.
190+
// NB: This must happen _after_ taking a reference to the sim cache,
191+
// waiting for a new block, and checking current slot authorization.
176192
let finish_by = self.calculate_deadline();
177193
let sim_cache = cache.clone();
178-
match self.handle_build(constants, sim_cache, finish_by, block_env.clone()).await {
194+
match self.handle_build(constants, sim_cache, finish_by, sim_env.signet.clone()).await
195+
{
179196
Ok(block) => {
180-
debug!(block = ?block.block_number(), tx_count = block.transactions().len(), "built block");
181-
let _ = submit_sender.send(SimResult { block, env: block_env });
197+
debug!(block = ?block.block_number(), tx_count = block.transactions().len(), "built simulated block");
198+
let _ = submit_sender.send(SimResult { block, env: sim_env });
182199
}
183200
Err(e) => {
184201
error!(err = %e, "failed to build block");

src/tasks/cache/task.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ use tokio::{
66
sync::{mpsc, watch},
77
task::JoinHandle,
88
};
9-
use trevm::revm::context::BlockEnv;
9+
10+
use crate::tasks::env::SimEnv;
1011

1112
/// Cache task for the block builder.
1213
///
@@ -16,8 +17,7 @@ use trevm::revm::context::BlockEnv;
1617
#[derive(Debug)]
1718
pub struct CacheTask {
1819
/// The channel to receive the block environment.
19-
env: watch::Receiver<Option<BlockEnv>>,
20-
20+
env: watch::Receiver<Option<SimEnv>>,
2121
/// The channel to receive the transaction bundles.
2222
bundles: mpsc::UnboundedReceiver<TxCacheBundle>,
2323
/// The channel to receive the transactions.
@@ -27,7 +27,7 @@ pub struct CacheTask {
2727
impl CacheTask {
2828
/// Create a new cache task with the given cache and channels.
2929
pub const fn new(
30-
env: watch::Receiver<Option<BlockEnv>>,
30+
env: watch::Receiver<Option<SimEnv>>,
3131
bundles: mpsc::UnboundedReceiver<TxCacheBundle>,
3232
txns: mpsc::UnboundedReceiver<TxEnvelope>,
3333
) -> Self {
@@ -45,10 +45,10 @@ impl CacheTask {
4545
break;
4646
}
4747
if let Some(env) = self.env.borrow_and_update().as_ref() {
48-
basefee = env.basefee;
49-
info!(basefee, number = env.number, timestamp = env.timestamp, "block env changed, clearing cache");
48+
basefee = env.signet.basefee;
49+
info!(basefee, env.signet.number, env.signet.timestamp, "rollup block env changed, clearing cache");
5050
cache.clean(
51-
env.number, env.timestamp
51+
env.signet.number, env.signet.timestamp
5252
);
5353
}
5454
}

0 commit comments

Comments
 (0)