Skip to content

perf(sapling-crypto)!: hold value commitments as bytes, not points - #638

Merged
ValarDragon merged 6 commits into
zakura-core:mainfrom
zecrocks:zecrocks/value-commitment-bytes
Nov 1, 2026
Merged

ValarDragon merged 6 commits into
zakura-core:mainfrom
zecrocks:zecrocks/value-commitment-bytes

Conversation

@emersonian

Copy link
Copy Markdown
Contributor

Problem

Parsing a Sapling bundle decompresses 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 compresses it straight back: the txid digest (cv().to_bytes() is the only field the digest re-serialises from a parsed point; everything else hashes the original bytes), prf_ock in note encryption, the v4 sighash, serialisation.

Profiled on a wallet's memo backfill (the drain that fetches and stores full transactions), that round trip was 26% of all CPU, inside a Transaction::read that was 37%.

Solution

ValueCommitment keeps its 32-byte encoding.

  • to_bytes() returns the stored bytes.
  • try_point() -> CtOption<jubjub::ExtendedPoint> decompresses and checks small order on demand.
  • derive() computes the point once and stores its encoding.
  • from_bytes_unvalidated() is what parsing uses; from_bytes_not_small_order() still validates eagerly for callers that want that.
  • CommitmentSum's AddAssign/SubAssign take &jubjub::ExtendedPoint instead of &ValueCommitment. The Sapling verifier (the only as_inner caller in this repository) calls try_point() and fails closed on an invalid encoding before summing; zcash_proofs reaches it through the same path.

The consensus checks on cv move from parse time to verification time, where a node checks the description anyway. Chain data a node has validated never fails them.

Behavior change (breaking)

  • ValueCommitment::as_inner() is removed; use try_point().
  • CommitmentSum: AddAssign<&ValueCommitment> / SubAssign<&ValueCommitment> become AddAssign<&jubjub::ExtendedPoint> / SubAssign<&jubjub::ExtendedPoint>.
  • Transaction::read accepts a bundle whose cv is not a valid point; verification rejects it instead. A wallet that stores such a transaction stores its bytes, as it stores every other field it does not verify.

The wallet-libraries workspace reads Sapling cv as bytes only (prf_ock, serialisation); its ValueCommitment uses are Orchard's type, so it needs no change. workspace.package.version is already 5.0.0 on main with refactor! commits, so this fits the open breaking cycle; the semver job should report the removal as covered by that bump. Downstream consumers of the verifier (the node) should be grepped for as_inner before this is merged upstream.

Verification

  • cargo test -p zakura-sapling-crypto --all-features: 78 passed (3 ignored, as on main), 1 doc-test; -p zakura-primitives: 72 + 1; -p zakura-proofs: passed.
  • cargo +1.97.1 clippy --no-deps --all-features --all-targets -- -D warnings on the three crates clean; cargo doc --no-deps clean; cargo fmt --check clean.
  • Microbenchmark over 30,752 testnet transactions (110 MB; 3,339 Sapling spends, 11,462 Sapling outputs, 112k transparent inputs and outputs), release build: Transaction::read 1.930 s to 0.993 s, 1.94x; 130 us to 67 us per Sapling description.
  • Wallet fixture with this built into the wallet stack: received-note digest unchanged across Sapling, Orchard and Ironwood; memo counts rose as before; no errors.

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.
@ValarDragon

Copy link
Copy Markdown
Contributor

@v12sec pls review

@v12-auditor

v12-auditor Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

1 finding · 47c2ebf...e9ce583 · View run

Finding IDSeverityFinding
F-297 ⚪ Info
Deferred checks amplify invalid transaction work

The changed commitment reader stores the first malformed Sapling cv instead of rejecting it immediately, so v5/v6 parsing continues through every remaining spend/output effect, ciphertext, proof byte array, authorization signature, and binding signature. Transaction construction then computes the v5/v6 transaction digest over the fully materialized bundle before verification can inspect that first commitment. For a near-2,000,000-byte transaction, this permits roughly the full payload to be copied and hashed after an invalid first cv; a spend-heavy payload also forces thousands of rk point decodes during parsing. Batch verification adds one Groth16 proof deserialization and another rk decode before try_point rejects, although signature and proof verification closures are not reached.

Copy link
Copy Markdown
Contributor

Review: node safety, and the rollout plan

Verdict: the change is consensus-equivalent. try_point() applies exactly the old parse-time rule (ExtendedPoint::from_bytes plus !is_small_order(), with ZIP 216 canonical encoding enforced by from_bytes), so the set of accepted cv encodings is unchanged. Only the point of rejection moves, from parsing to verification. Txids, the v4 sighash and prf_ock hash the original bytes, which equal the re-encoded point for every valid encoding. The single and batch verifiers both go through SaplingVerificationContextInner and fail closed.

The node (zakura-core/zakura) pins =4.0.0, so nothing changes there until it bumps.

There is one blocking issue, plus some follow-ups. The plan below covers three PRs: this one, then wallet-libraries and the node after the 5.0.0 release.


PR 1: revise this PR (zecrocks/value-commitment-bytes)

  1. Blocking: remove the panicking arithmetic from the public API. In crates/sapling-crypto/src/value/sums.rs, these impls call derived_point(), which does .expect(...):

    • Add<&ValueCommitment> for ValueCommitment and for CommitmentSum
    • Sub<&ValueCommitment> for ValueCommitment
    • Sum<ValueCommitment> and Sum<&ValueCommitment>

    Transaction::read now produces unchecked commitments, so any caller that sums the cvs of a parsed transaction can be crashed remotely. Replace these impls with a fallible API, for example:

    impl CommitmentSum {
        /// Sums value commitments, or returns `None` if any is not a
        /// valid, non-small-order point.
        pub fn try_sum<'a>(cvs: impl IntoIterator<Item = &'a ValueCommitment>) -> Option<CommitmentSum>
    }

    Update the two internal callers:

    • builder.rs (around lines 835–840) may expect, with a message saying it derived those commitments itself.
    • pczt/io_finalizer.rs (around lines 51–57) should return its existing error type rather than panic.

    Delete derived_point() if nothing else uses it. Any design works as long as this holds: no public, non-unsafe function panics on a ValueCommitment built by from_bytes_unvalidated or Transaction::read.

  2. Fix the stale doc comment. The ValueCommitment struct doc in value.rs (around line 133) still says from_bytes_not_small_order "is the only constructor that can be used with data received over the network". It should say that network data may use from_bytes_unvalidated and must pass try_point() before it is used as a point.

  3. Add a parity test. For each input, assert from_bytes_unvalidated(b).try_point().is_some() equals the old rule. Also assert to_bytes() == b, and for valid inputs to_bytes() == try_point().unwrap().to_bytes(). Inputs:

    • the identity, (0, −1) and the other small-order points;
    • the two ZIP 216 non-canonical encodings, (0, 1) and (0, −1) with the sign bit set;
    • v ≥ q, off-curve bytes, and all 0xFF;
    • a few hundred points from ValueCommitment::derive.
  4. Add an end-to-end test. This wasn't possible before, because such bundles never got past parsing. Take a valid Sapling test transaction. Separately replace one spend cv and one output cv with (a) the identity encoding and (b) off-curve bytes. For each case assert that:

    • Transaction::read succeeds and round-trips the bytes;
    • BatchValidator::check_bundle returns false;
    • the single verifier's check_spend / check_output return false;
    • CommitmentSum::try_sum returns None, with no panic.
  5. Fix the changelog fragment. Rename docs/changelog/unreleased/2.md to 638.md; its links currently point at zecrocks/zakura-common/pull/2. Add the Add/Sub/Sum removal and try_sum. Add one sentence: "The set of accepted cv encodings is unchanged; rejection moves from parsing to verification."

  6. Update the PR description. Add a "Downstream impact" section covering the two follow-up PRs below. Replace "zcash_proofs reaches it through the same path" with the file and function that show it.

  7. Reply to v12 F-297 (Info). A node rejects such transactions in its own early check before any proof work, and wallets only receive transactions from their own server.

Checks:

cargo test -p zakura-sapling-crypto --all-features
cargo test -p zakura-primitives
cargo test -p zakura-proofs
cargo +1.97.1 clippy --no-deps --all-features --all-targets -p zakura-sapling-crypto -p zakura-primitives -p zakura-proofs -- -D warnings
cargo fmt --check
cargo doc --no-deps -p zakura-sapling-crypto

