Skip to main content

zebra_chain/transparent/
utxo.rs

1//! Unspent transparent output data structures and functions.
2
3use std::collections::HashMap;
4
5use crate::{
6    block::{self, Block, Height},
7    transaction::{self, Transaction},
8    transparent,
9};
10
11/// An unspent `transparent::Output`, with accompanying metadata.
12#[derive(Clone, Debug, PartialEq, Eq, Hash)]
13#[cfg_attr(
14    any(test, feature = "proptest-impl"),
15    derive(proptest_derive::Arbitrary, serde::Serialize)
16)]
17pub struct Utxo {
18    /// The output itself.
19    pub output: transparent::Output,
20
21    // TODO: replace the height and from_coinbase fields with OutputLocation,
22    //       and provide lookup/calculation methods for height and from_coinbase
23    //
24    /// The height at which the output was created.
25    pub height: block::Height,
26    /// Whether the output originated in a coinbase transaction.
27    pub from_coinbase: bool,
28}
29
30/// A [`Utxo`], and the index of its transaction within its block.
31///
32/// This extra index is used to check that spends come after outputs,
33/// when a new output and its spend are both in the same block.
34///
35/// The extra index is only used during block verification,
36/// so it does not need to be sent to the state.
37#[derive(Clone, Debug, PartialEq, Eq)]
38#[cfg_attr(
39    any(test, feature = "proptest-impl"),
40    derive(proptest_derive::Arbitrary)
41)]
42//
43// TODO: after modifying UTXO to contain an OutputLocation, replace this type with UTXO
44pub struct OrderedUtxo {
45    /// An unspent transaction output.
46    pub utxo: Utxo,
47    /// The index of the transaction that created the output, in the block at `height`.
48    ///
49    /// Used to make sure that transaction can only spend outputs
50    /// that were created earlier in the chain.
51    ///
52    /// Note: this is different from `OutPoint.index`,
53    /// which is the index of the output in its transaction.
54    pub tx_index_in_block: usize,
55}
56
57impl AsRef<Utxo> for Utxo {
58    fn as_ref(&self) -> &Utxo {
59        self
60    }
61}
62
63impl AsRef<Utxo> for OrderedUtxo {
64    fn as_ref(&self) -> &Utxo {
65        &self.utxo
66    }
67}
68
69impl Utxo {
70    /// Create a new UTXO from its fields.
71    pub fn new(output: transparent::Output, height: block::Height, from_coinbase: bool) -> Utxo {
72        Utxo {
73            output,
74            height,
75            from_coinbase,
76        }
77    }
78
79    /// Create a new UTXO from an output and its transaction location.
80    pub fn from_location(
81        output: transparent::Output,
82        height: block::Height,
83        tx_index_in_block: usize,
84    ) -> Utxo {
85        // Coinbase transactions are always the first transaction in their block,
86        // we check the other consensus rules separately.
87        let from_coinbase = tx_index_in_block == 0;
88
89        Utxo {
90            output,
91            height,
92            from_coinbase,
93        }
94    }
95}
96
97impl OrderedUtxo {
98    /// Create a new ordered UTXO from its fields.
99    pub fn new(
100        output: transparent::Output,
101        height: block::Height,
102        tx_index_in_block: usize,
103    ) -> OrderedUtxo {
104        // Coinbase transactions are always the first transaction in their block,
105        // we check the other consensus rules separately.
106        let from_coinbase = tx_index_in_block == 0;
107
108        OrderedUtxo {
109            utxo: Utxo::new(output, height, from_coinbase),
110            tx_index_in_block,
111        }
112    }
113
114    /// Create a new ordered UTXO from a UTXO and transaction index.
115    pub fn from_utxo(utxo: Utxo, tx_index_in_block: usize) -> OrderedUtxo {
116        OrderedUtxo {
117            utxo,
118            tx_index_in_block,
119        }
120    }
121}
122
123/// A restriction that must be checked before spending a transparent output of a
124/// coinbase transaction.
125///
126/// See the function `transparent_coinbase_spend` in `zebra-state` for the
127/// consensus rules.
128#[derive(Copy, Clone, Debug, PartialEq, Eq)]
129#[cfg_attr(
130    any(test, feature = "proptest-impl"),
131    derive(proptest_derive::Arbitrary)
132)]
133pub enum CoinbaseSpendRestriction {
134    /// The UTXO is spent in a transaction with one or more transparent outputs
135    /// on a network where coinbase outputs must not be spent by transactions
136    /// with transparent outputs.
137    DisallowCoinbaseSpend,
138
139    /// The UTXO is spent in a transaction which only has shielded outputs, or
140    /// transactions spending coinbase outputs may have transparent outputs on
141    /// this network.
142    CheckCoinbaseMaturity {
143        /// The height at which the UTXO is spent
144        spend_height: block::Height,
145    },
146}
147
148/// Compute an index of [`Utxo`]s from outpoint and [`OrderedUtxo`] pairs.
149pub fn utxos_from_ordered_utxos(
150    ordered_utxos: impl IntoIterator<Item = (transparent::OutPoint, OrderedUtxo)>,
151) -> HashMap<transparent::OutPoint, Utxo> {
152    ordered_utxos
153        .into_iter()
154        .map(|(outpoint, ordered_utxo)| (outpoint, ordered_utxo.utxo))
155        .collect()
156}
157
158/// Compute an index of [`transparent::Output`]s, given an index of [`Utxo`]s.
159pub fn outputs_from_utxos(
160    utxos: HashMap<transparent::OutPoint, Utxo>,
161) -> HashMap<transparent::OutPoint, transparent::Output> {
162    utxos
163        .into_iter()
164        .map(|(outpoint, utxo)| (outpoint, utxo.output))
165        .collect()
166}
167
168/// Compute an index of newly created [`Utxo`]s, given a block and a
169/// list of precomputed transaction hashes.
170pub fn new_outputs(
171    block: &Block,
172    transaction_hashes: &[transaction::Hash],
173) -> HashMap<transparent::OutPoint, Utxo> {
174    utxos_from_ordered_utxos(new_ordered_outputs(block, transaction_hashes))
175}
176
177/// Compute an index of newly created [`Utxo`]s, given a block and a
178/// list of precomputed transaction hashes.
179///
180/// This is a test-only function, prefer [`new_outputs`].
181#[cfg(any(test, feature = "proptest-impl"))]
182pub fn new_outputs_with_height(
183    block: &Block,
184    height: Height,
185    transaction_hashes: &[transaction::Hash],
186) -> HashMap<transparent::OutPoint, Utxo> {
187    utxos_from_ordered_utxos(new_ordered_outputs_with_height(
188        block,
189        height,
190        transaction_hashes,
191    ))
192}
193
194/// Compute an index of newly created [`OrderedUtxo`]s, given a block and a
195/// list of precomputed transaction hashes.
196pub fn new_ordered_outputs(
197    block: &Block,
198    transaction_hashes: &[transaction::Hash],
199) -> HashMap<transparent::OutPoint, OrderedUtxo> {
200    let height = block.coinbase_height().expect("block has coinbase height");
201
202    new_ordered_outputs_with_height(block, height, transaction_hashes)
203}
204
205/// Compute an index of newly created [`OrderedUtxo`]s, given a block and a
206/// list of precomputed transaction hashes.
207///
208/// This function is intended for use in this module, and in tests.
209/// Prefer [`new_ordered_outputs`].
210pub fn new_ordered_outputs_with_height(
211    block: &Block,
212    height: Height,
213    transaction_hashes: &[transaction::Hash],
214) -> HashMap<transparent::OutPoint, OrderedUtxo> {
215    let mut new_ordered_outputs = HashMap::new();
216
217    for (tx_index_in_block, (transaction, hash)) in block
218        .transactions
219        .iter()
220        .zip(transaction_hashes.iter().cloned())
221        .enumerate()
222    {
223        new_ordered_outputs.extend(new_transaction_ordered_outputs(
224            transaction,
225            hash,
226            tx_index_in_block,
227            height,
228        ));
229    }
230
231    new_ordered_outputs
232}
233
234/// Compute an index of newly created [`OrderedUtxo`]s, given a transaction,
235/// its precomputed transaction hash, the transaction's index in its block,
236/// and the block's height.
237///
238/// This function is only for use in this module, and in tests.
239pub fn new_transaction_ordered_outputs(
240    transaction: &Transaction,
241    hash: transaction::Hash,
242    tx_index_in_block: usize,
243    height: block::Height,
244) -> HashMap<transparent::OutPoint, OrderedUtxo> {
245    let mut new_ordered_outputs = HashMap::new();
246
247    for (output_index_in_transaction, output) in transaction.outputs().iter().cloned().enumerate() {
248        let output_index_in_transaction = output_index_in_transaction
249            .try_into()
250            .expect("unexpectedly large number of outputs");
251
252        new_ordered_outputs.insert(
253            transparent::OutPoint {
254                hash,
255                index: output_index_in_transaction,
256            },
257            OrderedUtxo::new(output, height, tx_index_in_block),
258        );
259    }
260
261    new_ordered_outputs
262}