Skip to main content

zebra_state/service/check/
utxo.rs

1//! Consensus rule checks for the finalized state.
2
3use std::collections::HashMap;
4
5use zebra_chain::{
6    amount,
7    transparent::{self, CoinbaseSpendRestriction::*},
8};
9
10use crate::{
11    constants::MIN_TRANSPARENT_COINBASE_MATURITY,
12    service::{
13        finalized_state::ZebraDb,
14        non_finalized_state::{Chain, SpendingTransactionId},
15    },
16    SemanticallyVerifiedBlock,
17    ValidateContextError::{
18        self, DuplicateTransparentSpend, EarlyTransparentSpend, ImmatureTransparentCoinbaseSpend,
19        MissingTransparentOutput, UnshieldedTransparentCoinbaseSpend,
20    },
21};
22
23/// Lookup all the [`transparent::Utxo`]s spent by a [`SemanticallyVerifiedBlock`].
24/// If any of the spends are invalid, return an error.
25/// Otherwise, return the looked up UTXOs.
26///
27/// Checks for the following kinds of invalid spends:
28///
29/// Double-spends:
30/// - duplicate spends that are both in this block,
31/// - spends of an output that was spent by a previous block,
32///
33/// Missing spends:
34/// - spends of an output that hasn't been created yet,
35///   (in linear chain and transaction order),
36/// - spends of UTXOs that were never created in this chain,
37///
38/// Invalid spends:
39/// - spends of an immature transparent coinbase output,
40/// - unshielded spends of a transparent coinbase output.
41pub fn transparent_spend(
42    semantically_verified: &SemanticallyVerifiedBlock,
43    non_finalized_chain: &Chain,
44    non_finalized_chain_spent_utxos: &imbl::HashMap<transparent::OutPoint, SpendingTransactionId>,
45    finalized_state: &ZebraDb,
46) -> Result<HashMap<transparent::OutPoint, transparent::OrderedUtxo>, ValidateContextError> {
47    let mut block_spends = HashMap::new();
48
49    for (spend_tx_index_in_block, transaction) in
50        semantically_verified.block.transactions.iter().enumerate()
51    {
52        // Coinbase inputs represent new coins,
53        // so there are no UTXOs to mark as spent.
54        let inputs = transaction.inputs();
55        let spends = inputs.iter().filter_map(transparent::Input::outpoint);
56
57        // The restriction depends only on the transaction, network and height, so compute it
58        // once per transaction rather than once per spend: it inspects the transaction's
59        // transparent outputs, which would make this loop quadratic in inputs and outputs.
60        let spend_restriction = transaction
61            .coinbase_spend_restriction(&finalized_state.network(), semantically_verified.height);
62
63        for spend in spends {
64            let utxo = transparent_spend_chain_order(
65                spend,
66                spend_tx_index_in_block,
67                &semantically_verified.new_outputs,
68                non_finalized_chain,
69                non_finalized_chain_spent_utxos,
70                finalized_state,
71            )?;
72
73            // The state service returns UTXOs from pending blocks,
74            // which can be rejected by later contextual checks.
75            // This is a particular issue for v5 transactions,
76            // because their authorizing data is only bound to the block data
77            // during contextual validation (#2336).
78            //
79            // We don't want to use UTXOs from invalid pending blocks,
80            // so we check transparent coinbase maturity and shielding
81            // using known valid UTXOs during non-finalized chain validation.
82            transparent_coinbase_spend(spend, spend_restriction, utxo.as_ref())?;
83
84            // We don't delete the UTXOs until the block is committed,
85            // so we  need to check for duplicate spends within the same block.
86            //
87            // See `transparent_spend_chain_order` for the relevant consensus rule.
88            if block_spends.insert(spend, utxo).is_some() {
89                return Err(DuplicateTransparentSpend {
90                    outpoint: spend,
91                    location: "the same block",
92                });
93            }
94        }
95    }
96
97    remaining_transaction_value(semantically_verified, &block_spends)?;
98
99    Ok(block_spends)
100}
101
102/// Check that transparent spends occur in chain order.
103///
104/// Because we are in the non-finalized state, we need to check spends within the same block,
105/// spent non-finalized UTXOs, and unspent non-finalized and finalized UTXOs.
106///
107/// "Any input within this block can spend an output which also appears in this block
108/// (assuming the spend is otherwise valid).
109/// However, the TXID corresponding to the output must be placed at some point
110/// before the TXID corresponding to the input.
111/// This ensures that any program parsing block chain transactions linearly
112/// will encounter each output before it is used as an input."
113///
114/// <https://developer.bitcoin.org/reference/block_chain.html#merkle-trees>
115///
116/// "each output of a particular transaction
117/// can only be used as an input once in the block chain.
118/// Any subsequent reference is a forbidden double spend-
119/// an attempt to spend the same satoshis twice."
120///
121/// <https://developer.bitcoin.org/devguide/block_chain.html#introduction>
122///
123/// # Consensus
124///
125/// > Every non-null prevout MUST point to a unique UTXO in either a preceding block,
126/// > or a previous transaction in the same block.
127///
128/// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
129fn transparent_spend_chain_order(
130    spend: transparent::OutPoint,
131    spend_tx_index_in_block: usize,
132    block_new_outputs: &HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
133    non_finalized_chain: &Chain,
134    non_finalized_chain_spent_utxos: &imbl::HashMap<transparent::OutPoint, SpendingTransactionId>,
135    finalized_state: &ZebraDb,
136) -> Result<transparent::OrderedUtxo, ValidateContextError> {
137    if let Some(output) = block_new_outputs.get(&spend) {
138        // reject the spend if it uses an output from this block,
139        // but the output was not created by an earlier transaction
140        //
141        // we know the spend is invalid, because transaction IDs are unique
142        //
143        // (transaction IDs also commit to transaction inputs,
144        // so it should be cryptographically impossible for a transaction
145        // to spend its own outputs)
146        if output.tx_index_in_block >= spend_tx_index_in_block {
147            return Err(EarlyTransparentSpend { outpoint: spend });
148        } else {
149            // a unique spend of a previous transaction's output is ok
150            return Ok(output.clone());
151        }
152    }
153
154    // This check must come before the created output lookup, because the created outputs
155    // include outputs that are already spent in the non-finalized chain.
156    if non_finalized_chain_spent_utxos.contains_key(&spend) {
157        // reject the spend if its UTXO is already spent in the
158        // non-finalized parent chain
159        return Err(DuplicateTransparentSpend {
160            outpoint: spend,
161            location: "the non-finalized chain",
162        });
163    }
164
165    non_finalized_chain
166        .created_ordered_utxo(&spend)
167        .map(|utxo| utxo.as_ref().clone())
168        .or_else(|| finalized_state.utxo(&spend))
169        // we don't keep spent UTXOs in the finalized state,
170        // so all we can say is that it's missing from both
171        // the finalized and non-finalized chains
172        // (it might have been spent in the finalized state,
173        // or it might never have existed in this chain)
174        .ok_or(MissingTransparentOutput {
175            outpoint: spend,
176            location: "the non-finalized and finalized chain",
177        })
178}
179
180/// Check that `utxo` is spendable, based on the coinbase `spend_restriction`.
181///
182/// # Consensus
183///
184/// > A transaction with one or more transparent inputs from coinbase transactions
185/// > MUST have no transparent outputs (i.e. tx_out_count MUST be 0).
186/// > Inputs from coinbase transactions include Founders’ Reward outputs and
187/// > funding stream outputs.
188///
189/// > A transaction MUST NOT spend a transparent output of a coinbase transaction
190/// > from a block less than 100 blocks prior to the spend.
191/// > Note that transparent outputs of coinbase transactions include
192/// > Founders’ Reward outputs and transparent funding stream outputs.
193///
194/// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
195pub fn transparent_coinbase_spend(
196    outpoint: transparent::OutPoint,
197    spend_restriction: transparent::CoinbaseSpendRestriction,
198    utxo: &transparent::Utxo,
199) -> Result<(), ValidateContextError> {
200    if !utxo.from_coinbase {
201        return Ok(());
202    }
203
204    match spend_restriction {
205        CheckCoinbaseMaturity { spend_height } => {
206            let min_spend_height = utxo.height + MIN_TRANSPARENT_COINBASE_MATURITY.into();
207            let min_spend_height =
208                min_spend_height.expect("valid UTXOs have coinbase heights far below Height::MAX");
209            if spend_height >= min_spend_height {
210                Ok(())
211            } else {
212                Err(ImmatureTransparentCoinbaseSpend {
213                    outpoint,
214                    spend_height,
215                    min_spend_height,
216                    created_height: utxo.height,
217                })
218            }
219        }
220        DisallowCoinbaseSpend => Err(UnshieldedTransparentCoinbaseSpend { outpoint }),
221    }
222}
223
224/// Reject negative remaining transaction value.
225///
226/// "As in Bitcoin, the remaining value in the transparent transaction value pool
227/// of a non-coinbase transaction is available to miners as a fee.
228///
229/// The remaining value in the transparent transaction value pool of a
230/// coinbase transaction is destroyed.
231///
232/// Consensus rule: The remaining value in the transparent transaction value pool
233/// MUST be nonnegative."
234///
235/// <https://zips.z.cash/protocol/protocol.pdf#transactions>
236pub fn remaining_transaction_value(
237    semantically_verified: &SemanticallyVerifiedBlock,
238    utxos: &HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
239) -> Result<(), ValidateContextError> {
240    for (tx_index_in_block, transaction) in
241        semantically_verified.block.transactions.iter().enumerate()
242    {
243        if transaction.is_coinbase() {
244            continue;
245        }
246
247        // Check the remaining transparent value pool for this transaction
248        let value_balance = transaction.value_balance(utxos);
249        match value_balance {
250            Ok(vb) => match vb.remaining_transaction_value() {
251                Ok(_) => Ok(()),
252                Err(amount_error @ amount::Error::Constraint { .. })
253                    if amount_error.invalid_value() < 0 =>
254                {
255                    Err(ValidateContextError::NegativeRemainingTransactionValue {
256                        amount_error,
257                        height: semantically_verified.height,
258                        tx_index_in_block,
259                        transaction_hash: semantically_verified.transaction_hashes
260                            [tx_index_in_block],
261                    })
262                }
263                Err(amount_error) => {
264                    Err(ValidateContextError::CalculateRemainingTransactionValue {
265                        amount_error,
266                        height: semantically_verified.height,
267                        tx_index_in_block,
268                        transaction_hash: semantically_verified.transaction_hashes
269                            [tx_index_in_block],
270                    })
271                }
272            },
273            Err(value_balance_error) => {
274                Err(ValidateContextError::CalculateTransactionValueBalances {
275                    value_balance_error,
276                    height: semantically_verified.height,
277                    tx_index_in_block,
278                    transaction_hash: semantically_verified.transaction_hashes[tx_index_in_block],
279                })
280            }
281        }?
282    }
283
284    Ok(())
285}