valar-pczt 0.5.1

Valar Group fork of pczt with shielded-voting getters, maintained until the getters are upstreamed to zcash/librustzcash.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! The transparent fields of a PCZT.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::Ordering;

use crate::{
    common::{Global, Zip32Derivation},
    roles::combiner::{merge_map, merge_optional},
};

use getset::Getters;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

#[cfg(feature = "transparent")]
use zcash_script::script::Evaluable;

/// PCZT fields that are specific to producing the transaction's transparent bundle (if
/// any).
#[derive(Clone, Debug, Serialize, Deserialize, Getters)]
pub struct Bundle {
    #[getset(get = "pub")]
    pub(crate) inputs: Vec<Input>,
    #[getset(get = "pub")]
    pub(crate) outputs: Vec<Output>,
}

/// Information about a transparent input within a transaction.
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, Getters)]
pub struct Input {
    //
    // Transparent effecting data.
    //
    // These are required fields that are part of the final transaction, and are filled in
    // by the Constructor when adding an output.
    //
    #[getset(get = "pub")]
    pub(crate) prevout_txid: [u8; 32],
    #[getset(get = "pub")]
    pub(crate) prevout_index: u32,

    /// The sequence number of this input.
    ///
    /// - This is set by the Constructor.
    /// - If omitted, the sequence number is assumed to be the final sequence number
    ///   (`0xffffffff`).
    #[getset(get = "pub")]
    pub(crate) sequence: Option<u32>,

    /// The minimum Unix timstamp that this input requires to be set as the transaction's
    /// lock time.
    ///
    /// - This is set by the Constructor.
    /// - This must be greater than or equal to 500000000.
    pub(crate) required_time_lock_time: Option<u32>,

    /// The minimum block height that this input requires to be set as the transaction's
    /// lock time.
    ///
    /// - This is set by the Constructor.
    /// - This must be greater than 0 and less than 500000000.
    pub(crate) required_height_lock_time: Option<u32>,

    /// A satisfying witness for the `script_pubkey` of the input being spent.
    ///
    /// This is set by the Spend Finalizer.
    pub(crate) script_sig: Option<Vec<u8>>,

    // These are required by the Transaction Extractor, to derive the shielded sighash
    // needed for computing the binding signatures.
    #[getset(get = "pub")]
    pub(crate) value: u64,
    #[getset(get = "pub")]
    pub(crate) script_pubkey: Vec<u8>,

    /// The script required to spend this output, if it is P2SH.
    ///
    /// Set to `None` if this is a P2PKH output.
    pub(crate) redeem_script: Option<Vec<u8>>,

    /// A map from a pubkey to a signature created by it.
    ///
    /// - Each pubkey should appear in `script_pubkey` or `redeem_script`.
    /// - Each entry is set by a Signer, and should contain an ECDSA signature that is
    ///   valid under the corresponding pubkey.
    /// - These are required by the Spend Finalizer to assemble `script_sig`.
    #[serde_as(as = "BTreeMap<[_; 33], _>")]
    pub(crate) partial_signatures: BTreeMap<[u8; 33], Vec<u8>>,

    /// The sighash type to be used for this input.
    ///
    /// - Signers must use this sighash type to produce their signatures. Signers that
    ///   cannot produce signatures for this sighash type must not provide a signature.
    /// - Spend Finalizers must fail to finalize inputs which have signatures not matching
    ///   this sighash type.
    pub(crate) sighash_type: u8,

    /// A map from a pubkey to the BIP 32 derivation path at which its corresponding
    /// spending key can be found.
    ///
    /// - The pubkeys should appear in `script_pubkey` or `redeem_script`.
    /// - Each entry is set by an Updater.
    /// - Individual entries may be required by a Signer.
    /// - It is not required that the map include entries for all of the used pubkeys.
    ///   In particular, it is not possible to include entries for non-BIP-32 pubkeys.
    #[serde_as(as = "BTreeMap<[_; 33], _>")]
    pub(crate) bip32_derivation: BTreeMap<[u8; 33], Zip32Derivation>,

