1use 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#[cfg(test)]
38pub const ADDRESS_HEIGHTS_FULL_RANGE: RangeInclusive<Height> = Height(1)..=Height::MAX;
39
40#[derive(Clone, Debug, Default, Eq, PartialEq, Getters)]
43pub struct AddressUtxos {
44 #[getter(skip)]
46 utxos: BTreeMap<OutputLocation, transparent::Output>,
47
48 #[getter(skip)]
50 tx_ids: BTreeMap<TransactionLocation, transaction::Hash>,
51
52 #[getter(skip)]
54 network: Network,
55
56 last_height_and_hash: Option<(block::Height, block::Hash)>,
59}
60
61impl AddressUtxos {
62 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 #[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
107pub 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 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 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 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 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 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
236fn 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 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 None
269 };
270
271 (finalized_utxos, finalized_tip_range)
272}
273
274fn 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 let required_min_non_finalized_root = finalized_tip_range.start().0 + 1;
329
330 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 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 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 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 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
446fn finalized_scan_limit(max_entries: usize, chain_spent_count: usize) -> usize {
457 max_entries.saturating_add(chain_spent_count)
458}
459
460fn 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 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 match max_entries {
487 Some(max_entries) => utxos.into_iter().take(max_entries).collect(),
488 None => utxos,
489 }
490}
491
492fn 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 let transaction_locations: BTreeSet<TransactionLocation> = utxos
508 .keys()
509 .map(|output_location| output_location.transaction_location())
510 .collect();
511
512 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 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 fn heights(utxos: &BTreeMap<OutputLocation, transparent::Output>) -> Vec<u32> {
549 utxos.keys().map(|location| location.height().0).collect()
550 }
551
552 #[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 #[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 #[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 let spent = BTreeSet::from([all_finalized[0].0]);
598
599 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 assert_eq!(heights(&query(max_entries)), vec![20]);
612
613 let limit = finalized_scan_limit(max_entries, spent.len());
615 assert_eq!(heights(&query(limit)), vec![20, 30]);
616 }
617}