|
| 1 | +//! Remote block source add-on for importing blocks from a remote L2 node |
| 2 | +//! and building new blocks on top. |
| 3 | +
|
| 4 | +use crate::args::RemoteBlockSourceArgs; |
| 5 | +use alloy_primitives::Signature; |
| 6 | +use alloy_provider::{Provider, ProviderBuilder}; |
| 7 | +use alloy_rpc_client::RpcClient; |
| 8 | +use alloy_transport::layers::RetryBackoffLayer; |
| 9 | +use futures::StreamExt; |
| 10 | +use reth_network_api::{FullNetwork, PeerId}; |
| 11 | +use reth_scroll_node::ScrollNetworkPrimitives; |
| 12 | +use reth_tasks::shutdown::Shutdown; |
| 13 | +use reth_tokio_util::EventStream; |
| 14 | +use rollup_node_chain_orchestrator::{ChainOrchestratorEvent, ChainOrchestratorHandle}; |
| 15 | +use scroll_alloy_network::Scroll; |
| 16 | +use scroll_network::NewBlockWithPeer; |
| 17 | +use tokio::time::{interval, Duration}; |
| 18 | + |
| 19 | +/// Remote block source add-on that imports blocks from a trusted remote L2 node |
| 20 | +/// and triggers block building on top of each imported block. |
| 21 | +#[derive(Debug)] |
| 22 | +pub struct RemoteBlockSourceAddOn<N> |
| 23 | +where |
| 24 | + N: FullNetwork<Primitives = ScrollNetworkPrimitives>, |
| 25 | +{ |
| 26 | + /// Configuration for the remote block source. |
| 27 | + config: RemoteBlockSourceArgs, |
| 28 | + /// Handle to the chain orchestrator for sending commands. |
| 29 | + handle: ChainOrchestratorHandle<N>, |
| 30 | + /// Tracks the last block number we imported from remote. |
| 31 | + /// This is different from local head because we build blocks on top of imports. |
| 32 | + last_imported_block: u64, |
| 33 | +} |
| 34 | + |
| 35 | +impl<N> RemoteBlockSourceAddOn<N> |
| 36 | +where |
| 37 | + N: FullNetwork<Primitives = ScrollNetworkPrimitives> + Send + Sync + 'static, |
| 38 | +{ |
| 39 | + /// Creates a new remote block source add-on. |
| 40 | + pub async fn new( |
| 41 | + config: RemoteBlockSourceArgs, |
| 42 | + handle: ChainOrchestratorHandle<N>, |
| 43 | + ) -> eyre::Result<Self> { |
| 44 | + let last_imported_block = handle.status().await?.l2.fcs.head_block_info().number; |
| 45 | + Ok(Self { config, handle, last_imported_block }) |
| 46 | + } |
| 47 | + |
| 48 | + /// Runs the remote block source until shutdown. |
| 49 | + pub async fn run_until_shutdown(mut self, mut shutdown: Shutdown) -> eyre::Result<()> { |
| 50 | + let Some(url) = self.config.url.clone() else { |
| 51 | + tracing::error!(target: "scroll::remote_source", "URL required when remote-source is enabled"); |
| 52 | + return Err(eyre::eyre!("URL required when remote-source is enabled")); |
| 53 | + }; |
| 54 | + |
| 55 | + // Build remote provider with retry layer |
| 56 | + let retry_layer = RetryBackoffLayer::new(10, 100, 330); |
| 57 | + let client = RpcClient::builder().layer(retry_layer).http(url); |
| 58 | + let remote = ProviderBuilder::<_, _, Scroll>::default().connect_client(client); |
| 59 | + |
| 60 | + // Get event listener for waiting on block completion |
| 61 | + let mut event_stream = match self.handle.get_event_listener().await { |
| 62 | + Ok(stream) => stream, |
| 63 | + Err(e) => { |
| 64 | + tracing::error!(target: "scroll::remote_source", ?e, "Failed to get event listener"); |
| 65 | + return Err(eyre::eyre!(e)); |
| 66 | + } |
| 67 | + }; |
| 68 | + |
| 69 | + let mut poll_interval = interval(Duration::from_millis(self.config.poll_interval_ms)); |
| 70 | + |
| 71 | + loop { |
| 72 | + tokio::select! { |
| 73 | + biased; |
| 74 | + _guard = &mut shutdown => break, |
| 75 | + _ = poll_interval.tick() => { |
| 76 | + if let Err(e) = self.follow_and_build(&remote, &mut event_stream).await { |
| 77 | + tracing::error!(target: "scroll::remote_source", ?e, "Sync error"); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + Ok(()) |
| 84 | + } |
| 85 | + |
| 86 | + /// Follows the remote node and builds blocks on top of imported blocks. |
| 87 | + async fn follow_and_build<P: Provider<Scroll>>( |
| 88 | + &mut self, |
| 89 | + remote: &P, |
| 90 | + event_stream: &mut EventStream<ChainOrchestratorEvent>, |
| 91 | + ) -> eyre::Result<()> { |
| 92 | + loop { |
| 93 | + // Get remote head |
| 94 | + let remote_block = remote |
| 95 | + .get_block_by_number(alloy_eips::BlockNumberOrTag::Latest) |
| 96 | + .full() |
| 97 | + .await? |
| 98 | + .ok_or_else(|| eyre::eyre!("Remote block not found"))?; |
| 99 | + |
| 100 | + let remote_head = remote_block.header.number; |
| 101 | + |
| 102 | + // Compare against last imported block |
| 103 | + if remote_head <= self.last_imported_block { |
| 104 | + tracing::trace!(target: "scroll::remote_source", |
| 105 | + last_imported = self.last_imported_block, |
| 106 | + remote_head, |
| 107 | + "Already synced with remote"); |
| 108 | + return Ok(()); |
| 109 | + } |
| 110 | + |
| 111 | + let blocks_behind = remote_head - self.last_imported_block; |
| 112 | + tracing::info!(target: "scroll::remote_source", |
| 113 | + last_imported = self.last_imported_block, |
| 114 | + remote_head, |
| 115 | + blocks_behind, |
| 116 | + "Catching up"); |
| 117 | + |
| 118 | + // Fetch and import the next block from remote |
| 119 | + let next_block_num = self.last_imported_block + 1; |
| 120 | + let block = remote |
| 121 | + .get_block_by_number(next_block_num.into()) |
| 122 | + .full() |
| 123 | + .await? |
| 124 | + .ok_or_else(|| eyre::eyre!("Block {} not found", next_block_num))? |
| 125 | + .into_consensus() |
| 126 | + .map_transactions(|tx| tx.inner.into_inner()); |
| 127 | + |
| 128 | + // Create NewBlockWithPeer with dummy peer_id and signature (trusted source) |
| 129 | + let block_with_peer = NewBlockWithPeer { |
| 130 | + peer_id: PeerId::default(), |
| 131 | + block, |
| 132 | + signature: Signature::new(Default::default(), Default::default(), false), |
| 133 | + }; |
| 134 | + |
| 135 | + // Import the block (this will cause a reorg if we had a locally built block at this |
| 136 | + // height) |
| 137 | + let chain_import = match self.handle.import_block(block_with_peer).await { |
| 138 | + Ok(Ok(chain_import)) => { |
| 139 | + self.last_imported_block = next_block_num; |
| 140 | + chain_import |
| 141 | + } |
| 142 | + Ok(Err(e)) => { |
| 143 | + return Err(eyre::eyre!("Import block failed: {}", e)); |
| 144 | + } |
| 145 | + Err(e) => { |
| 146 | + return Err(eyre::eyre!("chain orchestrator command channel error: {}", e)); |
| 147 | + } |
| 148 | + }; |
| 149 | + |
| 150 | + if !chain_import.result.is_valid() { |
| 151 | + tracing::info!(target: "scroll::remote_source", |
| 152 | + result = ?chain_import.result, |
| 153 | + "Imported block is not valid according to forkchoice, skipping build"); |
| 154 | + continue; |
| 155 | + } |
| 156 | + |
| 157 | + // Trigger block building on top of the imported block |
| 158 | + self.handle.build_block(); |
| 159 | + |
| 160 | + // Wait for BlockSequenced event |
| 161 | + tracing::debug!(target: "scroll::remote_source", "Waiting for block to be built..."); |
| 162 | + loop { |
| 163 | + match event_stream.next().await { |
| 164 | + Some(ChainOrchestratorEvent::BlockSequenced(block)) => { |
| 165 | + tracing::info!(target: "scroll::remote_source", |
| 166 | + block_number = block.header.number, |
| 167 | + block_hash = ?block.hash_slow(), |
| 168 | + "Block built successfully, proceeding to next"); |
| 169 | + break; |
| 170 | + } |
| 171 | + Some(_) => { |
| 172 | + // Ignore other events, keep waiting |
| 173 | + } |
| 174 | + None => { |
| 175 | + return Err(eyre::eyre!("Event stream ended unexpectedly")); |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + // Loop continues to process next block |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments