WIP: [EXPERIMENTAL] Schnorr batch verification for blocks

bitcoin/bitcoin: PR #29491

Provider refusals

write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.

1 major finding · 5 minor findings · 12 suggestions

Findings

Link

[major] · Unhashed first inputs allow invalid signatures to cancel with predictable coefficients

Known or NULL auxiliary randomness, or secp256k1_batch_reset, permits cancelling invalid signatures; no current Core caller uses these modes, so a block-acceptance exploit against this integration is not established.

Location: src/secp256k1/src/modules/schnorrsig/batch_add_impl.h:133 (head).

Details and suggested fix

When batch->len == 0, secp256k1_batch_add_schnorrsig sets ai = 1 but skips the only function that hashes the signature, message and public key. With room for two signatures, start from two valid signatures, change s2 to s2+1 modulo the curve order, compute its nonzero coefficient a2, then change s1 to s1-a2. For residual R + e*P - s*G, the residuals become a2*G and -G, whose weighted sum is zero. Neither challenge depends on s, and adjusting the unhashed first signature does not change a2. Both signatures fail individually while all parsing guards pass. Successful transparent verification clears len, so the omission repeats after flushing. The tweak-check add function has the same omission and permits adjusting the first tweak after computing later coefficients.

The header permits NULL auxiliary randomness, while native reset discards the auxiliary prefix entirely. Core instead supplies fresh GetRandBytes output and recreates the batch on reset. Hash every input in both add functions, including each sub-batch's first input while retaining its coefficient of one. Preserve or reseed the auxiliary prefix on reset, and add cancellation regression tests for NULL auxiliary randomness and post-reset reuse.


Link

[minor] · Batched tweak checks can accept non-binary parity values

A non-binary tweaked_pk_parity can pass batch verification although individual verification rejects it; Bitcoin Core does not currently call this batch API, so production impact is unconfirmed.

Location: src/secp256k1/src/modules/extrakeys/batch_add_impl.h:115 (head).

Details and suggested fix

secp256k1_ge_set_xo_var negates its initial square root whenever its binary parity differs from the supplied integer. With tweaked_pk_parity == 2, it always negates that root. If this produces the correct tweaked point, a single-item batch succeeds with coefficient one. Individual secp256k1_xonly_pubkey_tweak_add_check instead compares the actual binary parity directly with the supplied integer and rejects it. This violates the new header's promise that a parity mismatch fails verification. Set batch->result = 0 and return when parity is neither zero nor one, and compare batched and individual results for values such as -1 and 2.


Link

[minor] · Randomized Schnorr batch-verification test is never registered

The registry never invokes test_schnorrsig_sign_batch_verify, so its randomized round-trip, bit-flip, scalar-rejection and varying-message-length assertions provide no test coverage.

Location: src/secp256k1/src/modules/schnorrsig/batch_add_tests_impl.h:240 (head).

Details and suggested fix

REPEAT_TEST(test_schnorrsig_sign_batch_verify) defines a function containing the COUNT loop; it does not register that function. tests_batch_add_schnorrsig contains only the randomizer-generation and API tests, and no other call invokes the omitted wrapper. Add CASE1(test_schnorrsig_sign_batch_verify) to this table so the existing randomized body actually runs.


Link

[minor] · Extracted ecmult helper loses the randomized NULL generator-scalar mode

Both randomized entry points now always pass a non-NULL generator scalar to their tested functions, losing the base test's randomized absent-generator mode.

Location: src/secp256k1/src/tests.c:5328 (head).

Details and suggested fix

ecmult_multi_random_generate_inp chooses a nullable g_scalar_ptr, but g_scalar = g_scalar_ptr changes only its local parameter. Both callers initialize their own pointer to &g_scalar and pass that unchanged to multiplication. A pointer to a zero scalar gives the same mathematical result, so the equality assertions need not expose the loss, including the new internal function's NULL-and-zero-points early return. Return the chosen pointer or a presence flag from the helper and use it in both callers.


Link

[minor] · Automake skips batch_example when MuSig is disabled

Standalone Automake configurations with examples, Schnorr and batching enabled omit batch_example from the build and make check whenever MuSig is disabled, although the example needs no MuSig APIs.

Location: src/secp256k1/Makefile.am:212 (head).

Details and suggested fix

The ENABLE_MODULE_BATCH block is nested inside ENABLE_MODULE_MUSIG. The configure dependencies require Schnorr for MuSig, not MuSig for Schnorr, so enabling examples, Schnorr and batching while disabling MuSig is supported. Move this block outside the MuSig conditional and guard it with both ENABLE_MODULE_BATCH and ENABLE_MODULE_SCHNORRSIG, matching examples/CMakeLists.txt.


Link

[minor] · Batch example treats randomness errors as successful setup

If fill_random fails in any generation helper, the standalone batch example reports successful setup and proceeds with incomplete key, message or tweak generation instead of taking its error exit.

Location: src/secp256k1/examples/batch.c:37 (head).

Details and suggested fix

