Skip to content

Commit 0f4793b

Browse files
authored
perf(sapling-crypto)!: hold value commitments as bytes, not points (#638)
* perf(sapling-crypto)!: hold value commitments as bytes, not points Parsing a Sapling bundle decompressed every spend's and output's cv into a Jubjub point - a field square root each, plus a small-order check - and every consumer short of proof and binding-signature verification then compressed it straight back: the txid digest (cv().to_bytes() is the only field the digest re-serialises from a parsed point), the outgoing cipher key (prf_ock), the sighash, serialisation. Profiled on a wallet's memo backfill, that round trip was 26% of all CPU. ValueCommitment now keeps its 32 bytes. to_bytes() returns them; try_point() decompresses and checks small order on demand, by value; derive() computes the point once and stores its encoding; from_bytes_unvalidated() is the parser's constructor and from_bytes_not_small_order() still validates eagerly for callers that want that. The verifier calls try_point() and fails closed on an invalid encoding, and CommitmentSum takes the point rather than the commitment, so the callers that need arithmetic validate first. The consensus checks move from parse time to verification time, where a node checks the description anyway. Microbenchmark over 30,752 testnet transactions (110 MB; 3,339 Sapling spends, 11,462 outputs): Transaction::read 1.930 s to 0.993 s, 1.94x; 130 to 67 us per Sapling description. The wallet crates read cv as bytes only (prf_ock, serialisation), so they need no change; as_inner()'s only caller in this repository is the verifier. BREAKING CHANGE: ValueCommitment::as_inner() is removed (use try_point()); CommitmentSum's AddAssign/SubAssign take &jubjub::ExtendedPoint; a parsed cv is no longer validated at parse time. * docs(changelog): fragment for #2 * fix(sapling-crypto)!: sum value commitments fallibly with CommitmentSum::try_sum The Add, Sub and Sum impls over ValueCommitment decoded each point with an expect. Transaction::read now yields unvalidated commitments, so summing the cvs of a parsed transaction could panic. Replace them with CommitmentSum::try_sum, which returns None on an invalid commitment; the builder expects on its own commitments and the PCZT IO finalizer returns ValueCommitMismatch. Correct the ValueCommitment doc on network data, and test that try_point accepts exactly the encodings parsing used to accept. * test(zcash_primitives): an invalid Sapling cv parses and fails verification Corrupt a spend cv and an output cv of a valid testnet transaction, first to the identity and then to bytes off the curve. The transaction still reads and round-trips, and the batch validator, the single verifier and CommitmentSum::try_sum all reject it. * docs(changelog): fragment for #638
1 parent cd74fe7 commit 0f4793b

11 files changed

Lines changed: 497 additions & 89 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/sapling-crypto/src/builder.rs‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -835,14 +835,12 @@ fn bundle_with_key_lookup<SP: SpendProver, OP: OutputProver, R: Rng, V: TryFrom<
835835

836836
// Verify that bsk and bvk are consistent.
837837
let bvk = {
838-
let spends = shielded_spends
839-
.iter()
840-
.map(|spend| spend.cv())
841-
.sum::<CommitmentSum>();
842-
let outputs = shielded_outputs
843-
.iter()
844-
.map(|output| output.cv())
845-
.sum::<CommitmentSum>();
838+
// This builder derived every one of these commitments itself.
839+
let spends = CommitmentSum::try_sum(shielded_spends.iter().map(|spend| spend.cv()))
840+
.expect("value commitments derived by the builder are valid points");
841+
let outputs =
842+
CommitmentSum::try_sum(shielded_outputs.iter().map(|output| output.cv()))
843+
.expect("value commitments derived by the builder are valid points");
846844
(spends - outputs).into_bvk(value_balance_i64)
847845
};
848846
assert_eq!(redjubjub::VerificationKey::from(&bsk), bvk);

‎crates/sapling-crypto/src/pczt/io_finalizer.rs‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,16 +45,10 @@ impl super::Bundle {
4545

4646
// Verify that bsk and bvk are consistent.
4747
let bvk = {
48-
let spends = self
49-
.spends
50-
.iter()
51-
.map(|spend| spend.cv())
52-
.sum::<CommitmentSum>();
53-
let outputs = self
54-
.outputs
55-
.iter()
56-
.map(|output| output.cv())
57-
.sum::<CommitmentSum>();
48+
let spends = CommitmentSum::try_sum(self.spends.iter().map(|spend| spend.cv()))
49+
.ok_or(IoFinalizerError::ValueCommitMismatch)?;
50+
let outputs = CommitmentSum::try_sum(self.outputs.iter().map(|output| output.cv()))
51+
.ok_or(IoFinalizerError::ValueCommitMismatch)?;
5852
(spends - outputs).into_bvk(
5953
i64::try_from(self.value_sum).map_err(|_| IoFinalizerError::InvalidValueSum)?,
6054
)

‎crates/sapling-crypto/src/value.rs‎

Lines changed: 182 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,23 @@ impl ValueCommitTrapdoor {
130130
/// [`NoteValue`] and [`ValueCommitTrapdoor`] are zero. However, the only constructor
131131
/// available for `ValueCommitTrapdoor` is [`ValueCommitTrapdoor::random`], which will
132132
/// produce zero with negligible probability (assuming a non-broken PRNG).
133-
/// - [`ValueCommitment::from_bytes_not_small_order`] enforces this by definition, and is
134-
/// the only constructor that can be used with data received over the network.
133+
/// - [`ValueCommitment::from_bytes_not_small_order`] enforces this by definition.
134+
/// - Data received over the network may also be wrapped with
135+
/// [`ValueCommitment::from_bytes_unvalidated`] (transaction parsing does this), but must
136+
/// then pass [`ValueCommitment::try_point`] before it is used as a point.
137+
///
138+
/// # Representation
139+
///
140+
/// Held as its 32-byte encoding. Nearly every consumer of a value commitment wants exactly
141+
/// those bytes - the txid digest, the outgoing cipher key, serialization - and a wallet never
142+
/// wants anything else, while decompressing the point costs a field square root and
143+
/// compressing it back an inversion. The point is recovered, and the "not small order" rule
144+
/// checked, only by [`ValueCommitment::try_point`], which proof and binding-signature
145+
/// verification call before they use it.
135146
#[derive(Clone, Debug)]
136-
pub struct ValueCommitment(jubjub::ExtendedPoint);
147+
pub struct ValueCommitment {
148+
bytes: [u8; 32],
149+
}
137150

138151
impl ValueCommitment {
139152
/// Derives a `ValueCommitment` by $\mathsf{ValueCommit^{Sapling}}$.
@@ -145,17 +158,22 @@ impl ValueCommitment {
145158
let cv = (VALUE_COMMITMENT_VALUE_GENERATOR * jubjub::Scalar::from(value.0))
146159
+ (VALUE_COMMITMENT_RANDOMNESS_GENERATOR * rcv.0);
147160

148-
ValueCommitment(cv.into())
161+
ValueCommitment {
162+
bytes: jubjub::ExtendedPoint::from(cv).to_bytes(),
163+
}
149164
}
150165

151-
/// Returns the inner Jubjub point representing this value commitment.
166+
/// Wraps a value commitment's byte representation without validating it.
152167
///
153-
/// This is public for access by `zcash_proofs`.
154-
pub fn as_inner(&self) -> &jubjub::ExtendedPoint {
155-
&self.0
168+
/// The encoding is checked - canonical, on the curve, not of small order - when a point
169+
/// is asked for via [`ValueCommitment::try_point`]. This is what transaction parsing uses,
170+
/// so that a wallet decoding a transaction it will only ever trial-decrypt does not pay a
171+
/// square root per spend and output for a check that verification performs anyway.
172+
pub fn from_bytes_unvalidated(bytes: [u8; 32]) -> Self {
173+
ValueCommitment { bytes }
156174
}
157175

158-
/// Deserializes a value commitment from its byte representation.
176+
/// Deserializes a value commitment from its byte representation, validating it.
159177
///
160178
/// Returns `None` if `bytes` is an invalid representation of a Jubjub point, or the
161179
/// resulting point is of small order.
@@ -167,13 +185,26 @@ impl ValueCommitment {
167185
/// [spenddesc]: https://zips.z.cash/protocol/protocol.pdf#spenddesc
168186
/// [outputdesc]: https://zips.z.cash/protocol/protocol.pdf#outputdesc
169187
pub fn from_bytes_not_small_order(bytes: &[u8; 32]) -> CtOption<ValueCommitment> {
170-
jubjub::ExtendedPoint::from_bytes(bytes)
171-
.and_then(|cv| CtOption::new(ValueCommitment(cv), !cv.is_small_order()))
188+
let cv = ValueCommitment { bytes: *bytes };
189+
cv.try_point().map(|_| cv)
190+
}
191+
192+
/// Recovers the Jubjub point this value commitment encodes.
193+
///
194+
/// Returns `None` if the encoding is not a valid Jubjub point, or the point is of small
195+
/// order - the consensus rules of [Zcash Protocol Spec § 4.4][spenddesc] and
196+
/// [§ 4.5][outputdesc], enforced here rather than at parse time.
197+
///
198+
/// [spenddesc]: https://zips.z.cash/protocol/protocol.pdf#spenddesc
199+
/// [outputdesc]: https://zips.z.cash/protocol/protocol.pdf#outputdesc
200+
pub fn try_point(&self) -> CtOption<jubjub::ExtendedPoint> {
201+
jubjub::ExtendedPoint::from_bytes(&self.bytes)
202+
.and_then(|cv| CtOption::new(cv, !cv.is_small_order()))
172203
}
173204

174205
/// Serializes this value commitment to its canonical byte representation.
175206
pub fn to_bytes(&self) -> [u8; 32] {
176-
self.0.to_bytes()
207+
self.bytes
177208
}
178209
}
179210

@@ -228,13 +259,147 @@ pub mod testing {
228259

229260
#[cfg(test)]
230261
mod tests {
262+
use alloc::vec::Vec;
263+
231264
use proptest::prelude::*;
232265

266+
use ff::{Field, PrimeField};
267+
use group::GroupEncoding;
268+
233269
use super::{
234-
BalanceError, CommitmentSum, TrapdoorSum, ValueCommitment, ValueSum,
270+
BalanceError, CommitmentSum, NoteValue, TrapdoorSum, ValueCommitTrapdoor, ValueCommitment,
271+
ValueSum,
235272
testing::{arb_note_value_bounded, arb_trapdoor},
236273
};
237274

275+
/// The rule transaction parsing applied before value commitments were held as bytes: a
276+
/// canonical (ZIP 216) encoding of a Jubjub point that is not of small order.
277+
fn parse_time_rule(bytes: [u8; 32]) -> bool {
278+
Option::<jubjub::AffinePoint>::from(jubjub::AffinePoint::from_bytes(bytes))
279+
.is_some_and(|p| !bool::from(jubjub::ExtendedPoint::from(p).is_small_order()))
280+
}
281+
282+
/// The little-endian encoding of a field's modulus.
283+
fn modulus<F: PrimeField<Repr = [u8; 32]>>() -> [u8; 32] {
284+
add_le(&(-F::ONE).to_repr(), 1)
285+
}
286+
287+
fn add_le(bytes: &[u8; 32], mut carry: u16) -> [u8; 32] {
288+
let mut out = *bytes;
289+
for b in out.iter_mut() {
290+
let sum = u16::from(*b) + carry;
291+
*b = sum as u8;
292+
carry = sum >> 8;
293+
}
294+
out
295+
}
296+
297+
/// The eight points of Jubjub's torsion subgroup, as `[r]P` for points `P` decoded from
298+
/// successive encodings, where `r` is the order of the prime-order subgroup.
299+
fn small_order_points() -> Vec<jubjub::ExtendedPoint> {
300+
let r = modulus::<jubjub::Fr>();
301+
let mut points: Vec<jubjub::ExtendedPoint> = Vec::new();
302+
for v in 0u8..=255 {
303+
let mut bytes = [0u8; 32];
304+
bytes[0] = v;
305+
let Some(p) =
306+
Option::<jubjub::AffinePoint>::from(jubjub::AffinePoint::from_bytes(bytes))
307+
else {
308+
continue;
309+
};
310+
let p = jubjub::ExtendedPoint::from(p);
311+
let mut torsion = jubjub::ExtendedPoint::identity();
312+
for bit in (0..256).rev().map(|i| (r[i / 8] >> (i % 8)) & 1 == 1) {
313+
torsion = torsion.double();
314+
if bit {
315+
torsion += p;
316+
}
317+
}
318+
if !points.contains(&torsion) {
319+
points.push(torsion);
320+
}
321+
if points.len() == 8 {
322+
return points;
323+
}
324+
}
325+
panic!("found only {} small-order points", points.len());
326+
}
327+
328+
/// `try_point` accepts exactly the encodings that parsing used to accept, and a value
329+
/// commitment keeps the bytes it was given.
330+
#[test]
331+
fn try_point_matches_the_parse_time_rule() {
332+
let small_order = small_order_points();
333+
let identity = jubjub::ExtendedPoint::identity().to_bytes();
334+
let minus_one = (-jubjub::Fq::ONE).to_repr();
335+
assert!(small_order.iter().any(|p| p.to_bytes() == identity));
336+
assert!(small_order.iter().any(|p| p.to_bytes() == minus_one));
337+
338+
let with_sign = |mut b: [u8; 32]| {
339+
b[31] |= 0x80;
340+
b
341+
};
342+
let q = modulus::<jubjub::Fq>();
343+
344+
let mut invalid = small_order.iter().map(|p| p.to_bytes()).collect::<Vec<_>>();
345+
// The ZIP 216 non-canonical encodings of (0, 1) and (0, -1).
346+
invalid.push(with_sign(identity));
347+
invalid.push(with_sign(minus_one));
348+
// `v` at or beyond the field modulus.
349+
invalid.push(q);
350+
invalid.push(add_le(&q, 1));
351+
invalid.push(with_sign(q));
352+
invalid.push([0xff; 32]);
353+
// Field elements that are the `v` of no curve point.
354+
invalid.extend(
355+
(2u8..=255)
356+
.map(|v| {
357+
let mut b = [0u8; 32];
358+
b[0] = v;
359+
b
360+
})
361+
.filter(|b| bool::from(jubjub::AffinePoint::from_bytes(*b).is_none()))
362+
.take(5),
363+
);
364+
assert_eq!(invalid.len(), 8 + 2 + 4 + 5);
365+
366+
let mut rcv = jubjub::Fr::from(0x9e37_79b9_7f4a_7c15);
367+
let valid = (0u64..300)
368+
.map(|i| {
369+
rcv = rcv.square() + jubjub::Fr::ONE;
370+
ValueCommitment::derive(NoteValue(i * 1_000_003), ValueCommitTrapdoor(rcv))
371+
.to_bytes()
372+
})
373+
.collect::<Vec<_>>();
374+
375+
for (bytes, expected) in invalid
376+
.iter()
377+
.map(|b| (b, false))
378+
.chain(valid.iter().map(|b| (b, true)))
379+
{
380+
let cv = ValueCommitment::from_bytes_unvalidated(*bytes);
381+
let point = cv.try_point();
382+
assert_eq!(bool::from(point.is_some()), parse_time_rule(*bytes));
383+
assert_eq!(bool::from(point.is_some()), expected);
384+
assert_eq!(
385+
bool::from(ValueCommitment::from_bytes_not_small_order(bytes).is_some()),
386+
expected
387+
);
388+
assert_eq!(cv.to_bytes(), *bytes);
389+
if expected {
390+
assert_eq!(point.unwrap().to_bytes(), *bytes);
391+
}
392+
}
393+
394+
// Small-order points are on the curve; only the small-order rule rejects them.
395+
for p in &small_order {
396+
assert!(bool::from(p.is_small_order()));
397+
assert!(bool::from(
398+
jubjub::AffinePoint::from_bytes(p.to_bytes()).is_some()
399+
));
400+
}
401+
}
402+
238403
proptest! {
239404
#[test]
240405
fn bsk_consistent_with_bvk(
@@ -257,10 +422,12 @@ mod tests {
257422
.sum::<TrapdoorSum>()
258423
.into_bsk();
259424

260-
let bvk = values
425+
let cvs = values
261426
.into_iter()
262427
.map(|(value, rcv)| ValueCommitment::derive(value, rcv))
263-
.sum::<CommitmentSum>()
428+
.collect::<Vec<_>>();
429+
let bvk = CommitmentSum::try_sum(&cvs)
430+
.expect("derived commitments are valid points")
264431
.into_bvk(value_balance);
265432

266433
assert_eq!(redjubjub::VerificationKey::from(&bsk), bvk);

‎crates/sapling-crypto/src/value/sums.rs‎

Lines changed: 21 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,18 @@ impl CommitmentSum {
183183
CommitmentSum(jubjub::ExtendedPoint::identity())
184184
}
185185

186+
/// Sums value commitments, or returns `None` if any of them is not a canonical
187+
/// encoding of a Jubjub point that is not of small order.
188+
///
189+
/// A [`ValueCommitment`] parsed from a transaction is not validated until its point is
190+
/// recovered, so summing one must be able to fail.
191+
pub fn try_sum<'a>(cvs: impl IntoIterator<Item = &'a ValueCommitment>) -> Option<Self> {
192+
cvs.into_iter().try_fold(Self::zero(), |mut acc, cv| {
193+
acc += &cv.try_point().into_option()?;
194+
Some(acc)
195+
})
196+
}
197+
186198
/// Transform this value commitment sum into the corresponding RedJubjub public key.
187199
///
188200
/// This is public for access by `zcash_proofs`.
@@ -210,39 +222,18 @@ impl CommitmentSum {
210222
}
211223
}
212224

213-
impl Add<&ValueCommitment> for ValueCommitment {
214-
type Output = CommitmentSum;
215-
216-
fn add(self, rhs: &Self) -> Self::Output {
217-
CommitmentSum(self.0 + rhs.0)
225+
/// Accumulates a value commitment's point. A verifier obtains it with
226+
/// [`ValueCommitment::try_point`] and rejects the description if that fails.
227+
impl AddAssign<&jubjub::ExtendedPoint> for CommitmentSum {
228+
fn add_assign(&mut self, rhs: &jubjub::ExtendedPoint) {
229+
self.0 += rhs;
218230
}
219231
}
220232

221-
impl Add<&ValueCommitment> for CommitmentSum {
222-
type Output = CommitmentSum;
223-
224-
fn add(self, rhs: &ValueCommitment) -> Self::Output {
225-
CommitmentSum(self.0 + rhs.0)
226-
}
227-
}
228-
229-
impl AddAssign<&ValueCommitment> for CommitmentSum {
230-
fn add_assign(&mut self, rhs: &ValueCommitment) {
231-
self.0 += rhs.0;
232-
}
233-
}
234-
235-
impl Sub<&ValueCommitment> for ValueCommitment {
236-
type Output = CommitmentSum;
237-
238-
fn sub(self, rhs: &Self) -> Self::Output {
239-
CommitmentSum(self.0 - rhs.0)
240-
}
241-
}
242-
243-
impl SubAssign<&ValueCommitment> for CommitmentSum {
244-
fn sub_assign(&mut self, rhs: &ValueCommitment) {
245-
self.0 -= rhs.0;
233+
/// See [`AddAssign<&jubjub::ExtendedPoint>`].
234+
impl SubAssign<&jubjub::ExtendedPoint> for CommitmentSum {
235+
fn sub_assign(&mut self, rhs: &jubjub::ExtendedPoint) {
236+
self.0 -= rhs;
246237
}
247238
}
248239

@@ -253,15 +244,3 @@ impl Sub<CommitmentSum> for CommitmentSum {
253244
CommitmentSum(self.0 - rhs.0)
254245
}
255246
}
256-
257-
impl Sum<ValueCommitment> for CommitmentSum {
258-
fn sum<I: Iterator<Item = ValueCommitment>>(iter: I) -> Self {
259-
iter.fold(CommitmentSum::zero(), |acc, cv| acc + &cv)
260-
}
261-
}
262-
263-
impl<'a> Sum<&'a ValueCommitment> for CommitmentSum {
264-
fn sum<I: Iterator<Item = &'a ValueCommitment>>(iter: I) -> Self {
265-
iter.fold(CommitmentSum::zero(), |acc, cv| acc + cv)
266-
}
267-
}

0 commit comments

Comments
 (0)