zebra_rpc/sync.rs
1//! Syncer task for maintaining a non-finalized state in Zebra's ReadStateService and updating `ChainTipSender` via RPCs
2
3use std::{
4 net::SocketAddr,
5 sync::Arc,
6 time::{Duration, Instant},
7};
8
9use tokio::task::JoinHandle;
10use tonic::{Status, Streaming};
11use tower::BoxError;
12use zebra_chain::{
13 block::{self, Block, Height},
14 parameters::Network,
15 serialization::BytesInDisplayOrder,
16};
17use zebra_state::{
18 spawn_init_read_only, ChainTipBlock, ChainTipChange, ChainTipSender, CheckpointVerifiedBlock,
19 HashOrHeight, LatestChainTip, NonFinalizedState, ReadStateService, SemanticallyVerifiedBlock,
20 ValidateContextError, ZebraDb,
21};
22
23use zebra_chain::diagnostic::task::WaitForPanics;
24
25use crate::indexer::{
26 indexer_client::IndexerClient, BlockAndHash, BlockRequest, Empty,
27 NonFinalizedStateChangeRequest,
28};
29
30#[cfg(test)]
31mod tests;
32
33/// How long to wait between calls to `subscribe_to_non_finalized_state_change` when it returns an error.
34const POLL_DELAY: Duration = Duration::from_secs(5);
35
36/// How long to wait for a message on a gRPC subscription stream before assuming the stream is dead
37/// and re-subscribing.
38///
39/// Generous, because legitimate gaps between blocks/tip changes can be several minutes; this is a
40/// backstop against a wedged connection that the keep-alive ping below doesn't catch. Re-subscribing
41/// is cheap and resumes from the syncer's current chain tips, so an occasional false trigger during
42/// a quiet period is harmless.
43const STREAM_MESSAGE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
44
45/// HTTP/2 keep-alive ping interval for the indexer gRPC connection, so a half-open connection is
46/// detected promptly instead of hanging a stream read indefinitely.
47const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(60);
48
49/// How long to wait for a keep-alive ping response before treating the connection as dead.
50const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20);
51
52/// How long to wait before re-subscribing after a block fails to commit to the non-finalized state.
53///
54/// A block can persistently fail to commit (e.g. [`ValidateContextError::NotReadyToBeCommitted`])
55/// when the secondary finalized state hasn't yet caught up with the primary. Without this delay,
56/// re-subscribing immediately turns that into a full-speed busy loop that saturates the logs.
57const COMMIT_RETRY_DELAY: Duration = Duration::from_secs(1);
58
59/// How long to wait before re-subscribing after a subscription stream ends or returns an error.
60///
61/// A stream ending isn't necessarily a connection failure: the server can drop a subscription while
62/// it's still reachable, and re-subscribing then succeeds and is dropped again. Without this delay
63/// that becomes a full-speed subscribe/drop loop that saturates the logs on both sides.
64const STREAM_RESTART_DELAY: Duration = Duration::from_secs(1);
65
66/// How long to wait for a single `get_block` fetch while bridging the finalized gap before giving
67/// up. A single block fetch from a co-located node should return promptly, so this bounds a wedged
68/// connection without false-triggering; the bridge retries on the next subscription.
69const GET_BLOCK_TIMEOUT: Duration = Duration::from_secs(30);
70
71/// How long to wait to establish a gRPC subscription stream before assuming the request is wedged
72/// and retrying. The subscription handshake should complete promptly.
73const SUBSCRIBE_TIMEOUT: Duration = Duration::from_secs(30);
74
75/// Syncs non-finalized blocks in the best chain from a trusted Zebra node's RPC methods.
76#[derive(Debug)]
77pub struct TrustedChainSync {
78 /// gRPC client for calling Zebra's indexer methods.
79 pub indexer_rpc_client: IndexerClient<tonic::transport::Channel>,
80 /// The read state service.
81 db: ZebraDb,
82 /// The non-finalized state - currently only contains the best chain.
83 non_finalized_state: NonFinalizedState,
84 /// The chain tip sender for updating [`LatestChainTip`] and [`ChainTipChange`].
85 chain_tip_sender: ChainTipSender,
86 /// The non-finalized state sender, for updating the [`ReadStateService`] when the non-finalized best chain changes.
87 non_finalized_state_sender: tokio::sync::watch::Sender<NonFinalizedState>,
88 /// Flipped to `true` once `sync()` receives its first parseable block from the
89 /// `non_finalized_state_change` stream, which stops [`update_finalized_chain_tip`] so `sync()`
90 /// becomes the sole caller of `try_catch_up_with_primary` on the shared secondary db.
91 started_sync_sender: tokio::sync::watch::Sender<bool>,
92}
93
94async fn update_finalized_chain_tip(
95 db: ZebraDb,
96 mut indexer_rpc_client: IndexerClient<tonic::transport::Channel>,
97 mut finalized_chain_tip_sender: ChainTipSender,
98 mut started_sync_receiver: tokio::sync::watch::Receiver<bool>,
99) {
100 let mut chain_tip_change_stream = None;
101 let mut pending_tip_update = false;
102
103 loop {
104 // Stop as soon as `sync()` has received its first parseable non-finalized block. From then
105 // on `sync()` is the sole caller of `try_catch_up_with_primary` on the shared secondary, so
106 // this task must not advance the secondary's view concurrently (which would let a block be
107 // finalized between `sync()`'s check and its commit, failing as a duplicate-effects error).
108 // `sync()` also owns the published chain tip from then on, via its (higher) non-finalized
109 // tip, so publishing our lagging finalized tip would drag the reported tip backwards.
110 if *started_sync_receiver.borrow() {
111 return;
112 }
113
114 let Some(ref mut chain_tip_change) = chain_tip_change_stream else {
115 chain_tip_change_stream = match tokio::time::timeout(
116 SUBSCRIBE_TIMEOUT,
117 indexer_rpc_client.chain_tip_change(Empty {}),
118 )
119 .await
120 {
121 Ok(Ok(response)) => Some(response.into_inner()),
122 Ok(Err(err)) => {
123 tracing::warn!(?err, "failed to subscribe to chain tip changes");
124 tokio::time::sleep(POLL_DELAY).await;
125 None
126 }
127 Err(_) => {
128 tracing::warn!("timed out subscribing to chain tip changes");
129 tokio::time::sleep(POLL_DELAY).await;
130 None
131 }
132 };
133
134 continue;
135 };
136
137 // The message is only a signal that the primary's best chain advanced. We publish our own
138 // finalized tip below, not the primary's (non-finalized) best tip, so the hash is unused.
139 //
140 // Stop immediately if `sync()` takes over while we're parked here, rather than waiting for
141 // the next chain-tip change, so we never catch up concurrently with `sync()`'s commits.
142 let message = tokio::select! {
143 biased;
144 _ = started_sync_receiver.changed() => return,
145 _ = tokio::time::sleep(POLL_DELAY), if pending_tip_update => None,
146 message = tokio::time::timeout(STREAM_MESSAGE_TIMEOUT, chain_tip_change.message()),
147 if !pending_tip_update => Some(message),
148 };
149
150 match message {
151 None | Some(Ok(Ok(Some(_)))) => {}
152 Some(Ok(Ok(None))) => {
153 tracing::warn!("chain_tip_change stream ended unexpectedly");
154 chain_tip_change_stream = None;
155 tokio::time::sleep(STREAM_RESTART_DELAY).await;
156 continue;
157 }
158 Some(Ok(Err(err))) => {
159 tracing::warn!(?err, "error receiving chain tip change");
160 chain_tip_change_stream = None;
161 tokio::time::sleep(STREAM_RESTART_DELAY).await;
162 continue;
163 }
164 Some(Err(_)) => {
165 tracing::debug!("chain tip change stream timed out, re-subscribing");
166 chain_tip_change_stream = None;
167 continue;
168 }
169 }
170 // Keep the consumed notification until a complete secondary tip can be published.
171 pending_tip_update = true;
172
173 // Don't advance the secondary or publish once `sync()` has taken over (it may have done so
174 // while we waited above), so we never catch up concurrently with `sync()`'s commits.
175 if *started_sync_receiver.borrow() {
176 return;
177 }
178
179 // Catch the secondary's finalized state up to the primary, then publish its finalized tip.
180 //
181 // This keeps the finalized tip current while the secondary is still catching up, before
182 // `TrustedChainSync::sync()` has any non-finalized blocks of its own to publish.
183 //
184 // # Correctness
185 //
186 // Catching up with the primary db instance concurrent with commits to the non-finalized state
187 // when the underlying Zebra node is syncing blocks rapidly could cause repeated commit failures.
188 if let Err(error) = db.spawn_try_catch_up_with_primary().await {
189 tracing::debug!(
190 ?error,
191 "failed to catch up to the primary database while updating the finalized tip"
192 );
193 continue;
194 }
195
196 if let Some(tip_block) = finalized_chain_tip_block(&db)
197 .await
198 .expect("`db` is a read-only secondary that returns `None` for incomplete blocks")
199 {
200 // Re-check immediately before publishing, after the awaits above: `sync()` can take over
201 // while we wait on `spawn_try_catch_up_with_primary` or `finalized_chain_tip_block`, so
202 // checking any earlier would leave a window where we still publish the stale tip.
203 //
204 // `sync()`'s `ChainTipSender` latches onto the non-finalized tip, but this task holds a
205 // separate `finalized_sender()` handle that doesn't, so `set_finalized_tip` would keep
206 // overwriting the non-finalized tip rather than becoming a no-op. The task therefore
207 // stops itself. The non-finalized state only grows once populated, so this handover is
208 // permanent.
209 if *started_sync_receiver.borrow() {
210 return;
211 }
212
213 finalized_chain_tip_sender.set_finalized_tip(tip_block);
214 pending_tip_update = false;
215 }
216 #[cfg(test)]
217 if pending_tip_update {
218 let _ = tests::INCOMPLETE_TIP_READ.try_with(|notify| notify.notify_one());
219 }
220 }
221}
222
223/// Reads the finalized tip block from the secondary db instance and converts it to a
224/// [`ChainTipBlock`].
225async fn finalized_chain_tip_block(
226 db: &ZebraDb,
227) -> Result<Option<ChainTipBlock>, zebra_state::BlockReadError> {
228 let db = db.clone();
229 tokio::task::spawn_blocking(move || {
230 let Some((height, hash)) = db.tip() else {
231 return Ok(None);
232 };
233 Ok(db
234 .block(height.into())?
235 .map(|block| CheckpointVerifiedBlock::with_hash(block, hash))
236 .map(ChainTipBlock::from))
237 })
238 .wait_for_panics()
239 .await
240}
241
242impl TrustedChainSync {
243 /// Creates a new [`TrustedChainSync`] with a [`ChainTipSender`], then spawns a task to sync blocks
244 /// from the node's non-finalized best chain.
245 ///
246 /// Returns the [`LatestChainTip`], [`ChainTipChange`], and a [`JoinHandle`] for the sync task.
247 pub async fn spawn(
248 indexer_rpc_address: SocketAddr,
249 db: ZebraDb,
250 non_finalized_state_sender: tokio::sync::watch::Sender<NonFinalizedState>,
251 ) -> Result<(LatestChainTip, ChainTipChange, JoinHandle<()>), BoxError> {
252 let non_finalized_state = NonFinalizedState::new(&db.network());
253 let (chain_tip_sender, latest_chain_tip, chain_tip_change) =
254 ChainTipSender::new(None, &db.network());
255 let channel =
256 tonic::transport::Endpoint::from_shared(format!("http://{indexer_rpc_address}"))?
257 .keep_alive_while_idle(true)
258 .http2_keep_alive_interval(KEEPALIVE_INTERVAL)
259 .keep_alive_timeout(KEEPALIVE_TIMEOUT)
260 .connect()
261 .await?;
262 let indexer_rpc_client = IndexerClient::new(channel);
263 let finalized_chain_tip_sender = chain_tip_sender.finalized_sender();
264
265 // `sync()` flips this to `true` as soon as it receives its first parseable non-finalized
266 // block, which stops `update_finalized_chain_tip` so `sync()` becomes the sole caller of
267 // `try_catch_up_with_primary` on the shared secondary db.
268 let (started_sync_sender, started_sync_receiver) = tokio::sync::watch::channel(false);
269
270 let mut syncer = Self {
271 indexer_rpc_client: indexer_rpc_client.clone(),
272 db: db.clone(),
273 non_finalized_state,
274 chain_tip_sender,
275 non_finalized_state_sender,
276 started_sync_sender,
277 };
278
279 // Spawn a task to send finalized chain tip changes to the chain tip change and latest chain tip channels.
280 tokio::spawn(async move {
281 update_finalized_chain_tip(
282 db,
283 indexer_rpc_client,
284 finalized_chain_tip_sender,
285 started_sync_receiver,
286 )
287 .await
288 });
289
290 let sync_task = tokio::spawn(async move {
291 syncer.sync().await;
292 });
293
294 Ok((latest_chain_tip, chain_tip_change, sync_task))
295 }
296
297 /// Starts syncing blocks from the node's non-finalized best chain and checking for chain tip changes in the finalized state.
298 ///
299 /// When the best chain tip in Zebra is not available in the finalized state or the local non-finalized state,
300 /// gets any unavailable blocks in Zebra's best chain from the RPC server, adds them to the local non-finalized state, then
301 /// sends the updated chain tip block and non-finalized state to the [`ChainTipSender`] and non-finalized state sender.
302 #[tracing::instrument(skip_all)]
303 async fn sync(&mut self) {
304 let mut non_finalized_blocks_listener = None;
305 // The hash of the block that most recently failed to commit, used to avoid re-logging the
306 // same warning at full rate while a block persistently fails to commit.
307 let mut last_failed_commit_hash = None;
308 // Whether we've signalled `update_finalized_chain_tip` to stop, so we only send once.
309 let mut signalled_started = false;
310 self.try_catch_up_with_primary().await;
311 if let Some(finalized_tip_block) = finalized_chain_tip_block(&self.db)
312 .await
313 .expect("`db` is a read-only secondary that returns `None` for incomplete blocks")
314 {
315 self.chain_tip_sender.set_finalized_tip(finalized_tip_block);
316 }
317
318 loop {
319 let Some(ref mut non_finalized_state_change) = non_finalized_blocks_listener else {
320 non_finalized_blocks_listener = match self
321 .subscribe_to_non_finalized_state_change()
322 .await
323 {
324 Ok(listener) => Some(listener),
325 Err(err) => {
326 tracing::warn!(?err, "failed to subscribe to non-finalized state changes");
327 tokio::time::sleep(POLL_DELAY).await;
328 None
329 }
330 };
331
332 continue;
333 };
334
335 let message = match tokio::time::timeout(
336 STREAM_MESSAGE_TIMEOUT,
337 non_finalized_state_change.message(),
338 )
339 .await
340 {
341 Ok(Ok(Some(block_and_hash))) => block_and_hash,
342 Ok(Ok(None)) => {
343 tracing::warn!("non-finalized state change stream ended unexpectedly");
344 non_finalized_blocks_listener = None;
345 tokio::time::sleep(STREAM_RESTART_DELAY).await;
346 continue;
347 }
348 Ok(Err(err)) => {
349 tracing::warn!(?err, "error receiving non-finalized state change");
350 non_finalized_blocks_listener = None;
351 tokio::time::sleep(STREAM_RESTART_DELAY).await;
352 continue;
353 }
354 Err(_) => {
355 tracing::debug!("non-finalized state change stream timed out, re-subscribing");
356 non_finalized_blocks_listener = None;
357 continue;
358 }
359 };
360
361 let Some((block, hash)) = message.decode() else {
362 tracing::warn!("received malformed non-finalized state change message");
363 non_finalized_blocks_listener = None;
364 tokio::time::sleep(STREAM_RESTART_DELAY).await;
365 continue;
366 };
367
368 // We have a parseable block from the stream, so take over the finalized tip: stop
369 // `update_finalized_chain_tip` so it no longer catches up the shared secondary db
370 // concurrently with our commits below.
371 if !signalled_started {
372 self.started_sync_sender.send_replace(true);
373 signalled_started = true;
374 }
375
376 if self.non_finalized_state.any_chain_contains(&hash) {
377 // Expected and harmless: on a resumed or multi-chain stream the server can re-send a
378 // block the syncer already has (e.g. a fork's shared ancestors), so this is logged
379 // at debug rather than warn to avoid noise.
380 tracing::debug!(
381 ?hash,
382 "non-finalized state already contains block, skipping"
383 );
384 continue;
385 }
386
387 // Skip blocks that are already finalized on the secondary. The server streams its
388 // entire non-finalized chain on initial subscription, which can start below our
389 // secondary's finalized tip when the secondary has caught up past the server's
390 // non-finalized root. Trying to commit those blocks fails with NotReadyToBeCommitted
391 // and triggers an endless re-subscribe loop.
392 if let Some(height) = block.coinbase_height() {
393 if self
394 .db
395 .finalized_tip_height()
396 .is_some_and(|tip| height <= tip)
397 {
398 tracing::debug!(?height, "skipping block already finalized on secondary");
399 continue;
400 }
401 }
402
403 // Stamp the receipt time so equal-work ties resolve like the source node: the
404 // listener streams the best chain first, so arrival order mirrors its preference.
405 let mut block = SemanticallyVerifiedBlock::with_hash(Arc::new(block), hash);
406 block.received_time = Some(Instant::now());
407 match self.try_commit(block.clone()).await {
408 Ok(()) => {
409 last_failed_commit_hash = None;
410 }
411 Err(error) => {
412 // Only log on transitions to avoid saturating the logs when the same block
413 // persistently fails to commit (e.g. when the secondary finalized state hasn't
414 // caught up with the primary yet).
415 if last_failed_commit_hash != Some(hash) {
416 tracing::warn!(
417 ?error,
418 ?hash,
419 "failed to commit block to non-finalized state"
420 );
421 last_failed_commit_hash = Some(hash);
422 }
423
424 non_finalized_blocks_listener = None;
425
426 // Back off before re-subscribing so a persistently failing block doesn't turn
427 // re-subscription into a full-speed busy loop.
428 tokio::time::sleep(COMMIT_RETRY_DELAY).await;
429 }
430 };
431 }
432 }
433
434 async fn try_commit(
435 &mut self,
436 block: SemanticallyVerifiedBlock,
437 ) -> Result<(), ValidateContextError> {
438 self.try_catch_up_with_primary().await;
439
440 // When the non-finalized state is empty and the incoming block doesn't build directly on
441 // the secondary's finalized tip, the secondary's finalized state is lagging the primary's.
442 // The streamed non-finalized blocks start at the primary's finalized tip, which can be
443 // several blocks above ours, so the incoming block has no parent to attach to. Bridge that
444 // gap by fetching the missing (already-finalized) blocks from the primary, so the incoming
445 // block has a contiguous chain to commit onto.
446 if self.non_finalized_state.best_chain().is_none()
447 && self.db.finalized_tip_hash() != block.block.header.previous_block_hash
448 {
449 self.fill_finalized_gap(block.height).await;
450 }
451
452 self.commit(block)
453 }
454
455 /// Commits `block` to the non-finalized state, starting a new chain if it builds on the
456 /// finalized tip or extending an existing chain otherwise, prunes newly-finalized blocks, and
457 /// publishes the updated chain tip and non-finalized state.
458 ///
459 /// Updating the channels here (rather than only after `try_commit` returns) means the bridge
460 /// blocks committed by [`Self::fill_finalized_gap`] also advance the published chain tip.
461 fn commit(&mut self, block: SemanticallyVerifiedBlock) -> Result<(), ValidateContextError> {
462 if self.db.finalized_tip_hash() == block.block.header.previous_block_hash {
463 self.prune_finalized();
464 self.non_finalized_state.commit_new_chain(block, &self.db)?;
465 } else {
466 self.non_finalized_state.commit_block(block, &self.db)?;
467 self.prune_finalized();
468 }
469
470 self.update_channels();
471
472 Ok(())
473 }
474
475 /// Fetches the blocks between the secondary's finalized tip and `target_height` (exclusive)
476 /// from the primary and commits them to the non-finalized state.
477 ///
478 /// These blocks are finalized on the primary but not yet on the lagging secondary. Committing
479 /// them as non-finalized bridge blocks gives the block at `target_height` a contiguous chain to
480 /// attach to; they are dropped again by [`Self::prune_finalized`] as the secondary catches up.
481 ///
482 /// This is best-effort: if a block can't be fetched or committed, it returns early and lets the
483 /// caller's commit fail so the block is retried on the next subscription.
484 async fn fill_finalized_gap(&mut self, target_height: Height) {
485 loop {
486 // Try to advance the secondary's finalized state first: if it catches up to the gap on
487 // its own, we can stop fetching blocks. This also drops any bridge blocks the secondary
488 // has since finalized, so the next height is recomputed from where we actually are.
489 self.try_catch_up_with_primary().await;
490 self.prune_finalized();
491
492 // The next height to bridge is just above the highest block we already have: the
493 // non-finalized tip if we've committed bridge blocks, otherwise the finalized tip.
494 let Some(highest) = self
495 .non_finalized_state
496 .best_tip()
497 .map(|(height, _hash)| height)
498 .max(self.db.finalized_tip_height())
499 else {
500 return;
501 };
502
503 let Ok(next_height) = highest.next() else {
504 return;
505 };
506
507 // Stop once the chain reaches the streamed block's parent, whether by the finalized
508 // state catching up or by the bridge blocks we fetched.
509 if next_height >= target_height {
510 return;
511 }
512
513 let (block, hash) = match self.get_block(next_height.into()).await {
514 Ok(block_and_hash) => block_and_hash,
515 Err(error) => {
516 tracing::warn!(
517 ?error,
518 ?next_height,
519 "failed to fetch a block while bridging the finalized gap; \
520 will retry on the next subscription"
521 );
522 return;
523 }
524 };
525
526 let mut block = SemanticallyVerifiedBlock::with_hash(Arc::new(block), hash);
527 block.received_time = Some(Instant::now());
528 if let Err(error) = self.commit(block) {
529 tracing::warn!(
530 ?error,
531 ?next_height,
532 "failed to commit a block while bridging the finalized gap; \
533 will retry on the next subscription"
534 );
535 return;
536 }
537 }
538 }
539
540 /// Fetches a single block from the primary by hash or height via the indexer gRPC.
541 async fn get_block(
542 &self,
543 hash_or_height: HashOrHeight,
544 ) -> Result<(Block, block::Hash), Status> {
545 // Encode the request as a single `hash_or_height` byte string: a 32-byte hash in display
546 // order, or a 4-byte big-endian height. The server tells them apart by length.
547 let hash_or_height = match hash_or_height {
548 HashOrHeight::Hash(hash) => hash.bytes_in_display_order().to_vec(),
549 HashOrHeight::Height(height) => height.0.to_be_bytes().to_vec(),
550 };
551 let request = BlockRequest { hash_or_height };
552
553 let response = tokio::time::timeout(
554 GET_BLOCK_TIMEOUT,
555 self.indexer_rpc_client.clone().get_block(request),
556 )
557 .await
558 .map_err(|_| Status::deadline_exceeded("get_block request timed out"))??;
559
560 response
561 .into_inner()
562 .decode()
563 .ok_or_else(|| Status::internal("failed to decode block from get_block response"))
564 }
565
566 /// Calls the `non_finalized_state_change()` method on the indexer gRPC client to subscribe
567 /// to non-finalized state changes, and returns the response stream.
568 ///
569 /// Passes the tip hashes of every chain currently in this syncer's non-finalized state so the
570 /// server only streams blocks after the tips we already have, instead of re-sending the whole
571 /// non-finalized state on every (re)subscription. When the non-finalized state is empty, the
572 /// request carries no tips and the server streams every non-finalized block.
573 async fn subscribe_to_non_finalized_state_change(
574 &mut self,
575 ) -> Result<Streaming<BlockAndHash>, Status> {
576 let request = NonFinalizedStateChangeRequest {
577 chain_tip_hashes: self
578 .non_finalized_state
579 .chain_iter()
580 .map(|c| c.non_finalized_tip_hash().bytes_in_display_order().to_vec())
581 .collect(),
582 };
583
584 tokio::time::timeout(
585 SUBSCRIBE_TIMEOUT,
586 self.indexer_rpc_client
587 .clone()
588 .non_finalized_state_change(request),
589 )
590 .await
591 .map_err(|_| {
592 Status::deadline_exceeded("non_finalized_state_change subscription timed out")
593 })?
594 .map(|a| a.into_inner())
595 }
596
597 /// Tries to catch up to the primary db instance for an up-to-date view of finalized blocks.
598 async fn try_catch_up_with_primary(&self) {
599 let _ = self.db.spawn_try_catch_up_with_primary().await;
600 }
601
602 /// Finalizes any non-finalized blocks that are at or below the finalized tip height.
603 ///
604 /// The secondary's finalized state follows the primary, so after catching up it may have
605 /// advanced past the root of the non-finalized state. This drops those now-finalized blocks so
606 /// the non-finalized state only tracks blocks above the finalized tip. Does nothing when the
607 /// non-finalized state is empty.
608 fn prune_finalized(&mut self) {
609 let finalized_tip_height = self.db.finalized_tip_height().unwrap_or(Height::MIN);
610 while self
611 .non_finalized_state
612 .root_height()
613 .is_some_and(|root_height| root_height <= finalized_tip_height)
614 {
615 tracing::trace!("finalizing block past the reorg limit");
616 self.non_finalized_state.finalize();
617 }
618 }
619
620 /// Sends the new chain tip and non-finalized state to the latest chain channels.
621 // TODO: Replace this with the `update_latest_chain_channels()` fn in `write.rs`.
622 fn update_channels(&mut self) {
623 // If the final receiver was just dropped, ignore the error.
624 let _ = self
625 .non_finalized_state_sender
626 .send(self.non_finalized_state.clone());
627
628 let best_chain = self.non_finalized_state.best_chain().expect("unexpected empty non-finalized state: must commit at least one block before updating channels");
629
630 let tip_block = best_chain
631 .tip_block()
632 .expect(
633 "unexpected empty chain: must commit at least one block before updating channels",
634 )
635 .clone();
636
637 self.chain_tip_sender
638 .set_best_non_finalized_tip(Some(tip_block.into()));
639 }
640}
641
642/// Accepts a [zebra-state configuration](zebra_state::Config), a [`Network`], and
643/// the [`SocketAddr`] of a Zebra node's RPC server.
644///
645/// Initializes a [`ReadStateService`] and a [`TrustedChainSync`] to update the
646/// non-finalized best chain and the latest chain tip.
647///
648/// Returns a [`ReadStateService`], [`LatestChainTip`], [`ChainTipChange`], and
649/// a [`JoinHandle`] for the sync task.
650pub fn init_read_state_with_syncer(
651 config: zebra_state::Config,
652 network: &Network,
653 indexer_rpc_address: SocketAddr,
654) -> tokio::task::JoinHandle<
655 Result<
656 (
657 ReadStateService,
658 LatestChainTip,
659 ChainTipChange,
660 tokio::task::JoinHandle<()>,
661 ),
662 BoxError,
663 >,
664> {
665 let network = network.clone();
666 tokio::spawn(async move {
667 if config.ephemeral {
668 return Err("standalone read state service cannot be used with ephemeral state".into());
669 }
670
671 // The outer `?` propagates a `JoinError` if the blocking task panicked or was
672 // cancelled, and the inner `?` propagates a `StateInitError` (e.g. a missing
673 // read-only database).
674 let (read_state, db, non_finalized_state_sender) =
675 spawn_init_read_only(config, &network).await??;
676 let (latest_chain_tip, chain_tip_change, sync_task) =
677 TrustedChainSync::spawn(indexer_rpc_address, db, non_finalized_state_sender).await?;
678 Ok((read_state, latest_chain_tip, chain_tip_change, sync_task))
679 })
680}