1use std::{
4 path::{Path, PathBuf},
5 sync::Arc,
6};
7
8use indexmap::IndexMap;
9use tokio::sync::{
10 mpsc::{UnboundedReceiver, UnboundedSender},
11 oneshot, watch,
12};
13
14use tracing::Span;
15use zebra_chain::{
16 block::{self, Height},
17 parallel::tree::NoteCommitmentTrees,
18};
19
20use crate::{
21 constants::MAX_BLOCK_REORG_HEIGHT,
22 service::{
23 check,
24 finalized_state::{FinalizedState, ZebraDb},
25 non_finalized_state::NonFinalizedState,
26 precomputed_trees::PrecomputedTrees,
27 queued_blocks::{QueuedCheckpointVerified, QueuedSemanticallyVerified},
28 read, ChainTipBlock, ChainTipSender, InvalidateError, ReconsiderError,
29 },
30 GetBlockTemplateChainInfo, SemanticallyVerifiedBlock, ValidateContextError,
31};
32
33#[allow(unused_imports)]
35use crate::service::{
36 chain_tip::{ChainTipChange, LatestChainTip},
37 non_finalized_state::Chain,
38};
39
40const PARENT_ERROR_MAP_LIMIT: usize = MAX_BLOCK_REORG_HEIGHT as usize * 2;
44
45#[tracing::instrument(
48 level = "debug",
49 skip(finalized_state, non_finalized_state, prepared),
50 fields(
51 height = ?prepared.height,
52 hash = %prepared.hash,
53 chains = non_finalized_state.chain_count()
54 )
55)]
56pub(crate) fn validate_and_commit_non_finalized(
57 finalized_state: &ZebraDb,
58 non_finalized_state: &mut NonFinalizedState,
59 prepared: SemanticallyVerifiedBlock,
60) -> Result<(), ValidateContextError> {
61 check::initial_contextual_validity(finalized_state, non_finalized_state, &prepared)?;
62 let parent_hash = prepared.block.header.previous_block_hash;
63
64 if finalized_state.finalized_tip_hash() == parent_hash {
65 non_finalized_state.commit_new_chain(prepared, finalized_state)?;
66 } else {
67 non_finalized_state.commit_block(prepared, finalized_state)?;
68 }
69
70 Ok(())
71}
72
73fn finalize_root_blocks(
75 finalized_state: &mut FinalizedState,
76 non_finalized_state: &mut NonFinalizedState,
77 prev_finalized_note_commitment_trees: &mut Option<NoteCommitmentTrees>,
78) {
79 while non_finalized_state.should_finalize_root() {
80 tracing::trace!("finalizing a block past the reorg or index entry limit");
81 let contextually_verified_with_trees = non_finalized_state.finalize();
82 *prev_finalized_note_commitment_trees = finalized_state
83 .commit_finalized_direct(
84 contextually_verified_with_trees,
85 prev_finalized_note_commitment_trees.take(),
86 "commit contextually-verified request",
87 )
88 .expect(
89 "unexpected finalized block commit error: note commitment and history trees were \
90 already checked by the non-finalized state",
91 )
92 .1
93 .into();
94 }
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub(crate) enum NonFinalizedWriteOutcome {
101 Rejected(block::Hash),
103
104 Committed(block::Hash),
106}
107
108fn forget_evicted_blocks(
113 non_finalized_state: &mut NonFinalizedState,
114 non_finalized_rejected_sender: &UnboundedSender<NonFinalizedWriteOutcome>,
115) -> bool {
116 let evicted = non_finalized_state.take_evicted_block_hashes();
117 for &hash in &evicted {
118 let _ = non_finalized_rejected_sender.send(NonFinalizedWriteOutcome::Rejected(hash));
120 }
121
122 !evicted.is_empty()
123}
124
125fn finalize_root_blocks_and_forget_evicted(
129 finalized_state: &mut FinalizedState,
130 non_finalized_state: &mut NonFinalizedState,
131 prev_finalized_note_commitment_trees: &mut Option<NoteCommitmentTrees>,
132 non_finalized_rejected_sender: &UnboundedSender<NonFinalizedWriteOutcome>,
133 chain_tip_sender: &mut ChainTipSender,
134 non_finalized_state_sender: &watch::Sender<NonFinalizedState>,
135 backup_dir_path: Option<&Path>,
136) {
137 finalize_root_blocks(
138 finalized_state,
139 non_finalized_state,
140 prev_finalized_note_commitment_trees,
141 );
142
143 if forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender) {
144 update_latest_chain_channels(
145 non_finalized_state,
146 &finalized_state.db,
147 chain_tip_sender,
148 non_finalized_state_sender,
149 backup_dir_path,
150 );
151 }
152}
153
154#[instrument(
163 level = "debug",
164 skip(
165 non_finalized_state,
166 finalized_state,
167 chain_tip_sender,
168 non_finalized_state_sender,
169 backup_dir_path,
170 ),
171 fields(chains = non_finalized_state.chain_count())
172)]
173fn update_latest_chain_channels(
174 non_finalized_state: &NonFinalizedState,
175 finalized_state: &ZebraDb,
176 chain_tip_sender: &mut ChainTipSender,
177 non_finalized_state_sender: &watch::Sender<NonFinalizedState>,
178 backup_dir_path: Option<&Path>,
179) -> Option<block::Height> {
180 let non_finalized_tip = non_finalized_state
182 .best_tip_block()
183 .map(ChainTipBlock::from);
184 let tip_block_height = if let Some(tip) = &non_finalized_tip {
185 Some(tip.height)
186 } else {
187 finalized_state.finalized_tip_height()
188 };
189
190 if let Some(backup_dir_path) = backup_dir_path {
191 non_finalized_state.write_to_backup(backup_dir_path);
192 }
193
194 let _ = non_finalized_state_sender.send(non_finalized_state.clone());
196
197 if let Some(tip) = non_finalized_tip {
198 chain_tip_sender.set_best_non_finalized_tip(tip);
199 } else {
200 let finalized_tip = finalized_state
201 .tip_block()
202 .expect("the finalized tip must have a complete stored body")
203 .map(crate::CheckpointVerifiedBlock::from)
204 .map(ChainTipBlock::from);
205 chain_tip_sender.clear_best_non_finalized_tip(finalized_tip);
206 }
207
208 tip_block_height
209}
210
211struct WriteBlockWorkerTask {
214 finalized_block_write_receiver: UnboundedReceiver<QueuedCheckpointVerified>,
215 non_finalized_block_write_receiver: UnboundedReceiver<NonFinalizedWriteMessage>,
216 finalized_state: FinalizedState,
217 non_finalized_state: NonFinalizedState,
218 invalid_block_reset_sender: UnboundedSender<(Option<block::Height>, block::Hash)>,
221 non_finalized_rejected_sender: UnboundedSender<NonFinalizedWriteOutcome>,
229 chain_tip_sender: ChainTipSender,
230 non_finalized_state_sender: watch::Sender<NonFinalizedState>,
231 backup_dir_path: Option<PathBuf>,
234}
235
236pub enum NonFinalizedWriteMessage {
238 Commit(QueuedSemanticallyVerified),
241 Invalidate {
244 hash: block::Hash,
245 rsp_tx: oneshot::Sender<Result<block::Hash, InvalidateError>>,
246 },
247 Reconsider {
250 hash: block::Hash,
251 rsp_tx: oneshot::Sender<Result<Vec<block::Hash>, ReconsiderError>>,
252 },
253 MiningCandidate {
260 block: Arc<block::Block>,
261 rsp_tx: oneshot::Sender<Option<GetBlockTemplateChainInfo>>,
262 },
263}
264
265impl From<QueuedSemanticallyVerified> for NonFinalizedWriteMessage {
266 fn from(block: QueuedSemanticallyVerified) -> Self {
267 NonFinalizedWriteMessage::Commit(block)
268 }
269}
270
271#[derive(Clone, Debug)]
275pub(super) struct BlockWriteSender {
276 pub non_finalized: Option<tokio::sync::mpsc::UnboundedSender<NonFinalizedWriteMessage>>,
279
280 pub finalized: Option<tokio::sync::mpsc::UnboundedSender<QueuedCheckpointVerified>>,
286}
287
288impl BlockWriteSender {
289 #[instrument(
291 level = "debug",
292 skip_all,
293 fields(
294 network = %non_finalized_state.network
295 )
296 )]
297 pub fn spawn(
298 finalized_state: FinalizedState,
299 non_finalized_state: NonFinalizedState,
300 chain_tip_sender: ChainTipSender,
301 non_finalized_state_sender: watch::Sender<NonFinalizedState>,
302 should_use_finalized_block_write_sender: bool,
303 backup_dir_path: Option<PathBuf>,
304 ) -> (
305 Self,
306 tokio::sync::mpsc::UnboundedReceiver<(Option<block::Height>, block::Hash)>,
307 tokio::sync::mpsc::UnboundedReceiver<NonFinalizedWriteOutcome>,
308 Option<Arc<std::thread::JoinHandle<()>>>,
309 ) {
310 let (non_finalized_block_write_sender, non_finalized_block_write_receiver) =
313 tokio::sync::mpsc::unbounded_channel();
314 let (finalized_block_write_sender, finalized_block_write_receiver) =
315 tokio::sync::mpsc::unbounded_channel();
316 let (invalid_block_reset_sender, invalid_block_write_reset_receiver) =
317 tokio::sync::mpsc::unbounded_channel();
318 let (non_finalized_rejected_sender, non_finalized_rejected_receiver) =
319 tokio::sync::mpsc::unbounded_channel();
320
321 let span = Span::current();
322 let task = std::thread::spawn(move || {
323 span.in_scope(|| {
324 WriteBlockWorkerTask {
325 finalized_block_write_receiver,
326 non_finalized_block_write_receiver,
327 finalized_state,
328 non_finalized_state,
329 invalid_block_reset_sender,
330 non_finalized_rejected_sender,
331 chain_tip_sender,
332 non_finalized_state_sender,
333 backup_dir_path,
334 }
335 .run()
336 })
337 });
338
339 (
340 Self {
341 non_finalized: Some(non_finalized_block_write_sender),
342 finalized: should_use_finalized_block_write_sender
343 .then_some(finalized_block_write_sender),
344 },
345 invalid_block_write_reset_receiver,
346 non_finalized_rejected_receiver,
347 Some(Arc::new(task)),
348 )
349 }
350}
351
352impl WriteBlockWorkerTask {
353 #[instrument(
357 level = "debug",
358 skip(self),
359 fields(
360 network = %self.non_finalized_state.network
361 )
362 )]
363 pub fn run(mut self) {
364 let Self {
365 finalized_block_write_receiver,
366 non_finalized_block_write_receiver,
367 finalized_state,
368 non_finalized_state,
369 invalid_block_reset_sender,
370 non_finalized_rejected_sender,
371 chain_tip_sender,
372 non_finalized_state_sender,
373 backup_dir_path,
374 } = &mut self;
375
376 let mut prev_finalized_note_commitment_trees = None;
377
378 while let Some(ordered_block) = finalized_block_write_receiver.blocking_recv() {
381 if invalid_block_reset_sender.is_closed() {
384 info!("StateService closed the block reset channel. Is Zebra shutting down?");
385 return;
386 }
387
388 let next_valid_height = finalized_state
395 .db
396 .finalized_tip_height()
397 .map(|height| (height + 1).expect("committed heights are valid"))
398 .unwrap_or(Height(0));
399
400 if ordered_block.0.height != next_valid_height {
401 debug!(
402 ?next_valid_height,
403 invalid_height = ?ordered_block.0.height,
404 invalid_hash = ?ordered_block.0.hash,
405 "got a block that was the wrong height. \
406 Assuming a parent block failed, and dropping this block",
407 );
408
409 std::mem::drop(ordered_block);
411 continue;
412 }
413
414 match finalized_state
416 .commit_finalized(ordered_block, prev_finalized_note_commitment_trees.take())
417 {
418 Ok((tip_block, note_commitment_trees)) => {
419 prev_finalized_note_commitment_trees = Some(note_commitment_trees);
420 chain_tip_sender.set_finalized_tip(tip_block);
421 }
422 Err(error) => {
423 let finalized_tip = finalized_state.db.tip();
424
425 info!(
429 ?error,
430 last_valid_height = ?finalized_tip.map(|tip| tip.0),
431 last_valid_hash = ?finalized_tip.map(|tip| tip.1),
432 "committing a block to the finalized state failed, resetting state queue",
433 );
434
435 let send_result = invalid_block_reset_sender.send((
436 finalized_state.db.finalized_tip_height(),
437 finalized_state.db.finalized_tip_hash(),
438 ));
439
440 if send_result.is_err() {
441 info!(
442 "StateService closed the block reset channel. Is Zebra shutting down?"
443 );
444 return;
445 }
446 }
447 }
448 }
449
450 if invalid_block_reset_sender.is_closed() {
453 info!("StateService closed the block reset channel. Is Zebra shutting down?");
454 return;
455 }
456
457 let restored_root = non_finalized_state.root_height();
460 finalize_root_blocks(
461 finalized_state,
462 non_finalized_state,
463 &mut prev_finalized_note_commitment_trees,
464 );
465 if non_finalized_state.root_height() != restored_root {
466 forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
467 update_latest_chain_channels(
468 non_finalized_state,
469 &finalized_state.db,
470 chain_tip_sender,
471 non_finalized_state_sender,
472 backup_dir_path.as_deref(),
473 );
474 }
475
476 let mut parent_error_map: IndexMap<block::Hash, ValidateContextError> = IndexMap::new();
478
479 let mut candidate_trees: Option<PrecomputedTrees> = None;
481
482 while let Some(msg) = non_finalized_block_write_receiver.blocking_recv() {
483 let queued_child_and_rsp_tx = match msg {
484 NonFinalizedWriteMessage::Commit(queued_child) => Some(queued_child),
485 NonFinalizedWriteMessage::MiningCandidate { block, rsp_tx } => {
486 let candidate = read::difficulty::mining_candidate_chain_info(
487 non_finalized_state,
488 &finalized_state.db,
489 &block,
490 );
491
492 let chain_info = match candidate {
493 Ok((chain_info, trees)) => {
494 candidate_trees = Some(trees);
495 Some(chain_info)
496 }
497 Err(error) => {
498 tracing::debug!(?error, "block can't be used for early mining work");
499 None
500 }
501 };
502
503 let _ = rsp_tx.send(chain_info);
504 continue;
505 }
506 NonFinalizedWriteMessage::Invalidate { hash, rsp_tx } => {
507 tracing::info!(?hash, "invalidating a block in the non-finalized state");
508 let _ = rsp_tx.send(non_finalized_state.invalidate_block(hash));
509 None
510 }
511 NonFinalizedWriteMessage::Reconsider { hash, rsp_tx } => {
512 tracing::info!(?hash, "reconsidering a block in the non-finalized state");
513 let _ = rsp_tx
514 .send(non_finalized_state.reconsider_block(hash, &finalized_state.db));
515 None
516 }
517 };
518
519 let Some((queued_child, rsp_tx, contextual)) = queued_child_and_rsp_tx else {
520 forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
521 update_latest_chain_channels(
522 non_finalized_state,
523 &finalized_state.db,
524 chain_tip_sender,
525 non_finalized_state_sender,
526 backup_dir_path.as_deref(),
527 );
528 continue;
529 };
530
531 let child_hash = queued_child.hash;
532 let parent_hash = queued_child.block.header.previous_block_hash;
533 let parent_error = parent_error_map.get(&parent_hash);
534
535 let replaced_snapshot = non_finalized_state_sender.borrow().clone();
541 let replaced_chain = non_finalized_state.best_chain().cloned();
542 let mut replaced_proposal = None;
543
544 let result = if let Some(parent_error) = parent_error {
554 Err(parent_error.for_descendant(parent_hash))
555 } else if let Some(contextual) = contextual {
556 candidate_trees = None;
558 non_finalized_state
559 .commit_prevalidated_contextual(*contextual, &finalized_state.db)
560 .map(|replaced| replaced_proposal = replaced)
561 } else {
562 tracing::trace!(?child_hash, "validating queued child");
563 non_finalized_state.precomputed_trees = candidate_trees.take();
566 let result = validate_and_commit_non_finalized(
567 &finalized_state.db,
568 non_finalized_state,
569 queued_child,
570 );
571 non_finalized_state.precomputed_trees = None;
572 result
573 };
574
575 if let Err(ref error) = result {
580 parent_error_map.insert(child_hash, error.clone());
582
583 if parent_error_map.len() > PARENT_ERROR_MAP_LIMIT {
585 parent_error_map.shift_remove_index(0);
587 }
588
589 let _ = non_finalized_rejected_sender
599 .send(NonFinalizedWriteOutcome::Rejected(child_hash));
600
601 let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
603
604 continue;
606 }
607
608 parent_error_map.shift_remove(&child_hash);
611
612 forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
613
614 let tip_block_height = update_latest_chain_channels(
621 non_finalized_state,
622 &finalized_state.db,
623 chain_tip_sender,
624 non_finalized_state_sender,
625 backup_dir_path.as_deref(),
626 )
627 .expect("just successfully inserted a non-finalized block above");
628
629 let _ =
632 non_finalized_rejected_sender.send(NonFinalizedWriteOutcome::Committed(child_hash));
633
634 let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
636 drop((replaced_snapshot, replaced_chain, replaced_proposal));
637
638 non_finalized_state.drop_passed_prepared_chain();
640
641 finalize_root_blocks_and_forget_evicted(
642 finalized_state,
643 non_finalized_state,
644 &mut prev_finalized_note_commitment_trees,
645 non_finalized_rejected_sender,
646 chain_tip_sender,
647 non_finalized_state_sender,
648 backup_dir_path.as_deref(),
649 );
650
651 metrics::counter!("state.full_verifier.committed.block.count").increment(1);
655 metrics::counter!("zcash.chain.verified.block.total").increment(1);
656
657 metrics::gauge!("state.full_verifier.committed.block.height")
658 .set(tip_block_height.0 as f64);
659
660 metrics::gauge!("zcash.chain.verified.block.height").set(tip_block_height.0 as f64);
664
665 tracing::trace!("finished processing queued block");
666 }
667
668 finalized_state.db.shutdown(true);
671 std::mem::drop(self.finalized_state);
672 }
673}
674
675#[cfg(test)]
676mod tests;