fill_random returns zero on failure, including operating-system errors and short reads. However, create_keypair, generate_schnorrsigs and generate_xonlypub_tweak_checks each return one from that failure branch. main treats one as success, prints ok, and proceeds to signing or batching despite incomplete setup. Return zero from all three helper failure branches so their existing if (!helper(...)) checks terminate the example with a nonzero process exit.


Optional improvements

Link

[suggestion] · Successful batched block checks no longer populate validation caches

For cache misses, repeated TestBlockValidity calls now redo Schnorr verification in both threading modes and script execution in the sequential path, rather than retaining those successful results.

Location: src/validation.cpp:2152 (head).

Details and suggested fix

TestBlockValidity passes fJustCheck=true specifically to populate validation caches. The collecting checker reads Schnorr cache entries but never stores misses after verification, and the new !batch guard prevents sequential full-script insertion. Queued full-script insertion was already absent at base; existing cache hits and inherited ECDSA caching still work. Retain pending cache keys when storage is requested and publish them only after successful batch verification, with a full-script entry published only after every input check for that transaction succeeds.


Link

[suggestion] · Deferred batch failures lose transaction and input attribution

Schnorr failures detected by final batch verification now produce a generic block-rejection diagnostic without identifying the failing transaction or input in validation logs.

Location: src/validation.cpp:2714 (head).

Details and suggested fix

Previously, individual verification returned SCRIPT_ERR_SCHNORR_SIG with the input index, txid, wtxid and spent outpoint, which reached the logged validation state. The sequential batch failure supplies no debug string, while the queue supplies only Schnorr batch validation failed. Ordinary script-execution failures still retain attribution. Keep enough provenance to rerun the affected script checks individually on batch failure, recovering the specific error and input diagnostic without changing which blocks are rejected.


Link

[suggestion] · Empty worker batches still participate in the completion barrier

Each batched queue round waits for every registered participant to verify and recreate even an empty batch, adding wakeups, allocation and reseeding to cache-hit or ECDSA-only blocks; the end-to-end cost is unmeasured.

Location: src/checkqueue.h:159 (head).

Details and suggested fix

Complete() wakes all workers, and every participant enters the verification phase once per round. Each then calls Verify() and Reset() before contributing to m_total_verified; the master cannot return until all have contributed. Reset() destroys and recreates scratch for 106 terms and calls GetRandBytes. Register outstanding batches only for workers that collect signatures, under m_mutex before retiring their jobs, and complete when nTodo == 0 and no outstanding batches remain. Preserve the required reset and reseeding behavior for batches that actually need reuse.


Link

[suggestion] · Generic CCheckQueue embeds script-specific batch processing

Exact BatchableResult dispatch makes the generic scheduler own Schnorr state and script-error translation, coupling synchronization logic to one workload despite existing non-script queue users.

Location: src/checkqueue.h:46 (head).

Details and suggested fix

Loop recognizes a particular result variant, unpacks signature vectors, calls BatchSchnorrVerifier::Add, Verify and Reset, and constructs SCRIPT_ERR_BATCH_VALIDATION_FAILED. This also introduces batchverify.h and script/script_error.h dependencies for ordinary jobs such as PrevectorJob and DumbCheck. Use an explicit per-worker accumulator policy that consumes job results and finalizes a round to std::optional<R>. A trivial policy can preserve ordinary checks, while the script policy owns batching and error translation. The existing once-per-worker finalization barrier can remain unchanged.


Link

[suggestion] · Batch mode leaves CheckInputScripts' completion contract implicit

The sole current batch caller finalizes correctly, but CheckInputScripts returns provisional true and permits check_for=Mempool although its batch branch always reports block-consensus errors.

Location: src/validation.cpp:2121 (head).

Details and suggested fix

The batch branch collects signatures and can return true before their cryptographic checks succeed. Its failures always use TX_CONSENSUS and block-script-verify-flag-failed, unlike the ordinary branch's context-dependent classification. The function comment describes only pvChecks deferral, and the declaration exposes batch independently of check_for. Assert that a non-null batch is used only with CheckInputScriptsFor::Block, and document that a successful return remains provisional until the caller verifies the batch.


Link

[suggestion] · Strauss state-allocation failures are discarded

If scratch fits the inputs but not Strauss state, the wrapper reports success with infinity; batch_verify has the same conditional issue without VERIFY, but no current triggering caller or build configuration was identified.

Location: src/secp256k1/src/ecmult_impl.h:442 (head).

Details and suggested fix

secp256k1_ecmult_strauss_batch_internal initializes the result to infinity and returns zero if state allocation fails. The wrapper discards that status and returns one, whereas base rejected failure of any allocation. secp256k1_batch_verify checks the status only with VERIFY_CHECK, then treats infinity as successful verification. Normal dispatch sizes batches with strauss_max_points, and batch creation preallocates state space, although its padding allowance is fixed while allocations round to ALIGNMENT.