    /// Mappings of the form `key = RIPEMD160(value)`.
    ///
    /// - These may be used by the Signer to inspect parts of `script_pubkey` or
    ///   `redeem_script`.
    pub(crate) ripemd160_preimages: BTreeMap<[u8; 20], Vec<u8>>,

    /// Mappings of the form `key = SHA256(value)`.
    ///
    /// - These may be used by the Signer to inspect parts of `script_pubkey` or
    ///   `redeem_script`.
    pub(crate) sha256_preimages: BTreeMap<[u8; 32], Vec<u8>>,

    /// Mappings of the form `key = RIPEMD160(SHA256(value))`.
    ///
    /// - These may be used by the Signer to inspect parts of `script_pubkey` or
    ///   `redeem_script`.
    pub(crate) hash160_preimages: BTreeMap<[u8; 20], Vec<u8>>,

    /// Mappings of the form `key = SHA256(SHA256(value))`.
    ///
    /// - These may be used by the Signer to inspect parts of `script_pubkey` or
    ///   `redeem_script`.
    pub(crate) hash256_preimages: BTreeMap<[u8; 32], Vec<u8>>,

    /// Proprietary fields related to the note being spent.
    #[getset(get = "pub")]
    pub(crate) proprietary: BTreeMap<String, Vec<u8>>,
}

/// Information about a transparent output within a transaction.
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, Getters)]
pub struct Output {
    //
    // Transparent effecting data.
    //
    // These are required fields that are part of the final transaction, and are filled in
    // by the Constructor when adding an output.
    //
    #[getset(get = "pub")]
    pub(crate) value: u64,
    #[getset(get = "pub")]
    pub(crate) script_pubkey: Vec<u8>,

    /// The script required to spend this output, if it is P2SH.
    ///
    /// Set to `None` if this is a P2PKH output.
    pub(crate) redeem_script: Option<Vec<u8>>,

    /// A map from a pubkey to the BIP 32 derivation path at which its corresponding
    /// spending key can be found.
    ///
    /// - The pubkeys should appear in `script_pubkey` or `redeem_script`.
    /// - Each entry is set by an Updater.
    /// - Individual entries may be required by a Signer.
    /// - It is not required that the map include entries for all of the used pubkeys.
    ///   In particular, it is not possible to include entries for non-BIP-32 pubkeys.
    #[serde_as(as = "BTreeMap<[_; 33], _>")]
    pub(crate) bip32_derivation: BTreeMap<[u8; 33], Zip32Derivation>,

    /// The user-facing address to which this output is being sent, if any.
    ///
    /// - This is set by an Updater.
    /// - Signers must parse this address (if present) and confirm that it contains
    ///   `recipient` (either directly, or e.g. as a receiver within a Unified Address).
    #[getset(get = "pub")]
    pub(crate) user_address: Option<String>,

    /// Proprietary fields related to the note being spent.
    #[getset(get = "pub")]
    pub(crate) proprietary: BTreeMap<String, Vec<u8>>,
}

