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
//! Abstractions over the proving system and parameters.

use bellman::groth16::{create_random_proof, Proof};
use bls12_381::Bls12;
use rand_core::RngCore;

use crate::{
    bundle::GrothProofBytes,
    circuit::{self, GROTH_PROOF_SIZE},
    value::{NoteValue, ValueCommitTrapdoor},
    MerklePath,
};

use super::{
    circuit::{Output, OutputParameters, Spend, SpendParameters, ValueCommitmentOpening},
    Diversifier, Note, PaymentAddress, ProofGenerationKey, Rseed,
};

/// Interface for creating Sapling Spend proofs.
pub trait SpendProver {
    /// The proof type created by this prover.
    type Proof;

    /// Prepares an instance of the Sapling Spend circuit for the given inputs.
    ///
    /// Returns `None` if `diversifier` is not a valid Sapling diversifier.
    #[allow(clippy::too_many_arguments)]
    fn prepare_circuit(
        proof_generation_key: ProofGenerationKey,
        diversifier: Diversifier,
        rseed: Rseed,
        value: NoteValue,
        alpha: jubjub::Fr,
        rcv: ValueCommitTrapdoor,
        anchor: bls12_381::Scalar,
        merkle_path: MerklePath,
    ) -> Option<circuit::Spend>;

    /// Create the proof for a Sapling [`SpendDescription`].
    ///
    /// [`SpendDescription`]: crate::bundle::SpendDescription
    fn create_proof<R: RngCore>(&self, circuit: circuit::Spend, rng: &mut R) -> Self::Proof;

    /// Encodes the given Sapling [`SpendDescription`] proof, erasing its type.
    ///
    /// [`SpendDescription`]: crate::bundle::SpendDescription
    fn encode_proof(proof: Self::Proof) -> GrothProofBytes;
}

/// Interface for creating Sapling Output proofs.
pub trait OutputProver {
    /// The proof type created by this prover.
    type Proof;

    /// Prepares an instance of the Sapling Output circuit for the given inputs.
    ///
    /// Returns `None` if `diversifier` is not a valid Sapling diversifier.
    fn prepare_circuit(
        esk: jubjub::Fr,
        payment_address: PaymentAddress,
        rcm: jubjub::Fr,
        value: NoteValue,
        rcv: ValueCommitTrapdoor,
    ) -> circuit::Output;

    /// Create the proof for a Sapling [`OutputDescription`].
    ///
    /// [`OutputDescription`]: crate::bundle::OutputDescription
    fn create_proof<R: RngCore>(&self, circuit: circuit::Output, rng: &mut R) -> Self::Proof;

    /// Encodes the given Sapling [`OutputDescription`] proof, erasing its type.
    ///
    /// [`OutputDescription`]: crate::bundle::OutputDescription
    fn encode_proof(proof: Self::Proof) -> GrothProofBytes;
}

impl SpendProver for SpendParameters {
    type Proof = Proof<Bls12>;

    fn prepare_circuit(
        proof_generation_key: ProofGenerationKey,
        diversifier: Diversifier,
        rseed: Rseed,
        value: NoteValue,
        alpha: jubjub::Fr,
        rcv: ValueCommitTrapdoor,
        anchor: bls12_381::Scalar,
        merkle_path: MerklePath,
    ) -> Option<Spend> {
        // Construct the value commitment
        let value_commitment_opening = ValueCommitmentOpening {
            value,
            randomness: rcv.inner(),
        };

        // Construct the viewing key
        let viewing_key = proof_generation_key.to_viewing_key();

        // Construct the payment address with the viewing key / diversifier
        let payment_address = viewing_key.to_payment_address(diversifier)?;

        let note = Note::from_parts(payment_address, value, rseed);

        // We now have the full witness for our circuit
        let pos: u64 = merkle_path.position().into();
        Some(Spend {
            value_commitment_opening: Some(value_commitment_opening),
            proof_generation_key: Some(proof_generation_key),
            payment_address: Some(payment_address),
            commitment_randomness: Some(note.rcm()),
            ar: Some(alpha),
            auth_path: merkle_path
                .path_elems()
                .iter()
                .enumerate()
                .map(|(i, node)| Some(((*node).into(), pos >> i & 0x1 == 1)))
                .collect(),
            anchor: Some(anchor),
        })
    }

