Skip to main content

zcash_primitives/transaction/components/
sprout.rs

1//! Structs representing the components within Zcash transactions.
2
3use alloc::vec::Vec;
4use corez::io::{self, Read, Write};
5
6use super::GROTH_PROOF_SIZE;
7use zcash_protocol::value::ZatBalance;
8
9// π_A + π_A' + π_B + π_B' + π_C + π_C' + π_K + π_H
10const PHGR_PROOF_SIZE: usize = 33 + 33 + 65 + 33 + 33 + 33 + 33 + 33;
11
12const ZC_NUM_JS_INPUTS: usize = 2;
13const ZC_NUM_JS_OUTPUTS: usize = 2;
14
15#[derive(Debug, Clone)]
16pub struct Bundle {
17    pub joinsplits: Vec<JsDescription>,
18    pub joinsplit_pubkey: [u8; 32],
19    pub joinsplit_sig: [u8; 64],
20}
21
22impl Bundle {
23    /// The value balance for the bundle. When this is positive,
24    /// its value is added to the transparent value pool; when it
25    /// is negative, its value is subtracted from the transparent
26    /// value pool.
27    pub fn value_balance(&self) -> Option<ZatBalance> {
28        self.joinsplits
29            .iter()
30            .try_fold(ZatBalance::zero(), |total, js| total + js.net_value())
31    }
32}
33
34#[derive(Clone)]
35#[allow(clippy::upper_case_acronyms)]
36pub(crate) enum SproutProof {
37    Groth([u8; GROTH_PROOF_SIZE]),
38    PHGR([u8; PHGR_PROOF_SIZE]),
39}
40
41impl core::fmt::Debug for SproutProof {
42    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
43        match self {
44            SproutProof::Groth(_) => write!(f, "SproutProof::Groth"),
45            SproutProof::PHGR(_) => write!(f, "SproutProof::PHGR"),
46        }
47    }
48}
49
50#[derive(Clone)]
51pub struct JsDescription {
52    pub(crate) vpub_old: ZatBalance,
53    pub(crate) vpub_new: ZatBalance,
54    pub(crate) anchor: [u8; 32],
55    pub(crate) nullifiers: [[u8; 32]; ZC_NUM_JS_INPUTS],
56    pub(crate) commitments: [[u8; 32]; ZC_NUM_JS_OUTPUTS],
57    pub(crate) ephemeral_key: [u8; 32],
58    pub(crate) random_seed: [u8; 32],
59    pub(crate) macs: [[u8; 32]; ZC_NUM_JS_INPUTS],
60    pub(crate) proof: SproutProof,
61    pub(crate) ciphertexts: [[u8; 601]; ZC_NUM_JS_OUTPUTS],
62}
63
64impl core::fmt::Debug for JsDescription {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
66        write!(
67            f,
68            "JSDescription(
69                vpub_old = {:?}, vpub_new = {:?},
70                anchor = {:?},
71                nullifiers = {:?},
72                commitments = {:?},
73                ephemeral_key = {:?},
74                random_seed = {:?},
75                macs = {:?})",
76            self.vpub_old,
77            self.vpub_new,
78            self.anchor,
79            self.nullifiers,
80            self.commitments,
81            self.ephemeral_key,
82            self.random_seed,
83            self.macs
84        )
85    }
86}
87
88impl JsDescription {
89    pub fn read<R: Read>(mut reader: R, use_groth: bool) -> io::Result<Self> {
90        // Consensus rule (§4.3): Canonical encoding is enforced here
91        let vpub_old = {
92            let mut tmp = [0u8; 8];
93            reader.read_exact(&mut tmp)?;
94            ZatBalance::from_u64_le_bytes(tmp)
95        }
96        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "vpub_old out of range"))?;
97
98        // Consensus rule (§4.3): Canonical encoding is enforced here
99        let vpub_new = {
100            let mut tmp = [0u8; 8];
101            reader.read_exact(&mut tmp)?;
102            ZatBalance::from_u64_le_bytes(tmp)
103        }
104        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "vpub_new out of range"))?;
105
106        // Consensus rule (§4.3): One of vpub_old and vpub_new being zero is
107        // enforced by CheckTransactionWithoutProofVerification() in zcashd.
108
109        let mut anchor = [0u8; 32];
110        reader.read_exact(&mut anchor)?;
111
112        let mut nullifiers = [[0u8; 32]; ZC_NUM_JS_INPUTS];
113        nullifiers
114            .iter_mut()
115            .try_for_each(|nf| reader.read_exact(nf))?;
116
117        let mut commitments = [[0u8; 32]; ZC_NUM_JS_OUTPUTS];
118        commitments
119            .iter_mut()
120            .try_for_each(|cm| reader.read_exact(cm))?;
121
122        // Consensus rule (§4.3): Canonical encoding is enforced by
123        // ZCNoteDecryption::decrypt() in zcashd
124        let mut ephemeral_key = [0u8; 32];
125        reader.read_exact(&mut ephemeral_key)?;
126
127        let mut random_seed = [0u8; 32];
128        reader.read_exact(&mut random_seed)?;
129
130        let mut macs = [[0u8; 32]; ZC_NUM_JS_INPUTS];
131        macs.iter_mut().try_for_each(|mac| reader.read_exact(mac))?;
132
133        let proof = if use_groth {
134            // Consensus rules (§4.3):
135            // - Canonical encoding is enforced in librustzcash_sprout_verify()
136            // - Proof validity is enforced in librustzcash_sprout_verify()
137            let mut proof = [0u8; GROTH_PROOF_SIZE];
138            reader.read_exact(&mut proof)?;
139            SproutProof::Groth(proof)
140        } else {
141            // Consensus rules (§4.3):
142            // - Canonical encoding is enforced by PHGRProof in zcashd
143            // - Proof validity is enforced by JSDescription::Verify() in zcashd
144            let mut proof = [0u8; PHGR_PROOF_SIZE];
145            reader.read_exact(&mut proof)?;
146            SproutProof::PHGR(proof)
147        };
148
149        let mut ciphertexts = [[0u8; 601]; ZC_NUM_JS_OUTPUTS];
150        ciphertexts
151            .iter_mut()
152            .try_for_each(|ct| reader.read_exact(ct))?;
153
154        Ok(JsDescription {
155            vpub_old,
156            vpub_new,
157            anchor,
158            nullifiers,
159            commitments,
160            ephemeral_key,
161            random_seed,
162            macs,
163            proof,
164            ciphertexts,
165        })
166    }
167
168    pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
169        writer.write_all(&self.vpub_old.to_i64_le_bytes())?;
170        writer.write_all(&self.vpub_new.to_i64_le_bytes())?;
171        writer.write_all(&self.anchor)?;
172        writer.write_all(&self.nullifiers[0])?;
173        writer.write_all(&self.nullifiers[1])?;
174        writer.write_all(&self.commitments[0])?;
175        writer.write_all(&self.commitments[1])?;
176        writer.write_all(&self.ephemeral_key)?;
177        writer.write_all(&self.random_seed)?;
178        writer.write_all(&self.macs[0])?;
179        writer.write_all(&self.macs[1])?;
180
181        match &self.proof {
182            SproutProof::Groth(p) => writer.write_all(p)?,
183            SproutProof::PHGR(p) => writer.write_all(p)?,
184        }
185
186        writer.write_all(&self.ciphertexts[0])?;
187        writer.write_all(&self.ciphertexts[1])
188    }
189
190    /// The net value for the JoinSplit. When this is positive,
191    /// its value is added to the transparent value pool; when it
192    /// is negative, its value is subtracted from the transparent
193    /// value pool.
194    pub fn net_value(&self) -> ZatBalance {
195        (self.vpub_new - self.vpub_old).expect("difference is in range [-MAX_MONEY..=MAX_MONEY]")
196    }
197
198    /// Returns the value added to the Sprout pool by this JoinSplit.
199    pub fn vpub_old(&self) -> ZatBalance {
200        self.vpub_old
201    }
202
203    /// Returns the value removed from the Sprout pool by this JoinSplit.
204    pub fn vpub_new(&self) -> ZatBalance {
205        self.vpub_new
206    }
207
208    /// Returns the Sprout note commitment tree anchor for this JoinSplit.
209    pub fn anchor(&self) -> &[u8; 32] {
210        &self.anchor
211    }
212
213    /// Returns the nullifiers for the input notes of this JoinSplit.
214    pub fn nullifiers(&self) -> &[[u8; 32]; ZC_NUM_JS_INPUTS] {
215        &self.nullifiers
216    }
217
218    /// Returns the note commitments for the output notes of this JoinSplit.
219    pub fn commitments(&self) -> &[[u8; 32]; ZC_NUM_JS_OUTPUTS] {
220        &self.commitments
221    }
222
223    /// Returns the random seed for this JoinSplit.
224    pub fn random_seed(&self) -> &[u8; 32] {
225        &self.random_seed
226    }
227
228    /// Returns the message authentication codes for this JoinSplit.
229    pub fn macs(&self) -> &[[u8; 32]; ZC_NUM_JS_INPUTS] {
230        &self.macs
231    }
232
233    /// Returns the Groth16 proof bytes for this JoinSplit, if it uses Groth16.
234    /// Returns `None` for PHGR proofs (pre-Sapling).
235    pub fn groth_proof_bytes(&self) -> Option<&[u8; GROTH_PROOF_SIZE]> {
236        match &self.proof {
237            SproutProof::Groth(bytes) => Some(bytes),
238            SproutProof::PHGR(_) => None,
239        }
240    }
241}