impl Bundle {
    /// Merges this bundle with another.
    ///
    /// Returns `None` if the bundles have conflicting data.
    pub(crate) fn merge(
        mut self,
        other: Self,
        self_global: &Global,
        other_global: &Global,
    ) -> Option<Self> {
        // Destructure `other` to ensure we handle everything.
        let Self {
            mut inputs,
            mut outputs,
        } = other;

        match (
            self_global.inputs_modifiable(),
            other_global.inputs_modifiable(),
            self.inputs.len().cmp(&inputs.len()),
        ) {
            // Fail if the merge would add inputs to a non-modifiable bundle.
            (false, _, Ordering::Less) | (_, false, Ordering::Greater) => return None,
            // If the other bundle has more inputs than us, move them over; these cannot
            // conflict by construction.
            (true, _, Ordering::Less) => self.inputs.extend(inputs.drain(self.inputs.len()..)),
            // Do nothing otherwise.
            (_, _, Ordering::Equal) | (_, true, Ordering::Greater) => (),
        }

        match (
            self_global.outputs_modifiable(),
            other_global.outputs_modifiable(),
            self.outputs.len().cmp(&outputs.len()),
        ) {
            // Fail if the merge would add outputs to a non-modifiable bundle.
            (false, _, Ordering::Less) | (_, false, Ordering::Greater) => return None,
            // If the other bundle has more outputs than us, move them over; these cannot
            // conflict by construction.
            (true, _, Ordering::Less) => self.outputs.extend(outputs.drain(self.outputs.len()..)),
            // Do nothing otherwise.
            (_, _, Ordering::Equal) | (_, true, Ordering::Greater) => (),
        }

        // Leverage the early-exit behaviour of zip to confirm that the remaining data in
        // the other bundle matches this one.
        for (lhs, rhs) in self.inputs.iter_mut().zip(inputs.into_iter()) {
            // Destructure `rhs` to ensure we handle everything.
            let Input {
                prevout_txid,
                prevout_index,
                sequence,
                required_time_lock_time,
                required_height_lock_time,
                script_sig,
                value,
                script_pubkey,
                redeem_script,
                partial_signatures,
                sighash_type,
                bip32_derivation,
                ripemd160_preimages,
                sha256_preimages,
                hash160_preimages,
                hash256_preimages,
                proprietary,
            } = rhs;

            if lhs.prevout_txid != prevout_txid
                || lhs.prevout_index != prevout_index
                || lhs.value != value
                || lhs.script_pubkey != script_pubkey
                || lhs.sighash_type != sighash_type
            {
                return None;
            }

            if !(merge_optional(&mut lhs.sequence, sequence)
                && merge_optional(&mut lhs.required_time_lock_time, required_time_lock_time)
                && merge_optional(
                    &mut lhs.required_height_lock_time,
                    required_height_lock_time,
                )
                && merge_optional(&mut lhs.script_sig, script_sig)
                && merge_optional(&mut lhs.redeem_script, redeem_script)
                && merge_map(&mut lhs.partial_signatures, partial_signatures)
                && merge_map(&mut lhs.bip32_derivation, bip32_derivation)
                && merge_map(&mut lhs.ripemd160_preimages, ripemd160_preimages)
                && merge_map(&mut lhs.sha256_preimages, sha256_preimages)
                && merge_map(&mut lhs.hash160_preimages, hash160_preimages)
                && merge_map(&mut lhs.hash256_preimages, hash256_preimages)
                && merge_map(&mut lhs.proprietary, proprietary))
            {
                return None;
            }
        }

        for (lhs, rhs) in self.outputs.iter_mut().zip(outputs.into_iter()) {
            // Destructure `rhs` to ensure we handle everything.
            let Output {
                value,
                script_pubkey,
                redeem_script,
                bip32_derivation,
                user_address,
                proprietary,
            } = rhs;

            if lhs.value != value || lhs.script_pubkey != script_pubkey {
                return None;
            }

            if !(merge_optional(&mut lhs.redeem_script, redeem_script)
                && merge_map(&mut lhs.bip32_derivation, bip32_derivation)
                && merge_optional(&mut lhs.user_address, user_address)
                && merge_map(&mut lhs.proprietary, proprietary))
            {
                return None;
            }
        }

        Some(self)
    }
}

