secp256k1 source research and implementation scope

The fresh-key factory candidate accepts all unknown keys in the same call and shares one field inversion across their odd-multiple tables. The bounded FreshEcdsaWorkspace<N> owns seven projectives and prefix fields per key, sixteen native affine output entries per key, and decoded public equations. Strict SEC133/65 decoding occurs in the call. Q is already affine, so the 700 nontrivial Z coordinates for 100 keys produce all 800 odd multiples with one inverse; beta images are derived with the existing constant. Client inverse hints still satisfy an independently checked s*w=1 for every record. This shares coordinate normalization, never signature equations or acceptance probabilities. The Native/Jacobian/Window8 modes reuse their existing public point arithmetic.

Every invocation invalidates previous tables before parsing input, including capacity/error exits. Reusing scratch therefore provides no prior-call key or proof cache. Admission validates all records before producing verdicts; a malformed row returns its index with no verdict writes. A caller that needs per-record errors must explicitly perform and charge a fallback, not report an atomic admission error as N completed verifications. Expensive changed-digest invalid/mixed cohorts still evaluate every independent equation. Native tests cover changed distinct cohorts, both SEC1 formats, 306 saved oracle rows, both S policies, wrong hints, error recovery, capacity and table lifetime.

Scratch allocation is input-independent, but its constructor/copies/cleanup belong inside any endpoint that creates the workspace per call. A benchmark with an already allocated caller workspace must label that scope separately. The fixed-array factory intentionally retains projectives and native outputs simultaneously; its exact target-dependent byte count is exposed. Packed or streaming phase layouts can be compared separately without changing the math. The existing raw direct-projective path is a useful fresh control because it builds Q odd multiples without affine normalization. No source-level cost estimate substitutes for matched IC whole-call/body/page evidence.

The reusable implementation is algo/secp256k1. The benchmark cases stage synthetic deterministic keys, messages, signatures, parsed points and prepared tables before a later physical measurement message. Benchmark keys are public test material, never application credentials. No neighboring repository is modified.

The direct baseline is the reviewed Showtime crypto/ecdsa extraction from Motoko compute plugins revision d0c568136ddcdcb14dd6746020156508572498f1. Its pinned RustCrypto k256 0.13.4 vendor includes public-only GLV decomposition, width-five wNAF, an immutable generator table, mixed addition, a 512-byte prepared public table and an inversion-free final homogeneous-coordinate check. Wasm64 uses the existing 10x26 coordinate backend to avoid software-expanded u128 products. Generic secret multiplication and signing retain constant-time paths.

Local scalar verification originally uses Stein binary GCD. The new variants provide a fixed addition-chain inverse control, established Bernstein-Yang safegcd through pinned crypto-bigint 0.6.1, a supplied checked inverse hint and exact independent verification sharing one S inversion. Hint inputs remain untrusted until s*w == 1; normal and hinted verification use the same explicit low-S policy. The batch implementation evaluates each row's own equation and does not depend on probabilistic cancellation bounds.

The standard API preserves strict SEC1 and compact ECDSA encodings. The distinct r || w and R33 || s32 experiment types have no implicit conversion at public verification boundaries. Inversion is a bijection on nonzero scalars, but inverse encoding loses cheap low-S checking. Explicit-R signatures validate their curve point and check sR=zG+rQ. Their single-signature implementations are controls, not evidence of a batch speedup or a new standardized scheme.

BIP340 uses even-Y key lifting, canonical input bounds including legal zero components, tagged challenge hashing and final identity/parity/X checks. The existing plugin corrected rare upstream nonce-reduction/zero-S boundary errors; those vendor corrections remain intact. The inherited constant-time signer and factory-created signing context are reused without exposing an arbitrary cached secret/public pair importer.

Measurement interpretation

