zcash_keys/keys/transparent/gap_limits.rs
1//! Types and operations specific to generation of transparent addresses using a "gap limit"
2//! strategy, as described by [`BIP 44`].
3//!
4//! [`BIP 44`]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
5
6use alloc::vec::Vec;
7use core::hash::Hash;
8use core::ops::Range;
9
10use crate::{
11 address::Address,
12 keys::{
13 AddressGenerationError, UnifiedAddressRequest, UnifiedFullViewingKey,
14 UnifiedIncomingViewingKey,
15 transparent::{
16 IncomingViewingKey, NonHardenedChildIndex, NonHardenedChildRange, TransparentKeyScope,
17 },
18 },
19};
20use transparent::address::TransparentAddress;
21use zcash_address::unified::Typecode;
22use zip32::DiversifierIndex;
23
24/// Configuration for gap limits used in transparent address management.
25///
26/// A "gap limit" is the number of consecutive unused addresses that the wallet will generate
27/// before stopping. This concept comes from BIP-44 HD wallet standards: when scanning for
28/// funds, the wallet generates addresses sequentially and stops when it encounters a "gap"
29/// of unused addresses equal to this limit. In recovery, a wallet will discover funds
30/// belonging to generated addresses. Note that order of operations matters; if a wallet scans
31/// blocks for transparent outputs instead of querying the UTXO set, out-of-order scanning may
32/// result in funds not being found; as a result, wallets should still fall back to making
33/// temporally unlinkable, private queries to the UTXO set for each address controlled by the
34/// wallet at any time that a gap in scanned blocks is introduced by out-of-order scanning.
35///
36/// In Zcash, we define individual gap limits for the following address types:
37/// - **External addresses**: Addresses shared with external parties.
38/// - **Internal (change) addresses**: Used for transparent change outputs.
39/// - **Ephemeral addresses**: Used for single-use purposes like ZIP-320 TEX address transfers.
40#[derive(Debug, Copy, Clone, PartialEq, Eq)]
41pub struct GapLimits {
42 external: u32,
43 internal: u32,
44 ephemeral: u32,
45}
46
47impl GapLimits {
48 /// Constructs a new `GapLimits` value from its constituent parts.
49 ///
50 /// The gap limits recommended for use with this crate are supplied by the [`Default`]
51 /// implementation for this type.
52 ///
53 /// This constructor is only available under the `unstable` feature, as it is not recommended
54 /// for general use.
55 #[cfg(any(test, feature = "test-dependencies", feature = "unstable"))]
56 pub fn new(external: u32, internal: u32, ephemeral: u32) -> Self {
57 Self {
58 external,
59 internal,
60 ephemeral,
61 }
62 }
63
64 /// Returns the gap limit for external-scoped addresses.
65 pub fn external(&self) -> u32 {
66 self.external
67 }
68
69 /// Returns the gap limit for internal-scoped addresses.
70 pub fn internal(&self) -> u32 {
71 self.internal
72 }
73
74 /// Returns the gap limit for ephemeral-scoped addresses.
75 pub fn ephemeral(&self) -> u32 {
76 self.ephemeral
77 }
78
79 /// Returns the gap limit for the given transparent key scope, or `None` if the key scope is
80 /// one for which gap limits are not managed by this type.
81 pub fn limit_for(&self, scope: TransparentKeyScope) -> Option<u32> {
82 match scope {
83 TransparentKeyScope::EXTERNAL => Some(self.external()),
84 TransparentKeyScope::INTERNAL => Some(self.internal()),
85 TransparentKeyScope::EPHEMERAL => Some(self.ephemeral()),
86 _ => None,
87 }
88 }
89}
90
91/// The default gap limits supported by this implementation are:
92///
93/// - external addresses: 10
94/// - transparent internal (change) addresses: 5
95/// - ephemeral addresses: 10
96///
97/// These limits are chosen with the following rationale:
98/// - At present, many wallets query light wallet servers with a set of addresses, because querying
99/// for each address independently and in a fashion that is not susceptible to clustering via
100/// timing correlation leads to undesirable delays in discovery of received funds. As such, it is
101/// desirable to minimize the number of addresses that can be "linked", i.e. understood by the
102/// light wallet server to all belong to the same wallet.
103/// - For transparent change addresses it is always expected that an address will receive funds
104/// immediately following its generation except in the case of wallet failure.
105/// - For externally-scoped transparent addresses and ephemeral addresses, it is desirable to use a
106/// slightly larger gap limit to account for addresses that were shared with counterparties never
107/// having been used. However, we don't want to use the full 20-address gap limit space because
108/// it's possible that in the future, changes to the light wallet protocol will obviate the need to
109/// query for UTXOs in a fashion that links those addresses to one another. In such a
110/// circumstance, the gap limit will be adjusted upward and address rotation should then choose
111/// an address that is outside the current gap limit; after that change, newly generated
112/// addresses will not be exposed as linked in the view of the light wallet server.
113impl Default for GapLimits {
114 fn default() -> Self {
115 Self {
116 external: 10,
117 internal: 5,
118 ephemeral: 10,
119 }
120 }
121}
122
123/// A trait providing wallet storage operations required for transparent address gap limit
124/// management.
125///
126/// Implementations of this trait allow the gap limit logic in [`generate_gap_addresses`] to query
127/// and update the wallet's transparent address state without being coupled to a specific storage
128/// backend.
129pub trait AddressStore {
130 /// The type of errors produced by the wallet storage backend.
131 type Error;
132
133 /// A wallet-internal account identifier.
134 type AccountRef: Copy + Eq + Hash;
135
136 /// Returns the transparent address index at the start of the first gap of at least `gap_limit`
137 /// indices in the given account, considering only addresses derived for the specified key scope.
138 ///
139 /// Returns `Ok(None)` if the gap would start at an index greater than the maximum valid
140 /// non-hardened transparent child index.
141 fn find_gap_start(
142 &self,
143 account_ref: Self::AccountRef,
144 key_scope: TransparentKeyScope,
145 gap_limit: u32,
146 ) -> Result<Option<NonHardenedChildIndex>, Self::Error>;
147
148 /// Persists a range of derived transparent addresses to the wallet storage.
149 ///
150 /// Each entry in the list contains the wallet-level address, the raw transparent address,
151 /// and the child index from which the address was derived.
152 fn store_address_range(
153 &mut self,
154 account_id: Self::AccountRef,
155 key_scope: TransparentKeyScope,
156 list: Vec<(Address, TransparentAddress, NonHardenedChildIndex)>,
157 ) -> Result<(), Self::Error>;
158
159 /// Checks addresses that have just been added to the wallet against transaction involvement
160 /// the wallet has already observed, and records whatever that reveals.
161 ///
162 /// A wallet recognizes transparent involvement by joining the transactions it stores against
163 /// the addresses it holds, and both sides of that join change over time: a transaction may
164 /// arrive after the address it pays is held, and an address may be added after a transaction
165 /// naming it is stored. Checking each newly stored transaction against the address book
166 /// maintains only the first case; an implementation of this method maintains the second.
167 /// Without one, a transaction stored before its address entered the wallet is never
168 /// recognized.
169 ///
170 /// `added` is the list just passed to [`Self::store_address_range`], in the same form. An
171 /// implementation must consider every entry, including entries that were already stored:
172 /// storing a range is idempotent and carries no record of which entries were new.
173 ///
174 /// Returns [`ReconcileOutcome::AddressesUsed`] if, as a result of this check, any address in
175 /// `added` is now known to have received an output in a mined transaction, carrying the
176 /// highest child index among those addresses. Returns [`ReconcileOutcome::Unchanged`]
177 /// otherwise. [`generate_gap_addresses`] uses the answer to decide whether the account's gap
178 /// start has moved, and so whether a further window of addresses must be derived and checked
179 /// in turn.
180 ///
181 /// This method must be idempotent: repeated calls with the same addresses must not record
182 /// anything beyond what the first call recorded.
183 fn reconcile_stored_addresses(
184 &mut self,
185 account_id: Self::AccountRef,
186 key_scope: TransparentKeyScope,
187 added: &[(Address, TransparentAddress, NonHardenedChildIndex)],
188 ) -> Result<ReconcileOutcome, Self::Error>;
189}
190
191/// What checking newly stored addresses against previously observed transaction involvement
192/// revealed, as reported by [`AddressStore::reconcile_stored_addresses`].
193#[derive(Debug, Copy, Clone, PartialEq, Eq)]
194pub enum ReconcileOutcome {
195 /// No address that was checked is newly known to have received an output in a mined
196 /// transaction, so the account's transparent address gap is where it was.
197 Unchanged,
198 /// At least one address that was checked is newly known to have received an output in a
199 /// mined transaction. The value is the highest child index among those addresses; the
200 /// account's transparent address gap now starts beyond it.
201 AddressesUsed(NonHardenedChildIndex),
202}
203
204fn generate_external_address(
205 uivk: &UnifiedIncomingViewingKey,
206 ua_request: UnifiedAddressRequest,
207 index: NonHardenedChildIndex,
208) -> Result<(Address, TransparentAddress), AddressGenerationError> {
209 let transparent_address = uivk
210 .p2pkh()
211 .ok_or(AddressGenerationError::KeyNotAvailable(Typecode::P2PKH))?
212 .derive_address(index)
213 .map_err(|_| {
214 AddressGenerationError::InvalidTransparentChildIndex(DiversifierIndex::from(index))
215 })?;
216
217 // A key that has nothing but a transparent item now yields a transparent-only unified
218 // address, so `NoSatisfiableReceiver` here means that the key has a data item that this
219 // build cannot interpret, or that the request names a pool the key does not have. Emitting
220 // a bare transparent address in either case would silently discard receiving capability
221 // that the recipient has, so the error propagates.
222 let ua = uivk.address(index.into(), ua_request)?;
223
224 Ok((Address::from(ua), transparent_address))
225}
226
227/// Generates a list of addresses for the given range of transparent child indices.
228///
229/// For external-scoped addresses, a unified address is generated using the provided
230/// [`UnifiedAddressRequest`]; for internal and ephemeral scopes, the raw transparent address is
231/// returned.
232///
233/// External addresses are derived from the P2PKH component of `account_uivk`; internal and
234/// ephemeral addresses are derived from the P2PKH component of `account_ufvk`.
235///
236/// Returns an empty list for the external scope if `account_uivk` has a P2SH component, and
237/// for any scope if the account lacks the transparent key required for that scope and
238/// `require_key` is `false`. Returns an error if the key is required but unavailable, or if
239/// the key scope is unsupported.
240pub fn generate_address_list(
241 account_uivk: &UnifiedIncomingViewingKey,
242 account_ufvk: Option<&UnifiedFullViewingKey>,
243 key_scope: TransparentKeyScope,
244 request: UnifiedAddressRequest,
245 range_to_store: Range<NonHardenedChildIndex>,
246 require_key: bool,
247) -> Result<Vec<(Address, TransparentAddress, NonHardenedChildIndex)>, AddressGenerationError> {
248 let account_pubkey = account_ufvk.and_then(|ufvk| ufvk.p2pkh());
249 let has_scope_key = match key_scope {
250 TransparentKeyScope::EXTERNAL => match (account_uivk.p2pkh(), account_uivk.p2sh()) {
251 (Some(_), _) => true,
252 // External addresses are not generated from a P2SH component.
253 // TODO: generate them for derivable script templates (#3341).
254 (None, Some(_)) => return Ok(vec![]),
255 (None, None) => false,
256 },
257 _ => account_pubkey.is_some(),
258 };
259 if !has_scope_key {
260 return if require_key {
261 Err(AddressGenerationError::KeyNotAvailable(Typecode::P2PKH))
262 } else {
263 // No addresses to generate
264 Ok(vec![])
265 };
266 }
267
268 let gen_addrs = |key_scope: TransparentKeyScope, index: NonHardenedChildIndex| match key_scope {
269 TransparentKeyScope::EXTERNAL => generate_external_address(account_uivk, request, index),
270 TransparentKeyScope::INTERNAL => {
271 let internal_address = account_pubkey
272 .ok_or(AddressGenerationError::KeyNotAvailable(Typecode::P2PKH))?
273 .derive_internal_ivk()?
274 .derive_address(index)?;
275 Ok((Address::from(internal_address), internal_address))
276 }
277 TransparentKeyScope::EPHEMERAL => {
278 let ephemeral_address = account_pubkey
279 .ok_or(AddressGenerationError::KeyNotAvailable(Typecode::P2PKH))?
280 .derive_ephemeral_ivk()?
281 .derive_ephemeral_address(index)?;
282 Ok((Address::from(ephemeral_address), ephemeral_address))
283 }
284 _ => Err(AddressGenerationError::UnsupportedTransparentKeyScope(
285 key_scope,
286 )),
287 };
288
289 NonHardenedChildRange::from(range_to_store)
290 .into_iter()
291 .map(|transparent_child_index| {
292 let (address, transparent_address) = gen_addrs(key_scope, transparent_child_index)?;
293 Ok((address, transparent_address, transparent_child_index))
294 })
295 .collect::<Result<Vec<_>, _>>()
296}
297
298/// Errors that can occur when generating transparent gap addresses.
299#[derive(Debug)]
300pub enum GapAddressesError<SE> {
301 /// An error occurred in the underlying wallet storage backend.
302 Storage(SE),
303 /// An error occurred while deriving a transparent address.
304 AddressGeneration(AddressGenerationError),
305 /// The specified account was not found in the wallet database.
306 AccountUnknown,
307}
308
309/// Generates transparent addresses to fill the gap for a given account and key scope.
310///
311/// This function queries the wallet backend (via [`AddressStore`]) to find the start
312/// of the first gap of unused addresses, then generates enough addresses to maintain the
313/// configured gap limit. If no gap exists (i.e., the address space is exhausted), this is a
314/// no-op.
315///
316/// Each window of addresses is checked against previously observed transaction involvement via
317/// [`AddressStore::reconcile_stored_addresses`], and a window in which that check finds an
318/// address used moves the gap, so a further window is derived and checked in turn. This
319/// continues until a window is checked without moving the gap. The gap start is read afresh
320/// each round, and the next round runs only if it lies beyond the highest address the previous
321/// round found used. That address lies within the previous window, so the gap start strictly
322/// increases; the non-hardened child index space is finite, so the number of rounds is bounded.
323#[allow(clippy::too_many_arguments)]
324pub fn generate_gap_addresses<DbT, SE>(
325 wallet_db: &mut DbT,
326 gap_limits: &GapLimits,
327 account_id: DbT::AccountRef,
328 account_uivk: &UnifiedIncomingViewingKey,
329 account_ufvk: Option<&UnifiedFullViewingKey>,
330 key_scope: TransparentKeyScope,
331 request: UnifiedAddressRequest,
332 require_key: bool,
333) -> Result<(), GapAddressesError<SE>>
334where
335 DbT: AddressStore<Error = SE>,
336{
337 let gap_limit = gap_limits
338 .limit_for(key_scope)
339 .ok_or(GapAddressesError::AddressGeneration(
340 AddressGenerationError::UnsupportedTransparentKeyScope(key_scope),
341 ))?;
342
343 let mut highest_used: Option<NonHardenedChildIndex> = None;
344 while let Some(gap_start) = wallet_db
345 .find_gap_start(account_id, key_scope, gap_limit)
346 .map_err(GapAddressesError::Storage)?
347 {
348 // Reconciliation reported an address used at or beyond this gap start, so the store
349 // disagrees with it. Deriving a window that overlaps the previous one could repeat
350 // forever, so stop here; that window has already been stored and checked.
351 if highest_used.is_some_and(|used| gap_start <= used) {
352 break;
353 }
354
355 let address_list = generate_address_list(
356 account_uivk,
357 account_ufvk,
358 key_scope,
359 request,
360 gap_start..gap_start.saturating_add(gap_limit),
361 require_key,
362 )
363 .map_err(GapAddressesError::AddressGeneration)?;
364
365 wallet_db
366 .store_address_range(account_id, key_scope, address_list.clone())
367 .map_err(GapAddressesError::Storage)?;
368
369 match wallet_db
370 .reconcile_stored_addresses(account_id, key_scope, &address_list)
371 .map_err(GapAddressesError::Storage)?
372 {
373 ReconcileOutcome::Unchanged => break,
374 ReconcileOutcome::AddressesUsed(highest) => highest_used = Some(highest),
375 }
376 }
377
378 Ok(())
379}