#[cfg(feature = "transparent")]
impl Bundle {
    pub(crate) fn into_parsed(
        self,
    ) -> Result<transparent::pczt::Bundle, transparent::pczt::ParseError> {
        let inputs = self
            .inputs
            .into_iter()
            .map(|input| {
                transparent::pczt::Input::parse(
                    input.prevout_txid,
                    input.prevout_index,
                    input.sequence,
                    input.required_time_lock_time,
                    input.required_height_lock_time,
                    input.script_sig,
                    input.value,
                    input.script_pubkey,
                    input.redeem_script,
                    input.partial_signatures,
                    input.sighash_type,
                    input
                        .bip32_derivation
                        .into_iter()
                        .map(|(k, v)| {
                            transparent::pczt::Bip32Derivation::parse(
                                v.seed_fingerprint,
                                v.derivation_path,
                            )
                            .map(|v| (k, v))
                        })
                        .collect::<Result<_, _>>()?,
                    input.ripemd160_preimages,
                    input.sha256_preimages,
                    input.hash160_preimages,
                    input.hash256_preimages,
                    input.proprietary,
                )
            })
            .collect::<Result<_, _>>()?;

        let outputs = self
            .outputs
            .into_iter()
            .map(|output| {
                transparent::pczt::Output::parse(
                    output.value,
                    output.script_pubkey,
                    output.redeem_script,
                    output
                        .bip32_derivation
                        .into_iter()
                        .map(|(k, v)| {
                            transparent::pczt::Bip32Derivation::parse(
                                v.seed_fingerprint,
                                v.derivation_path,
                            )
                            .map(|v| (k, v))
                        })
                        .collect::<Result<_, _>>()?,
                    output.user_address,
                    output.proprietary,
                )
            })
            .collect::<Result<_, _>>()?;

        transparent::pczt::Bundle::parse(inputs, outputs)
    }

    pub(crate) fn serialize_from(bundle: transparent::pczt::Bundle) -> Self {
        let inputs = bundle
            .inputs()
            .iter()
            .map(|input| Input {
                prevout_txid: (*input.prevout_txid()).into(),
                prevout_index: *input.prevout_index(),
                sequence: *input.sequence(),
                required_time_lock_time: *input.required_time_lock_time(),
                required_height_lock_time: *input.required_height_lock_time(),
                script_sig: input
                    .script_sig()
                    .as_ref()
                    .map(|script_sig| script_sig.to_bytes()),
                value: input.value().into_u64(),
                script_pubkey: input.script_pubkey().to_bytes(),
                redeem_script: input
                    .redeem_script()
                    .as_ref()
                    .map(|redeem_script| redeem_script.to_bytes()),
                partial_signatures: input.partial_signatures().clone(),
                sighash_type: input.sighash_type().encode(),
                bip32_derivation: input
                    .bip32_derivation()
                    .iter()
                    .map(|(k, v)| {
                        (
                            *k,
                            Zip32Derivation {
                                seed_fingerprint: *v.seed_fingerprint(),
                                derivation_path: v
                                    .derivation_path()
                                    .iter()
                                    .copied()
                                    .map(u32::from)
                                    .collect(),
                            },
                        )
                    })
                    .collect(),
                ripemd160_preimages: input.ripemd160_preimages().clone(),
                sha256_preimages: input.sha256_preimages().clone(),
                hash160_preimages: input.hash160_preimages().clone(),
                hash256_preimages: input.hash256_preimages().clone(),
                proprietary: input.proprietary().clone(),
            })
            .collect();

        let outputs = bundle
            .outputs()
            .iter()
            .map(|output| Output {
                value: output.value().into_u64(),
                script_pubkey: output.script_pubkey().to_bytes(),
                redeem_script: output
                    .redeem_script()
                    .as_ref()
                    .map(|redeem_script| redeem_script.to_bytes()),
                bip32_derivation: output
                    .bip32_derivation()
                    .iter()
                    .map(|(k, v)| {
                        (
                            *k,
                            Zip32Derivation {
                                seed_fingerprint: *v.seed_fingerprint(),
                                derivation_path: v
                                    .derivation_path()
                                    .iter()
                                    .copied()
                                    .map(u32::from)
                                    .collect(),
                            },
                        )
                    })
                    .collect(),
                user_address: output.user_address().clone(),
                proprietary: output.proprietary().clone(),
            })
            .collect();

        Self { inputs, outputs }
    }
}