Skip to main content

zcash_client_backend/data_api/
scanning.rs

1//! Common types used for managing a queue of scanning ranges.
2
3use std::fmt;
4use std::ops::Range;
5
6use zcash_protocol::consensus::BlockHeight;
7
8#[cfg(feature = "unstable-spanning-tree")]
9pub mod spanning_tree;
10
11/// Scanning range priority levels.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
13pub enum ScanPriority {
14    /// Block ranges that are ignored have lowest priority.
15    Ignored,
16    /// Block ranges that have already been scanned will not be re-scanned.
17    Scanned,
18    /// Block ranges to be scanned to advance the fully-scanned height.
19    Historic,
20    /// Block ranges adjacent to heights at which the user opened the wallet.
21    OpenAdjacent,
22    /// Blocks that must be scanned to complete note commitment tree shards adjacent to found notes.
23    FoundNote,
24    /// Blocks that must be scanned to complete the latest note commitment tree shard.
25    ChainTip,
26    /// Blocks within the chain-tip pruning window that must be scanned for any value reported as
27    /// spendable to remain spendable. When the chain tip advances, and after operations that
28    /// mutate `scan_queue` priorities (rewind, truncate, account import), the wallet places this
29    /// priority on the unscanned ranges of the `(chain_tip - PRUNING_DEPTH, chain_tip]` window,
30    /// so that re-establishing a usable anchor takes precedence over normal forward sync.
31    Anchor,
32    /// A previously scanned range that must be verified to check it is still in the
33    /// main chain, has highest priority.
34    Verify,
35}
36
37/// A range of blocks to be scanned, along with its associated priority.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct ScanRange {
40    block_range: Range<BlockHeight>,
41    priority: ScanPriority,
42}
43
44impl fmt::Display for ScanRange {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(
47            f,
48            "{:?}({}..{})",
49            self.priority, self.block_range.start, self.block_range.end,
50        )
51    }
52}
53
54impl ScanRange {
55    /// Constructs a scan range from its constituent parts.
56    pub fn from_parts(block_range: Range<BlockHeight>, priority: ScanPriority) -> Self {
57        assert!(
58            block_range.end >= block_range.start,
59            "{block_range:?} is invalid for ScanRange({priority:?})",
60        );
61        ScanRange {
62            block_range,
63            priority,
64        }
65    }
66
67    /// Returns the range of block heights to be scanned.
68    pub fn block_range(&self) -> &Range<BlockHeight> {
69        &self.block_range
70    }
71
72    /// Returns the priority with which the scan range should be scanned.
73    pub fn priority(&self) -> ScanPriority {
74        self.priority
75    }
76
77    /// Returns whether or not the scan range is empty.
78    pub fn is_empty(&self) -> bool {
79        self.block_range.is_empty()
80    }
81
82    /// Returns the number of blocks in the scan range.
83    pub fn len(&self) -> usize {
84        usize::try_from(u32::from(self.block_range.end) - u32::from(self.block_range.start))
85            .unwrap()
86    }
87
88    /// Shifts the start of the block range to the right if `block_height >
89    /// self.block_range().start`. Returns `None` if the resulting range would
90    /// be empty (or the range was already empty).
91    pub fn truncate_start(&self, block_height: BlockHeight) -> Option<Self> {
92        if block_height >= self.block_range.end || self.is_empty() {
93            None
94        } else {
95            Some(ScanRange {
96                block_range: self.block_range.start.max(block_height)..self.block_range.end,
97                priority: self.priority,
98            })
99        }
100    }
101
102    /// Shifts the end of the block range to the left if `block_height <
103    /// self.block_range().end`. Returns `None` if the resulting range would
104    /// be empty (or the range was already empty).
105    pub fn truncate_end(&self, block_height: BlockHeight) -> Option<Self> {
106        if block_height <= self.block_range.start || self.is_empty() {
107            None
108        } else {
109            Some(ScanRange {
110                block_range: self.block_range.start..self.block_range.end.min(block_height),
111                priority: self.priority,
112            })
113        }
114    }
115
116    /// Splits this scan range at the specified height, such that the provided height becomes the
117    /// end of the first range returned and the start of the second. Returns `None` if
118    /// `p <= self.block_range().start || p >= self.block_range().end`.
119    pub fn split_at(&self, p: BlockHeight) -> Option<(Self, Self)> {
120        (p > self.block_range.start && p < self.block_range.end).then_some((
121            ScanRange {
122                block_range: self.block_range.start..p,
123                priority: self.priority,
124            },
125            ScanRange {
126                block_range: p..self.block_range.end,
127                priority: self.priority,
128            },
129        ))
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::{ScanPriority, ScanRange};
136
137    fn scan_range(start: u32, end: u32) -> ScanRange {
138        ScanRange::from_parts((start.into())..(end.into()), ScanPriority::Scanned)
139    }
140
141    #[test]
142    fn truncate_start() {
143        let r = scan_range(5, 8);
144
145        assert_eq!(r.truncate_start(4.into()), Some(scan_range(5, 8)));
146        assert_eq!(r.truncate_start(5.into()), Some(scan_range(5, 8)));
147        assert_eq!(r.truncate_start(6.into()), Some(scan_range(6, 8)));
148        assert_eq!(r.truncate_start(7.into()), Some(scan_range(7, 8)));
149        assert_eq!(r.truncate_start(8.into()), None);
150        assert_eq!(r.truncate_start(9.into()), None);
151
152        let empty = scan_range(5, 5);
153        assert_eq!(empty.truncate_start(4.into()), None);
154        assert_eq!(empty.truncate_start(5.into()), None);
155        assert_eq!(empty.truncate_start(6.into()), None);
156    }
157
158    #[test]
159    fn truncate_end() {
160        let r = scan_range(5, 8);
161
162        assert_eq!(r.truncate_end(9.into()), Some(scan_range(5, 8)));
163        assert_eq!(r.truncate_end(8.into()), Some(scan_range(5, 8)));
164        assert_eq!(r.truncate_end(7.into()), Some(scan_range(5, 7)));
165        assert_eq!(r.truncate_end(6.into()), Some(scan_range(5, 6)));
166        assert_eq!(r.truncate_end(5.into()), None);
167        assert_eq!(r.truncate_end(4.into()), None);
168
169        let empty = scan_range(5, 5);
170        assert_eq!(empty.truncate_end(4.into()), None);
171        assert_eq!(empty.truncate_end(5.into()), None);
172        assert_eq!(empty.truncate_end(6.into()), None);
173    }
174
175    #[test]
176    fn split_at() {
177        let r = scan_range(5, 8);
178
179        assert_eq!(r.split_at(4.into()), None);
180        assert_eq!(r.split_at(5.into()), None);
181        assert_eq!(
182            r.split_at(6.into()),
183            Some((scan_range(5, 6), scan_range(6, 8)))
184        );
185        assert_eq!(
186            r.split_at(7.into()),
187            Some((scan_range(5, 7), scan_range(7, 8)))
188        );
189        assert_eq!(r.split_at(8.into()), None);
190        assert_eq!(r.split_at(9.into()), None);
191
192        let empty = scan_range(5, 5);
193        assert_eq!(empty.split_at(4.into()), None);
194        assert_eq!(empty.split_at(5.into()), None);
195        assert_eq!(empty.split_at(6.into()), None);
196    }
197}