zebra_consensus/primitives/
groth16.rs1use 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
31type VerifyResult = Result<(), VerificationError>;
33
34type Sender = watch::Sender<Option<VerifyResult>>;
36
37#[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 pub fn verify_single(self, pvk: &PreparedVerifyingKey<Bls12>) -> VerifyResult {
53 self.0.verify_single(pvk)
54 }
55}
56
57pub type BatchVerifyingKey = VerifyingKey<Bls12>;
60
61pub type ItemVerifyingKey = PreparedVerifyingKey<Bls12>;
64
65pub static JOINSPLIT_VERIFIER: Lazy<
74 ServiceFn<fn(Item) -> BoxFuture<'static, Result<(), BoxedError>>>,
75> = Lazy::new(|| {
76 tower::service_fn(
80 (|item: Item| {
81 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
93pub(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
122pub 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 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
172pub struct Verifier {
178 tx: Sender,
183}
184
185impl Verifier {
186 async fn verify_single_spawning(
188 item: Item,
189 pvk: &'static ItemVerifyingKey,
190 ) -> Result<(), BoxError> {
191 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}