1use std::sync::Arc;
4
5use indexmap::IndexMap;
6use tokio::sync::{
7 mpsc::{UnboundedReceiver, UnboundedSender},
8 oneshot, watch,
9};
10
11use tracing::Span;
12use zebra_chain::{
13 block::{self, Height},
14 transparent::EXTRA_ZEBRA_COINBASE_DATA,
15};
16
17use crate::{
18 constants::MAX_BLOCK_REORG_HEIGHT,
19 service::{
20 check,
21 finalized_state::{FinalizedState, ZebraDb},
22 non_finalized_state::NonFinalizedState,
23 queued_blocks::{QueuedCheckpointVerified, QueuedSemanticallyVerified},
24 ChainTipBlock, ChainTipSender, InvalidateError, ReconsiderError,
25 },
26 SemanticallyVerifiedBlock, ValidateContextError,
27};
28
29#[allow(unused_imports)]
31use crate::service::{
32 chain_tip::{ChainTipChange, LatestChainTip},
33 non_finalized_state::Chain,
34};
35
36const PARENT_ERROR_MAP_LIMIT: usize = MAX_BLOCK_REORG_HEIGHT as usize * 2;
40
41#[tracing::instrument(
44 level = "debug",
45 skip(finalized_state, non_finalized_state, prepared),
46 fields(
47 height = ?prepared.height,
48 hash = %prepared.hash,
49 chains = non_finalized_state.chain_count()
50 )
51)]
52pub(crate) fn validate_and_commit_non_finalized(
53 finalized_state: &ZebraDb,
54 non_finalized_state: &mut NonFinalizedState,
55 prepared: SemanticallyVerifiedBlock,
56) -> Result<(), ValidateContextError> {
57 check::initial_contextual_validity(finalized_state, non_finalized_state, &prepared)?;
58 let parent_hash = prepared.block.header.previous_block_hash;
59
60 if finalized_state.finalized_tip_hash() == parent_hash {
61 non_finalized_state.commit_new_chain(prepared, finalized_state)?;
62 } else {
63 non_finalized_state.commit_block(prepared, finalized_state)?;
64 }
65
66 Ok(())
67}
68
69#[instrument(
81 level = "debug",
82 skip(
83 non_finalized_state,
84 chain_tip_sender,
85 non_finalized_state_sender,
86 last_zebra_mined_log_height
87 ),
88 fields(chains = non_finalized_state.chain_count())
89)]
90fn update_latest_chain_channels(
91 non_finalized_state: &NonFinalizedState,
92 chain_tip_sender: &mut ChainTipSender,
93 non_finalized_state_sender: &watch::Sender<NonFinalizedState>,
94 last_zebra_mined_log_height: &mut Option<Height>,
95) -> block::Height {
96 let best_chain = non_finalized_state.best_chain().expect("unexpected empty non-finalized state: must commit at least one block before updating channels");
97
98 let tip_block = best_chain
99 .tip_block()
100 .expect("unexpected empty chain: must commit at least one block before updating channels")
101 .clone();
102 let tip_block = ChainTipBlock::from(tip_block);
103
104 log_if_mined_by_zebra(&tip_block, last_zebra_mined_log_height);
105
106 let tip_block_height = tip_block.height;
107
108 let _ = non_finalized_state_sender.send(non_finalized_state.clone());
110
111 chain_tip_sender.set_best_non_finalized_tip(tip_block);
112
113 tip_block_height
114}
115
116struct WriteBlockWorkerTask {
119 finalized_block_write_receiver: UnboundedReceiver<QueuedCheckpointVerified>,
120 non_finalized_block_write_receiver: UnboundedReceiver<NonFinalizedWriteMessage>,
121 finalized_state: FinalizedState,
122 non_finalized_state: NonFinalizedState,
123 invalid_block_reset_sender: UnboundedSender<block::Hash>,
124 chain_tip_sender: ChainTipSender,
125 non_finalized_state_sender: watch::Sender<NonFinalizedState>,
126}
127
128pub enum NonFinalizedWriteMessage {
130 Commit(QueuedSemanticallyVerified),
133 Invalidate {
136 hash: block::Hash,
137 rsp_tx: oneshot::Sender<Result<block::Hash, InvalidateError>>,
138 },
139 Reconsider {
142 hash: block::Hash,
143 rsp_tx: oneshot::Sender<Result<Vec<block::Hash>, ReconsiderError>>,
144 },
145}
146
147impl From<QueuedSemanticallyVerified> for NonFinalizedWriteMessage {
148 fn from(block: QueuedSemanticallyVerified) -> Self {
149 NonFinalizedWriteMessage::Commit(block)
150 }
151}
152
153#[derive(Clone, Debug)]
157pub(super) struct BlockWriteSender {
158 pub non_finalized: Option<tokio::sync::mpsc::UnboundedSender<NonFinalizedWriteMessage>>,
161
162 pub finalized: Option<tokio::sync::mpsc::UnboundedSender<QueuedCheckpointVerified>>,
168}
169
170impl BlockWriteSender {
171 #[instrument(
173 level = "debug",
174 skip_all,
175 fields(
176 network = %non_finalized_state.network
177 )
178 )]
179 pub fn spawn(
180 finalized_state: FinalizedState,
181 non_finalized_state: NonFinalizedState,
182 chain_tip_sender: ChainTipSender,
183 non_finalized_state_sender: watch::Sender<NonFinalizedState>,
184 should_use_finalized_block_write_sender: bool,
185 ) -> (
186 Self,
187 tokio::sync::mpsc::UnboundedReceiver<block::Hash>,
188 Option<Arc<std::thread::JoinHandle<()>>>,
189 ) {
190 let (non_finalized_block_write_sender, non_finalized_block_write_receiver) =
193 tokio::sync::mpsc::unbounded_channel();
194 let (finalized_block_write_sender, finalized_block_write_receiver) =
195 tokio::sync::mpsc::unbounded_channel();
196 let (invalid_block_reset_sender, invalid_block_write_reset_receiver) =
197 tokio::sync::mpsc::unbounded_channel();
198
199 let span = Span::current();
200 let task = std::thread::spawn(move || {
201 span.in_scope(|| {
202 WriteBlockWorkerTask {
203 finalized_block_write_receiver,
204 non_finalized_block_write_receiver,
205 finalized_state,
206 non_finalized_state,
207 invalid_block_reset_sender,
208 chain_tip_sender,
209 non_finalized_state_sender,
210 }
211 .run()
212 })
213 });
214
215 (
216 Self {
217 non_finalized: Some(non_finalized_block_write_sender),
218 finalized: Some(finalized_block_write_sender)
219 .filter(|_| should_use_finalized_block_write_sender),
220 },
221 invalid_block_write_reset_receiver,
222 Some(Arc::new(task)),
223 )
224 }
225}
226
227impl WriteBlockWorkerTask {
228 #[instrument(
232 level = "debug",
233 skip(self),
234 fields(
235 network = %self.non_finalized_state.network
236 )
237 )]
238 pub fn run(mut self) {
239 let Self {
240 finalized_block_write_receiver,
241 non_finalized_block_write_receiver,
242 finalized_state,
243 non_finalized_state,
244 invalid_block_reset_sender,
245 chain_tip_sender,
246 non_finalized_state_sender,
247 } = &mut self;
248
249 let mut last_zebra_mined_log_height = None;
250 let mut prev_finalized_note_commitment_trees = None;
251
252 while let Some(ordered_block) = finalized_block_write_receiver.blocking_recv() {
255 if invalid_block_reset_sender.is_closed() {
258 info!("StateService closed the block reset channel. Is Zebra shutting down?");
259 return;
260 }
261
262 let next_valid_height = finalized_state
269 .db
270 .finalized_tip_height()
271 .map(|height| (height + 1).expect("committed heights are valid"))
272 .unwrap_or(Height(0));
273
274 if ordered_block.0.height != next_valid_height {
275 debug!(
276 ?next_valid_height,
277 invalid_height = ?ordered_block.0.height,
278 invalid_hash = ?ordered_block.0.hash,
279 "got a block that was the wrong height. \
280 Assuming a parent block failed, and dropping this block",
281 );
282
283 std::mem::drop(ordered_block);
285 continue;
286 }
287
288 match finalized_state
290 .commit_finalized(ordered_block, prev_finalized_note_commitment_trees.take())
291 {
292 Ok((finalized, note_commitment_trees)) => {
293 let tip_block = ChainTipBlock::from(finalized);
294 prev_finalized_note_commitment_trees = Some(note_commitment_trees);
295
296 log_if_mined_by_zebra(&tip_block, &mut last_zebra_mined_log_height);
297
298 chain_tip_sender.set_finalized_tip(tip_block);
299 }
300 Err(error) => {
301 let finalized_tip = finalized_state.db.tip();
302
303 info!(
307 ?error,
308 last_valid_height = ?finalized_tip.map(|tip| tip.0),
309 last_valid_hash = ?finalized_tip.map(|tip| tip.1),
310 "committing a block to the finalized state failed, resetting state queue",
311 );
312
313 let send_result =
314 invalid_block_reset_sender.send(finalized_state.db.finalized_tip_hash());
315
316 if send_result.is_err() {
317 info!(
318 "StateService closed the block reset channel. Is Zebra shutting down?"
319 );
320 return;
321 }
322 }
323 }
324 }
325
326 if invalid_block_reset_sender.is_closed() {
329 info!("StateService closed the block reset channel. Is Zebra shutting down?");
330 return;
331 }
332
333 let mut parent_error_map: IndexMap<block::Hash, ValidateContextError> = IndexMap::new();
335
336 while let Some(msg) = non_finalized_block_write_receiver.blocking_recv() {
337 let queued_child_and_rsp_tx = match msg {
338 NonFinalizedWriteMessage::Commit(queued_child) => Some(queued_child),
339 NonFinalizedWriteMessage::Invalidate { hash, rsp_tx } => {
340 tracing::info!(?hash, "invalidating a block in the non-finalized state");
341 let _ = rsp_tx.send(non_finalized_state.invalidate_block(hash));
342 None
343 }
344 NonFinalizedWriteMessage::Reconsider { hash, rsp_tx } => {
345 tracing::info!(?hash, "reconsidering a block in the non-finalized state");
346 let _ = rsp_tx
347 .send(non_finalized_state.reconsider_block(hash, &finalized_state.db));
348 None
349 }
350 };
351
352 let Some((queued_child, rsp_tx)) = queued_child_and_rsp_tx else {
353 update_latest_chain_channels(
354 non_finalized_state,
355 chain_tip_sender,
356 non_finalized_state_sender,
357 &mut last_zebra_mined_log_height,
358 );
359 continue;
360 };
361
362 let child_hash = queued_child.hash;
363 let parent_hash = queued_child.block.header.previous_block_hash;
364 let parent_error = parent_error_map.get(&parent_hash);
365
366 let result = if let Some(parent_error) = parent_error {
372 Err(parent_error.clone())
373 } else {
374 tracing::trace!(?child_hash, "validating queued child");
375 validate_and_commit_non_finalized(
376 &finalized_state.db,
377 non_finalized_state,
378 queued_child,
379 )
380 };
381
382 if let Err(ref error) = result {
387 parent_error_map.insert(child_hash, error.clone());
389
390 if parent_error_map.len() > PARENT_ERROR_MAP_LIMIT {
392 parent_error_map.shift_remove_index(0);
394 }
395
396 let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
398
399 continue;
401 }
402
403 let tip_block_height = update_latest_chain_channels(
410 non_finalized_state,
411 chain_tip_sender,
412 non_finalized_state_sender,
413 &mut last_zebra_mined_log_height,
414 );
415
416 let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
418
419 while non_finalized_state
420 .best_chain_len()
421 .expect("just successfully inserted a non-finalized block above")
422 > MAX_BLOCK_REORG_HEIGHT
423 {
424 tracing::trace!("finalizing block past the reorg limit");
425 let contextually_verified_with_trees = non_finalized_state.finalize();
426 prev_finalized_note_commitment_trees = finalized_state
427 .commit_finalized_direct(contextually_verified_with_trees, prev_finalized_note_commitment_trees.take(), "commit contextually-verified request")
428 .expect(
429 "unexpected finalized block commit error: note commitment and history trees were already checked by the non-finalized state",
430 ).1.into();
431 }
432
433 metrics::counter!("state.full_verifier.committed.block.count").increment(1);
437 metrics::counter!("zcash.chain.verified.block.total").increment(1);
438
439 metrics::gauge!("state.full_verifier.committed.block.height")
440 .set(tip_block_height.0 as f64);
441
442 metrics::gauge!("zcash.chain.verified.block.height").set(tip_block_height.0 as f64);
446
447 tracing::trace!("finished processing queued block");
448 }
449
450 finalized_state.db.shutdown(true);
453 std::mem::drop(self.finalized_state);
454 }
455}
456
457fn log_if_mined_by_zebra(
462 tip_block: &ChainTipBlock,
463 last_zebra_mined_log_height: &mut Option<Height>,
464) {
465 const LOG_RATE_LIMIT: u32 = 1000;
467
468 let height = tip_block.height.0;
469
470 if let Some(last_height) = last_zebra_mined_log_height {
471 if height < last_height.0 + LOG_RATE_LIMIT {
472 return;
474 }
475 };
476
477 let coinbase_data = tip_block.transactions[0].inputs()[0]
479 .extra_coinbase_data()
480 .expect("valid blocks must start with a coinbase input")
481 .clone();
482
483 if coinbase_data
484 .as_ref()
485 .starts_with(EXTRA_ZEBRA_COINBASE_DATA.as_bytes())
486 {
487 let text = String::from_utf8_lossy(coinbase_data.as_ref());
488
489 *last_zebra_mined_log_height = Some(Height(height));
490
491 if coinbase_data.as_ref() == EXTRA_ZEBRA_COINBASE_DATA.as_bytes() {
493 info!(
494 %text,
495 %height,
496 hash = %tip_block.hash,
497 "looks like this block was mined by Zebra!"
498 );
499 } else {
500 let text = text.replace(
506 |c: char| {
507 !EXTRA_ZEBRA_COINBASE_DATA
508 .to_ascii_lowercase()
509 .contains(c.to_ascii_lowercase())
510 },
511 "?",
512 );
513 let data = hex::encode(coinbase_data.as_ref());
514
515 info!(
516 %text,
517 %data,
518 %height,
519 hash = %tip_block.hash,
520 "looks like this block was mined by Zebra!"
521 );
522 }
523 }
524}