Skip to main content

pczt/roles/low_level_signer/
mod.rs

1//! A low-level variant of the Signer role, for dependency-constrained environments.
2
3use crate::Pczt;
4
5pub struct Signer {
6    pczt: Pczt,
7}
8
9impl Signer {
10    /// Instantiates the low-level Signer role with the given PCZT.
11    pub fn new(pczt: Pczt) -> Self {
12        Self { pczt }
13    }
14
15    /// Exposes the capability to sign the Ironwood spends.
16    ///
17    /// The bundle is parsed with a preverified signing parse that skips deriving each
18    /// spend's `FullViewingKey` (an expensive step the spend authorization signature
19    /// does not depend on). Callers that rely on the wire `fvk` bytes MUST have
20    /// already run the full Verifier checks over the identical PCZT bytes: they are
21    /// not validated here, and the signing closure sees each spend's `fvk` as `None`.
22    ///
23    /// The signing closure must not add, remove, or reorder actions. A well-behaved
24    /// closure leaves the returned PCZT's wire `fvk` bytes unchanged; a violating one
25    /// is detected and returns [`OrchardParseError::SigningClosureModifiedActions`],
26    /// leaving the PCZT unmodified.
27    #[cfg(feature = "orchard")]
28    pub fn sign_ironwood_with<E, F>(self, f: F) -> Result<Self, E>
29    where
30        E: From<OrchardParseError>,
31        F: FnOnce(&Pczt, &mut orchard::pczt::Bundle, &mut u8) -> Result<(), E>,
32    {
33        let mut pczt = self.pczt;
34
35        let mut tx_modifiable = pczt.global.tx_modifiable;
36        let anchor_requirement =
37            crate::common::AnchorRequirement::for_pre_authorization(pczt.global.tx_version);
38
39        let fvk_snapshot = snapshot_spend_fvks(&pczt.ironwood);
40        let mut parsed = pczt
41            .ironwood
42            .clone()
43            .into_ironwood_parsed_preverified_for_signing(anchor_requirement)
44            .map_err(OrchardParseError::Parse)?;
45
46        f(&pczt, &mut parsed.bundle, &mut tx_modifiable)?;
47
48        pczt.global.tx_modifiable = tx_modifiable;
49        pczt.ironwood = parsed.reserialize();
50        restore_spend_fvks(&mut pczt.ironwood, &fvk_snapshot).map_err(E::from)?;
51
52        Ok(Self { pczt })
53    }
54
55    /// Exposes the capability to sign the Orchard spends.
56    ///
57    /// The bundle is parsed with a preverified signing parse that skips deriving each
58    /// spend's `FullViewingKey` (an expensive step the spend authorization signature
59    /// does not depend on). Callers that rely on the wire `fvk` bytes MUST have
60    /// already run the full Verifier checks over the identical PCZT bytes: they are
61    /// not validated here, and the signing closure sees each spend's `fvk` as `None`.
62    ///
63    /// The signing closure must not add, remove, or reorder actions. A well-behaved
64    /// closure leaves the returned PCZT's wire `fvk` bytes unchanged; a violating one
65    /// is detected and returns [`OrchardParseError::SigningClosureModifiedActions`],
66    /// leaving the PCZT unmodified.
67    #[cfg(feature = "orchard")]
68    pub fn sign_orchard_with<E, F>(self, f: F) -> Result<Self, E>
69    where
70        E: From<OrchardParseError>,
71        F: FnOnce(&Pczt, &mut orchard::pczt::Bundle, &mut u8) -> Result<(), E>,
72    {
73        let mut pczt = self.pczt;
74
75        let mut tx_modifiable = pczt.global.tx_modifiable;
76        let anchor_requirement =
77            crate::common::AnchorRequirement::for_pre_authorization(pczt.global.tx_version);
78
79        let bundle_version = crate::orchard::orchard_bundle_version(&pczt.global)
80            .ok_or(OrchardParseError::UnsupportedConsensusBranchId)?;
81        let fvk_snapshot = snapshot_spend_fvks(&pczt.orchard);
82        let mut parsed = pczt
83            .orchard
84            .clone()
85            .into_parsed_with_version_preverified_for_signing(bundle_version, anchor_requirement)
86            .map_err(OrchardParseError::Parse)?;
87
88        f(&pczt, &mut parsed.bundle, &mut tx_modifiable)?;
89
90        pczt.global.tx_modifiable = tx_modifiable;
91        pczt.orchard = parsed.reserialize();
92        restore_spend_fvks(&mut pczt.orchard, &fvk_snapshot).map_err(E::from)?;
93
94        Ok(Self { pczt })
95    }
96
97    /// Exposes the capability to sign the Sapling spends.
98    #[cfg(feature = "sapling")]
99    pub fn sign_sapling_with<E, F>(self, f: F) -> Result<Self, E>
100    where
101        E: From<crate::sapling::ParseError>,
102        F: FnOnce(&Pczt, &mut sapling::pczt::Bundle, &mut u8) -> Result<(), E>,
103    {
104        let mut pczt = self.pczt;
105
106        let mut tx_modifiable = pczt.global.tx_modifiable;
107        let anchor_requirement =
108            crate::common::AnchorRequirement::for_pre_authorization(pczt.global.tx_version);
109
110        let mut parsed = pczt.sapling.clone().into_parsed(anchor_requirement)?;
111
112        f(&pczt, &mut parsed.bundle, &mut tx_modifiable)?;
113
114        pczt.global.tx_modifiable = tx_modifiable;
115        pczt.sapling = parsed.reserialize();
116
117        Ok(Self { pczt })
118    }
119
120    /// Exposes the capability to sign the transparent spends.
121    #[cfg(feature = "transparent")]
122    pub fn sign_transparent_with<E, F>(self, f: F) -> Result<Self, E>
123    where
124        E: From<transparent::pczt::ParseError>,
125        F: FnOnce(
126            &Pczt,
127            &mut transparent::pczt::Bundle<zcash_protocol::value::Zatoshis>,
128            &mut u8,
129        ) -> Result<(), E>,
130    {
131        let mut pczt = self.pczt;
132
133        let mut tx_modifiable = pczt.global.tx_modifiable;
134
135        let mut bundle = pczt.transparent.clone().into_parsed()?;
136
137        f(&pczt, &mut bundle, &mut tx_modifiable)?;
138
139        pczt.global.tx_modifiable = tx_modifiable;
140        pczt.transparent = crate::transparent::Bundle::serialize_from(bundle);
141
142        Ok(Self { pczt })
143    }
144
145    /// Finishes the low-level Signer role, returning the updated PCZT.
146    pub fn finish(self) -> Pczt {
147        self.pczt
148    }
149}
150
151/// A by-position snapshot of each spend's wire `(rk, fvk)` bytes: the `fvk` that the
152/// preverified signing parse drops and must restore, paired with the `rk` used as a
153/// per-position tamper check. See [`restore_spend_fvks`].
154#[cfg(feature = "orchard")]
155type SpendFvkSnapshot = alloc::vec::Vec<([u8; 32], Option<[u8; 96]>)>;
156
157/// Snapshots each action's spend `(rk, fvk)` wire bytes, by position, for
158/// [`restore_spend_fvks`] to restore after serialization.
159#[cfg(feature = "orchard")]
160fn snapshot_spend_fvks(bundle: &crate::orchard::Bundle) -> SpendFvkSnapshot {
161    bundle
162        .actions()
163        .iter()
164        .map(|action| (action.spend.rk, action.spend.fvk))
165        .collect()
166}
167
168/// Restores the wire `fvk` bytes from [`snapshot_spend_fvks`] into each spend by
169/// position, after checking the signing closure did not resize or reorder the action
170/// list.
171///
172/// Positional restore is only sound if each position still holds its original action,
173/// so this checks the action count and each position's wire `rk` — the one
174/// always-present spend field that pins an action's identity, since a nullifier can
175/// be shared — against the snapshot before writing any `fvk`. On a mismatch it writes
176/// nothing and returns [`OrchardParseError::SigningClosureModifiedActions`].
177#[cfg(feature = "orchard")]
178fn restore_spend_fvks(
179    bundle: &mut crate::orchard::Bundle,
180    snapshot: &SpendFvkSnapshot,
181) -> Result<(), OrchardParseError> {
182    // Reject a resized or reordered list before writing: a count change misaligns
183    // every later `fvk`, and a reorder moves `rk`s off their snapshotted positions.
184    if bundle.actions.len() != snapshot.len() {
185        return Err(OrchardParseError::SigningClosureModifiedActions);
186    }
187    for (action, (rk, _)) in bundle.actions.iter().zip(snapshot) {
188        if action.spend.rk != *rk {
189            return Err(OrchardParseError::SigningClosureModifiedActions);
190        }
191    }
192    for (action, (_, fvk)) in bundle.actions.iter_mut().zip(snapshot) {
193        action.spend.fvk = *fvk;
194    }
195    Ok(())
196}
197
198/// Errors that can occur while parsing an Orchard-protocol bundle of a PCZT for
199/// signing.
200#[cfg(feature = "orchard")]
201#[derive(Debug)]
202pub enum OrchardParseError {
203    /// The bundle data was structurally invalid.
204    Parse(crate::orchard::ParseError),
205    /// The PCZT's consensus branch ID is unrecognized, or predates NU5 (under which
206    /// the Orchard protocol is not supported).
207    UnsupportedConsensusBranchId,
208    /// A signing closure passed to [`Signer::sign_orchard_with`] or
209    /// [`Signer::sign_ironwood_with`] added, removed, or reordered actions, which
210    /// those methods forbid. The PCZT is left unmodified.
211    SigningClosureModifiedActions,
212}
213
214#[cfg(feature = "orchard")]
215impl From<crate::orchard::ParseError> for OrchardParseError {
216    fn from(e: crate::orchard::ParseError) -> Self {
217        OrchardParseError::Parse(e)
218    }
219}
220
221#[cfg(all(test, feature = "orchard"))]
222mod tests {
223    use alloc::collections::BTreeMap;
224    use alloc::string::String;
225    use alloc::vec::Vec;
226
227    use crate::orchard::{Action, Bundle, EncCiphertext, NoteVersion, Output, Spend};
228
229    use super::{OrchardParseError, restore_spend_fvks, snapshot_spend_fvks};
230
231    #[test]
232    fn restore_spend_fvks_preserves_duplicate_nullifiers_by_position() {
233        let first_fvk = Some([7u8; 96]);
234        let second_fvk = Some([9u8; 96]);
235        // Shared nullifier, distinct `rk`s: proves the restore keys on position, not
236        // the (here ambiguous) nullifier.
237        let mut bundle = bundle_with_duplicate_nullifier_fvks([first_fvk, second_fvk]);
238        let snapshot = snapshot_spend_fvks(&bundle);
239
240        bundle.actions[0].spend.fvk = None;
241        bundle.actions[1].spend.fvk = None;
242
243        restore_spend_fvks(&mut bundle, &snapshot).expect("actions were not modified");
244
245        assert_eq!(bundle.actions[0].spend.fvk, first_fvk);
246        assert_eq!(bundle.actions[1].spend.fvk, second_fvk);
247    }
248
249    #[test]
250    fn restore_spend_fvks_rejects_reordered_actions() {
251        let first_fvk = Some([7u8; 96]);
252        let second_fvk = Some([9u8; 96]);
253        let mut bundle = bundle_with_duplicate_nullifier_fvks([first_fvk, second_fvk]);
254        let snapshot = snapshot_spend_fvks(&bundle);
255
256        // A signing closure swaps the two actions; their distinct wire `rk`s move too.
257        bundle.actions.swap(0, 1);
258
259        assert!(matches!(
260            restore_spend_fvks(&mut bundle, &snapshot),
261            Err(OrchardParseError::SigningClosureModifiedActions)
262        ));
263        // Left as the closure left it: `fvk`s were not restored onto swapped actions.
264        assert_eq!(bundle.actions[0].spend.fvk, second_fvk);
265        assert_eq!(bundle.actions[1].spend.fvk, first_fvk);
266    }
267
268    /// Returns a two-action bundle whose spends share a nullifier but carry
269    /// distinct wire `rk`s and the given distinct `fvk`s.
270    fn bundle_with_duplicate_nullifier_fvks(fvks: [Option<[u8; 96]>; 2]) -> Bundle {
271        Bundle {
272            actions: fvks
273                .into_iter()
274                .enumerate()
275                // Distinct `rk` per action (`[10; 32]`, `[11; 32]`), shared
276                // nullifier `[3; 32]`.
277                .map(|(i, fvk)| Action {
278                    cv_net: Some([0; 32]),
279                    spend: Spend {
280                        nullifier: [3u8; 32],
281                        rk: [10 + i as u8; 32],
282                        spend_auth_sig: None,
283                        recipient: None,
284                        value: None,
285                        rho: None,
286                        rseed: None,
287                        fvk,
288                        witness: None,
289                        alpha: None,
290                        zip32_derivation: None,
291                        dummy_sk: None,
292                        proprietary: BTreeMap::new(),
293                    },
294                    output: Output {
295                        cmx: Some([0; 32]),
296                        ephemeral_key: [0; 32],
297                        enc_ciphertext: EncCiphertext::Encrypted(Vec::new()),
298                        out_ciphertext: Vec::new(),
299                        recipient: None,
300                        value: None,
301                        rseed: None,
302                        ock: None,
303                        zip32_derivation: None,
304                        user_address: Option::<String>::None,
305                        proprietary: BTreeMap::new(),
306                    },
307                    rcv: None,
308                })
309                .collect(),
310            flags: 0,
311            value_sum: (0, false),
312            anchor: Some([0; 32]),
313            note_version: NoteVersion::V2,
314            zkproof: None,
315            bsk: None,
316        }
317    }
318}