Skip to main content

zebra_consensus/primitives/
groth16.rs

1//! Async Groth16 verifier service for Sprout JoinSplit proofs
2
3use std::fmt;
4
5use bellman::{gadgets::multipack, VerificationError};
6use bls12_381::Bls12;
7use futures::{future::BoxFuture, FutureExt};
8use groth16::{batch, PreparedVerifyingKey, VerifyingKey};
9use once_cell::sync::Lazy;
10
11use tokio::sync::watch;
12use tower::util::ServiceFn;
13
14use tower_batch_control::RequestWeight;
15use tower_fallback::BoxedError;
16
17use crate::BoxError;
18
19use super::spawn_fifo_and_convert;
20
21mod params;
22#[cfg(test)]
23mod tests;
24#[cfg(test)]
25mod vectors;
26
27pub use params::SPROUT;
28
29use crate::error::TransactionError;
30
31/// The type of verification results.
32type VerifyResult = Result<(), VerificationError>;
33
34/// The type of the batch sender channel.
35type Sender = watch::Sender<Option<VerifyResult>>;
36
37/// The type of the batch item.
38/// This is a newtype around a Groth16 verification item.
39#[derive(Clone, Debug)]
40pub struct Item(batch::Item<Bls12>);
41
42impl RequestWeight for Item {}
43
44impl<T: Into<batch::Item<Bls12>>> From<T> for Item {
45    fn from(value: T) -> Self {
46        Self(value.into())
47    }
48}
49
50impl Item {
51    /// Convenience method to call a method on the inner value to perform non-batched verification.
52    pub fn verify_single(self, pvk: &PreparedVerifyingKey<Bls12>) -> VerifyResult {
53        self.0.verify_single(pvk)
54    }
55}
56
57/// The type of a raw verifying key.
58/// This is the key used to verify batches.
59pub type BatchVerifyingKey = VerifyingKey<Bls12>;
60
61/// The type of a prepared verifying key.
62/// This is the key used to verify individual items.
63pub type ItemVerifyingKey = PreparedVerifyingKey<Bls12>;
64
65/// Global batch verification context for Groth16 proofs of JoinSplit statements.
66///
67/// This service does not yet batch verifications, see
68/// <https://github.com/ZcashFoundation/zebra/issues/3127>
69///
70/// Note that making a `Service` call requires mutable access to the service, so
71/// you should call `.clone()` on the global handle to create a local, mutable
72/// handle.
73pub static JOINSPLIT_VERIFIER: Lazy<
74    ServiceFn<fn(Item) -> BoxFuture<'static, Result<(), BoxedError>>>,
75> = Lazy::new(|| {
76    // We just need a Service to use: there is no batch verification for JoinSplits.
77    //
78    // See the note on [`SPEND_VERIFIER`] for details.
79    tower::service_fn(
80        (|item: Item| {
81            // TODO: Simplify the call stack here.
82            Verifier::verify_single_spawning(item, SPROUT.prepared_verifying_key())
83                .map(|result| {
84                    result
85                        .map_err(|e| TransactionError::Groth16(e.to_string()))
86                        .map_err(tower_fallback::BoxedError::from)
87                })
88                .boxed()
89        }) as fn(_) -> _,
90    )
91});
92
93/// Compute the [h_{Sig} hash function][1] which is used in JoinSplit descriptions.
94///
95/// `random_seed`: the random seed from the JoinSplit description.
96/// `nf1`: the first nullifier from the JoinSplit description.
97/// `nf2`: the second nullifier from the JoinSplit description.
98/// `joinsplit_pub_key`: the JoinSplit public validation key from the transaction.
99///
100/// [1]: https://zips.z.cash/protocol/protocol.pdf#hsigcrh
101pub(super) fn h_sig(
102    random_seed: &[u8; 32],
103    nf1: &[u8; 32],
104    nf2: &[u8; 32],
105    joinsplit_pub_key: &[u8; 32],
106) -> [u8; 32] {
107    let h_sig: [u8; 32] = blake2b_simd::Params::new()
108        .hash_length(32)
109        .personal(b"ZcashComputehSig")
110        .to_state()
111        .update(random_seed)
112        .update(nf1)
113        .update(nf2)
114        .update(joinsplit_pub_key)
115        .finalize()
116        .as_bytes()
117        .try_into()
118        .expect("32 byte array");
119    h_sig
120}
121
122/// Create a Groth16 verification [`Item`] from a JoinSplit description and public key.
123pub fn joinsplit_to_item(
124    js: &zcash_primitives::transaction::components::sprout::JsDescription,
125    joinsplit_pub_key: &[u8; 32],
126) -> Result<Item, TransactionError> {
127    let rt = js.anchor();
128    let nf1 = &js.nullifiers()[0];
129    let nf2 = &js.nullifiers()[1];
130    let mac1 = &js.macs()[0];
131    let mac2 = &js.macs()[1];
132    let cm1 = &js.commitments()[0];
133    let cm2 = &js.commitments()[1];
134
135    let h_sig = h_sig(js.random_seed(), nf1, nf2, joinsplit_pub_key);
136
137    let vpub_old = js.vpub_old().to_i64_le_bytes();
138    let vpub_new = js.vpub_new().to_i64_le_bytes();
139
140    let mut public_input = Vec::with_capacity((32 * 8) + (8 * 2));
141    public_input.extend(rt);
142    public_input.extend(h_sig);
143    public_input.extend(nf1);
144    public_input.extend(mac1);
145    public_input.extend(nf2);
146    public_input.extend(mac2);
147    public_input.extend(cm1);
148    public_input.extend(cm2);
149    public_input.extend(vpub_old);
150    public_input.extend(vpub_new);
151
152    let public_input = multipack::bytes_to_bits(&public_input);
153    let primary_inputs = multipack::compute_multipacking(&public_input);
154
155    // V4 transactions always use Groth16 proofs for JoinSplits (V2/V3 use PHGR13).
156    // The proof type is determined at deserialization time by the transaction version
157    // (see zcash_primitives JsDescription::read), so a V4 sprout bundle will always
158    // contain Groth16 proofs. This function must only be called for V4 transactions.
159    let proof_bytes = js.groth_proof_bytes().ok_or_else(|| {
160        TransactionError::MalformedGroth16(
161            "expected Groth16 proof in JoinSplit but found PHGR13 (wrong transaction version?)"
162                .into(),
163        )
164    })?;
165
166    let proof = groth16::Proof::read(&proof_bytes[..])
167        .map_err(|e| TransactionError::MalformedGroth16(e.to_string()))?;
168
169    Ok(Item::from((proof, primary_inputs)))
170}
171
172/// Groth16 signature verifier implementation
173///
174/// This is the core implementation for the batch verification logic of the groth
175/// verifier. It handles batching incoming requests, driving batches to
176/// completion, and reporting results.
177pub struct Verifier {
178    /// A channel for broadcasting the result of a batch to the futures for each batch item.
179    ///
180    /// Each batch gets a newly created channel, so there is only ever one result sent per channel.
181    /// Tokio doesn't have a oneshot multi-consumer channel, so we use a watch channel.
182    tx: Sender,
183}
184
185impl Verifier {
186    /// Verify a single item using a thread pool, and return the result.
187    async fn verify_single_spawning(
188        item: Item,
189        pvk: &'static ItemVerifyingKey,
190    ) -> Result<(), BoxError> {
191        // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
192        spawn_fifo_and_convert(move || item.verify_single(pvk)).await
193    }
194}
195
196impl fmt::Debug for Verifier {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        let name = "Verifier";
199        f.debug_struct(name)
200            .field("batch", &"..")
201            .field("tx", &self.tx)
202            .finish()
203    }
204}