zebra_state/service/non_finalized_state/chain/
index.rs1use 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#[derive(Clone, Debug, Default, Eq, PartialEq)]
22pub(crate) struct BlockTransparentTransfers {
23 by_address: HashMap<transparent::Address, AddressBlockTransfers>,
24}
25
26#[derive(Clone, Debug, Eq, PartialEq)]
28pub(crate) struct AddressBlockTransfers {
29 balance: Amount<NegativeAllowed>,
31
32 received: u64,
35
36 created: Vec<(OutputLocation, Arc<transparent::OrderedUtxo>)>,
39
40 spent: Vec<OutputLocation>,
42
43 transactions: Vec<(TransactionLocation, transaction::Hash)>,
45}
46
47impl BlockTransparentTransfers {
48 pub(crate) fn new(block: &ContextuallyVerifiedBlock, network: &Network) -> Self {
54 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 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 pub(crate) fn for_addresses<'a>(
132 &'a self,
133 addresses: &'a HashSet<transparent::Address>,
134 ) -> impl Iterator<Item = &'a AddressBlockTransfers> + 'a {
135 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 #[cfg(test)]
158 pub(crate) fn len(&self) -> usize {
159 self.by_address.len()
160 }
161
162 #[cfg(test)]
164 pub(crate) fn get(&self, address: &transparent::Address) -> Option<&AddressBlockTransfers> {
165 self.by_address.get(address)
166 }
167}
168
169fn 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 pub(crate) fn balance(&self) -> Amount<NegativeAllowed> {
198 self.balance
199 }
200
201 pub(crate) fn received(&self) -> u64 {
203 self.received
204 }
205
206 pub(crate) fn created(&self) -> &[(OutputLocation, Arc<transparent::OrderedUtxo>)] {
208 &self.created
209 }
210
211 pub(crate) fn spent(&self) -> &[OutputLocation] {
213 &self.spent
214 }
215
216 pub(crate) fn transactions(&self) -> &[(TransactionLocation, transaction::Hash)] {
219 &self.transactions
220 }
221}
222
223pub 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;