    fn create_proof<R: RngCore>(&self, circuit: Spend, rng: &mut R) -> Self::Proof {
        create_random_proof(circuit, &self.0, rng).expect("proving should not fail")
    }

    fn encode_proof(proof: Self::Proof) -> GrothProofBytes {
        let mut zkproof = [0u8; GROTH_PROOF_SIZE];
        proof
            .write(&mut zkproof[..])
            .expect("should be able to serialize a proof");
        zkproof
    }
}

impl OutputProver for OutputParameters {
    type Proof = Proof<Bls12>;

    fn prepare_circuit(
        esk: jubjub::Fr,
        payment_address: PaymentAddress,
        rcm: jubjub::Fr,
        value: NoteValue,
        rcv: ValueCommitTrapdoor,
    ) -> Output {
        // Construct the value commitment for the proof instance
        let value_commitment_opening = ValueCommitmentOpening {
            value,
            randomness: rcv.inner(),
        };

        // We now have a full witness for the output proof.
        Output {
            value_commitment_opening: Some(value_commitment_opening),
            payment_address: Some(payment_address),
            commitment_randomness: Some(rcm),
            esk: Some(esk),
        }
    }

    fn create_proof<R: RngCore>(&self, circuit: Output, rng: &mut R) -> Self::Proof {
        create_random_proof(circuit, &self.0, rng).expect("proving should not fail")
    }

    fn encode_proof(proof: Self::Proof) -> GrothProofBytes {
        let mut zkproof = [0u8; GROTH_PROOF_SIZE];
        proof
            .write(&mut zkproof[..])
            .expect("should be able to serialize a proof");
        zkproof
    }
}

#[cfg(any(test, feature = "test-dependencies"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-dependencies")))]
pub mod mock {
    use ff::Field;

    use super::{OutputProver, SpendProver};
    use crate::{
        bundle::GrothProofBytes,
        circuit::{self, ValueCommitmentOpening, GROTH_PROOF_SIZE},
        value::{NoteValue, ValueCommitTrapdoor},
        Diversifier, MerklePath, PaymentAddress, ProofGenerationKey, Rseed,
    };

    pub struct MockSpendProver;

    impl SpendProver for MockSpendProver {
        type Proof = GrothProofBytes;

        fn prepare_circuit(
            proof_generation_key: ProofGenerationKey,
            diversifier: Diversifier,
            _rseed: Rseed,
            value: NoteValue,
            alpha: jubjub::Fr,
            rcv: ValueCommitTrapdoor,
            anchor: bls12_381::Scalar,
            _merkle_path: MerklePath,
        ) -> Option<circuit::Spend> {
            let payment_address = proof_generation_key
                .to_viewing_key()
                .ivk()
                .to_payment_address(diversifier);
            Some(circuit::Spend {
                value_commitment_opening: Some(ValueCommitmentOpening {
                    value,
                    randomness: rcv.inner(),
                }),
                proof_generation_key: Some(proof_generation_key),
                payment_address,
                commitment_randomness: Some(jubjub::Scalar::ZERO),
                ar: Some(alpha),
                auth_path: vec![],
                anchor: Some(anchor),
            })
        }

        fn create_proof<R: rand_core::RngCore>(
            &self,
            _circuit: circuit::Spend,
            _rng: &mut R,
        ) -> Self::Proof {
            [0u8; GROTH_PROOF_SIZE]
        }

        fn encode_proof(proof: Self::Proof) -> GrothProofBytes {
            proof
        }
    }

    pub struct MockOutputProver;

    impl OutputProver for MockOutputProver {
        type Proof = GrothProofBytes;

        fn prepare_circuit(
            esk: jubjub::Fr,
            payment_address: PaymentAddress,
            rcm: jubjub::Fr,
            value: NoteValue,
            rcv: ValueCommitTrapdoor,
        ) -> circuit::Output {
            circuit::Output {
                value_commitment_opening: Some(ValueCommitmentOpening {
                    value,
                    randomness: rcv.inner(),
                }),
                payment_address: Some(payment_address),
                commitment_randomness: Some(rcm),
                esk: Some(esk),
            }
        }

        fn create_proof<R: rand_core::RngCore>(
            &self,
            _circuit: circuit::Output,
            _rng: &mut R,
        ) -> Self::Proof {
            [0u8; GROTH_PROOF_SIZE]
        }

        fn encode_proof(proof: Self::Proof) -> GrothProofBytes {
            proof
        }
    }
}