Skip to main content

zebra_state/service/non_finalized_state/chain/
index.rs

1//! Transparent address indexes for non-finalized chains.
2//!
3//! Each block's address changes are built once, when a chain adds the block, and every chain
4//! containing the block shares them. Chains keep these records by height, so forks, read
5//! snapshots, and finalization never copy address histories.
6
7use std::{
8    collections::{HashMap, HashSet},
9    sync::Arc,
10};
11
12use zebra_chain::{
13    amount::{Amount, NegativeAllowed},
14    parameters::Network,
15    transaction, transparent,
16};
17
18use crate::{ContextuallyVerifiedBlock, OutputLocation, TransactionLocation};
19
20/// The transparent transfers of one non-finalized block, by address.
21#[derive(Clone, Debug, Default, Eq, PartialEq)]
22pub(crate) struct BlockTransparentTransfers {
23    by_address: HashMap<transparent::Address, AddressBlockTransfers>,
24}
25
26/// The transparent transfers of one address in one non-finalized block.
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub(crate) struct AddressBlockTransfers {
29    /// The change this block makes to the address balance.
30    balance: Amount<NegativeAllowed>,
31
32    /// The total value of the outputs this block creates for the address, saturating at
33    /// `u64::MAX` like the finalized index (#10556).
34    received: u64,
35
36    /// The outputs this block creates for the address, in chain order. They are shared with the
37    /// block's output map.
38    created: Vec<(OutputLocation, Arc<transparent::OrderedUtxo>)>,
39
40    /// The locations of the address outputs this block spends, in chain order.
41    spent: Vec<OutputLocation>,
42
43    /// The transactions in this block that send to or spend from the address, in chain order.
44    transactions: Vec<(TransactionLocation, transaction::Hash)>,
45}
46
47impl BlockTransparentTransfers {
48    /// Builds the address changes of `block`.
49    ///
50    /// # Panics
51    ///
52    /// If `block` is missing a created output, or outside tests, a spent output.
53    pub(crate) fn new(block: &ContextuallyVerifiedBlock, network: &Network) -> Self {
54        // Balances are summed in i128, so no partial sum can overflow.
55        let mut by_address: HashMap<transparent::Address, (i128, AddressBlockTransfers)> =
56            HashMap::new();
57
58        for (index, (transaction, hash)) in block
59            .block
60            .transactions
61            .iter()
62            .zip(block.transaction_hashes.iter())
63            .enumerate()
64        {
65            let tx_location = TransactionLocation::from_usize(block.height, index);
66            let output_count = transaction
67                .transparent_bundle()
68                .map_or(0, |bundle| bundle.vout.len());
69            for output_index in 0..output_count {
70                let outpoint = transparent::OutPoint {
71                    hash: *hash,
72                    index: output_index.try_into().expect("valid indexes fit in u32"),
73                };
74                let utxo = block
75                    .new_outputs
76                    .get(&outpoint)
77                    .expect("new_outputs contains all created UTXOs");
78                let Some(address) = utxo.utxo.output.address(network) else {
79                    continue;
80                };
81
82                let value = utxo.utxo.output.value();
83                let (balance, transfers) =
84                    address_entry(&mut by_address, address, tx_location, hash);
85                *balance += i128::from(value.zatoshis());
86                transfers.received = transfers.received.saturating_add(u64::from(value));
87                transfers.created.push((
88                    OutputLocation::from_outpoint(transaction_location(utxo), &outpoint),
89                    utxo.clone(),
90                ));
91            }
92
93            for spent_outpoint in transaction.spent_outpoints() {
94                // TODO: fix tests to supply correct spent outputs, then turn this into an expect()
95                let Some(spent_output) = block.spent_outputs.get(&spent_outpoint) else {
96                    if !cfg!(test) {
97                        panic!(
98                            "unexpected missing spent output: all spent outputs must be indexed"
99                        );
100                    }
101                    continue;
102                };
103                let Some(address) = spent_output.utxo.output.address(network) else {
104                    continue;
105                };
106
107                let (balance, transfers) =
108                    address_entry(&mut by_address, address, tx_location, hash);
109                *balance -= i128::from(spent_output.utxo.output.value().zatoshis());
110                transfers.spent.push(OutputLocation::from_outpoint(
111                    transaction_location(spent_output),
112                    &spent_outpoint,
113                ));
114            }
115        }
116
117        let by_address = by_address
118            .into_iter()
119            .map(|(address, (balance, mut transfers))| {
120                transfers.balance = Amount::try_from(balance)
121                    .expect("one block can't move more than the money supply for an address");
122                transfers.spent.sort_unstable();
123                (address, transfers)
124            })
125            .collect();
126
127        Self { by_address }
128    }
129
130    /// Returns the transfers of each of `addresses` that this block changes.
131    pub(crate) fn for_addresses<'a>(
132        &'a self,
133        addresses: &'a HashSet<transparent::Address>,
134    ) -> impl Iterator<Item = &'a AddressBlockTransfers> + 'a {
135        // Look up whichever side is smaller.
136        let (by_lookup, by_scan) = if addresses.len() <= self.by_address.len() {
137            (Some(addresses), None)
138        } else {
139            (None, Some(addresses))
140        };
141
142        let looked_up = by_lookup
143            .into_iter()
144            .flatten()
145            .filter_map(|address| self.by_address.get(address));
146        let scanned = by_scan.into_iter().flat_map(move |addresses| {
147            self.by_address
148                .iter()
149                .filter(move |(address, _)| addresses.contains(*address))
150                .map(|(_, transfers)| transfers)
151        });
152
153        looked_up.chain(scanned)
154    }
155
156    /// Returns the number of addresses this block changes.
157    #[cfg(test)]
158    pub(crate) fn len(&self) -> usize {
159        self.by_address.len()
160    }
161
162    /// Returns the transfers of `address` in this block, if it changes the address.
163    #[cfg(test)]
164    pub(crate) fn get(&self, address: &transparent::Address) -> Option<&AddressBlockTransfers> {
165        self.by_address.get(address)
166    }
167}
168
169/// Returns the balance accumulator and transfers of `address` in a block being indexed, recording
170/// that the transaction at `tx_location` changes the address.
171fn address_entry<'a>(
172    by_address: &'a mut HashMap<transparent::Address, (i128, AddressBlockTransfers)>,
173    address: transparent::Address,
174    tx_location: TransactionLocation,
175    hash: &transaction::Hash,
176) -> (&'a mut i128, &'a mut AddressBlockTransfers) {
177    let (balance, transfers) = by_address.entry(address).or_insert_with(|| {
178        (
179            0,
180            AddressBlockTransfers {
181                balance: Amount::zero(),
182                received: 0,
183                created: Vec::new(),
184                spent: Vec::new(),
185                transactions: Vec::new(),
186            },
187        )
188    });
189    if transfers.transactions.last().map(|(location, _)| *location) != Some(tx_location) {
190        transfers.transactions.push((tx_location, *hash));
191    }
192    (balance, transfers)
193}
194
195impl AddressBlockTransfers {
196    /// Returns the change this block makes to the address balance.
197    pub(crate) fn balance(&self) -> Amount<NegativeAllowed> {
198        self.balance
199    }
200
201    /// Returns the total value of the outputs this block creates for the address.
202    pub(crate) fn received(&self) -> u64 {
203        self.received
204    }
205
206    /// Returns the outputs this block creates for the address, in chain order.
207    pub(crate) fn created(&self) -> &[(OutputLocation, Arc<transparent::OrderedUtxo>)] {
208        &self.created
209    }
210
211    /// Returns the locations of the address outputs this block spends, in chain order.
212    pub(crate) fn spent(&self) -> &[OutputLocation] {
213        &self.spent
214    }
215
216    /// Returns the transactions in this block that send to or spend from the address, in chain
217    /// order.
218    pub(crate) fn transactions(&self) -> &[(TransactionLocation, transaction::Hash)] {
219        &self.transactions
220    }
221}
222
223/// Returns the transaction location for an [`transparent::OrderedUtxo`].
224pub fn transaction_location(ordered_utxo: &transparent::OrderedUtxo) -> TransactionLocation {
225    TransactionLocation::from_usize(ordered_utxo.utxo.height, ordered_utxo.tx_index_in_block)
226}
227
228#[cfg(test)]
229pub(in crate::service::non_finalized_state) mod tests;