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
//! Sapling _Output descriptions_, as described in [protocol specification §7.4][ps].
//!
//! [ps]: https://zips.z.cash/protocol/protocol.pdf#outputencoding

use std::io;

use crate::{
    block::MAX_BLOCK_BYTES,
    primitives::Groth16Proof,
    serialization::{
        serde_helpers, SerializationError, TrustedPreallocate, ZcashDeserialize, ZcashSerialize,
    },
};

use super::{commitment, keys, note};

/// A _Output Description_, as described in [protocol specification §7.4][ps].
///
/// # Differences between Transaction Versions
///
/// `V4` transactions serialize the fields of spends and outputs together.
/// `V5` transactions split them into multiple arrays.
///
/// [ps]: https://zips.z.cash/protocol/protocol.pdf#outputencoding
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Output {
    /// A value commitment to the value of the input note.
    pub cv: commitment::NotSmallOrderValueCommitment,
    /// The u-coordinate of the note commitment for the output note.
    #[serde(with = "serde_helpers::Fq")]
    pub cm_u: jubjub::Fq,
    /// An encoding of an ephemeral Jubjub public key.
    pub ephemeral_key: keys::EphemeralPublicKey,
    /// A ciphertext component for the encrypted output note.
    pub enc_ciphertext: note::EncryptedNote,
    /// A ciphertext component for the encrypted output note.
    pub out_ciphertext: note::WrappedNoteKey,
    /// The ZK output proof.
    pub zkproof: Groth16Proof,
}

/// Wrapper for `Output` serialization in a `V4` transaction.
///
/// <https://zips.z.cash/protocol/protocol.pdf#outputencoding>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputInTransactionV4(pub Output);

/// The serialization prefix fields of an `Output` in Transaction V5.
///
/// In `V5` transactions, spends are split into multiple arrays, so the prefix
/// and proof must be serialised and deserialized separately.
///
/// Serialized as `OutputDescriptionV5` in [protocol specification §7.3][ps].
///
/// [ps]: https://zips.z.cash/protocol/protocol.pdf#outputencoding
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct OutputPrefixInTransactionV5 {
    /// A value commitment to the value of the input note.
    pub cv: commitment::NotSmallOrderValueCommitment,
    /// The u-coordinate of the note commitment for the output note.
    #[serde(with = "serde_helpers::Fq")]
    pub cm_u: jubjub::Fq,
    /// An encoding of an ephemeral Jubjub public key.
    pub ephemeral_key: keys::EphemeralPublicKey,
    /// A ciphertext component for the encrypted output note.
    pub enc_ciphertext: note::EncryptedNote,
    /// A ciphertext component for the encrypted output note.
    pub out_ciphertext: note::WrappedNoteKey,
}

impl Output {
    /// Remove the V4 transaction wrapper from this output.
    pub fn from_v4(output: OutputInTransactionV4) -> Output {
        output.0
    }

    /// Add a V4 transaction wrapper to this output.
    pub fn into_v4(self) -> OutputInTransactionV4 {
        OutputInTransactionV4(self)
    }

    /// Combine the prefix and non-prefix fields from V5 transaction
    /// deserialization.
    pub fn from_v5_parts(prefix: OutputPrefixInTransactionV5, zkproof: Groth16Proof) -> Output {
        Output {
            cv: prefix.cv,
            cm_u: prefix.cm_u,
            ephemeral_key: prefix.ephemeral_key,
            enc_ciphertext: prefix.enc_ciphertext,
            out_ciphertext: prefix.out_ciphertext,
            zkproof,
        }
    }

    /// Split out the prefix and non-prefix fields for V5 transaction
    /// serialization.
    pub fn into_v5_parts(self) -> (OutputPrefixInTransactionV5, Groth16Proof) {
        let prefix = OutputPrefixInTransactionV5 {
            cv: self.cv,
            cm_u: self.cm_u,
            ephemeral_key: self.ephemeral_key,
            enc_ciphertext: self.enc_ciphertext,
            out_ciphertext: self.out_ciphertext,
        };

        (prefix, self.zkproof)
    }
}

impl OutputInTransactionV4 {
    /// Add V4 transaction wrapper to this output.
    pub fn from_output(output: Output) -> OutputInTransactionV4 {
        OutputInTransactionV4(output)
    }

