ed25519_zebra/batch.rs
1//! Performs batch Ed25519 signature verification.
2//!
3//! Batch verification asks whether *all* signatures in some set are valid,
4//! rather than asking whether *each* of them is valid. This allows sharing
5//! computations among all signature verifications, performing less work overall
6//! at the cost of higher latency (the entire batch must complete), complexity of
7//! caller code (which must assemble a batch of signatures across work-items),
8//! and loss of the ability to easily pinpoint failing signatures.
9//!
10//! In addition to these general tradeoffs, design flaws in Ed25519 specifically
11//! mean that batched verification may not agree with individual verification.
12//! Some signatures may verify as part of a batch but not on their own.
13//! This problem is fixed by [ZIP215], a precise specification for edge cases
14//! in Ed25519 signature validation that ensures that batch verification agrees
15//! with individual verification in all cases.
16//!
17//! This crate implements ZIP215, so batch verification always agrees with
18//! individual verification, but this is not guaranteed by other implementations.
19//! **Be extremely careful when using Ed25519 in a consensus-critical context
20//! like a blockchain.**
21//!
22//! This batch verification implementation is adaptive in the sense that it
23//! detects multiple signatures created with the same verification key and
24//! automatically coalesces terms in the final verification equation. In the
25//! limiting case where all signatures in the batch are made with the same
26//! verification key, coalesced batch verification runs twice as fast as ordinary
27//! batch verification.
28//!
29//! 
30//!
31//! This optimization doesn't help much with Zcash, where public keys are random,
32//! but could be useful in proof-of-stake systems where signatures come from a
33//! set of validators (provided that system uses the ZIP215 rules).
34//!
35//! # Example
36//! ```
37//! # use ed25519_zebra::*;
38//! let mut batch = batch::Verifier::new();
39//! for _ in 0..32 {
40//! let sk = SigningKey::new(rand::thread_rng());
41//! let vk_bytes = VerificationKeyBytes::from(&sk);
42//! let msg = b"BatchVerifyTest";
43//! let sig = sk.sign(&msg[..]);
44//! batch.queue((vk_bytes, sig, &msg[..]));
45//! }
46//! assert!(batch.verify(rand::thread_rng()).is_ok());
47//! ```
48//!
49//! [ZIP215]: https://zips.z.cash/zip-0215
50
51use alloc::vec::Vec;
52use core::convert::TryFrom;
53
54use curve25519_dalek::{
55 digest::Update,
56 edwards::{CompressedEdwardsY, EdwardsPoint},
57 scalar::Scalar,
58 traits::{IsIdentity, VartimeMultiscalarMul},
59};
60use hashbrown::HashMap;
61use rand_core::{CryptoRng, RngCore};
62use sha2::Sha512;
63
64use crate::{Error, VerificationKey, VerificationKeyBytes};
65use ed25519::Signature;
66
67// Shim to generate a u128 without importing `rand`.
68fn gen_u128<R: RngCore + CryptoRng>(mut rng: R) -> u128 {
69 let mut bytes = [0u8; 16];
70 rng.fill_bytes(&mut bytes[..]);
71 u128::from_le_bytes(bytes)
72}
73
74/// A batch verification item.
75///
76/// This struct exists to allow batch processing to be decoupled from the
77/// lifetime of the message. This is useful when using the batch verification API
78/// in an async context.
79#[derive(Clone, Debug)]
80pub struct Item {
81 vk_bytes: VerificationKeyBytes,
82 sig: Signature,
83 k: Scalar,
84}
85
86impl<'msg, M: AsRef<[u8]> + ?Sized> From<(VerificationKeyBytes, Signature, &'msg M)> for Item {
87 fn from(tup: (VerificationKeyBytes, Signature, &'msg M)) -> Self {
88 let (vk_bytes, sig, msg) = tup;
89 // Compute k now to avoid dependency on the msg lifetime.
90 let k = Scalar::from_hash(
91 Sha512::default()
92 .chain(&sig.r_bytes()[..])
93 .chain(&vk_bytes.0[..])
94 .chain(msg),
95 );
96 Self { vk_bytes, sig, k }
97 }
98}
99
100impl Item {
101 /// Perform non-batched verification of this `Item`.
102 ///
103 /// This is useful (in combination with `Item::clone`) for implementing fallback
104 /// logic when batch verification fails. In contrast to
105 /// [`VerificationKey::verify`](crate::VerificationKey::verify), which requires
106 /// borrowing the message data, the `Item` type is unlinked from the lifetime of
107 /// the message.
108 pub fn verify_single(self) -> Result<(), Error> {
109 VerificationKey::try_from(self.vk_bytes)
110 .and_then(|vk| vk.verify_prehashed(&self.sig, self.k))
111 }
112}
113
114/// A batch verification context.
115#[derive(Default)]
116pub struct Verifier {
117 /// Signature data queued for verification.
118 signatures: HashMap<VerificationKeyBytes, Vec<(Scalar, Signature)>>,
119 /// Caching this count avoids a hash traversal to figure out
120 /// how much to preallocate.
121 batch_size: usize,
122}
123
124impl Verifier {
125 /// Construct a new batch verifier.
126 pub fn new() -> Verifier {
127 Verifier::default()
128 }
129
130 /// Queue a (key, signature, message) tuple for verification.
131 pub fn queue<I: Into<Item>>(&mut self, item: I) {
132 let Item { vk_bytes, sig, k } = item.into();
133
134 self.signatures
135 .entry(vk_bytes)
136 // The common case is 1 signature per public key.
137 // We could also consider using a smallvec here.
138 .or_insert_with(|| Vec::with_capacity(1))
139 .push((k, sig));
140 self.batch_size += 1;
141 }
142
143 /// Perform batch verification, returning `Ok(())` if all signatures were
144 /// valid and `Err` otherwise.
145 #[allow(non_snake_case)]
146 pub fn verify<R: RngCore + CryptoRng>(self, mut rng: R) -> Result<(), Error> {
147 // The batch verification equation is
148 //
149 // 8*[-sum(z_i * s_i)]B + 8*sum([z_i]R_i) + 8*sum([z_i * k_i]A_i) = 0.
150 //
151 // where for each signature i,
152 // - A_i is the verification key;
153 // - R_i is the signature's R value;
154 // - s_i is the signature's s value;
155 // - k_i is the hash of the message and other data;
156 // - z_i is a random 128-bit Scalar.
157 //
158 // Normally n signatures would require a multiscalar multiplication of
159 // size 2*n + 1, together with 2*n point decompressions (to obtain A_i
160 // and R_i). However, because we store batch entries in a HashMap
161 // indexed by the verification key, we can "coalesce" all z_i * k_i
162 // terms for each distinct verification key into a single coefficient.
163 //
164 // For n signatures from m verification keys, this approach instead
165 // requires a multiscalar multiplication of size n + m + 1 together with
166 // n + m point decompressions. When m = n, so all signatures are from
167 // distinct verification keys, this is as efficient as the usual method.
168 // However, when m = 1 and all signatures are from a single verification
169 // key, this is nearly twice as fast.
170
171 let m = self.signatures.keys().count();
172
173 let mut A_coeffs = Vec::with_capacity(m);
174 let mut As = Vec::with_capacity(m);
175 let mut R_coeffs = Vec::with_capacity(self.batch_size);
176 let mut Rs = Vec::with_capacity(self.batch_size);
177 let mut B_coeff = Scalar::ZERO;
178
179 for (vk_bytes, sigs) in self.signatures.iter() {
180 let A = CompressedEdwardsY(vk_bytes.0)
181 .decompress()
182 .ok_or(Error::InvalidSignature)?;
183
184 let mut A_coeff = Scalar::ZERO;
185
186 for (k, sig) in sigs.iter() {
187 let R = CompressedEdwardsY(*sig.r_bytes())
188 .decompress()
189 .ok_or(Error::InvalidSignature)?;
190 let s = Option::<Scalar>::from(Scalar::from_canonical_bytes(*sig.s_bytes()))
191 .ok_or(Error::InvalidSignature)?;
192 let z = Scalar::from(gen_u128(&mut rng));
193 B_coeff -= z * s;
194 Rs.push(R);
195 R_coeffs.push(z);
196 A_coeff += z * k;
197 }
198
199 As.push(A);
200 A_coeffs.push(A_coeff);
201 }
202
203 use core::iter::once;
204 use curve25519_dalek::constants::ED25519_BASEPOINT_POINT as B;
205 let check = EdwardsPoint::vartime_multiscalar_mul(
206 once(&B_coeff).chain(A_coeffs.iter()).chain(R_coeffs.iter()),
207 once(&B).chain(As.iter()).chain(Rs.iter()),
208 );
209
210 if check.mul_by_cofactor().is_identity() {
211 Ok(())
212 } else {
213 Err(Error::InvalidSignature)
214 }
215 }
216}