1use std::{
2 collections::{BTreeMap, BTreeSet},
3 hash::Hash,
4 ops::Range,
5};
6
7use shardtree::store::Checkpoint;
8
9#[cfg(feature = "orchard")]
10use crate::data_api::ORCHARD_SHARD_HEIGHT;
11
12use rayon::{
13 iter::{IndexedParallelIterator as _, ParallelIterator},
14 slice::ParallelSliceMut as _,
15};
16use tracing::{debug, info, trace, warn};
17
18use incrementalmerkletree::{Hashable, Marking, Position, Retention, frontier::Frontier};
19use shardtree::{
20 LocatedPrunableTree, ShardTree,
21 error::{InsertionError, ShardTreeError},
22 store::ShardStore,
23};
24use transparent::{address::TransparentAddress, bundle::OutPoint};
25use zcash_keys::{address::Receiver, encoding::AddressCodec as _};
26use zcash_primitives::transaction::Transaction;
27use zcash_protocol::{
28 PoolType, ShieldedPool,
29 consensus::{self, BlockHeight},
30 value::{BalanceError, Zatoshis},
31};
32use zcash_script::solver::ScriptKind;
33
34use crate::{
35 TransferType,
36 data_api::{
37 DecryptedTransaction, SAPLING_SHARD_HEIGHT, ScannedBlock, TransactionStatus,
38 WalletCommitmentTrees, anchor_retention::AnchorRetention, chain::ChainState,
39 ll::ReceivedShieldedOutput,
40 },
41 scanning::ScanError,
42 wallet::{Recipient, WalletTransparentOutput},
43};
44
45use super::{LowLevelWalletRead, LowLevelWalletWrite, PutBlockMetaError, TxMeta};
46
47#[cfg(feature = "orchard")]
48use crate::data_api::anchor_retention::{AnchorRetentionInterval, PoolMigrationParams};
49
50#[cfg(feature = "transparent-inputs")]
51use {
52 crate::data_api::Account,
53 std::collections::HashSet,
54 zcash_keys::keys::{
55 ReceiverRequirement::*,
56 UnifiedAddressRequest,
57 transparent::{
58 TransparentKeyScope,
59 gap_limits::{AddressStore, GapAddressesError, GapLimits, generate_gap_addresses},
60 },
61 },
62};
63
64pub const PRUNING_DEPTH: u32 = 100;
72
73pub(crate) fn determine_fee<DbT, T: TxMeta>(
74 _wallet_db: &DbT,
75 tx: &T,
76) -> Result<Option<Zatoshis>, DbT::Error>
77where
78 DbT: LowLevelWalletRead,
79 DbT::Error: From<BalanceError>,
80{
81 tx.fee_paid(|_outpoint| {
82 #[cfg(not(feature = "transparent-inputs"))]
83 {
84 Ok(None)
88 }
89
90 #[cfg(feature = "transparent-inputs")]
92 if let Some(out) = _wallet_db.get_wallet_transparent_output(_outpoint, None)? {
93 Ok(Some(out.txout().value()))
94 } else {
95 Ok(None)
97 }
98 })
99}
100
101#[cfg(feature = "transparent-inputs")]
106pub fn generate_transparent_gap_addresses<DbT, SE>(
107 wallet_db: &mut DbT,
108 gap_limits: GapLimits,
109 account_id: <DbT as LowLevelWalletRead>::AccountId,
110 key_scope: TransparentKeyScope,
111 request: UnifiedAddressRequest,
112) -> Result<(), GapAddressesError<SE>>
113where
114 DbT: LowLevelWalletWrite<Error = SE>
115 + AddressStore<Error = SE, AccountRef = <DbT as LowLevelWalletRead>::AccountRef>,
116 DbT::TxRef: Eq + Hash,
117{
118 let account_ref = wallet_db
119 .get_account_ref(account_id)
120 .map_err(GapAddressesError::Storage)?;
121
122 let account = wallet_db
123 .get_account_internal(account_ref)
124 .map_err(GapAddressesError::Storage)?
125 .ok_or(GapAddressesError::AccountUnknown)?;
126
127 generate_gap_addresses(
128 wallet_db,
129 &gap_limits,
130 account_ref,
131 &account.uivk(),
132 account.ufvk(),
133 key_scope,
134 request,
135 false,
136 )?;
137
138 Ok(())
139}
140
141#[derive(Debug)]
142#[non_exhaustive]
143pub enum PutBlocksError<SE, TE> {
144 NonSequentialBlocks {
146 prev_height: BlockHeight,
147 block_height: BlockHeight,
148 },
149 Continuity(ScanError),
154 Storage(SE),
156 ShardTree(ShardTreeError<TE>),
158 ShardTreeForBlockRange {
164 pool: ShieldedPool,
166 block_range: Range<BlockHeight>,
169 error: ShardTreeError<TE>,
171 },
172 #[cfg(feature = "transparent-inputs")]
173 GapAddresses(GapAddressesError<SE>),
174}
175
176impl<SE, TE> PutBlocksError<SE, TE> {
177 fn tree_update(
182 pool: ShieldedPool,
183 from_height: BlockHeight,
184 last_scanned_height: BlockHeight,
185 error: ShardTreeError<TE>,
186 ) -> Self {
187 match error {
188 ShardTreeError::Insert(InsertionError::Conflict(address)) => {
189 PutBlocksError::Continuity(ScanError::CommitmentTreeConflict {
190 pool,
191 at_height: from_height + 1,
192 address,
193 })
194 }
195 error => PutBlocksError::ShardTreeForBlockRange {
196 pool,
197 block_range: from_height..(last_scanned_height + 1),
198 error,
199 },
200 }
201 }
202}
203
204impl<SE, TE> From<ShardTreeError<TE>> for PutBlocksError<SE, TE> {
205 fn from(value: ShardTreeError<TE>) -> Self {
206 PutBlocksError::ShardTree(value)
207 }
208}
209
210#[cfg(feature = "transparent-inputs")]
211impl<SE, TE> From<GapAddressesError<SE>> for PutBlocksError<SE, TE> {
212 fn from(value: GapAddressesError<SE>) -> Self {
213 PutBlocksError::GapAddresses(value)
214 }
215}
216
217#[cfg(not(feature = "transparent-inputs"))]
219pub trait PutBlocksDbT<SE, TE, AR>:
220 LowLevelWalletWrite<Error = SE> + WalletCommitmentTrees<Error = TE>
221{
222}
223
224#[cfg(not(feature = "transparent-inputs"))]
225impl<T: LowLevelWalletWrite<Error = SE> + WalletCommitmentTrees<Error = TE>, SE, TE, AR>
226 PutBlocksDbT<SE, TE, AR> for T
227{
228}
229
230#[cfg(feature = "transparent-inputs")]
238pub trait PutBlocksDbT<SE, TE, AR>:
239 LowLevelWalletWrite<Error = SE>
240 + WalletCommitmentTrees<Error = TE>
241 + AddressStore<Error = SE, AccountRef = AR>
242{
243}
244
245#[cfg(feature = "transparent-inputs")]
246impl<
247 T: LowLevelWalletWrite<Error = SE>
248 + WalletCommitmentTrees<Error = TE>
249 + AddressStore<Error = SE, AccountRef = AR>,
250 SE,
251 TE,
252 AR,
253> PutBlocksDbT<SE, TE, AR> for T
254{
255}
256
257#[cfg(not(feature = "transparent-inputs"))]
262pub trait PutBlocksRowsDbT<SE, AR>: LowLevelWalletWrite<Error = SE> {}
263
264#[cfg(not(feature = "transparent-inputs"))]
265impl<T: LowLevelWalletWrite<Error = SE>, SE, AR> PutBlocksRowsDbT<SE, AR> for T {}
266
267#[cfg(feature = "transparent-inputs")]
278pub trait PutBlocksRowsDbT<SE, AR>:
279 LowLevelWalletWrite<Error = SE> + AddressStore<Error = SE, AccountRef = AR>
280{
281}
282
283#[cfg(feature = "transparent-inputs")]
284impl<T: LowLevelWalletWrite<Error = SE> + AddressStore<Error = SE, AccountRef = AR>, SE, AR>
285 PutBlocksRowsDbT<SE, AR> for T
286{
287}
288
289#[derive(Default)]
296pub struct PutBlocksRows {
297 pub sapling_commitments: Vec<Option<(sapling::Node, Retention<BlockHeight>)>>,
300 #[cfg(feature = "orchard")]
303 pub orchard_commitments:
304 Vec<Option<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>>,
305 #[cfg(feature = "orchard")]
308 pub ironwood_commitments:
309 Vec<Option<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>>,
310 pub note_positions: Vec<(ShieldedPool, Position)>,
313 pub last_scanned_height: Option<BlockHeight>,
316}
317
318pub fn put_blocks_rows<DbT, P, SE, TE>(
362 wallet_db: &mut DbT,
363 params: &P,
364 #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
365 from_state: &ChainState,
366 blocks: Vec<ScannedBlock<<DbT as LowLevelWalletRead>::AccountId>>,
367) -> Result<PutBlocksRows, PutBlocksError<SE, TE>>
368where
369 DbT: PutBlocksRowsDbT<SE, <DbT as LowLevelWalletRead>::AccountRef>,
370 DbT::TxRef: Eq + Hash,
371 P: consensus::Parameters,
372{
373 if blocks.is_empty() {
374 return Ok(PutBlocksRows::default());
375 }
376
377 let initial_block = blocks.first().expect("blocks is known to be nonempty");
378 let mut initial_block_sequential = from_state.block_height() + 1 == initial_block.height();
379 {
380 initial_block_sequential &= from_state.final_sapling_tree().tree_size()
381 + u64::try_from(initial_block.sapling().commitments().len()).unwrap()
382 == u64::from(initial_block.sapling().final_tree_size());
383 }
384 #[cfg(feature = "orchard")]
385 {
386 initial_block_sequential &= from_state.final_orchard_tree().tree_size()
387 + u64::try_from(initial_block.orchard().commitments().len()).unwrap()
388 == u64::from(initial_block.orchard().final_tree_size());
389 initial_block_sequential &= from_state.final_ironwood_tree().tree_size()
390 + u64::try_from(initial_block.ironwood().commitments().len()).unwrap()
391 == u64::from(initial_block.ironwood().final_tree_size());
392 }
393 if !initial_block_sequential {
394 return Err(PutBlocksError::NonSequentialBlocks {
395 prev_height: from_state.block_height(),
396 block_height: initial_block.height(),
397 });
398 }
399
400 let spend_tracking_floor = spend_tracking_floor(
401 wallet_db
402 .block_fully_scanned_height()
403 .map_err(PutBlocksError::Storage)?,
404 from_state.block_height(),
405 blocks.last().map(|block| block.height()),
406 );
407
408 let mut sapling_commitments = vec![];
409 #[cfg(feature = "orchard")]
410 let mut orchard_commitments = vec![];
411 #[cfg(feature = "orchard")]
412 let mut ironwood_commitments = vec![];
413 let mut last_scanned_height = None;
414 let mut note_positions = vec![];
415
416 #[cfg(feature = "transparent-inputs")]
417 let mut tx_refs = HashSet::new();
418
419 for block in blocks.into_iter() {
420 if last_scanned_height
421 .iter()
422 .any(|prev| block.height() != *prev + 1)
423 {
424 return Err(PutBlocksError::NonSequentialBlocks {
425 prev_height: last_scanned_height.expect("last scanned height is known"),
426 block_height: block.height(),
427 });
428 }
429
430 wallet_db
432 .put_block_meta(
433 block.height(),
434 block.block_hash(),
435 block.block_time(),
436 block.sapling().final_tree_size(),
437 block.sapling().commitments().len().try_into().unwrap(),
438 #[cfg(feature = "orchard")]
439 block.orchard().final_tree_size(),
440 #[cfg(feature = "orchard")]
441 block.orchard().commitments().len().try_into().unwrap(),
442 #[cfg(feature = "orchard")]
443 block.ironwood().final_tree_size(),
444 #[cfg(feature = "orchard")]
445 block.ironwood().commitments().len().try_into().unwrap(),
446 )
447 .map_err(|error| match error {
448 PutBlockMetaError::HashMismatch { stored } => {
449 PutBlocksError::Continuity(ScanError::BlockHashMismatch {
450 at_height: block.height(),
451 stored,
452 scanned: block.block_hash(),
453 })
454 }
455 PutBlockMetaError::Storage(error) => PutBlocksError::Storage(error),
456 })?;
457
458 for tx in block.transactions() {
459 let tx_ref = wallet_db
460 .put_tx_meta(tx, block.height())
461 .map_err(PutBlocksError::Storage)?;
462
463 #[cfg(feature = "transparent-inputs")]
464 tx_refs.insert(tx_ref);
465
466 wallet_db
467 .queue_tx_retrieval(std::iter::once(tx.txid()), None)
468 .map_err(PutBlocksError::Storage)?;
469
470 #[cfg(feature = "transparent-inputs")]
475 wallet_db
476 .put_transparent_address_observations(tx_ref, tx.transparent_address_observations())
477 .map_err(PutBlocksError::Storage)?;
478
479 let _ = mark_notes_spent(
483 wallet_db,
484 tx_ref,
485 #[cfg(feature = "transparent-inputs")]
486 tx.transparent_spends().iter().map(|spend| spend.outpoint()),
487 tx.sapling_spends().iter().map(|spend| spend.nf()),
488 #[cfg(feature = "orchard")]
489 tx.orchard_spends().iter().map(|spend| spend.nf()),
490 #[cfg(feature = "orchard")]
491 tx.ironwood_spends().iter().map(|spend| spend.nf()),
492 )
493 .map_err(PutBlocksError::Storage)?;
494
495 put_shielded_outputs(
496 wallet_db,
497 params,
498 tx_ref,
499 None,
500 tx.sapling_outputs(),
501 |wallet_db, output| {
504 Ok(output
505 .nf()
506 .map(|nf| wallet_db.detect_sapling_spend(nf))
507 .transpose()?
508 .flatten())
509 },
510 |wallet_db, output, tx_ref, spent_in| {
511 wallet_db.put_received_sapling_note(
512 output,
513 tx_ref,
514 Some(block.height()),
515 spent_in,
516 )
517 },
518 |_account_id| (),
519 )
520 .map_err(PutBlocksError::Storage)?;
521
522 #[cfg(feature = "orchard")]
523 put_shielded_outputs(
524 wallet_db,
525 params,
526 tx_ref,
527 None,
528 tx.orchard_outputs(),
529 |wallet_db, output| {
532 Ok(output
533 .nf()
534 .map(|nf| wallet_db.detect_orchard_spend(nf))
535 .transpose()?
536 .flatten())
537 },
538 |wallet_db, output, tx_ref, spent_in| {
539 wallet_db.put_received_orchard_note(
540 output,
541 tx_ref,
542 Some(block.height()),
543 spent_in,
544 )
545 },
546 |_account_id| (),
547 )
548 .map_err(PutBlocksError::Storage)?;
549
550 #[cfg(feature = "orchard")]
551 put_shielded_outputs(
552 wallet_db,
553 params,
554 tx_ref,
555 None,
556 tx.ironwood_outputs(),
557 |wallet_db, output| {
560 Ok(output
561 .nf()
562 .map(|nf| wallet_db.detect_ironwood_spend(nf))
563 .transpose()?
564 .flatten())
565 },
566 |wallet_db, output, tx_ref, spent_in| {
567 wallet_db.put_received_ironwood_note(
568 output,
569 tx_ref,
570 Some(block.height()),
571 spent_in,
572 )
573 },
574 |_account_id| (),
575 )
576 .map_err(PutBlocksError::Storage)?;
577
578 #[cfg(feature = "transparent-inputs")]
585 for output in tx.transparent_outputs() {
586 put_received_transparent_output(
587 wallet_db,
588 tx_ref,
589 output,
590 block.height(),
591 |_, _| (),
592 )
593 .map_err(PutBlocksError::Storage)?;
594 }
595 }
596
597 if should_track_spends(spend_tracking_floor, block.height()) {
600 wallet_db
601 .track_block_sapling_nullifiers(block.height(), block.sapling().nullifier_map())
602 .map_err(PutBlocksError::Storage)?;
603
604 #[cfg(feature = "orchard")]
605 wallet_db
606 .track_block_orchard_nullifiers(block.height(), block.orchard().nullifier_map())
607 .map_err(PutBlocksError::Storage)?;
608
609 #[cfg(feature = "orchard")]
610 wallet_db
611 .track_block_ironwood_nullifiers(block.height(), block.ironwood().nullifier_map())
612 .map_err(PutBlocksError::Storage)?;
613
614 #[cfg(feature = "transparent-inputs")]
615 wallet_db
616 .track_block_transparent_spends(block.height(), block.transparent_spend_map())
617 .map_err(PutBlocksError::Storage)?;
618 }
619
620 note_positions.extend(block.transactions().iter().flat_map(|wtx| {
621 let iter = wtx
622 .sapling_outputs()
623 .iter()
624 .map(|out| (ShieldedPool::Sapling, out.note_commitment_tree_position()));
625 #[cfg(feature = "orchard")]
626 let iter = iter.chain(
627 wtx.orchard_outputs()
628 .iter()
629 .map(|out| (ShieldedPool::Orchard, out.note_commitment_tree_position())),
630 );
631 #[cfg(feature = "orchard")]
632 let iter = iter.chain(
633 wtx.ironwood_outputs()
634 .iter()
635 .map(|out| (ShieldedPool::Ironwood, out.note_commitment_tree_position())),
636 );
637
638 iter
639 }));
640
641 last_scanned_height = Some(block.height());
642 let block_commitments = block.into_commitments();
643 trace!(
644 "Sapling commitments for {:?}: {:?}",
645 last_scanned_height,
646 block_commitments
647 .sapling
648 .iter()
649 .map(|(_, r)| *r)
650 .collect::<Vec<_>>()
651 );
652 #[cfg(feature = "orchard")]
653 trace!(
654 "Orchard commitments for {:?}: {:?}",
655 last_scanned_height,
656 block_commitments
657 .orchard
658 .iter()
659 .map(|(_, r)| *r)
660 .collect::<Vec<_>>()
661 );
662
663 sapling_commitments.extend(block_commitments.sapling.into_iter().map(Some));
664 #[cfg(feature = "orchard")]
665 orchard_commitments.extend(block_commitments.orchard.into_iter().map(Some));
666 #[cfg(feature = "orchard")]
667 ironwood_commitments.extend(block_commitments.ironwood.into_iter().map(Some));
668 }
669
670 #[cfg(feature = "transparent-inputs")]
671 for (account_id, key_scope) in wallet_db
672 .find_involved_accounts(tx_refs)
673 .map_err(PutBlocksError::Storage)?
674 {
675 if let Some(t_key_scope) = key_scope {
676 generate_transparent_gap_addresses(
677 wallet_db,
678 gap_limits,
679 account_id,
680 t_key_scope,
681 UnifiedAddressRequest::unsafe_custom(Allow, Allow, Require),
682 )
683 .map_err(PutBlocksError::GapAddresses)?;
684 }
685 }
686
687 wallet_db
689 .prune_tracked_spends(PRUNING_DEPTH)
690 .map_err(PutBlocksError::Storage)?;
691
692 Ok(PutBlocksRows {
693 sapling_commitments,
694 #[cfg(feature = "orchard")]
695 orchard_commitments,
696 #[cfg(feature = "orchard")]
697 ironwood_commitments,
698 note_positions,
699 last_scanned_height,
700 })
701}
702
703pub fn put_blocks<DbT, P, SE, TE>(
732 wallet_db: &mut DbT,
733 params: &P,
734 #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
735 from_state: &ChainState,
736 blocks: Vec<ScannedBlock<<DbT as LowLevelWalletRead>::AccountId>>,
737 chain_tip: Option<BlockHeight>,
738 anchor_retention: Option<&AnchorRetention>,
739) -> Result<(), PutBlocksError<SE, TE>>
740where
741 DbT: PutBlocksDbT<SE, TE, <DbT as LowLevelWalletRead>::AccountRef>,
742 DbT::TxRef: Eq + Hash,
743 P: consensus::Parameters,
744{
745 let rows = put_blocks_rows(
746 wallet_db,
747 params,
748 #[cfg(feature = "transparent-inputs")]
749 gap_limits,
750 from_state,
751 blocks,
752 )?;
753
754 let mut sapling_commitments = rows.sapling_commitments;
755 #[cfg(feature = "orchard")]
756 let mut orchard_commitments = rows.orchard_commitments;
757 #[cfg(feature = "orchard")]
758 let mut ironwood_commitments = rows.ironwood_commitments;
759 let note_positions = rows.note_positions;
760 let last_scanned_height = rows.last_scanned_height;
761
762 if let Some(last_scanned_height) = last_scanned_height {
765 let mut checkpoints = batch_checkpoints(
766 from_state,
767 last_scanned_height,
768 chain_tip,
769 anchor_retention,
770 &sapling_commitments,
771 #[cfg(feature = "orchard")]
772 &orchard_commitments,
773 #[cfg(feature = "orchard")]
774 &ironwood_commitments,
775 );
776 let checkpoint_floor = checkpoints.checkpoint_floor;
777
778 assign_block_end_retention(
779 &mut sapling_commitments,
780 Position::from(from_state.final_sapling_tree().tree_size()),
781 checkpoint_floor,
782 anchor_retention,
783 &mut checkpoints.sapling,
784 );
785 #[cfg(feature = "orchard")]
786 assign_block_end_retention(
787 &mut orchard_commitments,
788 Position::from(from_state.final_orchard_tree().tree_size()),
789 checkpoint_floor,
790 anchor_retention,
791 &mut checkpoints.orchard,
792 );
793 #[cfg(feature = "orchard")]
794 assign_block_end_retention(
795 &mut ironwood_commitments,
796 Position::from(from_state.final_ironwood_tree().tree_size()),
797 checkpoint_floor,
798 anchor_retention,
799 &mut checkpoints.ironwood,
800 );
801
802 const CHUNK_SIZE: usize = 1024;
804 let sapling_subtrees = build_subtrees::<_, SAPLING_SHARD_HEIGHT>(
805 Position::from(from_state.final_sapling_tree().tree_size()),
806 &mut sapling_commitments,
807 CHUNK_SIZE,
808 );
809
810 #[cfg(feature = "orchard")]
811 let orchard_subtrees = build_subtrees::<_, ORCHARD_SHARD_HEIGHT>(
812 Position::from(from_state.final_orchard_tree().tree_size()),
813 &mut orchard_commitments,
814 CHUNK_SIZE,
815 );
816
817 #[cfg(feature = "orchard")]
820 let ironwood_subtrees = build_subtrees::<_, ORCHARD_SHARD_HEIGHT>(
821 Position::from(from_state.final_ironwood_tree().tree_size()),
822 &mut ironwood_commitments,
823 CHUNK_SIZE,
824 );
825
826 {
828 let mut sapling_subtrees = sapling_subtrees.into_iter();
829 let mut missing_checkpoints = checkpoints.sapling.into_iter();
830 wallet_db.with_sapling_tree_mut(|sapling_tree| {
831 update_tree(
832 "Sapling",
833 from_state.final_sapling_tree(),
834 from_state.block_height(),
835 checkpoint_floor,
836 sapling_tree,
837 anchor_retention,
838 &mut sapling_subtrees,
839 &mut missing_checkpoints,
840 )
841 .map_err(|error| {
842 PutBlocksError::tree_update(
843 ShieldedPool::Sapling,
844 from_state.block_height(),
845 last_scanned_height,
846 error,
847 )
848 })
849 })?;
850 }
851
852 #[cfg(feature = "orchard")]
854 {
855 let mut orchard_subtrees = orchard_subtrees.into_iter();
856 let mut missing_checkpoints = checkpoints.orchard.into_iter();
857 wallet_db.with_orchard_tree_mut(|orchard_tree| {
858 update_tree(
859 "Orchard",
860 from_state.final_orchard_tree(),
861 from_state.block_height(),
862 checkpoint_floor,
863 orchard_tree,
864 anchor_retention,
865 &mut orchard_subtrees,
866 &mut missing_checkpoints,
867 )
868 .map_err(|error| {
869 PutBlocksError::tree_update(
870 ShieldedPool::Orchard,
871 from_state.block_height(),
872 last_scanned_height,
873 error,
874 )
875 })
876 })?;
877 }
878
879 #[cfg(feature = "orchard")]
881 {
882 let mut ironwood_subtrees = ironwood_subtrees.into_iter();
883 let mut missing_checkpoints = checkpoints.ironwood.into_iter();
884 wallet_db.with_ironwood_tree_mut(|ironwood_tree| {
885 update_tree(
886 "Ironwood",
887 from_state.final_ironwood_tree(),
888 from_state.block_height(),
889 checkpoint_floor,
890 ironwood_tree,
891 anchor_retention,
892 &mut ironwood_subtrees,
893 &mut missing_checkpoints,
894 )
895 .map_err(|error| {
896 PutBlocksError::tree_update(
897 ShieldedPool::Ironwood,
898 from_state.block_height(),
899 last_scanned_height,
900 error,
901 )
902 })
903 })?;
904 }
905
906 wallet_db
907 .notify_scan_complete(
908 Range {
909 start: from_state.block_height() + 1,
910 end: last_scanned_height + 1,
911 },
912 ¬e_positions,
913 )
914 .map_err(PutBlocksError::Storage)?;
915 }
916
917 Ok(())
918}
919
920#[cfg(not(feature = "transparent-inputs"))]
921type GapError<DbT> = <DbT as LowLevelWalletRead>::Error;
922
923#[cfg(not(feature = "transparent-inputs"))]
925pub trait StoreDecryptedTxDbT: LowLevelWalletWrite {}
926
927#[cfg(not(feature = "transparent-inputs"))]
928impl<T: LowLevelWalletWrite> StoreDecryptedTxDbT for T {}
929
930#[cfg(feature = "transparent-inputs")]
931type GapError<DbT> = GapAddressesError<<DbT as LowLevelWalletRead>::Error>;
932
933#[cfg(feature = "transparent-inputs")]
941pub trait StoreDecryptedTxDbT:
942 LowLevelWalletWrite
943 + AddressStore<
944 Error = <Self as LowLevelWalletRead>::Error,
945 AccountRef = <Self as LowLevelWalletRead>::AccountRef,
946 >
947where
948 <Self as LowLevelWalletRead>::Error: From<GapError<Self>>,
949{
950}
951
952#[cfg(feature = "transparent-inputs")]
953impl<
954 T: LowLevelWalletWrite
955 + AddressStore<
956 Error = <T as LowLevelWalletRead>::Error,
957 AccountRef = <T as LowLevelWalletRead>::AccountRef,
958 >,
959> StoreDecryptedTxDbT for T
960where
961 <T as LowLevelWalletRead>::Error: From<GapError<T>>,
962{
963}
964
965pub fn store_decrypted_tx<DbT, P>(
988 wallet_db: &mut DbT,
989 params: &P,
990 #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
991 chain_tip_height: BlockHeight,
992 d_tx: DecryptedTransaction<Transaction, <DbT as LowLevelWalletRead>::AccountId>,
993) -> Result<(), <DbT as LowLevelWalletRead>::Error>
994where
995 DbT: StoreDecryptedTxDbT,
996 <DbT as LowLevelWalletRead>::AccountId: core::fmt::Debug,
997 <DbT as LowLevelWalletRead>::Error: From<BalanceError> + From<GapError<DbT>>,
998 P: consensus::Parameters,
999{
1000 let funding_accounts = wallet_db.get_funding_accounts(d_tx.tx())?;
1001
1002 let funding_account = funding_accounts.iter().next().copied();
1004 if funding_accounts.len() > 1 {
1005 warn!(
1006 "More than one wallet account detected as funding transaction {:?}, selecting {:?}",
1007 d_tx.tx().txid(),
1008 funding_account.unwrap()
1009 )
1010 }
1011
1012 let wallet_transparent_outputs =
1013 detect_wallet_transparent_outputs::<_, _, <DbT as LowLevelWalletRead>::Error>(
1014 params,
1015 d_tx.tx(),
1016 d_tx.mined_height(),
1017 funding_account,
1018 #[cfg(feature = "transparent-inputs")]
1019 |address| wallet_db.find_account_for_transparent_address(address),
1020 )?;
1021
1022 if funding_account.is_none()
1025 && wallet_transparent_outputs.is_empty()
1026 && !d_tx.has_decrypted_outputs()
1027 {
1028 wallet_db.delete_retrieval_queue_entries(d_tx.tx().txid())?;
1029 return Ok(());
1030 }
1031
1032 info!("Storing decrypted transaction with id {}", d_tx.tx().txid());
1033 let observed_height = d_tx.mined_height().unwrap_or(chain_tip_height + 1);
1034
1035 let fee = determine_fee(wallet_db, d_tx.tx())?;
1038
1039 let tx_ref = wallet_db.put_tx_data(d_tx.tx(), fee, None, None, observed_height)?;
1040 if let Some(height) = d_tx.mined_height() {
1041 wallet_db.set_transaction_status(d_tx.tx().txid(), TransactionStatus::Mined(height))?;
1042 }
1043
1044 #[cfg(feature = "transparent-inputs")]
1047 wallet_db.put_transparent_address_observations(
1048 tx_ref,
1049 &crate::wallet::transparent_address_observations(d_tx.tx()),
1050 )?;
1051
1052 #[cfg(feature = "orchard")]
1065 {
1066 let migration_params = PoolMigrationParams::new(
1067 zcash_protocol::zip318::BlockSpacing::for_network(params),
1068 AnchorRetentionInterval::default(),
1069 );
1070 let classification = crate::data_api::zip318::classify_decrypted_tx(
1071 d_tx.tx(),
1072 d_tx.orchard_outputs(),
1073 d_tx.ironwood_outputs(),
1074 &migration_params,
1075 );
1076 wallet_db.put_zip318_classification(tx_ref, classification)?;
1077 }
1078
1079 let has_wallet_shielded_spend = mark_notes_spent(
1080 wallet_db,
1081 tx_ref,
1082 #[cfg(feature = "transparent-inputs")]
1083 d_tx.tx()
1084 .transparent_bundle()
1085 .iter()
1086 .flat_map(|b| b.vin.iter())
1087 .map(|txin| txin.prevout()),
1088 d_tx.tx()
1089 .sapling_bundle()
1090 .iter()
1091 .flat_map(|b| b.shielded_spends().iter())
1092 .map(|spend| spend.nullifier()),
1093 #[cfg(feature = "orchard")]
1094 d_tx.tx()
1095 .orchard_bundle()
1096 .iter()
1097 .flat_map(|b| b.actions().iter())
1098 .map(|action| action.nullifier()),
1099 #[cfg(feature = "orchard")]
1100 d_tx.tx()
1101 .ironwood_bundle()
1102 .iter()
1103 .flat_map(|b| b.actions().iter())
1104 .map(|action| action.nullifier()),
1105 )?;
1106
1107 #[cfg(feature = "transparent-inputs")]
1111 let mut tx_has_wallet_outputs = false;
1112 #[cfg(feature = "transparent-inputs")]
1113 {
1114 tx_has_wallet_outputs |= !d_tx.sapling_outputs().is_empty();
1115
1116 #[cfg(feature = "orchard")]
1117 {
1118 tx_has_wallet_outputs |= !d_tx.orchard_outputs().is_empty();
1119 tx_has_wallet_outputs |= !d_tx.ironwood_outputs().is_empty();
1120 }
1121
1122 tx_has_wallet_outputs |= !wallet_transparent_outputs.is_empty();
1129 }
1130
1131 #[cfg(feature = "transparent-inputs")]
1133 let mut gap_update_set = HashSet::new();
1134
1135 put_shielded_outputs(
1136 wallet_db,
1137 params,
1138 tx_ref,
1139 funding_account,
1140 d_tx.sapling_outputs(),
1141 |_, _| Ok(None),
1142 |wallet_db, output, tx_ref, spent_in| {
1143 wallet_db.put_received_sapling_note(output, tx_ref, d_tx.mined_height(), spent_in)
1144 },
1145 |_account_id| {
1146 #[cfg(feature = "transparent-inputs")]
1147 gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1148 },
1149 )?;
1150
1151 #[cfg(feature = "orchard")]
1152 put_shielded_outputs(
1153 wallet_db,
1154 params,
1155 tx_ref,
1156 funding_account,
1157 d_tx.orchard_outputs(),
1158 |_, _| Ok(None),
1159 |wallet_db, output, tx_ref, spent_in| {
1160 wallet_db.put_received_orchard_note(output, tx_ref, d_tx.mined_height(), spent_in)
1161 },
1162 |_account_id| {
1163 #[cfg(feature = "transparent-inputs")]
1164 gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1165 },
1166 )?;
1167
1168 #[cfg(feature = "orchard")]
1171 put_shielded_outputs(
1172 wallet_db,
1173 params,
1174 tx_ref,
1175 funding_account,
1176 d_tx.ironwood_outputs(),
1177 |_, _| Ok(None),
1178 |wallet_db, output, tx_ref, spent_in| {
1179 wallet_db.put_received_ironwood_note(output, tx_ref, d_tx.mined_height(), spent_in)
1180 },
1181 |_account_id| {
1182 #[cfg(feature = "transparent-inputs")]
1183 gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1184 },
1185 )?;
1186
1187 put_transparent_outputs(
1188 wallet_db,
1189 params,
1190 tx_ref,
1191 &wallet_transparent_outputs,
1192 #[cfg(feature = "transparent-inputs")]
1193 observed_height,
1194 #[cfg(feature = "transparent-inputs")]
1195 |account_id, t_key_scope| {
1196 gap_update_set.insert((account_id, t_key_scope));
1197 },
1198 )?;
1199
1200 #[cfg(feature = "transparent-inputs")]
1202 for (account_id, key_scope) in gap_update_set {
1203 generate_transparent_gap_addresses(
1204 wallet_db,
1205 gap_limits,
1206 account_id,
1207 key_scope,
1208 UnifiedAddressRequest::unsafe_custom(Allow, Allow, Require),
1209 )?;
1210 }
1211
1212 for (spending_tx_ref, spending_tx) in wallet_db.get_unknown_fee_spenders_of(tx_ref)? {
1215 if let Some(fee) = determine_fee(wallet_db, &spending_tx)? {
1216 wallet_db.update_tx_fee(spending_tx_ref, fee)?;
1217 }
1218 }
1219
1220 #[cfg(feature = "transparent-inputs")]
1225 if tx_has_wallet_outputs {
1226 wallet_db.queue_transparent_input_retrieval(tx_ref, &d_tx)?
1227 }
1228
1229 wallet_db.delete_retrieval_queue_entries(d_tx.tx().txid())?;
1232
1233 if d_tx.mined_height().is_none() && !(has_wallet_shielded_spend || d_tx.has_decrypted_outputs())
1237 {
1238 wallet_db.queue_tx_status(d_tx.tx().txid())?;
1239 }
1240
1241 Ok(())
1242}
1243
1244pub fn detect_wallet_transparent_outputs<P, AccountId, E>(
1255 params: &P,
1256 tx: &Transaction,
1257 mined_height: Option<BlockHeight>,
1258 funding_account: Option<AccountId>,
1259 #[cfg(feature = "transparent-inputs")] find_account_for_address: impl Fn(
1260 &TransparentAddress,
1261 ) -> Result<
1262 Option<(AccountId, Option<TransparentKeyScope>)>,
1263 E,
1264 >,
1265) -> Result<Vec<WalletTransparentOutput<AccountId>>, E>
1266where
1267 P: consensus::Parameters,
1268 AccountId: Copy + core::fmt::Debug + std::hash::Hash + std::cmp::Eq,
1269{
1270 let mut result = vec![];
1271 for (output_index, txout) in tx
1272 .transparent_bundle()
1273 .iter()
1274 .flat_map(|b| b.vout.iter())
1275 .enumerate()
1276 {
1277 let script_kind = txout.script_kind();
1278 if let Some(address) = script_kind
1279 .as_ref()
1280 .and_then(TransparentAddress::from_script_kind)
1281 {
1282 debug!(
1283 "{:?} output {} has recipient {}",
1284 tx.txid(),
1285 output_index,
1286 address.encode(params)
1287 );
1288
1289 #[allow(unused_mut)]
1290 let mut detected = false;
1291
1292 #[cfg(feature = "transparent-inputs")]
1294 if let Some((account_uuid, key_scope)) = find_account_for_address(&address)? {
1295 debug!(
1296 "{:?} output {} belongs to account {:?}",
1297 tx.txid(),
1298 output_index,
1299 account_uuid
1300 );
1301 result.push(
1302 WalletTransparentOutput::from_parts(
1303 OutPoint::new(tx.txid().into(), u32::try_from(output_index).unwrap()),
1304 txout.clone(),
1305 mined_height,
1306 Some(account_uuid),
1307 key_scope,
1308 funding_account,
1309 )
1310 .expect("txout.recipient_address extraction previously checked"),
1311 );
1312 detected = true;
1313 } else {
1314 debug!(
1315 "Address {} is not recognized as belonging to any of our accounts.",
1316 address.encode(params)
1317 );
1318 }
1319
1320 if !detected {
1321 if let Some(account_id) = funding_account {
1325 result.push(
1326 WalletTransparentOutput::from_parts(
1327 OutPoint::new(tx.txid().into(), u32::try_from(output_index).unwrap()),
1328 txout.clone(),
1329 mined_height,
1330 None,
1331 None,
1332 Some(account_id),
1333 )
1334 .expect("txout.recipient_address extraction previously checked"),
1335 );
1336 }
1337 }
1338 } else if let Some(script_kind) = script_kind {
1339 if !matches!(script_kind, ScriptKind::NullData { .. }) {
1343 warn!(
1344 "Ignoring unsupported script kind '{}' for tx {} output {}",
1345 script_kind.as_str(),
1346 tx.txid(),
1347 output_index
1348 );
1349 }
1350 } else {
1351 warn!(
1352 "Unable to determine recipient address for tx {} output {}",
1353 tx.txid(),
1354 output_index
1355 );
1356 }
1357 }
1358
1359 Ok(result)
1360}
1361
1362fn mark_notes_spent<'a, DbT>(
1363 wallet_db: &mut DbT,
1364 tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1365 #[cfg(feature = "transparent-inputs")] transparent_prevouts: impl Iterator<
1366 Item = &'a transparent::bundle::OutPoint,
1367 >,
1368 sapling_nfs: impl Iterator<Item = &'a sapling::Nullifier>,
1369 #[cfg(feature = "orchard")] orchard_nfs: impl Iterator<Item = &'a orchard::note::Nullifier>,
1370 #[cfg(feature = "orchard")] ironwood_nfs: impl Iterator<Item = &'a orchard::note::Nullifier>,
1371) -> Result<bool, <DbT as LowLevelWalletRead>::Error>
1372where
1373 DbT: LowLevelWalletWrite,
1374{
1375 let mut has_wallet_shielded_spend = false;
1376
1377 #[cfg(feature = "transparent-inputs")]
1379 for outpoint in transparent_prevouts {
1380 wallet_db.mark_transparent_utxo_spent(outpoint, tx_ref)?;
1381 }
1382
1383 for nf in sapling_nfs {
1385 has_wallet_shielded_spend |= wallet_db.mark_sapling_note_spent(nf, tx_ref)?;
1386 }
1387
1388 #[cfg(feature = "orchard")]
1390 for nf in orchard_nfs {
1391 has_wallet_shielded_spend |= wallet_db.mark_orchard_note_spent(nf, tx_ref)?;
1392 }
1393
1394 #[cfg(feature = "orchard")]
1396 for nf in ironwood_nfs {
1397 has_wallet_shielded_spend |= wallet_db.mark_ironwood_note_spent(nf, tx_ref)?;
1398 }
1399
1400 Ok(has_wallet_shielded_spend)
1401}
1402
1403#[allow(clippy::too_many_arguments)]
1417fn put_shielded_outputs<DbT, P, Output>(
1418 wallet_db: &mut DbT,
1419 params: &P,
1420 tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1421 funding_account: Option<DbT::AccountId>,
1422 outputs: &[Output],
1423 detect_note_spent_in: impl Fn(
1424 &mut DbT,
1425 &Output,
1426 ) -> Result<
1427 Option<<DbT as LowLevelWalletRead>::TxRef>,
1428 <DbT as LowLevelWalletRead>::Error,
1429 >,
1430 put_received_note: impl Fn(
1431 &mut DbT,
1432 &Output,
1433 <DbT as LowLevelWalletRead>::TxRef,
1434 Option<<DbT as LowLevelWalletRead>::TxRef>,
1435 ) -> Result<(), <DbT as LowLevelWalletRead>::Error>,
1436 mut on_external_account: impl FnMut(<DbT as LowLevelWalletRead>::AccountId),
1437) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1438where
1439 DbT: LowLevelWalletWrite,
1440 P: consensus::Parameters,
1441 Output: ReceivedShieldedOutput<AccountId = <DbT as LowLevelWalletRead>::AccountId>,
1442{
1443 for output in outputs {
1444 match output.transfer_type() {
1448 TransferType::AccountInternal => {
1449 let spent_in = detect_note_spent_in(wallet_db, output)?;
1450 put_received_note(wallet_db, output, tx_ref, spent_in)?;
1451 }
1452 TransferType::Incoming => {
1453 let spent_in = detect_note_spent_in(wallet_db, output)?;
1454 put_received_note(wallet_db, output, tx_ref, spent_in)?;
1455 on_external_account(output.account_id());
1456 }
1457 TransferType::Outgoing => {}
1458 TransferType::WalletInternal => unreachable!(
1459 "TransferType::WalletInternal is only produced for transparent outputs"
1460 ),
1461 }
1462
1463 if let Some((from_account_uuid, recipient, value)) =
1464 shielded_sent_output_recipient(params, output, funding_account, |account, receiver| {
1465 wallet_db.select_receiving_address(account, receiver)
1466 })?
1467 {
1468 wallet_db.put_sent_output(
1469 from_account_uuid,
1470 tx_ref,
1471 output.index(),
1472 &recipient,
1473 value,
1474 output.memo(),
1475 )?;
1476 }
1477 }
1478
1479 Ok(())
1480}
1481
1482pub type SentOutput<AccountId> = (AccountId, Recipient<AccountId>, Zatoshis);
1485
1486pub fn shielded_sent_output_recipient<P, Output, E>(
1505 params: &P,
1506 output: &Output,
1507 funding_account: Option<Output::AccountId>,
1508 select_receiving_address: impl FnOnce(
1509 Output::AccountId,
1510 &Receiver,
1511 ) -> Result<Option<zcash_address::ZcashAddress>, E>,
1512) -> Result<Option<SentOutput<Output::AccountId>>, E>
1513where
1514 P: consensus::Parameters,
1515 Output: ReceivedShieldedOutput,
1516 Output::AccountId: Copy,
1517{
1518 Ok(match output.transfer_type() {
1519 TransferType::Outgoing => {
1520 let note = output.to_wallet_note();
1521
1522 let receiver = note.receiver();
1523 let recipient = Recipient::External {
1524 recipient_address: select_receiving_address(output.account_id(), &receiver)?
1525 .unwrap_or_else(|| receiver.to_zcash_address(params.network_type())),
1526 output_pool: PoolType::Shielded(note.pool()),
1527 };
1528
1529 Some((output.account_id(), recipient, note.value()))
1530 }
1531 TransferType::AccountInternal => {
1532 let note = output.to_wallet_note();
1533 let value = note.value();
1534
1535 let recipient = Recipient::InternalShielded {
1536 receiving_account: output.account_id(),
1537 external_address: None,
1538 note: Box::new(note),
1539 };
1540
1541 Some((output.account_id(), recipient, value))
1542 }
1543 TransferType::Incoming => match funding_account {
1544 Some(account_id) => {
1545 let note = output.to_wallet_note();
1546 let value = note.value();
1547
1548 let receiver = note.receiver();
1550 let recipient = Recipient::InternalShielded {
1551 receiving_account: output.account_id(),
1552 external_address: Some(
1553 select_receiving_address(output.account_id(), &receiver)?
1554 .unwrap_or_else(|| receiver.to_zcash_address(params.network_type())),
1555 ),
1556 note: Box::new(note),
1557 };
1558
1559 Some((account_id, recipient, value))
1560 }
1561 None => None,
1562 },
1563 TransferType::WalletInternal => {
1564 unreachable!("TransferType::WalletInternal is only produced for transparent outputs")
1565 }
1566 })
1567}
1568
1569#[cfg(feature = "transparent-inputs")]
1586fn put_received_transparent_output<DbT>(
1587 wallet_db: &mut DbT,
1588 tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1589 output: &WalletTransparentOutput<<DbT as LowLevelWalletRead>::AccountId>,
1590 observation_height: BlockHeight,
1591 mut on_received: impl FnMut(<DbT as LowLevelWalletRead>::AccountId, TransparentKeyScope),
1592) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1593where
1594 DbT: LowLevelWalletWrite,
1595{
1596 if output.recipient_account().is_none() {
1597 return Ok(());
1598 }
1599
1600 let (account_id, _) = wallet_db.put_transparent_output(output, observation_height, false)?;
1601
1602 if let Some(t_key_scope) = output.recipient_key_scope() {
1603 on_received(account_id, t_key_scope);
1604 }
1605
1606 wallet_db.queue_transparent_spend_detection(
1619 *output.recipient_address(),
1620 tx_ref,
1621 output.outpoint().n(),
1622 )?;
1623
1624 Ok(())
1625}
1626
1627fn put_transparent_outputs<DbT, P>(
1634 wallet_db: &mut DbT,
1635 params: &P,
1636 tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1637 outputs: &[WalletTransparentOutput<<DbT as LowLevelWalletRead>::AccountId>],
1638 #[cfg(feature = "transparent-inputs")] observation_height: BlockHeight,
1639 #[cfg(feature = "transparent-inputs")] mut on_received: impl FnMut(
1640 <DbT as LowLevelWalletRead>::AccountId,
1641 TransparentKeyScope,
1642 ),
1643) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1644where
1645 DbT: LowLevelWalletWrite,
1646 P: consensus::Parameters,
1647{
1648 for output in outputs {
1649 #[cfg(feature = "transparent-inputs")]
1652 put_received_transparent_output(
1653 wallet_db,
1654 tx_ref,
1655 output,
1656 observation_height,
1657 &mut on_received,
1658 )?;
1659
1660 if let Some((from_account, recipient)) =
1664 transparent_sent_output_recipient(params, output, |account, receiver| {
1665 wallet_db.select_receiving_address(account, receiver)
1666 })?
1667 {
1668 wallet_db.put_sent_output(
1669 from_account,
1670 tx_ref,
1671 output.index(),
1672 &recipient,
1673 output.value(),
1674 None,
1675 )?;
1676 }
1677 }
1678
1679 Ok(())
1680}
1681
1682pub fn transparent_sent_output_recipient<AccountId, P, E>(
1696 params: &P,
1697 output: &WalletTransparentOutput<AccountId>,
1698 select_receiving_address: impl FnOnce(
1699 AccountId,
1700 &Receiver,
1701 ) -> Result<Option<zcash_address::ZcashAddress>, E>,
1702) -> Result<Option<(AccountId, Recipient<AccountId>)>, E>
1703where
1704 AccountId: Copy,
1705 P: consensus::Parameters,
1706{
1707 let Some(&from_account) = output.funding_account() else {
1708 return Ok(None);
1709 };
1710
1711 let recipient = match output.recipient_account() {
1712 #[cfg(feature = "transparent-inputs")]
1713 Some(&receiving_account) => Recipient::InternalTransparent {
1714 receiving_account,
1715 recipient_address: *output.recipient_address(),
1716 },
1717 #[cfg(not(feature = "transparent-inputs"))]
1718 Some(_) => Recipient::External {
1719 recipient_address: Receiver::Transparent(*output.recipient_address())
1720 .to_zcash_address(params.network_type()),
1721 output_pool: PoolType::TRANSPARENT,
1722 },
1723 None => {
1724 let receiver = Receiver::Transparent(*output.recipient_address());
1725 let recipient_address = select_receiving_address(from_account, &receiver)?
1726 .unwrap_or_else(|| receiver.to_zcash_address(params.network_type()));
1727
1728 Recipient::External {
1729 recipient_address,
1730 output_pool: PoolType::TRANSPARENT,
1731 }
1732 }
1733 };
1734
1735 Ok(Some((from_account, recipient)))
1736}
1737
1738pub fn build_subtrees<H, const SHARD_HEIGHT: u8>(
1747 start_position: Position,
1748 commitments: &mut [Option<(H, Retention<BlockHeight>)>],
1749 chunk_size: usize,
1750) -> Vec<(LocatedPrunableTree<H>, BTreeMap<BlockHeight, Position>)>
1751where
1752 H: Clone + PartialEq + Hashable + Send + Sync,
1753{
1754 commitments
1755 .par_chunks_mut(chunk_size)
1756 .enumerate()
1757 .filter_map(|(i, chunk)| {
1758 let start = start_position + (i * chunk_size) as u64;
1759 let end = start + chunk.len() as u64;
1760
1761 shardtree::LocatedTree::from_iter(
1762 start..end,
1763 SHARD_HEIGHT.into(),
1764 chunk.iter_mut().map(|n| n.take().expect("always Some")),
1765 )
1766 })
1767 .map(|res| (res.subtree, res.checkpoints))
1768 .collect()
1769}
1770
1771pub fn checkpoint_positions<H>(
1773 subtrees: &[(LocatedPrunableTree<H>, BTreeMap<BlockHeight, Position>)],
1774) -> BTreeMap<BlockHeight, Position> {
1775 subtrees
1776 .iter()
1777 .flat_map(|(_, checkpoints)| checkpoints.iter())
1778 .map(|(k, v)| (*k, *v))
1779 .collect()
1780}
1781
1782pub fn ensure_checkpoints<'a, H, I: Iterator<Item = &'a BlockHeight>, const DEPTH: u8>(
1789 ensure_heights: I,
1790 created_checkpoints: &BTreeSet<BlockHeight>,
1791 block_end_positions: &BTreeMap<BlockHeight, Position>,
1792 state_final_tree: &Frontier<H, DEPTH>,
1793) -> Vec<(BlockHeight, Checkpoint)> {
1794 ensure_heights
1795 .filter(|ensure_height| !created_checkpoints.contains(ensure_height))
1796 .map(|ensure_height| {
1797 let checkpoint = block_end_positions
1798 .range::<BlockHeight, _>(..=*ensure_height)
1799 .last()
1800 .map_or_else(
1801 || {
1802 state_final_tree
1803 .value()
1804 .map_or_else(Checkpoint::tree_empty, |t| {
1805 Checkpoint::at_position(t.position())
1806 })
1807 },
1808 |(_, position)| Checkpoint::at_position(*position),
1809 );
1810 (*ensure_height, checkpoint)
1811 })
1812 .collect::<Vec<_>>()
1813}
1814
1815pub const SPEND_MAP_RETENTION_BLOCKS: u32 = 100;
1823
1824fn spend_tracking_floor(
1832 fully_scanned: Option<BlockHeight>,
1833 from_state_height: BlockHeight,
1834 batch_end: Option<BlockHeight>,
1835) -> Option<BlockHeight> {
1836 if fully_scanned == Some(from_state_height) {
1837 batch_end.and_then(|last| {
1838 let floor =
1839 BlockHeight::from(u32::from(last).saturating_sub(SPEND_MAP_RETENTION_BLOCKS));
1840 (floor > from_state_height + 1).then_some(floor)
1841 })
1842 } else {
1843 None
1844 }
1845}
1846
1847fn should_track_spends(
1854 spend_tracking_floor: Option<BlockHeight>,
1855 block_height: BlockHeight,
1856) -> bool {
1857 spend_tracking_floor.is_none_or(|floor| block_height >= floor)
1858}
1859
1860fn should_retain_anchor(anchor_retention: Option<&AnchorRetention>, height: BlockHeight) -> bool {
1864 anchor_retention.is_some_and(|retention| retention.retains(height))
1865}
1866
1867fn retain_anchor_checkpoint<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
1869 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
1870 anchor_retention: Option<&AnchorRetention>,
1871 height: BlockHeight,
1872) -> Result<(), ShardTreeError<S::Error>>
1873where
1874 S: ShardStore<CheckpointId = BlockHeight>,
1875 S::H: Clone + PartialEq + Hashable,
1876{
1877 if should_retain_anchor(anchor_retention, height) {
1878 tree.ensure_retained(height)?;
1879 }
1880 Ok(())
1881}
1882
1883pub fn cross_pool_ensure_heights(
1894 sapling: &BTreeSet<BlockHeight>,
1895 orchard: &BTreeSet<BlockHeight>,
1896 ironwood: &BTreeSet<BlockHeight>,
1897) -> [BTreeSet<BlockHeight>; 3] {
1898 let union = |a: &BTreeSet<BlockHeight>, b: &BTreeSet<BlockHeight>| {
1899 a.union(b).copied().collect::<BTreeSet<BlockHeight>>()
1900 };
1901 [
1902 union(orchard, ironwood),
1903 union(sapling, ironwood),
1904 union(sapling, orchard),
1905 ]
1906}
1907
1908pub fn batch_ensure_heights(
1932 sapling: &BTreeSet<BlockHeight>,
1933 orchard: &BTreeSet<BlockHeight>,
1934 ironwood: &BTreeSet<BlockHeight>,
1935 anchor_retention: Option<&AnchorRetention>,
1936 range: std::ops::RangeInclusive<BlockHeight>,
1937 window_heights: &BTreeSet<BlockHeight>,
1938) -> [BTreeSet<BlockHeight>; 3] {
1939 let mut ensure = cross_pool_ensure_heights(sapling, orchard, ironwood);
1940
1941 for pool in ensure.iter_mut() {
1942 pool.extend(window_heights.iter().copied());
1943 }
1944
1945 if let Some(retention) = anchor_retention {
1946 let retained = retention.retained_in_range(range);
1947 for pool in ensure.iter_mut() {
1948 pool.extend(retained.iter().copied());
1949 }
1950 }
1951
1952 ensure
1953}
1954
1955#[allow(clippy::too_many_arguments)]
1975pub fn update_tree<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
1976 protocol: &'static str,
1977 frontier: &Frontier<S::H, DEPTH>,
1978 frontier_height: BlockHeight,
1979 checkpoint_floor: BlockHeight,
1980 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
1981 anchor_retention: Option<&AnchorRetention>,
1982 subtrees: impl Iterator<Item = (LocatedPrunableTree<S::H>, BTreeMap<BlockHeight, Position>)>,
1983 missing_checkpoints: impl Iterator<Item = (BlockHeight, Checkpoint)>,
1984) -> Result<(), ShardTreeError<S::Error>>
1985where
1986 S: ShardStore<CheckpointId = BlockHeight>,
1987 S::H: Clone + PartialEq + Hashable,
1988{
1989 debug!(
1990 "{protocol} initial tree size at {frontier_height:?}: {:?}",
1991 frontier.tree_size()
1992 );
1993 let mut missing_checkpoints = missing_checkpoints.collect::<Vec<_>>();
1994
1995 let frontier_checkpoint = if frontier_height > checkpoint_floor
2001 || should_retain_anchor(anchor_retention, frontier_height)
2002 {
2003 Some(frontier_height)
2004 } else {
2005 let frontier_position = frontier.value().map(|leaf| leaf.position());
2006 missing_checkpoints
2007 .iter()
2008 .enumerate()
2009 .filter(|(_, (_, checkpoint))| {
2010 frontier_position.is_some() && checkpoint.position() == frontier_position
2011 })
2012 .min_by_key(|(_, (height, _))| *height)
2013 .map(|(entry_index, _)| entry_index)
2014 .map(|entry_index| missing_checkpoints.remove(entry_index).0)
2015 };
2016 let frontier_retention =
2017 frontier_checkpoint.map_or(Retention::Reference, |id| Retention::Checkpoint {
2018 id,
2019 marking: Marking::Reference,
2020 });
2021 if let Some(id) = frontier_checkpoint {
2022 retain_anchor_checkpoint(tree, anchor_retention, id)?;
2023 }
2024 tree.insert_frontier(frontier.clone(), frontier_retention)?;
2025
2026 for (subtree, checkpoints) in subtrees {
2027 for height in checkpoints.keys() {
2033 retain_anchor_checkpoint(tree, anchor_retention, *height)?;
2034 }
2035 tree.insert_tree(subtree, checkpoints)?;
2036 }
2037
2038 for (height, checkpoint) in missing_checkpoints {
2042 debug!(
2043 "Adding missing {protocol} checkpoint for height: {:?}: {:?}",
2044 height,
2045 checkpoint.position()
2046 );
2047 retain_anchor_checkpoint(tree, anchor_retention, height)?;
2048 tree.store_mut()
2049 .add_checkpoint(height, checkpoint)
2050 .map_err(ShardTreeError::Storage)?;
2051 }
2052
2053 Ok(())
2054}
2055
2056pub fn checkpoint_floor(
2065 chain_tip: Option<BlockHeight>,
2066 last_scanned_height: BlockHeight,
2067) -> BlockHeight {
2068 let reference_tip = chain_tip.map_or(last_scanned_height, |tip| tip.max(last_scanned_height));
2069 reference_tip.saturating_sub(PRUNING_DEPTH)
2070}
2071
2072pub fn keeps_checkpoint(
2076 checkpoint_floor: BlockHeight,
2077 anchor_retention: Option<&AnchorRetention>,
2078 height: BlockHeight,
2079) -> bool {
2080 height > checkpoint_floor || should_retain_anchor(anchor_retention, height)
2081}
2082
2083#[derive(Debug)]
2087pub struct BatchCheckpoints {
2088 pub checkpoint_floor: BlockHeight,
2090 pub sapling: Vec<(BlockHeight, Checkpoint)>,
2092 #[cfg(feature = "orchard")]
2094 pub orchard: Vec<(BlockHeight, Checkpoint)>,
2095 #[cfg(feature = "orchard")]
2097 pub ironwood: Vec<(BlockHeight, Checkpoint)>,
2098}
2099
2100pub fn batch_checkpoints<SH, #[cfg(feature = "orchard")] OH>(
2124 from_state: &ChainState,
2125 last_scanned_height: BlockHeight,
2126 chain_tip: Option<BlockHeight>,
2127 anchor_retention: Option<&AnchorRetention>,
2128 sapling_commitments: &[Option<(SH, Retention<BlockHeight>)>],
2129 #[cfg(feature = "orchard")] orchard_commitments: &[Option<(OH, Retention<BlockHeight>)>],
2130 #[cfg(feature = "orchard")] ironwood_commitments: &[Option<(OH, Retention<BlockHeight>)>],
2131) -> BatchCheckpoints {
2132 let checkpoint_floor = checkpoint_floor(chain_tip, last_scanned_height);
2133
2134 let sapling_block_ends = block_end_positions(
2136 Position::from(from_state.final_sapling_tree().tree_size()),
2137 sapling_commitments,
2138 );
2139 #[cfg(feature = "orchard")]
2140 let orchard_block_ends = block_end_positions(
2141 Position::from(from_state.final_orchard_tree().tree_size()),
2142 orchard_commitments,
2143 );
2144 #[cfg(feature = "orchard")]
2145 let ironwood_block_ends = block_end_positions(
2146 Position::from(from_state.final_ironwood_tree().tree_size()),
2147 ironwood_commitments,
2148 );
2149
2150 let created_heights = |block_ends: &BTreeMap<BlockHeight, Position>| {
2152 block_ends
2153 .keys()
2154 .copied()
2155 .filter(|height| keeps_checkpoint(checkpoint_floor, anchor_retention, *height))
2156 .collect::<BTreeSet<BlockHeight>>()
2157 };
2158 let sapling_created = created_heights(&sapling_block_ends);
2159 #[cfg(feature = "orchard")]
2160 let orchard_created = created_heights(&orchard_block_ends);
2161 #[cfg(feature = "orchard")]
2162 let ironwood_created = created_heights(&ironwood_block_ends);
2163 #[cfg(not(feature = "orchard"))]
2164 let (orchard_created, ironwood_created) = (BTreeSet::new(), BTreeSet::new());
2165
2166 let window_heights = (u32::from(from_state.block_height()) + 1
2167 ..=u32::from(last_scanned_height))
2168 .map(BlockHeight::from)
2169 .filter(|height| *height > checkpoint_floor)
2170 .collect::<BTreeSet<BlockHeight>>();
2171
2172 let [ensure_sapling, ensure_orchard, ensure_ironwood] = batch_ensure_heights(
2173 &sapling_created,
2174 &orchard_created,
2175 &ironwood_created,
2176 anchor_retention,
2177 from_state.block_height() + 1..=last_scanned_height,
2178 &window_heights,
2179 );
2180 #[cfg(not(feature = "orchard"))]
2181 let _ = (ensure_orchard, ensure_ironwood);
2182
2183 BatchCheckpoints {
2184 checkpoint_floor,
2185 sapling: ensure_checkpoints(
2186 ensure_sapling.iter(),
2187 &sapling_created,
2188 &sapling_block_ends,
2189 from_state.final_sapling_tree(),
2190 ),
2191 #[cfg(feature = "orchard")]
2192 orchard: ensure_checkpoints(
2193 ensure_orchard.iter(),
2194 &orchard_created,
2195 &orchard_block_ends,
2196 from_state.final_orchard_tree(),
2197 ),
2198 #[cfg(feature = "orchard")]
2199 ironwood: ensure_checkpoints(
2200 ensure_ironwood.iter(),
2201 &ironwood_created,
2202 &ironwood_block_ends,
2203 from_state.final_ironwood_tree(),
2204 ),
2205 }
2206}
2207
2208fn block_end_positions<H>(
2212 start_position: Position,
2213 commitments: &[Option<(H, Retention<BlockHeight>)>],
2214) -> BTreeMap<BlockHeight, Position> {
2215 commitments
2216 .iter()
2217 .enumerate()
2218 .filter_map(|(i, entry)| match entry {
2219 Some((_, Retention::Checkpoint { id, .. })) => Some((*id, start_position + i as u64)),
2220 _ => None,
2221 })
2222 .collect()
2223}
2224
2225pub fn assign_block_end_retention<H>(
2242 commitments: &mut [Option<(H, Retention<BlockHeight>)>],
2243 start_position: Position,
2244 checkpoint_floor: BlockHeight,
2245 anchor_retention: Option<&AnchorRetention>,
2246 missing_checkpoints: &mut Vec<(BlockHeight, Checkpoint)>,
2247) {
2248 for (index, (_, retention)) in commitments
2249 .iter_mut()
2250 .enumerate()
2251 .filter_map(|(index, entry)| entry.as_mut().map(|entry| (index, entry)))
2252 {
2253 if let Retention::Checkpoint { id, marking } = retention
2254 && !keeps_checkpoint(checkpoint_floor, anchor_retention, *id)
2255 {
2256 let position = start_position + index as u64;
2257 let carried = missing_checkpoints
2258 .iter()
2259 .enumerate()
2260 .filter(|(_, (_, checkpoint))| checkpoint.position() == Some(position))
2261 .min_by_key(|(_, (height, _))| *height)
2262 .map(|(entry_index, _)| entry_index);
2263 *retention = match carried {
2264 Some(entry_index) => Retention::Checkpoint {
2265 id: missing_checkpoints.remove(entry_index).0,
2266 marking: *marking,
2267 },
2268 None => match marking {
2269 Marking::Marked => Retention::Marked,
2270 Marking::Reference => Retention::Reference,
2271 Marking::None => Retention::Ephemeral,
2272 },
2273 };
2274 }
2275 }
2276}
2277
2278#[cfg(test)]
2279mod tests {
2280 #[cfg(feature = "orchard")]
2281 use {super::cross_pool_ensure_heights, std::collections::BTreeSet};
2282
2283 use core::num::NonZeroU32;
2284
2285 use proptest::prelude::*;
2286 use zcash_protocol::consensus::BlockHeight;
2287
2288 #[cfg(feature = "orchard")]
2289 use super::batch_ensure_heights;
2290 use super::{
2291 SPEND_MAP_RETENTION_BLOCKS, should_retain_anchor, should_track_spends, spend_tracking_floor,
2292 };
2293 use crate::data_api::anchor_retention::{AnchorRetention, AnchorRetentionInterval};
2294
2295 #[test]
2299 fn out_of_order_ranges_track_fully() {
2300 let h = BlockHeight::from;
2301 assert_eq!(
2303 spend_tracking_floor(Some(h(1_000)), h(500_000), Some(h(510_000))),
2304 None
2305 );
2306 assert_eq!(
2308 spend_tracking_floor(None, h(500_000), Some(h(510_000))),
2309 None
2310 );
2311 assert_eq!(
2313 spend_tracking_floor(Some(h(600_000)), h(500_000), Some(h(510_000))),
2314 None
2315 );
2316 }
2317
2318 #[test]
2322 fn frontier_batches_retain_the_trailing_window() {
2323 let from = BlockHeight::from(500_000);
2324 let last = BlockHeight::from(510_000);
2325 let floor = spend_tracking_floor(Some(from), from, Some(last)).expect("frontier ⇒ floor");
2326 assert_eq!(
2327 u32::from(last) - u32::from(floor),
2328 SPEND_MAP_RETENTION_BLOCKS
2329 );
2330
2331 let short = BlockHeight::from(500_000 + SPEND_MAP_RETENTION_BLOCKS / 2);
2332 assert_eq!(spend_tracking_floor(Some(from), from, Some(short)), None);
2333 assert_eq!(spend_tracking_floor(Some(from), from, None), None);
2334 }
2335
2336 #[test]
2337 fn spend_tracking_floor_gating() {
2338 let floor = BlockHeight::from(1000);
2339
2340 assert!(should_track_spends(None, BlockHeight::from(0)));
2342 assert!(should_track_spends(None, BlockHeight::from(999)));
2343
2344 assert!(should_track_spends(Some(floor), BlockHeight::from(1000)));
2346 assert!(should_track_spends(Some(floor), BlockHeight::from(1001)));
2347
2348 assert!(!should_track_spends(Some(floor), BlockHeight::from(999)));
2350 assert!(!should_track_spends(Some(floor), BlockHeight::from(0)));
2351 }
2352
2353 #[test]
2356 fn anchor_retention_gating() {
2357 for interval in [
2358 AnchorRetentionInterval::ZIP_318,
2359 AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero")),
2360 ] {
2361 let blocks = interval.block_count().get();
2362 let floor = BlockHeight::from(4 * blocks);
2363 let policy = AnchorRetention::new(
2364 floor,
2365 zcash_protocol::zip318::BlockSpacing::UNIFORM,
2366 interval,
2367 );
2368 let retention = Some(&policy);
2369
2370 assert!(!should_retain_anchor(None, BlockHeight::from(8 * blocks)));
2372
2373 assert!(should_retain_anchor(
2375 retention,
2376 BlockHeight::from(4 * blocks)
2377 ));
2378 assert!(should_retain_anchor(
2379 retention,
2380 BlockHeight::from(8 * blocks)
2381 ));
2382
2383 assert!(!should_retain_anchor(
2385 retention,
2386 BlockHeight::from(3 * blocks)
2387 ));
2388
2389 assert!(!should_retain_anchor(
2391 retention,
2392 BlockHeight::from(4 * blocks + 1)
2393 ));
2394 assert!(!should_retain_anchor(
2395 retention,
2396 BlockHeight::from(5 * blocks - 1)
2397 ));
2398 }
2399 }
2400
2401 #[cfg(feature = "orchard")]
2402 prop_compose! {
2403 fn arb_heights()(
2405 heights in proptest::collection::vec(0u32..100, 0..20),
2406 ) -> BTreeSet<BlockHeight> {
2407 heights.into_iter().map(BlockHeight::from).collect()
2408 }
2409 }
2410
2411 #[cfg(feature = "orchard")]
2412 fn union(a: &BTreeSet<BlockHeight>, b: &BTreeSet<BlockHeight>) -> BTreeSet<BlockHeight> {
2413 a.union(b).copied().collect()
2414 }
2415
2416 proptest! {
2417 #[test]
2422 #[cfg(feature = "orchard")]
2423 fn ensure_heights_align_all_pools(
2424 sapling in arb_heights(),
2425 orchard in arb_heights(),
2426 ironwood in arb_heights(),
2427 ) {
2428 let [ensure_sapling, ensure_orchard, ensure_ironwood] =
2429 cross_pool_ensure_heights(&sapling, &orchard, &ironwood);
2430
2431 let total = union(&union(&sapling, &orchard), &ironwood);
2432
2433 prop_assert_eq!(union(&sapling, &ensure_sapling), total.clone());
2434 prop_assert_eq!(union(&orchard, &ensure_orchard), total.clone());
2435 prop_assert_eq!(union(&ironwood, &ensure_ironwood), total);
2436
2437 prop_assert_eq!(ensure_sapling, union(&orchard, &ironwood));
2440 prop_assert_eq!(ensure_orchard, union(&sapling, &ironwood));
2441 prop_assert_eq!(ensure_ironwood, union(&sapling, &orchard));
2442 }
2443
2444 #[test]
2448 #[cfg(feature = "orchard")]
2449 fn ensure_heights_degrade_to_two_pools(
2450 sapling in arb_heights(),
2451 orchard in arb_heights(),
2452 ) {
2453 let [ensure_sapling, ensure_orchard, ensure_ironwood] =
2454 cross_pool_ensure_heights(&sapling, &orchard, &BTreeSet::new());
2455
2456 prop_assert_eq!(ensure_sapling, orchard.clone());
2457 prop_assert_eq!(ensure_orchard, sapling.clone());
2458 prop_assert_eq!(ensure_ironwood, union(&sapling, &orchard));
2459 }
2460 }
2461
2462 #[cfg(feature = "orchard")]
2471 #[test]
2472 fn retained_boundary_on_a_commitment_free_block_is_ensured() {
2473 let h = BlockHeight::from;
2474 let retention = AnchorRetention::new(
2477 h(1_000),
2478 zcash_protocol::zip318::BlockSpacing::UNIFORM,
2479 AnchorRetentionInterval::custom(NonZeroU32::new(12).unwrap()),
2480 );
2481
2482 let (sap_cp, orch_cp, iw_cp) = (
2483 BTreeSet::from([h(1_198)]),
2484 BTreeSet::from([h(1_205)]),
2485 BTreeSet::new(),
2486 );
2487
2488 for heights in cross_pool_ensure_heights(&sap_cp, &orch_cp, &iw_cp) {
2492 assert!(
2493 !heights.contains(&h(1_200)),
2494 "cross-pool alignment must not supply the boundary; the union is what does"
2495 );
2496 }
2497
2498 let [sapling, orchard, ironwood] = batch_ensure_heights(
2499 &sap_cp,
2500 &orch_cp,
2501 &iw_cp,
2502 Some(&retention),
2503 h(1_150)..=h(1_250),
2504 &BTreeSet::new(),
2505 );
2506
2507 for (pool, heights) in [
2508 ("sapling", &sapling),
2509 ("orchard", &orchard),
2510 ("ironwood", &ironwood),
2511 ] {
2512 assert!(
2513 heights.contains(&h(1_200)),
2514 "{pool} must ensure the retained boundary 1200, got {heights:?}"
2515 );
2516 }
2517 }
2518
2519 #[cfg(feature = "orchard")]
2523 #[test]
2524 fn no_retention_policy_is_exactly_cross_pool() {
2525 let h = BlockHeight::from;
2526 let sapling = BTreeSet::from([h(100), h(140)]);
2527 let orchard = BTreeSet::from([h(120)]);
2528 let ironwood = BTreeSet::from([h(160)]);
2529
2530 assert_eq!(
2531 batch_ensure_heights(
2532 &sapling,
2533 &orchard,
2534 &ironwood,
2535 None,
2536 h(1)..=h(1_000),
2537 &BTreeSet::new()
2538 ),
2539 cross_pool_ensure_heights(&sapling, &orchard, &ironwood)
2540 );
2541 }
2542}