    /// Remove the V4 transaction wrapper from this output.
    pub fn into_output(self) -> Output {
        self.0
    }
}

impl ZcashSerialize for OutputInTransactionV4 {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        let output = self.0.clone();
        output.cv.zcash_serialize(&mut writer)?;
        writer.write_all(&output.cm_u.to_bytes())?;
        output.ephemeral_key.zcash_serialize(&mut writer)?;
        output.enc_ciphertext.zcash_serialize(&mut writer)?;
        output.out_ciphertext.zcash_serialize(&mut writer)?;
        output.zkproof.zcash_serialize(&mut writer)?;
        Ok(())
    }
}

impl ZcashDeserialize for OutputInTransactionV4 {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        // # Consensus
        //
        // > Elements of an Output description MUST be valid encodings of the types given above.
        //
        // https://zips.z.cash/protocol/protocol.pdf#outputdesc
        //
        // > LEOS2IP_{256}(cmu) MUST be less than 𝑞_J.
        //
        // https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
        //
        // See comments below for each specific type.
        Ok(OutputInTransactionV4(Output {
            // Type is `ValueCommit^{Sapling}.Output`, i.e. J
            // https://zips.z.cash/protocol/protocol.pdf#abstractcommit
            // See [`commitment::NotSmallOrderValueCommitment::zcash_deserialize`].
            cv: commitment::NotSmallOrderValueCommitment::zcash_deserialize(&mut reader)?,
            // Type is `B^{[ℓ_{Sapling}_{Merkle}]}`, i.e. 32 bytes.
            // However, the consensus rule above restricts it even more.
            // See [`jubjub::Fq::zcash_deserialize`].
            cm_u: jubjub::Fq::zcash_deserialize(&mut reader)?,
            // Type is `KA^{Sapling}.Public`, i.e. J
            // https://zips.z.cash/protocol/protocol.pdf#concretesaplingkeyagreement
            // See [`keys::EphemeralPublicKey::zcash_deserialize`].
            ephemeral_key: keys::EphemeralPublicKey::zcash_deserialize(&mut reader)?,
            // Type is `Sym.C`, i.e. `B^Y^{\[N\]}`, i.e. arbitrary-sized byte arrays
            // https://zips.z.cash/protocol/protocol.pdf#concretesym but fixed to
            // 580 bytes in https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
            // See [`note::EncryptedNote::zcash_deserialize`].
            enc_ciphertext: note::EncryptedNote::zcash_deserialize(&mut reader)?,
            // Type is `Sym.C`, i.e. `B^Y^{\[N\]}`, i.e. arbitrary-sized byte arrays.
            // https://zips.z.cash/protocol/protocol.pdf#concretesym but fixed to
            // 80 bytes in https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
            // See [`note::WrappedNoteKey::zcash_deserialize`].
            out_ciphertext: note::WrappedNoteKey::zcash_deserialize(&mut reader)?,
            // Type is `ZKOutput.Proof`, described in
            // https://zips.z.cash/protocol/protocol.pdf#grothencoding
            // It is not enforced here; this just reads 192 bytes.
            // The type is validated when validating the proof, see
            // [`groth16::Item::try_from`]. In #3179 we plan to validate here instead.
            zkproof: Groth16Proof::zcash_deserialize(&mut reader)?,
        }))
    }
}

// In a V5 transaction, zkproof is deserialized separately, so we can only
// deserialize V5 outputs in the context of a V5 transaction.
//
// Instead, implement serialization and deserialization for the
// Output prefix fields, which are stored in the same array.

impl ZcashSerialize for OutputPrefixInTransactionV5 {
    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
        self.cv.zcash_serialize(&mut writer)?;
        writer.write_all(&self.cm_u.to_bytes())?;
        self.ephemeral_key.zcash_serialize(&mut writer)?;
        self.enc_ciphertext.zcash_serialize(&mut writer)?;
        self.out_ciphertext.zcash_serialize(&mut writer)?;
        Ok(())
    }
}