PR 2: zakura-core/wallet-libraries (after the 5.0.0 release)

  • In the root Cargo.toml, bump zcash_primitives (zakura-primitives, line 63) and sapling (zakura-sapling-crypto, line 84) from 4.0.0 to 5.0.0, along with the other zakura-* crates from common released in the same set.
  • No code changes are expected. Sapling cv is used only as bytes:
    • librustzcash/pczt/src/sapling.rs lines 643 and 688
    • librustzcash/zcash_client_backend/src/decrypt.rs line 183 (prf_ock)
    • zakura/transaction-wire/tests/common/mod.rs lines 86 and 93
  • Re-run the memo-backfill benchmark and the fixture digest check, and record the before/after numbers in the PR.
  • Add the changelog fragment the repository requires.

PR 3: zakura-core/zakura (after the 5.0.0 release)

After the bump, an invalid Sapling cv is still rejected twice: first by the node's early check, then by the library verifier's try_point. The parse-time rejection in to_librustzcash goes away, and several node tests and comments rely on it:

Layer Today After bump
check::sapling_point_encodings_are_valid (zakura-consensus/src/transaction.rs:508) rejects rejects
to_librustzcash → Transaction::read rejects accepts
sapling_crypto::BatchValidator never sees one rejects
  1. Bump sapling-crypto and zcash_primitives (root Cargo.toml lines 55 and 58), plus the other zakura-* crates from common, to =5.0.0.
  2. Rewrite sapling_small_order_cv_epk_deferred_but_caught_by_librustzcash (crates/zakura-chain/src/transaction/tests/vectors.rs, around line 2425). It asserts that to_librustzcash rejects a small-order cv, which will now fail. Don't just flip the assertion: rename the test, restate its doc, and assert that:
    • tx.sapling_point_encodings_are_valid() is false;
    • to_librustzcash now succeeds;
    • BatchValidator::check_bundle rejects the converted bundle (in a zakura-consensus test if zakura-chain can't reach the verifier).
  3. In sapling_point_checks_match_librustzcash_predicates (around line 3085), compare against from_bytes_unvalidated(b).try_point().is_some(), and rewrite the "read_value_commitment accepts a cv iff …" wording. Update the matching comment on is_valid_not_small_order in crates/zakura-chain/src/sapling/commitment.rs (around lines 55–62).
  4. At check::sapling_point_encodings_are_valid(&tx)?, add a comment saying it is now the only check before verification for Sapling cv. Keep the check.
  5. Coinbase: decrypts_successfully (zakura-chain/src/primitives/zcash_note_encryption.rs:15) used to return false for a coinbase with an invalid cv, because the conversion failed. It can now return true. Add or confirm a test that such a block is rejected on the semantic verification path.
  6. Switch binding_verification_key (zakura-chain/src/sapling/shielded_data.rs:334, used only in tests) to try_sum. This removes its second decode of each point.
  7. Add the changelog fragment and run ./scripts/changelog.py check.

Optional, separate PR: the node serializes and re-parses each transaction through to_librustzcash several times per verification (sighash setup, auth_digest, txid fallback, coinbase decryption check). Converting once and sharing the result would save more for the node than this PR does, and it doesn't depend on the 5.0.0 release.

Line numbers are as of e9ce583 and the current main of each repository; search for the named symbol if they have shifted.


Generated by Claude Code

…um::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.
…cation

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.

Copy link
Copy Markdown
Contributor

Re: v12 F-297 (Info): Deferred checks amplify invalid transaction work

The finding's description is accurate, and we accept it as Info. With this change, a transaction whose first Sapling cv is invalid gets fully parsed and its v5/v6 txid digest computed before try_point() rejects it. In BatchValidator::check_bundle, the first spend's Groth16 proof is also deserialised before check_spend reaches try_point(). No signature or proof verification runs on such a transaction.

This doesn't make a DoS vector, for two reasons:

  • The node doesn't use this parser at the network boundary. zakura-chain deserialises transactions with its own parser, which also keeps cv as bytes. The transaction verifier runs check::sapling_point_encodings_are_valid (crates/zakura-consensus/src/transaction.rs, in the verify-request path) before any conversion through to_librustzcash and before any proof or signature work. A transaction with a non-canonical or small-order cv is rejected there. So for the node, the extra work the finding describes happens only after that check has passed, which means it never happens for an invalid cv. The node also pins =4.0.0, and the plan above keeps that check when it moves to 5.0.0.
  • The extra cost is the cost of parsing. The work done before rejection is bounded by the transaction's size: a copy and one hash over at most the block-size limit, plus the rk decodes that parsing already did before this change. An attacker could already make a node parse and hash a maximum-size transaction that fails a later check, such as a bad proof or signature. This change adds no step whose cost exceeds that.

Wallets receive transactions from their own lightwalletd/indexer and only trial-decrypt them. For a wallet, parsing without validating cv is the intended behaviour, and it is where the ~1.94× parse speedup comes from.

Moving the check back into parsing would undo the purpose of this PR. A cheaper early exit in BatchValidator::check_bundle, validating every cv before deserialising any proof, is possible as a follow-up if we want it. We don't think it's needed for safety.


Generated by Claude Code

@ValarDragon
ValarDragon merged commit 0f4793b into zakura-core:main Nov 1, 2026
81 checks passed
p0mvn pushed a commit to zakura-core/zakura that referenced this pull request Nov 1, 2026
Demo only. Patch every Common crate to zakura-core/common@0f4793b, the
merge of zakura-core/common#638, which keeps Sapling value commitments as
bytes. That landed after 5.0.0-rc.2; replace the git pin with the next
Common release before merging.

librustzcash's parser now keeps `cv` as bytes, so `to_librustzcash` no
longer rejects an invalid Sapling `cv`. The node's early semantic check,
`check::sapling_point_encodings_are_valid`, becomes the first rejection
and the library verifier's `try_point` the second.

- Move `binding_verification_key` to `CommitmentSum::try_sum`; the `Sum`
  impl it used is removed, and this drops a second decode of each point.
- Comment that the early check is the only one before proof work.
- Rewrite the chain tests that asserted `to_librustzcash` rejects an
  invalid `cv`: they now assert the semantic check rejects it, conversion
  keeps the bytes, and `try_point` rejects the converted commitment.
- Pin the parity test to the verifier's `try_point`.
- Add a test that `BatchValidator::check_bundle` rejects real mainnet
  bundles with a small-order or off-curve spend or output `cv`.
- Add a test that a coinbase with an invalid Sapling `cv` is rejected
  with `SmallOrder`, since the coinbase decryption check can no longer be
  relied on to reject it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YAZUf8ugteNYiQRAkZfZUV
p0mvn added a commit to zakura-core/zakura that referenced this pull request Nov 1, 2026
…es) (#1907)

* build(deps): pin Common to the merge of zakura-core/common#638

Demo only. Patch every Common crate to zakura-core/common@0f4793b, the
merge of zakura-core/common#638, which keeps Sapling value commitments as
bytes. That landed after 5.0.0-rc.2; replace the git pin with the next
Common release before merging.

librustzcash's parser now keeps `cv` as bytes, so `to_librustzcash` no
longer rejects an invalid Sapling `cv`. The node's early semantic check,
`check::sapling_point_encodings_are_valid`, becomes the first rejection
and the library verifier's `try_point` the second.

- Move `binding_verification_key` to `CommitmentSum::try_sum`; the `Sum`
  impl it used is removed, and this drops a second decode of each point.
- Comment that the early check is the only one before proof work.
- Rewrite the chain tests that asserted `to_librustzcash` rejects an
  invalid `cv`: they now assert the semantic check rejects it, conversion
  keeps the bytes, and `try_point` rejects the converted commitment.
- Pin the parity test to the verifier's `try_point`.
- Add a test that `BatchValidator::check_bundle` rejects real mainnet
  bundles with a small-order or off-curve spend or output `cv`.
- Add a test that a coinbase with an invalid Sapling `cv` is rejected
  with `SmallOrder`, since the coinbase decryption check can no longer be
  relied on to reject it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YAZUf8ugteNYiQRAkZfZUV

* docs(changelog): fragment for #1907

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YAZUf8ugteNYiQRAkZfZUV

* build(deps): use published Common 5.0.0-rc.3

* build(deps): carry Common audit backlog to rc.3

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: roman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants