Skip to main content

zebra_state/service/read/address/
utxo.rs

1//! Transparent address index UTXO queries.
2//!
3//! In the functions in this module:
4//!
5//! The block write task commits blocks to the finalized state before updating
6//! `chain` with a cached copy of the best non-finalized chain from
7//! `NonFinalizedState.chain_set`. Then the block commit task can commit additional blocks to
8//! the finalized state after we've cloned the `chain`.
9//!
10//! This means that some blocks can be in both:
11//! - the cached [`Chain`], and
12//! - the shared finalized [`ZebraDb`] reference.
13
14use std::{
15    collections::{BTreeMap, BTreeSet, HashSet},
16    ops::RangeInclusive,
17};
18
19use derive_getters::Getters;
20use zebra_chain::{
21    block::{self, Height},
22    parameters::Network,
23    transaction, transparent,
24};
25
26use crate::{
27    service::{
28        finalized_state::ZebraDb, non_finalized_state::Chain, read::FINALIZED_STATE_QUERY_RETRIES,
29    },
30    BoxError, OutputLocation, TransactionLocation,
31};
32
33/// The full range of address heights.
34///
35/// The genesis coinbase transactions are ignored by a consensus rule,
36/// so they are not included in any address indexes.
37#[cfg(test)]
38pub const ADDRESS_HEIGHTS_FULL_RANGE: RangeInclusive<Height> = Height(1)..=Height::MAX;
39
40/// A convenience wrapper that efficiently stores unspent transparent outputs,
41/// and the corresponding transaction IDs.
42#[derive(Clone, Debug, Default, Eq, PartialEq, Getters)]
43pub struct AddressUtxos {
44    /// A set of unspent transparent outputs.
45    #[getter(skip)]
46    utxos: BTreeMap<OutputLocation, transparent::Output>,
47
48    /// The transaction IDs for each [`OutputLocation`] in `utxos`.
49    #[getter(skip)]
50    tx_ids: BTreeMap<TransactionLocation, transaction::Hash>,
51
52    /// The configured network for this state.
53    #[getter(skip)]
54    network: Network,
55
56    /// The last height and hash that was queried to produce these UTXOs, if any.
57    /// It will be None if the state is empty.
58    last_height_and_hash: Option<(block::Height, block::Hash)>,
59}
60
61impl AddressUtxos {
62    /// Creates a new set of address UTXOs.
63    pub fn new(
64        network: &Network,
65        utxos: BTreeMap<OutputLocation, transparent::Output>,
66        tx_ids: BTreeMap<TransactionLocation, transaction::Hash>,
67        last_height_and_hash: Option<(block::Height, block::Hash)>,
68    ) -> Self {
69        Self {
70            utxos,
71            tx_ids,
72            network: network.clone(),
73            last_height_and_hash,
74        }
75    }
76
77    /// Returns an iterator that provides the unspent output, its transaction hash,
78    /// its location in the chain, and the address it was sent to.
79    ///
80    /// The UTXOs are returned in chain order, across all addresses.
81    #[allow(dead_code)]
82    pub fn utxos(
83        &self,
84    ) -> impl Iterator<
85        Item = (
86            transparent::Address,
87            &transaction::Hash,
88            &OutputLocation,
89            &transparent::Output,
90        ),
91    > {
92        self.utxos.iter().map(|(out_loc, output)| {
93            (
94                output
95                    .address(&self.network)
96                    .expect("address indexes only contain outputs with addresses"),
97                self.tx_ids
98                    .get(&out_loc.transaction_location())
99                    .expect("address indexes are consistent"),
100                out_loc,
101                output,
102            )
103        })
104    }
105}
106
107/// Returns the unspent transparent outputs (UTXOs) for the supplied [`transparent::Address`]es
108/// in `query_height_range`, in chain order, at most `max_entries` of them; and the transaction
109/// IDs for the transactions containing those UTXOs.
110///
111/// If the addresses do not exist in the non-finalized `chain` or finalized `db`,
112/// returns an empty list.
113///
114/// Both limits are applied to the index scan, so the work this query does is bounded by what
115/// the caller asks for, rather than by the size of the addresses' UTXO sets.
116pub fn address_utxos<C>(
117    network: &Network,
118    chain: Option<C>,
119    db: &ZebraDb,
120    addresses: HashSet<transparent::Address>,
121    query_height_range: RangeInclusive<Height>,
122    max_entries: Option<usize>,
123) -> Result<AddressUtxos, BoxError>
124where
125    C: AsRef<Chain>,
126{
127    let mut utxo_error = None;
128    let address_count = addresses.len();
129
130    // The non-finalized chain can spend UTXOs that the finalized query returns, so a limited
131    // finalized query has to over-fetch by that many entries, or a full page of results can
132    // arrive short and look like the end of the address' UTXOs.
133    let finalized_limit = max_entries.map(|max_entries| {
134        let chain_spent_count = chain
135            .as_ref()
136            .map(|chain| {
137                chain
138                    .as_ref()
139                    .partial_transparent_spent_utxo_count(&addresses)
140            })
141            .unwrap_or(0);
142
143        finalized_scan_limit(max_entries, chain_spent_count)
144    });
145
146    // Retry the finalized UTXO query if it was interrupted by a finalizing block,
147    // and the non-finalized chain doesn't overlap the changed heights.
148    //
149    // TODO: refactor this into a generic retry(finalized_closure, process_and_check_closure) fn
150    for attempt in 0..=FINALIZED_STATE_QUERY_RETRIES {
151        debug!(?attempt, ?address_count, "starting address UTXO query");
152
153        let (finalized_utxos, finalized_tip_range) =
154            finalized_address_utxos(db, &addresses, query_height_range.clone(), finalized_limit);
155
156        debug!(
157            finalized_utxo_count = ?finalized_utxos.len(),
158            ?finalized_tip_range,
159            ?address_count,
160            ?attempt,
161            "finalized address UTXO response",
162        );
163
164        // Apply the non-finalized UTXO changes.
165        let chain_utxo_changes = chain_transparent_utxo_changes(
166            chain.as_ref(),
167            &addresses,
168            finalized_tip_range,
169            &query_height_range,
170            max_entries,
171        );
172
173        // If the UTXOs are valid, return them, otherwise, retry or return an error.
174        match chain_utxo_changes {
175            Ok((created_chain_utxos, spent_chain_utxos, last_height)) => {
176                debug!(
177                    chain_utxo_count = ?created_chain_utxos.len(),
178                    chain_utxo_spent = ?spent_chain_utxos.len(),
179                    ?address_count,
180                    ?attempt,
181                    "chain address UTXO response",
182                );
183
184                let utxos = apply_utxo_changes(
185                    finalized_utxos,
186                    created_chain_utxos,
187                    spent_chain_utxos,
188                    &query_height_range,
189                    max_entries,
190                );
191
192                let tx_ids = lookup_tx_ids_for_utxos(chain.as_ref(), db, &utxos);
193
194                debug!(
195                    full_utxo_count = ?utxos.len(),
196                    tx_id_count = ?tx_ids.len(),
197                    ?address_count,
198                    ?attempt,
199                    "full address UTXO response",
200                );
201
202                // Get the matching hash for the given height, if any
203                let last_height_and_hash = last_height.and_then(|height| {
204                    Some(height).zip(
205                        chain
206                            .as_ref()
207                            .and_then(|c| c.as_ref().hash_by_height(height))
208                            .or_else(|| db.hash(height)),
209                    )
210                });
211
212                return Ok(AddressUtxos::new(
213                    network,
214                    utxos,
215                    tx_ids,
216                    last_height_and_hash,
217                ));
218            }
219
220            Err(chain_utxo_error) => {
221                debug!(
222                    ?chain_utxo_error,
223                    ?address_count,
224                    ?attempt,
225                    "chain address UTXO response",
226                );
227
228                utxo_error = Some(Err(chain_utxo_error))
229            }
230        }
231    }
232
233    utxo_error.expect("unexpected missing error: attempts should set error or return")
234}
235
236/// Returns the unspent transparent outputs (UTXOs) for `addresses` in the finalized chain,
237/// and the finalized tip heights the UTXOs were queried at.
238///
239/// If the addresses do not exist in the finalized `db`, returns an empty list.
240//
241// TODO: turn the return type into a struct?
242fn finalized_address_utxos(
243    db: &ZebraDb,
244    addresses: &HashSet<transparent::Address>,
245    query_height_range: RangeInclusive<Height>,
246    limit: Option<usize>,
247) -> (
248    BTreeMap<OutputLocation, transparent::Output>,
249    Option<RangeInclusive<Height>>,
250) {
251    // # Correctness
252    //
253    // The StateService can commit additional blocks while we are querying address UTXOs.
254
255    // Check if the finalized state changed while we were querying it
256    let start_finalized_tip = db.finalized_tip_height();
257
258    let finalized_utxos = db.partial_finalized_address_utxos(addresses, query_height_range, limit);
259
260    let end_finalized_tip = db.finalized_tip_height();
261
262    let finalized_tip_range = if let (Some(start_finalized_tip), Some(end_finalized_tip)) =
263        (start_finalized_tip, end_finalized_tip)
264    {
265        Some(start_finalized_tip..=end_finalized_tip)
266    } else {
267        // State is empty
268        None
269    };
270
271    (finalized_utxos, finalized_tip_range)
272}
273
274/// Returns the UTXO changes (created and spent) for `addresses` in the
275/// non-finalized chain, matching or overlapping the UTXOs for the
276/// `finalized_tip_range`. Also returns the height of the last block in which
277/// the changes were located, or None if the state is empty.
278///
279/// Only returns the created UTXOs in `query_height_range` that the chain doesn't spend,
280/// at most `max_entries` of them. See [`Chain::partial_transparent_utxo_changes`] for details.
281///
282/// If the addresses do not exist in the non-finalized `chain`, returns an empty
283/// list.
284//
285// TODO: turn the return type into a struct?
286fn chain_transparent_utxo_changes<C>(
287    chain: Option<C>,
288    addresses: &HashSet<transparent::Address>,
289    finalized_tip_range: Option<RangeInclusive<Height>>,
290    query_height_range: &RangeInclusive<Height>,
291    max_entries: Option<usize>,
292) -> Result<
293    (
294        BTreeMap<OutputLocation, transparent::Output>,
295        BTreeSet<OutputLocation>,
296        Option<Height>,
297    ),
298    BoxError,
299>
300where
301    C: AsRef<Chain>,
302{
303    let address_count = addresses.len();
304
305    let finalized_tip_range = match finalized_tip_range {
306        Some(finalized_tip_range) => finalized_tip_range,
307        None => {
308            assert!(
309                chain.is_none(),
310                "unexpected non-finalized chain when finalized state is empty"
311            );
312
313            debug!(
314                ?finalized_tip_range,
315                ?address_count,
316                "chain address UTXO query: state is empty, no UTXOs available",
317            );
318
319            return Ok(Default::default());
320        }
321    };
322
323    // # Correctness
324    //
325    // We can compensate for deleted UTXOs by applying the overlapping non-finalized UTXO changes.
326
327    // Check if the finalized and non-finalized states match or overlap
328    let required_min_non_finalized_root = finalized_tip_range.start().0 + 1;
329
330    // Work out if we need to compensate for finalized query results from multiple heights:
331    // - Ok contains the finalized tip height (no need to compensate)
332    // - Err contains the required non-finalized chain overlap
333    let finalized_tip_status = required_min_non_finalized_root..=finalized_tip_range.end().0;
334    let finalized_tip_status = if finalized_tip_status.is_empty() {
335        let finalized_tip_height = *finalized_tip_range.end();
336        Ok(finalized_tip_height)
337    } else {
338        let required_non_finalized_overlap = finalized_tip_status;
339        Err(required_non_finalized_overlap)
340    };
341
342    if chain.is_none() {
343        if let Ok(finalized_tip_height) = finalized_tip_status {
344            debug!(
345                ?finalized_tip_status,
346                ?required_min_non_finalized_root,
347                ?finalized_tip_range,
348                ?address_count,
349                "chain address UTXO query: \
350                 finalized chain is consistent, and non-finalized chain is empty",
351            );
352
353            return Ok((
354                Default::default(),
355                Default::default(),
356                Some(finalized_tip_height),
357            ));
358        } else {
359            // We can't compensate for inconsistent database queries,
360            // because the non-finalized chain is empty.
361            debug!(
362                ?finalized_tip_status,
363                ?required_min_non_finalized_root,
364                ?finalized_tip_range,
365                ?address_count,
366                "chain address UTXO query: \
367                 finalized tip query was inconsistent, but non-finalized chain is empty",
368            );
369
370            return Err("unable to get UTXOs: \
371                        state was committing a block, and non-finalized chain is empty"
372                .into());
373        }
374    }
375
376    let chain = chain.unwrap();
377    let chain = chain.as_ref();
378
379    let non_finalized_root = chain.non_finalized_root_height();
380    let non_finalized_tip = chain.non_finalized_tip_height();
381
382    assert!(
383        non_finalized_root.0 <= required_min_non_finalized_root,
384        "unexpected chain gap: the best chain is updated after its previous root is finalized",
385    );
386
387    match finalized_tip_status {
388        Ok(finalized_tip_height) => {
389            // If we've already committed this entire chain, ignore its UTXO changes.
390            // This is more likely if the non-finalized state is just getting started.
391            if finalized_tip_height >= non_finalized_tip {
392                debug!(
393                    ?non_finalized_root,
394                    ?non_finalized_tip,
395                    ?finalized_tip_status,
396                    ?finalized_tip_range,
397                    ?address_count,
398                    "chain address UTXO query: \
399                     non-finalized blocks have all been finalized, no new UTXO changes",
400                );
401
402                return Ok((
403                    Default::default(),
404                    Default::default(),
405                    Some(finalized_tip_height),
406                ));
407            }
408        }
409
410        Err(ref required_non_finalized_overlap) => {
411            // We can't compensate for inconsistent database queries,
412            // because the non-finalized chain is below the inconsistent query range.
413            if *required_non_finalized_overlap.end() > non_finalized_tip.0 {
414                debug!(
415                    ?non_finalized_root,
416                    ?non_finalized_tip,
417                    ?finalized_tip_status,
418                    ?finalized_tip_range,
419                    ?address_count,
420                    "chain address UTXO query: \
421                     finalized tip query was inconsistent, \
422                     and some inconsistent blocks are missing from the non-finalized chain",
423                );
424
425                return Err("unable to get UTXOs: \
426                            state was committing a block, \
427                            that is missing from the non-finalized chain"
428                    .into());
429            }
430
431            // Correctness: some finalized UTXOs might have duplicate creates or spends,
432            // but we've just checked they can be corrected by applying the non-finalized UTXO changes.
433            assert!(
434                required_non_finalized_overlap
435                    .clone()
436                    .all(|height| chain.blocks.contains_key(&Height(height))),
437                "UTXO query inconsistency: chain must contain required overlap blocks",
438            );
439        }
440    }
441    let (created, spent) =
442        chain.partial_transparent_utxo_changes(addresses, query_height_range, max_entries);
443    Ok((created, spent, Some(non_finalized_tip)))
444}
445
446/// The number of UTXOs a limited finalized query has to ask for, when the caller wants
447/// `max_entries` of them and the non-finalized chain spends `chain_spent_count` of the
448/// addresses' UTXOs.
449///
450/// Any of the UTXOs the finalized query returns can turn out to be spent by the chain, so the
451/// query has to over-fetch by as many entries as the chain spends. Otherwise a full page comes
452/// back short, and a caller paging by count reads that as the end of the addresses' UTXOs.
453///
454/// The result is an over-approximation: it can make the query read entries that are then
455/// discarded, but never too few to fill the page.
456fn finalized_scan_limit(max_entries: usize, chain_spent_count: usize) -> usize {
457    max_entries.saturating_add(chain_spent_count)
458}
459
460/// Combines the supplied finalized and non-finalized UTXOs, removes the spent UTXOs and the
461/// UTXOs outside `query_height_range`, truncates the result to `max_entries`, and returns it.
462fn apply_utxo_changes(
463    finalized_utxos: BTreeMap<OutputLocation, transparent::Output>,
464    created_chain_utxos: BTreeMap<OutputLocation, transparent::Output>,
465    spent_chain_utxos: BTreeSet<OutputLocation>,
466    query_height_range: &RangeInclusive<Height>,
467    max_entries: Option<usize>,
468) -> BTreeMap<OutputLocation, transparent::Output> {
469    // Correctness: combine the created UTXOs, then remove spent UTXOs,
470    // to compensate for overlapping finalized and non-finalized blocks.
471    //
472    // The finalized UTXOs are already limited to the query height range, but the
473    // non-finalized ones are not.
474    let utxos: BTreeMap<_, _> = finalized_utxos
475        .into_iter()
476        .chain(
477            created_chain_utxos
478                .into_iter()
479                .filter(|(utxo_location, _)| query_height_range.contains(&utxo_location.height())),
480        )
481        .filter(|(utxo_location, _output)| !spent_chain_utxos.contains(utxo_location))
482        .collect();
483
484    // Truncate after collecting, so the entries that survive are the first in chain order,
485    // rather than the first in the order the two sources happened to be chained in.
486    match max_entries {
487        Some(max_entries) => utxos.into_iter().take(max_entries).collect(),
488        None => utxos,
489    }
490}
491
492/// Returns the [`transaction::Hash`]es containing the supplied UTXOs,
493/// from the non-finalized `chain` and finalized `db`.
494///
495/// # Panics
496///
497/// If any UTXO is not in the supplied state.
498fn lookup_tx_ids_for_utxos<C>(
499    chain: Option<C>,
500    db: &ZebraDb,
501    utxos: &BTreeMap<OutputLocation, transparent::Output>,
502) -> BTreeMap<TransactionLocation, transaction::Hash>
503where
504    C: AsRef<Chain>,
505{
506    // Get the unique set of transaction locations
507    let transaction_locations: BTreeSet<TransactionLocation> = utxos
508        .keys()
509        .map(|output_location| output_location.transaction_location())
510        .collect();
511
512    // First try the in-memory chain, then the disk database.
513    //
514    // Look up each location, rather than all the addresses' chain transactions, so the work
515    // done here is bounded by the number of UTXOs.
516    transaction_locations
517        .iter()
518        .map(|tx_loc| {
519            (
520                *tx_loc,
521                chain
522                    .as_ref()
523                    .and_then(|chain| chain.as_ref().transaction_hash_by_loc(*tx_loc).copied())
524                    .unwrap_or_else(|| {
525                        db.transaction_hash(*tx_loc)
526                            .expect("unexpected inconsistent UTXO indexes")
527                    }),
528            )
529        })
530        .collect()
531}
532
533#[cfg(test)]
534mod tests {
535    use zebra_chain::{amount::Amount, transparent::Script};
536
537    use super::*;
538
539    /// Returns a UTXO at `height`, and its location.
540    fn utxo(height: u32) -> (OutputLocation, transparent::Output) {
541        (
542            OutputLocation::from_usize(Height(height), 0, 0),
543            transparent::Output::new(Amount::zero(), Script::new(&[])),
544        )
545    }
546
547    /// Returns the heights of `utxos`, in chain order.
548    fn heights(utxos: &BTreeMap<OutputLocation, transparent::Output>) -> Vec<u32> {
549        utxos.keys().map(|location| location.height().0).collect()
550    }
551
552    /// The non-finalized chain creates UTXOs across the whole chain, not just the queried
553    /// range, so the ones outside it have to be dropped even though the finalized query
554    /// never returned them.
555    #[test]
556    fn created_chain_utxos_are_limited_to_the_query_height_range() {
557        let finalized = BTreeMap::from([utxo(30), utxo(40)]);
558        let created = BTreeMap::from([utxo(10), utxo(50)]);
559
560        let utxos = apply_utxo_changes(
561            finalized,
562            created,
563            BTreeSet::new(),
564            &(Height(20)..=Height(45)),
565            None,
566        );
567
568        assert_eq!(heights(&utxos), vec![30, 40]);
569    }
570
571    /// A truncated result keeps the first UTXOs in chain order, not the first in the order
572    /// the finalized and non-finalized sources are combined in.
573    #[test]
574    fn a_limited_result_keeps_the_lowest_utxos() {
575        let finalized = BTreeMap::from([utxo(30), utxo(40)]);
576        let created = BTreeMap::from([utxo(10), utxo(20)]);
577
578        let utxos = apply_utxo_changes(
579            finalized,
580            created,
581            BTreeSet::new(),
582            &ADDRESS_HEIGHTS_FULL_RANGE,
583            Some(3),
584        );
585
586        assert_eq!(heights(&utxos), vec![10, 20, 30]);
587    }
588
589    /// The over-fetch is what keeps a page full when the non-finalized chain spends some of
590    /// the UTXOs the finalized query returned.
591    #[test]
592    fn over_fetching_keeps_a_limited_page_full() {
593        let max_entries = 2;
594        let all_finalized = [utxo(10), utxo(20), utxo(30), utxo(40), utxo(50)];
595
596        // The chain spends the first UTXO the finalized query would return.
597        let spent = BTreeSet::from([all_finalized[0].0]);
598
599        // The finalized query returns the first `limit` UTXOs, whatever the limit is.
600        let query = |limit: usize| {
601            apply_utxo_changes(
602                all_finalized.iter().take(limit).cloned().collect(),
603                BTreeMap::new(),
604                spent.clone(),
605                &ADDRESS_HEIGHTS_FULL_RANGE,
606                Some(max_entries),
607            )
608        };
609
610        // Asking for exactly `max_entries` returns a short page, because one of them is spent.
611        assert_eq!(heights(&query(max_entries)), vec![20]);
612
613        // Over-fetching by the number of spends fills the page instead.
614        let limit = finalized_scan_limit(max_entries, spent.len());
615        assert_eq!(heights(&query(limit)), vec![20, 30]);
616    }
617}