impl ZcashDeserialize for OutputPrefixInTransactionV5 {
    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
        // # Consensus
        //
        // > Elements of an Output description MUST be valid encodings of the types given above.
        //
        // https://zips.z.cash/protocol/protocol.pdf#outputdesc
        //
        // > LEOS2IP_{256}(cmu) MUST be less than 𝑞_J.
        //
        // https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
        //
        // See comments below for each specific type.
        Ok(OutputPrefixInTransactionV5 {
            // Type is `ValueCommit^{Sapling}.Output`, i.e. J
            // https://zips.z.cash/protocol/protocol.pdf#abstractcommit
            // See [`commitment::NotSmallOrderValueCommitment::zcash_deserialize`].
            cv: commitment::NotSmallOrderValueCommitment::zcash_deserialize(&mut reader)?,
            // Type is `B^{[ℓ_{Sapling}_{Merkle}]}`, i.e. 32 bytes.
            // However, the consensus rule above restricts it even more.
            // See [`jubjub::Fq::zcash_deserialize`].
            cm_u: jubjub::Fq::zcash_deserialize(&mut reader)?,
            // Type is `KA^{Sapling}.Public`, i.e. J
            // https://zips.z.cash/protocol/protocol.pdf#concretesaplingkeyagreement
            // See [`keys::EphemeralPublicKey::zcash_deserialize`].
            ephemeral_key: keys::EphemeralPublicKey::zcash_deserialize(&mut reader)?,
            // Type is `Sym.C`, i.e. `B^Y^{\[N\]}`, i.e. arbitrary-sized byte arrays
            // https://zips.z.cash/protocol/protocol.pdf#concretesym but fixed to
            // 580 bytes in https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
            // See [`note::EncryptedNote::zcash_deserialize`].
            enc_ciphertext: note::EncryptedNote::zcash_deserialize(&mut reader)?,
            // Type is `Sym.C`, i.e. `B^Y^{\[N\]}`, i.e. arbitrary-sized byte arrays.
            // https://zips.z.cash/protocol/protocol.pdf#concretesym but fixed to
            // 80 bytes in https://zips.z.cash/protocol/protocol.pdf#outputencodingandconsensus
            // See [`note::WrappedNoteKey::zcash_deserialize`].
            out_ciphertext: note::WrappedNoteKey::zcash_deserialize(&mut reader)?,
        })
    }
}

/// The size of a v5 output, without associated fields.
///
/// This is the size of outputs in the initial array, there is another
/// array of zkproofs required in the transaction format.
pub(crate) const OUTPUT_PREFIX_SIZE: u64 = 32 + 32 + 32 + 580 + 80;
/// An output contains: a 32 byte cv, a 32 byte cmu, a 32 byte ephemeral key
/// a 580 byte encCiphertext, an 80 byte outCiphertext, and a 192 byte zkproof
///
/// [ps]: https://zips.z.cash/protocol/protocol.pdf#outputencoding
pub(crate) const OUTPUT_SIZE: u64 = OUTPUT_PREFIX_SIZE + 192;

/// The maximum number of sapling outputs in a valid Zcash on-chain transaction.
/// This maximum is the same for transaction V4 and V5, even though the fields are
/// serialized in a different order.
///
/// If a transaction contains more outputs than can fit in maximally large block, it might be
/// valid on the network and in the mempool, but it can never be mined into a block. So
/// rejecting these large edge-case transactions can never break consensus
impl TrustedPreallocate for OutputInTransactionV4 {
    fn max_allocation() -> u64 {
        // Since a serialized Vec<Output> uses at least one byte for its length,
        // the max allocation can never exceed (MAX_BLOCK_BYTES - 1) / OUTPUT_SIZE
        const MAX: u64 = (MAX_BLOCK_BYTES - 1) / OUTPUT_SIZE;
        // # Consensus
        //
        // > [NU5 onward] nSpendsSapling, nOutputsSapling, and nActionsOrchard MUST all be less than 2^16.
        //
        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
        //
        // This acts as nOutputsSapling and is therefore subject to the rule.
        // The maximum value is actually smaller due to the block size limit,
        // but we ensure the 2^16 limit with a static assertion.
        // (The check is not required pre-NU5, but it doesn't cause problems.)
        static_assertions::const_assert!(MAX < (1 << 16));
        MAX
    }
}

impl TrustedPreallocate for OutputPrefixInTransactionV5 {
    fn max_allocation() -> u64 {
        // Since V4 and V5 have the same fields,
        // and the V5 associated fields are required,
        // a valid max allocation can never exceed this size
        OutputInTransactionV4::max_allocation()
    }
}