Skip to main content

orchard/
lib.rs

1//! # orchard
2//!
3//! ## Nomenclature
4//!
5//! All types in the `orchard` crate, unless otherwise specified, are Orchard-specific
6//! types. For example, [`Address`] is documented as being a shielded payment address; we
7//! implicitly mean it is an Orchard payment address (as opposed to e.g. a Sapling payment
8//! address, which is also shielded).
9
10#![no_std]
11#![cfg_attr(docsrs, feature(doc_cfg))]
12// Temporary until we have more of the crate implemented.
13#![allow(dead_code)]
14// Catch documentation errors caused by code changes.
15#![deny(rustdoc::broken_intra_doc_links)]
16#![deny(missing_debug_implementations)]
17#![deny(missing_docs)]
18#![forbid(unsafe_code)]
19
20#[macro_use]
21extern crate alloc;
22
23#[cfg(feature = "std")]
24extern crate std;
25
26use alloc::vec::Vec;
27
28mod action;
29mod address;
30pub mod builder;
31pub mod bundle;
32#[cfg(feature = "circuit")]
33pub mod circuit;
34#[cfg(not(feature = "unstable-voting-circuits"))]
35mod constants;
36#[cfg(feature = "unstable-voting-circuits")]
37pub mod constants;
38pub mod keys;
39pub mod note;
40pub mod note_encryption;
41pub mod pczt;
42pub mod primitives;
43#[cfg(not(feature = "unstable-voting-circuits"))]
44mod spec;
45#[cfg(feature = "unstable-voting-circuits")]
46pub mod spec;
47pub mod tree;
48pub mod value;
49pub mod zip32;
50
51#[cfg(test)]
52mod test_vectors;
53
54// Proving and verifying keys are immutable and depend only on the circuit
55// version, so tests in this process can share one of each per version.
56#[cfg(all(test, feature = "circuit"))]
57struct CachedTestKeys {
58    circuit_version: circuit::OrchardCircuitVersion,
59    proving_key: std::sync::OnceLock<circuit::ProvingKey>,
60    verifying_key: std::sync::OnceLock<circuit::VerifyingKey>,
61}
62
63#[cfg(all(test, feature = "circuit"))]
64impl CachedTestKeys {
65    const fn new(circuit_version: circuit::OrchardCircuitVersion) -> Self {
66        Self {
67            circuit_version,
68            proving_key: std::sync::OnceLock::new(),
69            verifying_key: std::sync::OnceLock::new(),
70        }
71    }
72
73    fn proving_key(&self) -> &circuit::ProvingKey {
74        self.proving_key
75            .get_or_init(|| circuit::ProvingKey::build(self.circuit_version))
76    }
77
78    fn verifying_key(&self) -> &circuit::VerifyingKey {
79        self.verifying_key
80            .get_or_init(|| circuit::VerifyingKey::build(self.circuit_version))
81    }
82}
83
84#[cfg(all(test, feature = "circuit"))]
85fn cached_test_keys(circuit_version: circuit::OrchardCircuitVersion) -> &'static CachedTestKeys {
86    use circuit::OrchardCircuitVersion;
87
88    static INSECURE: CachedTestKeys = CachedTestKeys::new(OrchardCircuitVersion::InsecurePreNu6_2);
89    static FIXED: CachedTestKeys = CachedTestKeys::new(OrchardCircuitVersion::FixedPostNu6_2);
90    static POST_NU6_3: CachedTestKeys = CachedTestKeys::new(OrchardCircuitVersion::PostNu6_3);
91
92    match circuit_version {
93        OrchardCircuitVersion::InsecurePreNu6_2 => &INSECURE,
94        OrchardCircuitVersion::FixedPostNu6_2 => &FIXED,
95        OrchardCircuitVersion::PostNu6_3 => &POST_NU6_3,
96    }
97}
98
99pub use action::{Action, ActionFromPartsError};
100pub use address::Address;
101pub use bundle::Bundle;
102pub use constants::MERKLE_DEPTH_ORCHARD as NOTE_COMMITMENT_TREE_DEPTH;
103pub use constants::{L_ORCHARD_BASE, L_ORCHARD_SCALAR, L_VALUE};
104pub use note::{Note, NoteVersion};
105pub use tree::Anchor;
106
107/// A proof of the validity of an Orchard [`Bundle`].
108///
109/// [`Bundle`]: crate::bundle::Bundle
110#[derive(Clone)]
111pub struct Proof(Vec<u8>);
112
113impl core::fmt::Debug for Proof {
114    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115        if f.alternate() {
116            f.debug_tuple("Proof").field(&self.0).finish()
117        } else {
118            // By default, only show the proof length, not its contents.
119            f.debug_tuple("Proof")
120                .field(&format_args!("{} bytes", self.0.len()))
121                .finish()
122        }
123    }
124}
125
126impl AsRef<[u8]> for Proof {
127    fn as_ref(&self) -> &[u8] {
128        &self.0
129    }
130}
131
132impl memuse::DynamicUsage for Proof {
133    fn dynamic_usage(&self) -> usize {
134        self.0.dynamic_usage()
135    }
136
137    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
138        self.0.dynamic_usage_bounds()
139    }
140}
141
142impl Proof {
143    /// Constructs a new Proof value.
144    pub fn new(bytes: Vec<u8>) -> Self {
145        Proof(bytes)
146    }
147
148    /// The canonical byte length of a proof authorizing a bundle of `num_actions` actions.
149    ///
150    /// A valid Orchard proof always has exactly this length. The constants are fixed by the
151    /// halo2 action circuit; they are cross-checked against [`halo2_proofs::dev::CircuitCost`]
152    /// in the circuit tests. Use this to reject non-canonical (e.g. padded) proofs when
153    /// constructing a bundle from untrusted bytes; see [`Bundle::try_from_parts`].
154    ///
155    /// [`Bundle::try_from_parts`]: crate::Bundle::try_from_parts
156    pub const fn expected_proof_size(num_actions: usize) -> usize {
157        // The proof is a fixed base size plus a fixed contribution per action. These constants
158        // are determined by the halo2 action circuit; see the `circuit` module's round-trip
159        // tests, which cross-check them against `CircuitCost::proof_size`.
160        const BASE: usize = 2720;
161        const PER_ACTION: usize = 2272;
162        BASE + PER_ACTION * num_actions
163    }
164}
165
166/// The set of value pools supported by the Orchard protocol.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
168pub enum ValuePool {
169    /// The Orchard value pool.
170    Orchard,
171    /// The Ironwood value pool.
172    Ironwood,
173}
174
175/// The versions of the Orchard protocol.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
177pub enum ProtocolVersion {
178    /// The original version of the protocol, used in Zcash prior to NU6.2, only instantiated for
179    /// the Orchard value pool.
180    ///
181    /// Uses the historical unsound Orchard circuit. Cross-address transfers are permitted and
182    /// notes use the V2 plaintext format. Used to reconstruct the historical verifying key and to
183    /// parse/verify historical bundles, not to build new ones.
184    InsecureV1,
185    /// The version of the Orchard protocol used in Zcash for NU6.2, only instantiated for the
186    /// Orchard value pool.
187    ///
188    /// Uses the post-NU6.2 fixed Orchard circuit. Cross-address transfers are permitted and notes
189    /// use the V2 plaintext format.
190    V2,
191    /// The version of the Orchard protocol used in Zcash NU6.3, instantiated for both the Orchard
192    /// and Ironwood value pools.
193    ///
194    /// Uses the post-NU6.3 circuit for both the Orchard and Ironwood value pools.
195    ///
196    /// For transactional bundles affecting the [`ValuePool::Orchard`] value pool,
197    /// `enableCrossAddress = 0` is required by consensus, so cross-address transfers are
198    /// prohibited and Orchard actions are disallowed in coinbase. Notes use V2 plaintexts.
199    ///
200    /// For transactional bundles affecting the [`ValuePool::Ironwood`] value pool, cross-address
201    /// transfers are permitted and notes use V3 plaintexts.
202    V3,
203}