1use std::{
11 future::Future,
12 pin::Pin,
13 sync::Arc,
14 task::{Context, Poll},
15 time::Instant,
16};
17
18use chrono::Utc;
19use futures::stream::FuturesUnordered;
20use futures_util::FutureExt;
21use thiserror::Error;
22use tower::{Service, ServiceExt};
23use tracing::Instrument;
24
25use zebra_chain::{
26 amount::Amount,
27 block,
28 parameters::{subsidy::SubsidyError, Network},
29 transparent,
30 work::equihash,
31};
32use zebra_state as zs;
33
34use crate::{error::*, transaction as tx, BoxError};
35
36pub mod check;
37pub mod request;
38
39pub use request::Request;
40
41#[cfg(test)]
42mod tests;
43
44#[derive(Debug)]
46pub struct SemanticBlockVerifier<S, V> {
47 network: Network,
49 state_service: S,
50 transaction_verifier: V,
51}
52
53#[non_exhaustive]
56#[allow(missing_docs)]
57#[derive(Debug, Error)]
58pub enum VerifyBlockError {
59 #[error("unable to verify depth for block {hash} from chain state during block verification")]
60 Depth { source: BoxError, hash: block::Hash },
61
62 #[error(transparent)]
63 Block {
64 #[from]
65 source: BlockError,
66 },
67
68 #[error(transparent)]
69 Equihash {
70 #[from]
71 source: equihash::Error,
72 },
73
74 #[error(transparent)]
75 Time(zebra_chain::block::BlockTimeError),
76
77 #[error("unable to commit block after semantic verification: {0}")]
79 Commit(#[from] zs::CommitBlockError),
80
81 #[error("unable to validate block proposal: failed semantic verification (proof of work is not checked for proposals): {0}")]
82 ValidateProposal(#[source] BoxError),
84
85 #[error("invalid transaction: {0}")]
86 Transaction(#[from] TransactionError),
87
88 #[error("invalid block subsidy: {0}")]
89 Subsidy(#[from] SubsidyError),
90
91 #[error("state service error for block {hash}: {source}")]
94 StateService { source: BoxError, hash: block::Hash },
95}
96
97impl VerifyBlockError {
98 pub fn is_duplicate_request(&self) -> bool {
101 match self {
102 VerifyBlockError::Block { source, .. } => source.is_duplicate_request(),
103 VerifyBlockError::Commit(commit_err) => commit_err.is_duplicate_request(),
104 _ => false,
105 }
106 }
107
108 pub fn is_auth_commitment_mismatch(&self) -> bool {
113 match self {
114 VerifyBlockError::Commit(commit_err) => commit_err.is_auth_commitment_mismatch(),
115 _ => false,
116 }
117 }
118
119 pub fn is_body_header_mismatch(&self) -> bool {
128 matches!(
129 self,
130 VerifyBlockError::Block {
131 source: BlockError::BadMerkleRoot { .. }
132 | BlockError::DuplicateTransaction
133 | BlockError::Transaction(TransactionError::CoinbaseExpiryBlockHeight { .. }),
134 }
135 )
136 }
137
138 pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
143 match self {
144 VerifyBlockError::Commit(commit_err) => {
145 commit_err.is_descendant_of_auth_commitment_mismatch()
146 }
147 _ => false,
148 }
149 }
150
151 pub fn misbehavior_score(&self) -> u32 {
153 use VerifyBlockError::*;
154 match self {
155 Block { source } => source.misbehavior_score(),
156 Equihash { .. } | Subsidy(_) => 100,
157 Transaction(err) => err.mempool_misbehavior_score(),
158 Commit(err) => err.misbehavior_score(),
159 _other => 0,
160 }
161 }
162}
163
164fn record_phase(phase: &'static str, phase_start: &mut Instant) {
167 let now = Instant::now();
168 metrics::histogram!("zebra.consensus.block.phase.duration_seconds", "phase" => phase)
169 .record(now.duration_since(*phase_start).as_secs_f64());
170 *phase_start = now;
171}
172
173fn map_commit_error(source: BoxError, hash: block::Hash) -> VerifyBlockError {
181 if let Some(commit_err) = source
182 .downcast_ref::<zs::CommitSemanticallyVerifiedError>()
183 .map(zs::CommitSemanticallyVerifiedError::inner)
184 .or_else(|| source.downcast_ref::<zs::CommitBlockError>())
185 {
186 return VerifyBlockError::Commit(commit_err.clone());
187 }
188
189 VerifyBlockError::StateService { source, hash }
190}
191
192pub const MAX_BLOCK_SIGOPS: u32 = 20_000;
212
213pub const GLOBAL_SHIELDED_BUDGET: usize = 330;
221pub const ORCHARD_BLOCK_ACTION_LIMIT: usize = 330;
223pub const SAPLING_BLOCK_IO_LIMIT: usize = 300;
225pub const SPROUT_BLOCK_JOIN_SPLIT_LIMIT: usize = 0;
227
228#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
235pub struct ShieldedActionCounts {
236 pub orchard_actions: usize,
238 pub ironwood_actions: usize,
240 pub sapling_io: usize,
242 pub joinsplits: usize,
244}
245
246impl ShieldedActionCounts {
247 pub fn from_transaction(transaction: &zebra_chain::transaction::Transaction) -> Self {
249 Self {
250 orchard_actions: transaction.orchard_actions().count(),
251 ironwood_actions: transaction.ironwood_actions().count(),
252 sapling_io: transaction
253 .sapling_spends_count()
254 .saturating_add(transaction.sapling_outputs().count()),
255 joinsplits: transaction.joinsplit_count(),
256 }
257 }
258
259 pub fn saturating_add(self, other: Self) -> Self {
263 Self {
264 orchard_actions: self.orchard_actions.saturating_add(other.orchard_actions),
265 ironwood_actions: self.ironwood_actions.saturating_add(other.ironwood_actions),
266 sapling_io: self.sapling_io.saturating_add(other.sapling_io),
267 joinsplits: self.joinsplits.saturating_add(other.joinsplits),
268 }
269 }
270
271 pub fn shielded_cost(&self) -> usize {
274 self.orchard_actions
275 .saturating_add(self.ironwood_actions)
276 .saturating_add(self.sapling_io)
277 .saturating_add(self.joinsplits.saturating_mul(2))
278 }
279
280 pub fn exceeded_limit(&self) -> Option<(&'static str, usize, usize)> {
282 [
283 (
284 "Orchard actions",
285 self.orchard_actions,
286 ORCHARD_BLOCK_ACTION_LIMIT,
287 ),
288 (
289 "Ironwood actions",
290 self.ironwood_actions,
291 ORCHARD_BLOCK_ACTION_LIMIT,
292 ),
293 (
294 "Sapling inputs and outputs",
295 self.sapling_io,
296 SAPLING_BLOCK_IO_LIMIT,
297 ),
298 (
299 "Sprout JoinSplits",
300 self.joinsplits,
301 SPROUT_BLOCK_JOIN_SPLIT_LIMIT,
302 ),
303 (
304 "shielded actions across all pools",
305 self.shielded_cost(),
306 GLOBAL_SHIELDED_BUDGET,
307 ),
308 ]
309 .into_iter()
310 .find(|&(_, count, limit)| count > limit)
311 }
312}
313
314impl<S, V> SemanticBlockVerifier<S, V>
315where
316 S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
317 S::Future: Send + 'static,
318 V: Service<tx::BlockRequest, Response = tx::BlockResponse, Error = BoxError>
319 + Send
320 + Clone
321 + 'static,
322 V::Future: Send + 'static,
323{
324 pub fn new(network: &Network, state_service: S, transaction_verifier: V) -> Self {
326 Self {
327 network: network.clone(),
328 state_service,
329 transaction_verifier,
330 }
331 }
332}
333
334impl<S, V> Service<Request> for SemanticBlockVerifier<S, V>
335where
336 S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
337 S::Future: Send + 'static,
338 V: Service<tx::BlockRequest, Response = tx::BlockResponse, Error = BoxError>
339 + Send
340 + Clone
341 + 'static,
342 V::Future: Send + 'static,
343{
344 type Response = block::Hash;
345 type Error = VerifyBlockError;
346 type Future =
347 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
348
349 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
350 Poll::Ready(Ok(()))
354 }
355
356 fn call(&mut self, request: Request) -> Self::Future {
357 let received_time = Instant::now();
360
361 let mut state_service = self.state_service.clone();
362 let mut transaction_verifier = self.transaction_verifier.clone();
363 let network = self.network.clone();
364
365 let block = request.block();
366
367 let span = tracing::debug_span!("block", height = ?block.coinbase_height());
369
370 async move {
371 let hash = block.hash();
372 tracing::trace!("checking that block is not already in state");
374 match state_service
375 .ready()
376 .await
377 .map_err(|source| VerifyBlockError::Depth { source, hash })?
378 .call(zs::Request::KnownBlock(hash))
379 .await
380 .map_err(|source| VerifyBlockError::Depth { source, hash })?
381 {
382 zs::Response::KnownBlock(Some(location)) => {
383 return Err(BlockError::AlreadyInChain(hash, location).into())
384 }
385 zs::Response::KnownBlock(None) => {}
386 _ => unreachable!("wrong response to Request::KnownBlock"),
387 }
388
389 tracing::trace!("performing block checks");
390 let record_phases = !request.is_proposal();
393 let mut phase_start = Instant::now();
394 let height = block
395 .coinbase_height()
396 .ok_or(BlockError::MissingHeight(hash))?;
397
398 if height > block::Height::MAX {
401 Err(BlockError::MaxHeight(height, hash, block::Height::MAX))?;
402 }
403
404 if request.is_proposal() || network.disable_pow() {
408 check::difficulty_threshold_is_valid(&block.header, &network, &height, &hash)?;
409 } else {
410 check::difficulty_is_valid(&block.header, &network, &height, &hash)?;
413 check::equihash_solution_is_valid(&block.header)?;
414 }
415
416 check::coinbase_height_is_committed(&block, height)?;
429
430 let transaction_hashes: Arc<[_]> =
435 block.transactions.iter().map(|t| t.hash()).collect();
436
437 check::merkle_root_validity(&network, &block, &transaction_hashes)?;
438
439 let now = Utc::now();
444 check::time_is_valid_at(&block.header, now, &height, &hash)
445 .map_err(VerifyBlockError::Time)?;
446 let coinbase_tx = check::coinbase_is_first(&block)?;
447
448 let nsm_reissuance_is_active =
454 zebra_chain::parameters::subsidy::nsm_reissuance_is_active(height, &network);
455
456 let expected_subsidy_and_deferred_pool_balance_change = if nsm_reissuance_is_active {
457 None
458 } else {
459 let expected_block_subsidy =
460 zebra_chain::parameters::subsidy::block_subsidy(height, &network)?;
461
462 let deferred_pool_balance_change =
464 check::subsidy_is_valid(&block, &network, expected_block_subsidy)?;
465
466 Some((expected_block_subsidy, deferred_pool_balance_change))
467 };
468
469 check::shielded_action_limits_are_valid(&block, &network, height, hash)?;
471
472 tx::check::coinbase_outputs_are_decryptable(&coinbase_tx, &network, height)?;
476
477 if record_phases {
478 record_phase("block_checks", &mut phase_start);
479 }
480
481 let mut async_checks = FuturesUnordered::new();
483
484 let known_utxos = Arc::new(transparent::new_ordered_outputs(
485 &block,
486 &transaction_hashes,
487 ));
488
489 for (&transaction_hash, transaction) in
490 transaction_hashes.iter().zip(block.transactions.iter())
491 {
492 let rsp = transaction_verifier
493 .ready()
494 .await
495 .expect("transaction verifier is always ready")
496 .call(tx::BlockRequest {
497 transaction_hash,
498 transaction: transaction.clone(),
499 known_utxos: known_utxos.clone(),
500 height,
501 time: block.header.time,
502 });
503 async_checks.push(rsp);
504 }
505 tracing::trace!(len = async_checks.len(), "built async tx checks");
506
507 let mut sigops = 0;
511 let mut block_miner_fees = Ok(Amount::zero());
512
513 use futures::StreamExt;
514 while let Some(result) = async_checks.next().await {
515 tracing::trace!(?result, remaining = async_checks.len());
516 let response = result
517 .map_err(Into::into)
518 .map_err(VerifyBlockError::Transaction)?;
519
520 sigops += response.sigops;
521
522 if let Some(miner_fee) = response.miner_fee {
525 block_miner_fees += miner_fee;
526 }
527 }
528
529 if sigops > MAX_BLOCK_SIGOPS {
532 Err(BlockError::TooManyTransparentSignatureOperations {
533 height,
534 hash,
535 sigops,
536 })?;
537 }
538
539 let block_miner_fees =
540 block_miner_fees.map_err(|amount_error| BlockError::SummingMinerFees {
541 height,
542 hash,
543 source: amount_error,
544 })?;
545
546 if let Some((expected_block_subsidy, deferred_pool_balance_change)) =
547 expected_subsidy_and_deferred_pool_balance_change
548 {
549 check::miner_fees_are_valid(
550 &coinbase_tx,
551 height,
552 block_miner_fees,
553 expected_block_subsidy,
554 deferred_pool_balance_change,
555 &network,
556 )?;
557 }
558
559 if record_phases {
560 record_phase("transaction_verification", &mut phase_start);
561 }
562
563 let new_outputs = Arc::into_inner(known_utxos)
565 .expect("all verification tasks using known_utxos are complete");
566
567 let prepared_block = zs::SemanticallyVerifiedBlock {
568 block,
569 hash,
570 height,
571 new_outputs,
572 transaction_hashes,
573 received_time: Some(received_time),
574 };
575
576 if request.is_proposal() {
578 return match state_service
579 .ready()
580 .await
581 .map_err(VerifyBlockError::ValidateProposal)?
582 .call(zs::Request::CheckBlockProposalValidity(prepared_block))
583 .await
584 .map_err(VerifyBlockError::ValidateProposal)?
585 {
586 zs::Response::ValidBlockProposal => Ok(hash),
587 _ => unreachable!("wrong response for CheckBlockProposalValidity"),
588 };
589 }
590
591 match state_service
592 .ready()
593 .await
594 .map_err(|source| VerifyBlockError::StateService { source, hash })?
595 .call(zs::Request::CommitSemanticallyVerifiedBlock(prepared_block))
596 .await
597 {
598 Ok(zs::Response::Committed(committed_hash)) => {
599 assert_eq!(committed_hash, hash, "state must commit correct hash");
600 record_phase("state_commit", &mut phase_start);
601 Ok(hash)
602 }
603
604 Err(source) => Err(map_commit_error(source, hash)),
605
606 _ => unreachable!("wrong response for CommitSemanticallyVerifiedBlock"),
607 }
608 }
609 .instrument(span)
610 .boxed()
611 }
612}