Skip to main content

zebra_state/service/read/address/
tx_id.rs

1//! Reading address transaction IDs.
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, HashSet},
16    ops::RangeInclusive,
17};
18
19use zebra_chain::{block::Height, transaction, transparent};
20
21use crate::{
22    service::{
23        finalized_state::ZebraDb, non_finalized_state::Chain, read::FINALIZED_STATE_QUERY_RETRIES,
24    },
25    BoxError, TransactionLocation,
26};
27
28/// Returns the transaction IDs that sent or received funds from the supplied [`transparent::Address`]es,
29/// within `query_height_range`, in chain order, at most `max_entries` of them.
30///
31/// If the addresses do not exist in the non-finalized `chain` or finalized `db`,
32/// or the `query_height_range` is totally outside both the `chain` and `db` range,
33/// returns an empty list.
34pub fn transparent_tx_ids<C>(
35    chain: Option<C>,
36    db: &ZebraDb,
37    addresses: HashSet<transparent::Address>,
38    query_height_range: RangeInclusive<Height>,
39    max_entries: Option<usize>,
40) -> Result<BTreeMap<TransactionLocation, transaction::Hash>, BoxError>
41where
42    C: AsRef<Chain>,
43{
44    let mut tx_id_error = None;
45
46    // Retry the finalized tx ID query if it was interrupted by a finalizing block,
47    // and the non-finalized chain doesn't overlap the changed heights.
48    //
49    // TODO: refactor this into a generic retry(finalized_closure, process_and_check_closure) fn
50    for _ in 0..=FINALIZED_STATE_QUERY_RETRIES {
51        let (finalized_tx_ids, finalized_tip_range) =
52            finalized_transparent_tx_ids(db, &addresses, query_height_range.clone(), max_entries);
53
54        // Apply the non-finalized tx ID changes.
55        let chain_tx_id_changes = chain_transparent_tx_id_changes(
56            chain.as_ref(),
57            &addresses,
58            finalized_tip_range,
59            query_height_range.clone(),
60            max_entries,
61        );
62
63        // If the tx IDs are valid, return them, otherwise, retry or return an error.
64        match chain_tx_id_changes {
65            Ok(chain_tx_id_changes) => {
66                let tx_ids =
67                    apply_tx_id_changes(finalized_tx_ids, chain_tx_id_changes, max_entries);
68
69                return Ok(tx_ids);
70            }
71
72            Err(error) => tx_id_error = Some(Err(error)),
73        }
74    }
75
76    tx_id_error.expect("unexpected missing error: attempts should set error or return")
77}
78
79/// Returns the [`transaction::Hash`]es for `addresses` in the finalized chain `query_height_range`,
80/// and the finalized tip heights the transaction IDs were queried at.
81///
82/// If the addresses do not exist in the finalized `db`, returns an empty list.
83//
84// TODO: turn the return type into a struct?
85fn finalized_transparent_tx_ids(
86    db: &ZebraDb,
87    addresses: &HashSet<transparent::Address>,
88    query_height_range: RangeInclusive<Height>,
89    limit: Option<usize>,
90) -> (
91    BTreeMap<TransactionLocation, transaction::Hash>,
92    Option<RangeInclusive<Height>>,
93) {
94    // # Correctness
95    //
96    // The StateService can commit additional blocks while we are querying transaction IDs.
97
98    // Check if the finalized state changed while we were querying it
99    let start_finalized_tip = db.finalized_tip_height();
100
101    let finalized_tx_ids =
102        db.partial_finalized_transparent_tx_ids(addresses, query_height_range, limit);
103
104    let end_finalized_tip = db.finalized_tip_height();
105
106    let finalized_tip_range = if let (Some(start_finalized_tip), Some(end_finalized_tip)) =
107        (start_finalized_tip, end_finalized_tip)
108    {
109        Some(start_finalized_tip..=end_finalized_tip)
110    } else {
111        // State is empty
112        None
113    };
114
115    (finalized_tx_ids, finalized_tip_range)
116}
117
118/// Returns the extra transaction IDs for `addresses` in the non-finalized chain `query_height_range`,
119/// matching or overlapping the transaction IDs for the `finalized_tip_range`,
120/// at most `max_entries` of them, the first in chain order.
121///
122/// If the addresses do not exist in the non-finalized `chain`, returns an empty list.
123//
124// TODO: turn the return type into a struct?
125fn chain_transparent_tx_id_changes<C>(
126    chain: Option<C>,
127    addresses: &HashSet<transparent::Address>,
128    finalized_tip_range: Option<RangeInclusive<Height>>,
129    query_height_range: RangeInclusive<Height>,
130    max_entries: Option<usize>,
131) -> Result<BTreeMap<TransactionLocation, transaction::Hash>, BoxError>
132where
133    C: AsRef<Chain>,
134{
135    let address_count = addresses.len();
136
137    let finalized_tip_range = match finalized_tip_range {
138        Some(finalized_tip_range) => finalized_tip_range,
139        None => {
140            assert!(
141                chain.is_none(),
142                "unexpected non-finalized chain when finalized state is empty"
143            );
144
145            debug!(
146                ?finalized_tip_range,
147                ?address_count,
148                "chain address tx ID query: state is empty, no tx IDs available",
149            );
150
151            return Ok(Default::default());
152        }
153    };
154
155    // # Correctness
156    //
157    // We can compensate for addresses with mismatching blocks,
158    // by adding the overlapping non-finalized transaction IDs.
159    //
160    // If there is only one address, mismatches aren't possible,
161    // because tx IDs are added to the finalized state in chain order (and never removed),
162    // and they are queried in chain order.
163
164    // Check if the finalized and non-finalized states match or overlap
165    let required_min_non_finalized_root = finalized_tip_range.start().0 + 1;
166
167    // Work out if we need to compensate for finalized query results from multiple heights:
168    // - Ok contains the finalized tip height (no need to compensate)
169    // - Err contains the required non-finalized chain overlap
170    let finalized_tip_status = required_min_non_finalized_root..=finalized_tip_range.end().0;
171    let finalized_tip_status = if finalized_tip_status.is_empty() {
172        let finalized_tip_height = *finalized_tip_range.end();
173        Ok(finalized_tip_height)
174    } else {
175        let required_non_finalized_overlap = finalized_tip_status;
176        Err(required_non_finalized_overlap)
177    };
178
179    if chain.is_none() {
180        if address_count <= 1 || finalized_tip_status.is_ok() {
181            debug!(
182                ?finalized_tip_status,
183                ?required_min_non_finalized_root,
184                ?finalized_tip_range,
185                ?address_count,
186                "chain address tx ID query: \
187                 finalized chain is consistent, and non-finalized chain is empty",
188            );
189
190            return Ok(Default::default());
191        } else {
192            // We can't compensate for inconsistent database queries,
193            // because the non-finalized chain is empty.
194            debug!(
195                ?finalized_tip_status,
196                ?required_min_non_finalized_root,
197                ?finalized_tip_range,
198                ?address_count,
199                "chain address tx ID query: \
200                 finalized tip query was inconsistent, but non-finalized chain is empty",
201            );
202
203            return Err("unable to get tx IDs: \
204                        state was committing a block, and non-finalized chain is empty"
205                .into());
206        }
207    }
208
209    let chain = chain.unwrap();
210    let chain = chain.as_ref();
211
212    let non_finalized_root = chain.non_finalized_root_height();
213    let non_finalized_tip = chain.non_finalized_tip_height();
214
215    assert!(
216        non_finalized_root.0 <= required_min_non_finalized_root,
217        "unexpected chain gap: the best chain is updated after its previous root is finalized",
218    );
219
220    match finalized_tip_status {
221        Ok(finalized_tip_height) => {
222            // If we've already committed this entire chain, ignore its UTXO changes.
223            // This is more likely if the non-finalized state is just getting started.
224            if finalized_tip_height >= non_finalized_tip {
225                debug!(
226                    ?non_finalized_root,
227                    ?non_finalized_tip,
228                    ?finalized_tip_status,
229                    ?finalized_tip_range,
230                    ?address_count,
231                    "chain address tx ID query: \
232                     non-finalized blocks have all been finalized, no new UTXO changes",
233                );
234
235                return Ok(Default::default());
236            }
237        }
238
239        Err(ref required_non_finalized_overlap) => {
240            // We can't compensate for inconsistent database queries,
241            // because the non-finalized chain is below the inconsistent query range.
242            if address_count > 1 && *required_non_finalized_overlap.end() > non_finalized_tip.0 {
243                debug!(
244                    ?non_finalized_root,
245                    ?non_finalized_tip,
246                    ?finalized_tip_status,
247                    ?finalized_tip_range,
248                    ?address_count,
249                    "chain address tx ID query: \
250                     finalized tip query was inconsistent, \
251                     some inconsistent blocks are missing from the non-finalized chain, \
252                     and the query has multiple addresses",
253                );
254
255                return Err("unable to get tx IDs: \
256                            state was committing a block, \
257                            that is missing from the non-finalized chain, \
258                            and the query has multiple addresses"
259                    .into());
260            }
261
262            // Correctness: some finalized UTXOs might have duplicate creates or spends,
263            // but we've just checked they can be corrected by applying the non-finalized UTXO changes.
264            assert!(
265                address_count <= 1
266                    || required_non_finalized_overlap
267                        .clone()
268                        .all(|height| chain.blocks.contains_key(&Height(height))),
269                "tx ID query inconsistency: \
270                 chain must contain required overlap blocks \
271                 or query must only have one address",
272            );
273        }
274    }
275
276    Ok(chain.partial_transparent_tx_ids(addresses, query_height_range, max_entries))
277}
278
279/// Returns the combined finalized and non-finalized transaction IDs, truncated to `max_entries`.
280fn apply_tx_id_changes(
281    finalized_tx_ids: BTreeMap<TransactionLocation, transaction::Hash>,
282    chain_tx_ids: BTreeMap<TransactionLocation, transaction::Hash>,
283    max_entries: Option<usize>,
284) -> BTreeMap<TransactionLocation, transaction::Hash> {
285    // Correctness: compensate for inconsistent tx IDs finalized blocks across multiple addresses,
286    // by combining them with overlapping non-finalized block tx IDs.
287    let tx_ids: BTreeMap<_, _> = finalized_tx_ids.into_iter().chain(chain_tx_ids).collect();
288
289    // Truncate after merging, so the survivors are the first in chain order.
290    match max_entries {
291        Some(max_entries) => tx_ids.into_iter().take(max_entries).collect(),
292        None => tx_ids,
293    }
294}