Preserve the internal status through the wrapper after restoring its scratch checkpoint, and include strauss_ret in the batch result rather than relying solely on VERIFY_CHECK. Derive reservation padding from ALIGNMENT and add a test whose scratch fits the input arrays but not the state; the existing zero-byte-scratch test fails before this boundary.


Link

[suggestion] · batchverify fuzzing cannot reach flushing or post-reset reuse

The fuzz target adds at most 32 signatures, below the 53-signature capacity, and exits immediately after Reset(), leaving automatic flushing and reset recovery outside its assertions.

Location: src/test/fuzz/batchverify.cpp:27 (head).

Details and suggested fix

Each Schnorr signature consumes two of the wrapper's 106 terms, so the first automatic verification occurs on the 54th add. The 32-iteration limit cannot reach it, and the reset branch performs no subsequent Add or Verify. Use a bounded operation sequence that crosses the 52/53/54 boundary and interleaves Add, Verify and Reset. Reuse pre-generated tuples to limit signing cost, place invalid signatures before and after flushing, and compare against accumulated individual-verification results so failure retention and reset recovery affect the oracle.


Link

[suggestion] · Multi-worker batch-failure coverage depends on scheduling

test_CheckQueue_Batched can satisfy all failure and recovery assertions with one participant processing the invalid signatures, so it does not guarantee the multi-worker failure case described by its comment.

Location: src/test/checkqueue_tests.cpp:290 (head).

Details and suggested fix

A batch size of four creates scheduling opportunities but does not force distribution, and the test records neither job ownership nor which participants hold invalid batches. Add a synchronized case with batch_size=1 and one blocking check per worker. Wait until every worker has acquired a check, then release them to return invalid signatures and call Complete(). Assert the failure followed by successful empty and valid rounds. Keep the existing repeated workload as additional stress coverage.


Link

[suggestion] · Provisional Schnorr success lacks its script-validity rationale

Current tapscript semantics permit deferred verification, but CollectingSignatureChecker does not explain why replacing a cryptographic check with true preserves script validity.

Location: src/script/sigcache.cpp:100 (head).

Details and suggested fix

On a cache miss, the checker collects the signature and returns true. This works because an invalid nonempty signature for a 32-byte tapscript key aborts execution rather than producing a usable false stack value. Empty signatures and unknown key types bypass collection, while CheckSchnorrSignature handles signature length and hash type first. Document these dependencies at the checker, together with the requirement to verify collected signatures before accepting or caching the result. The current length comment and TakeCollectedSignatures ownership note do not explain this consensus reasoning.


Link

[suggestion] · Tweak-check benchmark retains setup-only keypairs

The tweak-check benchmark keeps one heap keypair per iteration although its measured callbacks use only serialized inputs, adding avoidable allocations and retained memory outside the timed work.

Location: src/secp256k1/src/modules/extrakeys/bench_impl.h:20 (head).

Details and suggested fix

keypairs is populated during setup and read only to free its elements later. Each keypair's useful lifetime ends after secp256k1_keypair_xonly_pub extracts the public key. Use a loop-local secp256k1_keypair for the checked derivation and remove the retained array, per-iteration allocation, assignments and frees. Both benchmark callbacks can continue using the same serialized keys, tweaks and parity values.


Link

[suggestion] · Queue failure/recovery coverage arrives after the batching protocol

The batched completion protocol enters in 224c44bb, but its direct failure/recovery test arrives only in 2af98f70, leaving intermediate revisions without that coverage.

Location: src/test/checkqueue_tests.cpp:278 at 2af98f70d804 (commit) (commit).

Details and suggested fix

224c44bb7fc4160fcd0bfaefa67166a63d7ebbd5 introduces per-round batch finalization, the m_total_verified == nTotal barrier, round reset and the CCheckQueueControl<T, R> constructor. The test-only commit 2af98f70d8044da3875c2f22647efe45d5c8a245 adds BatchedCheck and test_CheckQueue_Batched, covering failing rounds followed by empty and valid recovery rounds. Squash the latter into the former so those assertions can validate the protocol at its introduction. Its required types and batch operations are already available there, so the move needs no intervening single-threaded validation changes and leaves the final tree unchanged.


Link

[suggestion] · Integration commit carries a separate sigcache.cpp cleanup

224c44bb revisits sigcache.cpp only to replace a newly added temporary and push_back with emplace_back, adding a behavior-neutral file diff to the queue/validation integration change.

Location: src/script/sigcache.cpp:104 at 224c44bb7fc4 (commit) (commit).

Details and suggested fix

Put the final m_collected_signatures.emplace_back(sig64, pubkey, sighash) form directly into 353b8c44965d9b0da8646d39cced485e84b577ba, which introduces CollectingSignatureChecker. The queue/validation integration commit 224c44bb7fc4160fcd0bfaefa67166a63d7ebbd5 changes only those two lines in this file. SchnorrSignatureToVerify already exists from a877e5f305d5e01fe9ef9809875e6bfc50ca6ca4, so no later type dependency requires delaying the cleanup. Folding it into the introducing commit removes sigcache.cpp entirely from the integration diff while preserving behavior and the final tree.


Coverage details