Cases cover key derivation, compressed/uncompressed parse, fresh/staged signing, ordinary/reference/parsed/prepared/hinted/safegcd verification, table preparation, scalar inversion diagnostics, typed native-affine prepared-table candidates, exact batch inversion, BIP340 and both explicit experimental encodings. Single-record cases return one logical operation per run. Exact batch inversion returns the cohort size from operations_per_run, so the engine invokes it once rather than accidentally doing N squared work. Its workspace is bounded at 128 validated rows plus scalar-prefix products. Larger cohorts use consecutive tiles without dropping work: 500 rows run as 128 + 128 + 128 + 116 with four inversions, while operations_per_run() remains 500. All secp fixtures admit up to 1,024 records. BatchWorkspace::storage_bytes() reports target-dependent scratch excluding inputs, output and the temporary 128-row array of borrowed slice descriptors. This bounds scratch independently of the cohort size and trades additional inversions for lower retained memory.

Every complete signature, key, scalar inverse, table result or verification verdict is black-boxed and retained for checking outside the algorithm interval. Rows are selected by the engine's iteration index. Invalid and mixed verification patterns alter a public digest/message without making scalars malformed, so the complete equation still executes. Empty BIP340 negative messages become a different nonempty message. Key derivation, parsing, signing and inversion have no invalid-message concept: they keep valid inputs for every Pattern, and exact outputs are checked. Preparation cases check the resulting tables against the pattern's verification equation after timing.

distinct=false repeats one raw key across row fixtures; distinct=true uses different keys. Staged parsed/prepared/signing contexts retain one key for repeated-key fixtures and one context per distinct key otherwise, with construction in setup. This is fixture reuse, not an application registration or key-rotation cache. The table-preparation cases measure its cost explicitly. Whole-call instruction and page evidence must record this retained layout and preparation separately.

Historical Showtime wasm64 controls measured approximately 2.28M body instructions for fresh direct ECDSA and 2.03M for prepared verification. Those figures belong to their exact historical SDK, artifact, fixtures and PocketIC; they are not measurements of this extraction. The historical scratch16 variant saved only 0.143% of full guest instructions and no charged regions; scratch8 reduced explicit scratch but regressed instructions. Arithmetic changes require new matched IC measurements, including N=1, fresh keys, prepared reuse, rejected equations, query/update, all added hint/witness bytes and setup costs. Body-counter diagnostics and whole-call totals answer different questions. Do not add page charges twice or claim subtracting them is an observed total.

The native prepared-table candidate stores sixteen target-native affine points, including endomorphism images. Its verified factory takes a validated public point, batch-normalizes the same eight odd multiples as the canonical control, and derives the existing beta images once. The joint multiplication borrows these points directly: no per-call canonical decoding, table reconstruction or length assertion is needed. Both standard and hinted candidate verifiers use the same low-S policy and final homogeneous comparison. This retains more memory than 512 canonical bytes; actual table bytes and whole-call page costs must be compared before changing the default. The 306-case oracle corpus, malformed inputs and low/high-S/hint policy checks cover both paths, including the combined native-table/safegcd variant. The existing default inverse remains Stein until new multikey/batch IC measurements select otherwise.

The same opaque native table now has a separate BIP340 factory accepting only the even-Y x-only lift. Canonical/native/direct BIP340 table choices remain separately measurable. An independent prepared challenge context clones the existing RustCrypto SHA256 state after the fixed 64-byte challenge-tag prefix. It preserves the prefix byte count as well as the chaining value, removes one compression per verification, and accepts no arbitrary state or alternate tag. The prefix is public and independent of the key, so one boxed context is staged for the whole fixture. Cases isolate direct+midstate, canonical+midstate, native alone and native+midstate. Official BIP340 vectors and generated public test keys/messages exercise direct/native/prefix parity, SHA padding boundaries, malformed ranges and reuse after rejected signatures.

Absent table kinds occupy empty vectors rather than inline per-key optional tables; a prepared challenge is Option<Box<_>>. Explicit table-preparation cases alone reserve table-sized output slots because every complete output must remain available for checking after the timer. Verification cases stage one context for repeated-key fixtures and one per distinct key.

Remaining variants

The new verify-native-hint-jacobian case keeps ordinary compact ECDSA and its checked inverse hint. It borrows the same sixteen affine points and reuses the same GLV/width-five digit recoder. A separate public-only accumulator uses EFD dbl-2009-l (2 multiplications and 5 squares) and madd-2004-hmv (8 multiplications and 3 squares), explicitly handling infinity, equal points and opposite points. Its coordinate invariant is x=X/Z², y=Y/Z³; the final equation tests X=rZ² and, only when r+n<p, X=(r+n)Z². Lazy-reduction magnitude bounds are documented beside the formulas. None of these methods accept secret scalars through a signing path, and existing complete homogeneous arithmetic is unchanged. This is new local formula code requiring qualification, not a claim of an audited implementation.

The canonical baseline's raw Wasm already specializes symmetric field squares: the 10x26 multiplication function has 111 i64 multiplication operators versus 66 in the square function. Its source uses an always-inlined inner multiply specifically to permit that optimization. No duplicate squaring kernel is introduced on the assumption that source-level mul_inner(self) costs the same as a general multiplication. Static operator counts motivate the candidate; only matched IC counters qualify its actual cost.

The primary next cohort is 100 actual verifications in one physical call. Existing secp fixtures with distinct=false use one signer but vary the message, digest and signature by row; distinct=true varies signers as well. At 256-byte messages these provide one-key/distinct-signature and many-key populations. Exact tuple repetition is a separately labeled fixture and never enables proof or result caching. The arithmetic adapter still reports one logical operation per scalar invocation, so the engine performs all 100 equations, retains their verdicts and checks them after timing.

Wider immutable G windows may reduce additions but increase code/static first touch and Wasm size. Variable-key width five and complete mixed formulas are the current known baseline. No wider table is selected without measurements.

The separate verify-native-hint-jacobian-window8 candidate now widens only the shared G and beta*G streams. It retains the original sixteen-point per-key table and Q width-five recoder. The frozen shared table has 64 odd G multiples and their 64 beta images. A local deterministic Python generator checks all points, generator order and the beta/lambda relation and reproduces the checked-in table byte-for-byte. No runtime table construction or lazy cache is introduced. Its extra static bytes can open an additional 64 KiB charging region even when the per-key table size is unchanged; compare raw whole-call/page/body evidence for N=1 and primary N=100 rather than assigning a byte-based synthetic fee.

The new G recoder writes directly into its final digit row and uses a u16 window so 255+1 is representable. Native tests compile that exact private source to check reconstruction, signed odd-digit bounds, eight-bit spacing, zero, 64/128-bit carries and both signs. All 128 frozen table entries are exercised in both signs against complete arithmetic, together with full-width coefficient pairs, the 306 saved oracle rows including X>=n, RFC6979 S policies and bad-hint validation. Native correctness does not establish IC instruction savings.

A scalar32 experiment requires a real eight-u32 representation. Merely selecting the existing wide32.rs on wasm64 is incorrect because crypto-bigint's U256 still contains four u64 words. Coordinate-field 10x26 selection does not solve that separate scalar representation problem.

An optimized arbitrary-size public MSM is not implemented. BIP340 specifies transcript-seeded CSPRNG coefficients and weighted MSM; explicit-R ECDSA can use an analogous weighted point equation after full validation. Naive deterministic coefficient-one aggregation admits cancellation attacks. Neither experiment is exposed as a batch verifier until its coefficients, MSM, input binding, capacity and adversarial vectors have been independently qualified.

libsecp256k1 is a useful established C control: Jacobian/mixed formulas, safegcd, GLV/wNAF and wider generator precomputation. The cached Rust bindings and current build script special-case wasm32, so wasm64 headers, compiler flags and ABI need qualification before treating it as a drop-in. Safegcd is reused from the pinned crate; the separate Jacobian candidate above is newly authored public arithmetic.

Primary sources

Local provenance records exact imported files. Source review, native tests, Wasm compilation and IC performance qualification are separate evidence scopes; passing one does not establish the others or constitute an external crypto audit.