Skip to main content

zebra_chain/
transparent.rs

1//! Transparent-related (Bitcoin-inherited) functionality.
2
3mod address;
4mod keys;
5mod opcodes;
6mod script;
7pub(crate) mod serialize;
8mod utxo;
9
10use std::{collections::HashMap, fmt, ops::AddAssign};
11
12use zcash_script::{opcode::Evaluable as _, pattern::push_num};
13use zcash_transparent::{address::TransparentAddress, bundle::TxOut};
14
15use crate::{
16    amount::{Amount, NonNegative},
17    block,
18    parameters::Network,
19    serialization::ZcashSerialize,
20    transaction,
21    transparent::serialize::GENESIS_COINBASE_SCRIPT_SIG,
22};
23
24pub use address::Address;
25pub use script::Script;
26pub use utxo::{
27    new_ordered_outputs, new_outputs, outputs_from_utxos, utxos_from_ordered_utxos,
28    CoinbaseSpendRestriction, OrderedUtxo, Utxo,
29};
30
31#[cfg(any(test, feature = "proptest-impl"))]
32pub use utxo::{
33    new_ordered_outputs_with_height, new_outputs_with_height, new_transaction_ordered_outputs,
34};
35
36#[cfg(any(test, feature = "proptest-impl"))]
37mod arbitrary;
38
39#[cfg(test)]
40mod tests;
41
42#[cfg(any(test, feature = "proptest-impl"))]
43use proptest_derive::Arbitrary;
44
45/// The maturity threshold for transparent coinbase outputs.
46///
47/// "A transaction MUST NOT spend a transparent output of a coinbase transaction
48/// from a block less than 100 blocks prior to the spend. Note that transparent
49/// outputs of coinbase transactions include Founders' Reward outputs and
50/// transparent Funding Stream outputs."
51/// [7.1](https://zips.z.cash/protocol/nu5.pdf#txnencodingandconsensus)
52//
53// TODO: change type to HeightDiff
54pub const MIN_TRANSPARENT_COINBASE_MATURITY: u32 = 100;
55
56/// The rate used to calculate the dust threshold, in zatoshis per 1000 bytes.
57///
58/// History: <https://github.com/zcash/zcash/blob/v6.10.0/src/policy/policy.h#L43-L89>
59pub const ONE_THIRD_DUST_THRESHOLD_RATE: u32 = 100;
60
61/// OutPoint
62///
63/// A particular transaction output reference.
64#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
65#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
66#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
67pub struct OutPoint {
68    /// References the transaction that contains the UTXO being spent.
69    ///
70    /// # Correctness
71    ///
72    /// Consensus-critical serialization uses [`ZcashSerialize`].
73    /// [`serde`]-based hex serialization must only be used for testing.
74    #[cfg_attr(any(test, feature = "proptest-impl"), serde(with = "hex"))]
75    pub hash: transaction::Hash,
76
77    /// Identifies which UTXO from that transaction is referenced; the
78    /// first output is 0, etc.
79    // TODO: Use OutputIndex here
80    pub index: u32,
81}
82
83impl OutPoint {
84    /// Returns a new [`OutPoint`] from an in-memory output `index`.
85    ///
86    /// # Panics
87    ///
88    /// If `index` doesn't fit in a [`u32`].
89    pub fn from_usize(hash: transaction::Hash, index: usize) -> OutPoint {
90        OutPoint {
91            hash,
92            index: index
93                .try_into()
94                .expect("valid in-memory output indexes fit in a u32"),
95        }
96    }
97}
98
99/// A transparent input to a transaction.
100#[derive(Clone, Debug, Eq, PartialEq)]
101#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
102pub enum Input {
103    /// A reference to an output of a previous transaction.
104    PrevOut {
105        /// The previous output transaction reference.
106        outpoint: OutPoint,
107        /// The script that authorizes spending `outpoint`.
108        unlock_script: Script,
109        /// The sequence number for the output.
110        sequence: u32,
111    },
112    /// New coins created by the block reward.
113    Coinbase {
114        /// The height of this block.
115        height: block::Height,
116        /// Optional, arbitrary data miners can insert into a coinbase tx.
117        /// Limited to ~ 94 bytes.
118        data: Vec<u8>,
119        /// The sequence number for the output.
120        sequence: u32,
121    },
122}
123
124impl fmt::Display for Input {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Input::PrevOut {
128                outpoint,
129                unlock_script,
130                ..
131            } => {
132                let mut fmter = f.debug_struct("transparent::Input::PrevOut");
133
134                fmter.field("unlock_script_len", &unlock_script.as_raw_bytes().len());
135                fmter.field("outpoint", outpoint);
136
137                fmter.finish()
138            }
139            Input::Coinbase { height, data, .. } => {
140                let mut fmter = f.debug_struct("transparent::Input::Coinbase");
141
142                fmter.field("height", height);
143                fmter.field("data_len", &data.len());
144
145                fmter.finish()
146            }
147        }
148    }
149}
150
151impl Input {
152    /// Returns the miner data in this input, if it is an [`Input::Coinbase`].
153    pub fn miner_data(&self) -> Option<&Vec<u8>> {
154        match self {
155            Input::Coinbase { data, .. } => Some(data),
156            _ => None,
157        }
158    }
159
160    /// Returns the full coinbase script (the encoded height along with the optional miner data) if
161    /// this is an [`Input::Coinbase`]. Also returns `None` if the coinbase is for the genesis block
162    /// but does not match the expected genesis coinbase data.
163    pub fn coinbase_script(&self) -> Option<Vec<u8>> {
164        match self {
165            Input::PrevOut { .. } => None,
166            Input::Coinbase { height, data, .. } => {
167                if height.is_min() {
168                    (data.as_slice() == GENESIS_COINBASE_SCRIPT_SIG)
169                        .then_some(GENESIS_COINBASE_SCRIPT_SIG.to_vec())
170                } else {
171                    let mut script = push_num(height.into()).to_bytes();
172                    script.extend_from_slice(data);
173
174                    Some(script)
175                }
176            }
177        }
178    }
179
180    /// Returns the input's sequence number.
181    pub fn sequence(&self) -> u32 {
182        match self {
183            Input::PrevOut { sequence, .. } | Input::Coinbase { sequence, .. } => *sequence,
184        }
185    }
186
187    /// Sets the input's sequence number.
188    ///
189    /// Only for use in tests.
190    #[cfg(any(test, feature = "proptest-impl"))]
191    pub fn set_sequence(&mut self, new_sequence: u32) {
192        match self {
193            Input::PrevOut { sequence, .. } | Input::Coinbase { sequence, .. } => {
194                *sequence = new_sequence
195            }
196        }
197    }
198
199    /// If this is a [`Input::PrevOut`] input, returns this input's
200    /// [`OutPoint`]. Otherwise, returns `None`.
201    pub fn outpoint(&self) -> Option<OutPoint> {
202        if let Input::PrevOut { outpoint, .. } = self {
203            Some(*outpoint)
204        } else {
205            None
206        }
207    }
208
209    /// Set this input's [`OutPoint`].
210    ///
211    /// Should only be called on [`Input::PrevOut`] inputs.
212    ///
213    /// # Panics
214    ///
215    /// If `self` is a coinbase input.
216    #[cfg(any(test, feature = "proptest-impl"))]
217    pub fn set_outpoint(&mut self, new_outpoint: OutPoint) {
218        if let Input::PrevOut {
219            ref mut outpoint, ..
220        } = self
221        {
222            *outpoint = new_outpoint;
223        } else {
224            unreachable!("unexpected variant: Coinbase Inputs do not have OutPoints");
225        }
226    }
227
228    /// Get the value spent by this input, by looking up its [`OutPoint`] in `outputs`.
229    /// See [`Self::value`] for details.
230    ///
231    /// # Panics
232    ///
233    /// If the provided [`Output`]s don't have this input's [`OutPoint`].
234    pub(crate) fn value_from_outputs(
235        &self,
236        outputs: &HashMap<OutPoint, Output>,
237    ) -> Amount<NonNegative> {
238        match self {
239            Input::PrevOut { outpoint, .. } => {
240                outputs
241                    .get(outpoint)
242                    .unwrap_or_else(|| {
243                        panic!(
244                            "provided Outputs (length {:?}) don't have spent {:?}",
245                            outputs.len(),
246                            outpoint
247                        )
248                    })
249                    .value
250            }
251            Input::Coinbase { .. } => Amount::zero(),
252        }
253    }
254
255    /// Get the value spent by this input, looking up its [`OutPoint`] in plain or ordered UTXOs.
256    ///
257    /// This amount is added to the transaction value pool by this input.
258    ///
259    /// # Panics
260    ///
261    /// If the provided [`Utxo`]s don't have this input's [`OutPoint`].
262    pub fn value<U: AsRef<Utxo>>(&self, utxos: &HashMap<OutPoint, U>) -> Amount<NonNegative> {
263        self.outpoint().map_or(Amount::zero(), |outpoint| {
264            utxos
265                .get(&outpoint)
266                .unwrap_or_else(|| panic!("provided Utxos don't have spent {outpoint:?}"))
267                .as_ref()
268                .output
269                .value()
270        })
271    }
272}
273
274/// A transparent output from a transaction.
275///
276/// The most fundamental building block of a transaction is a
277/// transaction output -- the ZEC you own in your "wallet" is in
278/// fact a subset of unspent transaction outputs (or "UTXO"s) of the
279/// global UTXO set.
280///
281/// UTXOs are indivisible, discrete units of value which can only be
282/// consumed in their entirety. Thus, if I want to send you 1 ZEC and
283/// I only own one UTXO worth 2 ZEC, I would construct a transaction
284/// that spends my UTXO and sends 1 ZEC to you and 1 ZEC back to me
285/// (just like receiving change).
286#[derive(Clone, Debug, Eq, PartialEq, Hash)]
287#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary, Deserialize))]
288#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
289pub struct Output {
290    /// Transaction value.
291    // At https://en.bitcoin.it/wiki/Protocol_documentation#tx, this is an i64.
292    pub value: Amount<NonNegative>,
293
294    /// The lock script defines the conditions under which this output can be spent.
295    pub lock_script: Script,
296}
297
298impl Output {
299    /// Returns a new [`Output`].
300    pub fn new(amount: Amount<NonNegative>, lock_script: Script) -> Output {
301        Output {
302            value: amount,
303            lock_script,
304        }
305    }
306
307    /// Get the value contained in this output.
308    /// This amount is subtracted from the transaction value pool by this output.
309    pub fn value(&self) -> Amount<NonNegative> {
310        self.value
311    }
312
313    /// Return the destination address from a transparent output.
314    ///
315    /// Returns None if the address type is not valid or unrecognized.
316    pub fn address(&self, net: &Network) -> Option<Address> {
317        match TxOut::try_from(self).ok()?.recipient_address()? {
318            TransparentAddress::PublicKeyHash(pkh) => {
319                Some(Address::from_pub_key_hash(net.t_addr_kind(), pkh))
320            }
321            TransparentAddress::ScriptHash(sh) => {
322                Some(Address::from_script_hash(net.t_addr_kind(), sh))
323            }
324        }
325    }
326
327    /// Returns true if this output is considered dust.
328    pub fn is_dust(&self) -> bool {
329        let output_size: u32 = self
330            .zcash_serialized_size()
331            .try_into()
332            .expect("output size should fit in u32");
333
334        // https://github.com/zcash/zcash/blob/v6.10.0/src/primitives/transaction.cpp#L75-L80
335        let threshold = 3 * (ONE_THIRD_DUST_THRESHOLD_RATE * (output_size + 148) / 1000);
336
337        // https://github.com/zcash/zcash/blob/v6.10.0/src/primitives/transaction.h#L396-L399
338        self.value.zatoshis() < threshold as i64
339    }
340}
341
342/// A transparent output's index in its transaction.
343#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
344pub struct OutputIndex(u32);
345
346impl OutputIndex {
347    /// Create a transparent output index from the Zcash consensus integer type.
348    ///
349    /// `u32` is also the inner type.
350    pub const fn from_index(output_index: u32) -> OutputIndex {
351        OutputIndex(output_index)
352    }
353
354    /// Returns this index as the inner type.
355    pub const fn index(&self) -> u32 {
356        self.0
357    }
358
359    /// Create a transparent output index from `usize`.
360    #[allow(dead_code)]
361    pub fn from_usize(output_index: usize) -> OutputIndex {
362        OutputIndex(
363            output_index
364                .try_into()
365                .expect("the maximum valid index fits in the inner type"),
366        )
367    }
368
369    /// Return this index as `usize`.
370    #[allow(dead_code)]
371    pub fn as_usize(&self) -> usize {
372        self.0
373            .try_into()
374            .expect("the maximum valid index fits in usize")
375    }
376
377    /// Create a transparent output index from `u64`.
378    #[allow(dead_code)]
379    pub fn from_u64(output_index: u64) -> OutputIndex {
380        OutputIndex(
381            output_index
382                .try_into()
383                .expect("the maximum u64 index fits in the inner type"),
384        )
385    }
386
387    /// Return this index as `u64`.
388    #[allow(dead_code)]
389    pub fn as_u64(&self) -> u64 {
390        self.0.into()
391    }
392}
393
394impl AddAssign<u32> for OutputIndex {
395    fn add_assign(&mut self, rhs: u32) {
396        self.0 += rhs
397    }
398}