Repository navigation
xark 0.3.0
Circuits that changed
Every circuit. 0.3 compiles circuits with a new frontend (below), so every circuit built with 0.2 changes: rebuild and make new keys. Beyond that, these gadgets now check more:
xark-ed25519andxark-secp256k1: points must have canonical coordinates (each< p), so a point can't be given in two forms. About +1,000 constraints for an EdDSA verify and +560 for an ECDSA verify.xark-secp256r1: the same check, +3 constraints.xark-bignum:mod_neggave a wrong result for some inputs at full 256-bit width;mod_addcould overflow;mod_neg(0)is fixed.xark-bignum:mod_mul,mul_divmodandsub2derive their boundm − 1fromm(#62), and a typedBignumorfp!input range-checks its limbs when it's read (#63). Thebignum,bignum_ops,bignum_wide,fp_mul,sub2andis_lt_checkexamples change;bignum_wide,fp_mul,sub2andis_lt_checknow range-check the limbs they take as[Field; N]. The curve gadgets don't change.grumpkin_nova_foldtakes its inputs grouped by instance.- A
Time/Daysinput is checked to its range of steps, not just its bit width (Days<2024, 2024>is 366 days in 9 bits, and 366–511 were accepted):zkycchanges.scalar_rangechanges only in row order. - The bit and hash gadgets take fewer rows, each proven sound in Lean over the exact rows it emits (
formal/): XOR and OR with a constant fold to a linear form,to_bitscomputes bit 0 linearly,xor3/maj3/chi/chare one row each,reducehas tight carries, and a Merkle level swaps with one product. Every example using SHA-256, Keccak, BLAKE, AES, Merkle orto_bitschanges (27 of 71). - ECDSA on secp256k1 and P-256, and EdDSA on Ed25519, are rewritten around proven gadgets: non-native multiplication by pseudo-Mersenne certificates over 8×32-bit limbs, fused double-and-add over signed digits, and fake GLV (ePrint 2025/933) with a fixed-base comb, each gadget proven sound over its rows. Fewer rows (
examples/secp256k1_ecdsais 227,168 inxark inspect); the hintedR.xis checked canonical (< p), and Ed25519 keeps the cofactored check of RFC 8032. Keys for the ECDSA and EdDSA examples must be made again. - Grumpkin scalar multiplication (
scalar_mul,wide_scalar_mul,multi_scalar_mul) and the Pedersen hash are rewritten as proven gadgets: one fused incomplete step per bit over signed digits, and windowed lookups from constant tables for Pedersen (3,318 → 772 rows).scalar_mulpins its own bits boolean. The seven Grumpkin and Pedersen examples change. - The AES S-box is a select over its constant 256-byte table (687 → 34 rows), proven to output
S(x)for every byte:aesis 145,944 → 15,360 rows,aes256_gcm931,512 → 209,883. The five AES examples change.
Highlights
- Stable Rust only. Circuits compile with any stable Rust from 1.89, and are identical on every supported version. The pinned-nightly
xark-rustcis gone. - Typed inputs. One
xark::Inputtrait, implemented by#[input]or by hand, and everyday types (Timestamp,Days<FROM, TO>,Text,Choice<E>,Bitfield<E>,Country), in the circuit, in tests, on the command line and in clients. - Typed TypeScript clients.
xark clientgenerates a client that proves and verifies through xark-wasm, with the circuit's types and its Rust constructors. - A streaming Groth16 prover (
xark-groth16) that never holds the whole constraint system or key in memory, with arkworks' Groth16 removed. - Failing checks name their source line, everywhere inputs are checked.
- Gadgets proven in Lean over the rows they emit. 63 gadget templates (bits, hashes, AES, ECDSA, EdDSA, Grumpkin, Pedersen) are exported from the compiler and proven sound in
formal/; CI fails when the code stops emitting a proven template or a production call isn't covered, and the secp256k1 ECDSA circuit is composed in Lean from its calls, its rows hashed against the compiler's. Every minimizer run on the keyed path writes a certificate a Lean checker accepts, proven to mean the keyed rows have the same solutions and eliminate no input.
Changed
The npm package
@blueshift-gg/xark. The JS runtime is published as@blueshift-gg/xark; imports move from@blueshift-gg/xark-wasm(and its/client,/pool,/streamsubpaths) to the same subpaths of the new name.@blueshift-gg/xark-wasm@0.2.xstays published.
The toolchain and the frontend
- Stable Rust only. A circuit crate is compiled to wasm by the ambient stable
cargo(1.89 or later, for the CLI too) and lowered by the newxark-frontend. The pinned-nightly MIR compilerxark-rustcis removed. A circuit's R1CS is the same on every supported Rust version (cargo xtask digestschecks every example on 1.89, stable and beta in CI). - An integer input's range check is reused. Its bits serve a later
to_bits, bitwise operation or signed comparison of the input, so comparing twoi64(orTimestamp) inputs costs what comparing twou64s does (68 constraints, not 202). - What compiles is documented from the new frontend in docs/subset.md. Branches on witness values, small witness indices and short witness-bounded loops work. Constructs that can't compile soundly (a witness-sized
memory.grow, a circuit input declared inside a witness branch, a loop whose length depends on a witness and isn't provably short) are refused with a message naming the source line. - Circuit crates can use
std.#![cfg_attr(xark, no_std)]is no longer needed (xark initleaves it out): circuit code can usestdand crates that assume it.xarkand the gadgets stayno_stdlibraries, and the on-chain verifier doesn't depend on any of this. - Circuit code runs natively on the host. In a host build the
Fieldoperations compute instead of panicking: arithmetic on BN254, comparisons, and every hint as the solver computes it. A failedrequire/require_eqpanics at the caller's line, andwitness_begin/witness_endregions skip their checks as a circuit does. So a helper such asid.commitment(), or a whole gadget (xark_sha256::sha256, ECDSAverify), runs in tests and services. Only hint-lessField::advice()has no host value. - Packing narrow values into a word is free. An
|(or^) of values whose bits can't overlap (c << 16 | b << 8 | a) is their sum, and reading a piece back (>>, a mask,/or%by a power of two,as u8, a byte through memory) takes it off that sum instead of splitting the word into bits: such a round trip on threeu8inputs costs 28 constraints rather than 151. - Failing checks name their source line.
xark buildwritessources.json(which statement each constraint came from), and inputs that fail a check report that statement in Rust tests,xark prove/check, xark-wasm and clients:src/lib.rs:96:20 id.nationality.require_in(policy.allowed);rather than a constraint number. cargo testrebuilds a stale circuit, one older than any local source it came from (path-dependency gadgets andxarkincluded, from cargo's dep-info), instead of testing the previous build, and one built over another field (--field). Without anxarkto rebuild with, it warns (for another field, the tests fail, saying why).
Inputs
- One
Inputtrait for every circuit input. A type is a circuit input when it implementsxark::Input: itsTYPE(how clients see it, built from a fixed set of standard types) andread/writeof its field elements. The one impl serves the circuit build and the host (the prover's inputs,to_fields()for hashing, decoding public inputs), so a hand-written impl is a few lines with nocfgs.#[input]implements it for a struct (#[input(number(bits = B))]or#[input(bytes)]give it a standard encoding),xark::Enumfor a fieldless enum, and client functions for animplblock. It derivesClone,CopyandDebug(andPartialEq,Eqon an enum) unless listed;#[input(no_derive)]leaves them to you. It replaces#[derive(CircuitInput)],#[derive(Transparent)]andNativeInput. - Everyday input types:
Text,Choice<E>(one variant of an enum) andBitfield<E>(a set of them), each one field, with natural forms in tests ("A1938274",[US, GB]),--inputsand clients, and the ISO 3166Countryenum. Each compares withrequire_eqand==, as does an#[input]struct. Checks are sized to the enum: a set splits into one bit per variant, andChoice::require_in(set)costs about 510 constraints overCountry.Text::parseand the time types'parsereturn aResultfor input you didn't write. - Times, sized to their range.
Timestampis any moment as Unix seconds (ani64, as Solana'sClockand a JSDatehold it).Time<UNIT, FROM, TO>is a moment from the start of yearFROMto the end ofTOin wholeUNIT-second steps (SECOND…WEEK), andDays<FROM, TO>its days: in the circuit an unsigned integer just wide enough for the range (Days<1900, 2100>is 17 bits), range-checked on entry and compared at that width. A moment inside a step is that step (rounded down, as Unix time does), and one outside the range is refused with the range named. Both read"YYYY-MM-DD", an ISO 8601 date-time with a zone, or Unix seconds, are a JSDatein a generated client, and convert on the host (Days::from_timestamp,years_before), on chain too (const fns,no_std). Leap years count where a date is read or written; every day is 86,400 seconds.examples/zkycuses them: a privateIdentitychecked against a publicPolicybuilt withPolicy::default().on(today).min_age(18).worth_at_least(500_000). boolinputs. Aboolparameter or field is one field element, checked to be 0 or 1, usable as a condition and a value.- Struct fields are packed. An
#[input]struct's consecutive fields of known width (uN,iN,bool, aTime/DaysorTimestamp, aChoiceand aBitfield) share one field element, in declaration order, the first in its lowest bits, until the next would pass 253 bits. In the circuit the element is split into its bits once, which is also every field's range check (so a packedChoiceorDaysis range-checked on entry), and each field reads its own bits. AField, aText, an array, a nested struct or a field marked#[unpacked]keeps its own leaves and starts a new run, and a field with no packable neighbour stays as it is. Fewer leaves means fewer public inputs (fewer multiplications for the verifier, less instruction data, a smaller verifying key) and fewer hash rounds overto_fields(), which returns the packed elements: order a struct's fields so that narrow ones sit together. The packed element is named by its fields (policy.{born_by,min_net_worth}) andschema.jsonrecords each field's bits, so clients,--inputsand decoded public inputs keep every field by name. A hand-writtenInputimpl packs only what it declares withMember::packedand reads and writes withReader::member/Writer::member. - Signed integer inputs. An
i8…i128parameter or field is one field element holding its two's complement (-1i8is255), range-checked to its width like auN. Clients and--inputstake a negative number (or a"-…"string), and a generated client types itI8…I128. schema.json.xark buildwrites every input's name, visibility and type, and the public inputs in proof order. A build fails if one type name would stand for two different types, since clients look types up by name.- Natural input forms, read one way.
xark prove/check/verify --inputsread every value againstschema.json, in its natural form: a date, a variant name, an Ed25519 key or a hash as0x-hex bytes (decompressed for you), a scalar as a number. A missingschema.jsonasks forxark buildinstead of guessing how a value splits into leaves.xark setup's next step shows a template in these forms (or writesinputs.example.json), andxark inspectlists inputs by name and type. - Bytes are little-endian where they're an integer. A wide integer (a limbed number: a scalar, a bignum) given as a list of bytes is read little-endian, like
Field::from_le_bytes. A hex string is a number, most significant digit first. - Field inputs must be field elements. A
Fieldinput outside0 <= x < pis rejected instead of silently reduced, everywhere inputs are read. A value that wraps proves a different number than the one written (a 256-bit hash passed as aField).xark_prover::hex_to_field_decimalis replaced byfield_input_decimal. - Typed host inputs. The validator
#[circuit]generates (and its<Fn>Inputsstruct) takes typed values: aFieldanything that converts (cube(3, 27), anark_bn254::Fr, a decimal or0x-hex string), a gadget type its natural form. A number string reads the same everywhere (--inputs, the host validator, a client'sField): decimal digits or0x/0Xhex, nothing else (no+or_). Input structs can hold gadget types, and parameters can be arrays of them. - One dependency per circuit crate.
xarkre-exports the prover asxark::prover(host builds), so a circuit crate needs onlyxark. - A constant
Field(Field::constant,from_le_bytes,from_be_bytes) is reduced mod p when made, soto_decimal()gives the value the circuit sees.
TypeScript clients
xark client now generates a typed client; in 0.2 it scaffolded a snarkjs verification starter, and the xark-client npm package is removed.
- What it writes: one file,
<circuit>.ts, with the circuit'sschema.jsoninlined, so Node, a bundler and tsc all run it with no project settings, where-osays: a file, or a directory to write it in. A tuple struct's fields ("0") and raw identifiers (r#type, namedtype) give a client that compiles. Names keep underscores around them (_reserved); a field JavaScript can't hold (__proto__, orconstructoron a struct with Rust methods) is an error naming it. The types read like the circuit's: interfaces for input structs, enums as constants and a type (Country.USor"US";"XX"doesn't compile), named aliases for xark's standard types (Text,U8…U128,I8…I128; a time is aDate), and arrays of up to 16 elements as tuples, so a wrong length doesn't compile. - Proving and verifying:
Zkyc.prover(source)andZkyc.verifier(source), from a URL serving the build output or its bytes, each with only the methods it can run. They load xark-wasm themselves (node, web or workerd;{ wasm }passes your own).{ pool }proves on a worker pool from@blueshift-gg/xark/pool.provereturns aProof:toBytes()is the proof as an exported Solana verifier reads it (256 bytes,Proof::from_le_byteson chain), andtoBytesCompressed()is half the size;verifier.verify(bytes, required)reads either and checks it proves the public inputs you require. A malformed verifying key fails when the verifier is made. - The circuit's Rust in TypeScript:
#[input]on animplmakes its methods client functions, from any crate; on a trait'simpltoo (impl Default for PolicygivesPolicy.default()). Parameters may beSelfor&T; a generic function is refused where it's written, since a client couldn't choose its type.xark clientbuilds the crate's host code asclient.wasm, soPolicy.default().on(day).minAge(18)andIdentity.commitment(id)run the crate's Rust, chaining as in Rust. A method named like a field staysPolicy.method(value, …), andxark clientwarns. A Rust panic is an exception with its message.await Zkyc.ready(url)loadsclient.wasmon its own. - Bytes are a
Uint8Array, given and decoded;fromHexandtoHex(exported by every client) convert hex. - Field elements are a
Fieldclass:new Field(x)takes abigint, a safe integer, a decimal or0x-hex string, little-endian bytes (Field.fromBeBytesfor big-endian) or anotherField, and throws unless it's below the modulus. A field input (FieldInput) also takes a plain integer, checked the same way, and a number past 2^53 is refused rather than rounded. - One proof format for Solana and everywhere else: a client's
toBytes()is byte for byte whatxark exportmakes of the same proof, andxark verify(--proof) and xark-wasm'sverifyread a proof in either form (xark-wasm'ssolanaProofconverts; the encoders and the checked decoder arexark_groth16::solana, re-exported fromxark_backend::solana). - Pinning a prover:
Circuit.digestis the circuit the client was generated from, andprover(from, { digest })refuses acircuit.xbcwith another one (xark-wasm'scircuitDigestcomputes it). A verifier pins its verifying key:verifier(from, { keyHash })refuses avk.binwith another sha256, whichxark setupandxark ceremony finalizeprint and record inmetadata.json(verifying_key_sha256). - Loading and proving faster: a circuit fetches
client.wasmonce, however many provers and verifiers are made from its URL, andprover.preload()keeps the proving key decoded (about 2.2×pk.binin memory), so each proof skips decoding it: about half the proving time of a small circuit. xark-wasm'sProvingSessionis that decoded circuit and key, one per prover. - Typed errors: a refused input throws an
InputErrorwith itspathin the caller's names (id.netWorth, or a Rust function'sallowed), and inputs that fail a check aCheckFailedwith the statement'ssite(file, line, column, text, the functions it called into). A JSSetgoes as a list; a value that can't be sent (aMap, anArrayBuffer) is anInputErrortoo, not{}.verifyisfalsefor a bad proof and throws for public inputs that don't fit. - Hashing as the circuit does:
prover.fields("Identity", id)gives a value's field elements andprover.poseidon2(fields)hashes them. - The shared code is xark-wasm's
@blueshift-gg/xark/client, and every value is encoded by one Rust codec,xark-schema, shared with the CLI, so a client andxark prove --inputscan't disagree.
Proving and verifying
- Soundness is checked by tests, not by
xark prove.Circuit::check, which every#[circuit]validator calls, now also searches for witness variables the inputs leave free, so a circuit's tests fail on a "forgot to constrain a hint" bug that used to pass them.check_satisfiedchecks satisfaction only.xark proveonly solves, proves and verifies the proof against the key: it no longer refuses an under-constrained circuit (xark check --inputsstill runs the search). Proving ed25519 on an M3 Max takes 0.60 → 0.48 s. - Faster setup and proving. Setup multiplies fixed bases with signed windows and batched affine additions, and keeps no extra copy of the circuit while it picks a key form; proving solves witnesses from the compiled templates, builds the row source while the witness solves, and computes
hwhile the witness MSMs stream. On one 14-core machine: ed25519 setup 6.9 → 3.9 s and prove 8.6 → 6.8 s; secp256k1_ecdsa setup 4.9 → 2.9 s; aes256_gcm setup peak 3.1 → 2.8 GB. Keys, proofs and the keyed rows are unchanged. - A faster witness solve. Bits skip the field multiply, a non-native inverse is a 256-bit safegcd, and the hint program compiles in parallel. Proving on an M3 Max: secp256k1_ecdsa 0.38 → 0.28 s, secp256r1_ecdsa 0.54 → 0.38 s, ed25519 0.48 → 0.41 s. Witnesses, keys and proofs are unchanged.
- A streaming Groth16 prover.
xark proveusesxark-groth16, which never holds the whole constraint system or proving key in memory, always fromcircuit.xbc. Keys and proofs are compatible with the arkworks path (byte-identical for the same randomness), and existing key and proof files load. - arkworks' Groth16 removed.
xark-groth16owns key generation, proving, verification and theProof/VerifyingKey/ProvingKeytypes; arkworks is only the BN254 arithmetic.xark_backend::{setup, prove, stream_prove}are gone,xark_backend::ptau::setup_from_ptautakes a constraint source,xark_prover::XarkCircuitno longer implements arkworks' circuit trait, and verification rejects a wrong number of public inputs. - Proving from Rust:
xark_prover::circuit("name").prove(inputs)proves with the built circuit and itspk.binand returns the same bytesxark provewrites;prove_with_keytakes another key, andprove_devmakes throwaway keys.prove_only,prove_and_verifyandcheck_fieldsare no longer public. - The on-chain verifier skips the scalar multiplication for public inputs of 0, 1 or up to 128: booleans, enum values and counts verify cheaper (up to 38% less compute when all are small, about 0.5% more when all are large). The reference program's hash changes. The typed
Verifier::verifydoes the same asverify_instruction_datanow: it was the dearer of the two (78,538 against 77,043 CU for one input of 81), and is now the cheaper (76,621). - xark-wasm:
public_inputs_to_snarkjsbecomesdecode_public_inputs;SchemaandVerifyingKeyparse a schema or key once.
The CLI
xark exportwrites the verifier crate to<crate>/<name>-verifier/by default, named<name>-verifier, instead oftarget/xark/<name>/verifier, a crate namedverifierthat git ignored andcargo cleandeleted. It is a nested crate with its own[workspace], so the circuit crate neither builds nor packages it.--outstill chooses; a build output outside a crate'starget/keepsverifier/inside it.xark exporttakes any key and says how it was made, so--allow-insecureis gone. A key from OS randomness is a single-party trusted setup, sound unless whoever ran setup kept the randomness; a--deterministic-rngkey can be forged by anyone with the seed, and export warns about it. The crate'sSETUPconstant and README carry it:seeded,single-party,ceremony(two or more contributors; a ceremony of one issingle-party) orunknown, for a deploy script to check.xark setuphas no--insecure-dev-mode: without a.ptau, it makes the key from the machine's randomness, as it already did by default.--deterministic-rngand--domain smoothwork on their own, skip an auto-detected.ptau, and are refused with--ptau-file. The key'smetadata.jsonsays"setup_mode": "single-party".xark buildreuses an unchanged build: when thexarkbinary, the options, theXARK_*variables, the compiled module and every source file are the same as for the outputs intarget/xark/<name>/(and those are untouched), it says so and skips lowering.xark buildprints the circuit digest (a fingerprint of the R1CS, written totarget/xark/<name>/digest) and the three source lines that cost the most constraints.xark profileends with a breakdown by kind of constraint, saying what each is and how to have fewer, and the costliest functions including what they call (commitment → hash → perm);--jsoncarries both.--htmlwritesprofile.html: the same breakdown, the costliest lines opening onto their call chains, and the circuit's source with each line shaded by what it costs.--field(xark build,xark profile) takesbn254or a prime modulus in decimal; anything else (a typo, a composite) is an error before building. A build over another field suggestsxark profilenext, andsetup,proveandclientrebuild it for BN254 (keys, proofs and clients are BN254's), or refuse one built elsewhere (--out);inspectreads it as built.xark cleanalso removes the wasm build caches (target/xark-wasm, andtarget/xark-clientfromxark client).- Builds are reused while current, and never used stale.
xark check --inputs,xark testandxark profileskip their build when no source of the circuit has changed since (and the field andxarkare the same).xark prove,xark setup,xark clientandxark inspectbuild a circuit that's missing, or rebuild one older than its source, saying which file changed (so a proof or key is never of the old circuit;provethen asks forxark setupif the circuit changed), andxark exportwarns that its keys may be for an older circuit. --outis a directory forxark setup,xark proveandxark export, with a warning when it isn't empty (prove --outwas the proof's path, withpublic_inputs.binput beside it;exportstill never replaces aCargo.tomlorsrc/lib.rsit didn't write). Their next steps point at what they wrote there:--proving-key <dir>/pk.binaftersetup,--proofand--public-inputs(and the key beside a--proving-key) afterprove.- A key fits every build of its circuit. Keys record the circuit digest (
metadata.json'sdigest) besidecircuit.xbc's hash.prove,verifyandexportaccept a key from another build with the same digest, such as the same circuit compiled by another Rust version (which can store repeats differently, as 1.89 does for the Ed25519 and P-256 examples), instead of asking for a newxark setup. A minimized key'sr1cs.streamis marked with the digest too, soprovedoesn't rebuild its rows for another build and xark-wasm doesn't refuse them.xark inspectshows both fingerprints.
Added
-
Bignumup to 32 limbs (2752 bits at 86-bit limbs), enough for RSA-2048 (24 limbs) and RSA-2560. Above 16 limbs a multiply's carries get one more bit of headroom (about 230 constraints per 24-limb multiply); up to 16 limbs the rows are unchanged.xark_sha256::compressandh0are public, for messages padded by the caller. Thebignum_wideexample is a 24-limbmod_mul. -
Field::to_bits_canonical(): the 254 bits of the canonical representative (in[0, r)), with a comparison againstr − 1, so a value has one decomposition. -
xark_merkle::cond_swap(bit, a, b): a conditional swap in one product. -
require_eqof two different constants (outside a witness branch) is a compile error, andto_bitsof more than 253 bits is refused when it's built. -
<Fn>Inputs::to_json(), generated by#[circuit]: inputs built in Rust as the JSONxark prove --inputstakes, named as declared, likeinputs.example.json.xark prove --helpnow says--inputstakes both those names and the camelCase ones a TypeScript client uses. -
CircuitProof::to_solana_proof(),to_solana_public_inputs()andto_instruction_data(): a proof made in Rust as an exported Solana verifier reads it, the same bytes asxark export'sproof.solana.bin,public_inputs.solana.binandinstruction_data.bin. Getting them tookxark-groth16'ssolanamodule and decoding the proof by hand. -
Untyped integer literals mix with
Field:x * 2,2 * x,1 - x,x += 1,Field::from(2),0.into(),x == 0. They failed to build, because a literal is ani32and onlyu8..u128had impls;Field::from(2)built incargo testbut not inxark build. A negative literal is refused in both builds (write-Field::from(1u8)forp - 1). Ordered comparisons still need a typed literal (x < 5u32), whose type gives the bit width. -
Tests that the
alt_bn128syscalls and their Arkworks fallback reject a G1 point off the curve or with a coordinate>= q, and an off-subgroup G2 point in a pairing. The verifier relies on them for those checks, and nothing pinned it. -
bind(x), for a public input that only the verifier supplies (a recipient, a nonce): one constraint that any value satisfies, which ties the proof to the value it was made for. Leaving such an input unused is refused at build time, and the error now points tobindinstead ofrequire_eq.xark_hash::Hashgetsto_fields().examples/bound_recipientbinds a 32-byte address as two field elements, its 16-byte halves, so a program passes the address in unchanged. -
xark_verifier::verify_groth16_batch: several proofs of one circuit in a single pairing call. On chain each extra proof costs about 29k CU instead of 77k, so the compute limit allows about 46 proofs instead of 18. Needssolana-nostd-alt-bn1280.1.3. -
xark_poseidon2::native: the Poseidon2 permutation and hashes on the host, from the same code as the gadget. -
xark_prover::Circuit::check_satisfied(inputs):checkwithout its search for witness variables the inputs leave free.check_constrainedis the same ascheck. -
xark-schema,xark-frontendandxark-groth16are published. -
Exhaustive witness search (
xark_ir::witness_search), andcargo xtask diffteston every pull request: each example must accept exactly the inputs it should, with exactly one witness. It covers every example but the two ECDSA circuits (searched block by block), the whole ed25519 verify included. -
Every crate declares
rust-version = "1.89", and CI builds the workspace on 1.89. -
The slow CI checks (known-answer vectors, the EC gadget vectors, the example sweep, a publish rehearsal) run on every pull request instead of nightly. A weekly run keeps what can fail with no code change: the digest check on Rust stable and beta, and a long fuzz run. Generated clients and xark-wasm's streaming prover are tested in CI. Repository tasks are
cargo xtask(digests,difftest,publish, andwasm, which builds xark-wasm's packages);cargo xtask ciruns every check a pull request gets on your machine, side by side (about 7 minutes on 16 cores).
Removed
xark-aes'sgf_mul,gf_squareandgf_inv(the S-box no longer computesb²⁵⁴).xark-pedersen'sec_add,ec_doubleandscalar_mulhelpers (the hash no longer uses them;xark-grumpkinhas the point operations).xark-rustcand the pinned nightly.- snarkjs output:
snarkjs-verification_key.json,snarkjs-proof.json,snarkjs-public.json, and xark-wasm'sproof_to_snarkjs. Verify in JavaScript with xark-wasm or a generated client. - The proof bundle
<name>-<hash>.proof.json(it duplicatedproof.binandpublic_inputs.bin);xark proveprints the proof's SHA-256 fingerprint. --r1cs/--circuit(readingr1cs.json/circuit.json) fromprove,setup,verify,inspectandceremony init;prove --stream(it always streams);setup --cacheandr1cs.min.wcz.xark build --emit-jsonstill writes the JSON as a debugging view.xark export'sclient_call_example.rs(its dependencies didn't compile together); the generated README says how to sendinstruction_data.bin.- The
xark-clientnpm package.
Fixed
- A
TimeorDaysinput past the end of its range (a value its bits hold but no day of the type is) was accepted; it's refused as the input is read, packed or not. fp!'sassert_nonzerochecked only that the limbs weren't all zero, somitself, in range but not canonical, passed. It checks the value canonical first. The crate docs now say which results are canonical: onlymod_mul's andsub2's.- A
.ptauwhose τ is a root of unity of its size passed every admissibility check, and keys from it let any witness prove; it's refused. - Ed25519 points decode as RFC 8032 says:
x = 0with the sign bit set,y ≥ p, and aywith noxare refused, so each point has one encoding. - A ceremony finalized with no contributions kept the δ
initderives from the seed it records incircuit_meta.json, so anyone with the directory could forge proofs, yet it was marked production-safe and exported assingle-party(#66).xark ceremony finalizerefuses it; a key finalized before is labelledseeded, with a warning. blake2s_hash_one_blockandblake3_hash_one_blocktake the length as a const generic (::<LEN>, at most 64) and require the bytes past it to be zero; aFieldlength up to 2³² and any tail were accepted, so one message had many digests (#72).- The
--low-memoryspill file holds witness-derived data: on unix it's created readable by its owner only and unlinked at once, so it never outlives the process (#69). metadata.phase2_seed_hashis the SHA-256 of the seed's 32 bytes, not of the argument's text (#71).- A hostile
circuit.xbcfails to decode instead of aborting the process: counts are checked against the bytes left, variables and expansions are capped, a template call graph must be acyclic, and the panic hook is wrapped once rather than swapped around each decode, so overlapping decodes can't leave it removed (#64, #65, #68). - Verifying keys, proofs and public inputs over 64 MiB are refused before they're read, and a
.ptaufile's header is checked before it's read whole (#73, #70). - The
ec_incompleteexamples say why they need no on-curve check, andenforce_on_curvesays when it's optional (#67). - Two soundness holes in
xark-bignum's multiplication, each letting a prover make a valid proof of a wrong(a·b) mod min a circuit that takesmor the limbs from the prover. The curve gadgets were not affected.- The remainder's bound
m − 1was a separate argument nothing tied tom, so a larger one admittedr + m(#62).mod_mul,mul_divmod,sub2andBignum::{mul, sub2}now take onlymand derive the bound (minus_one). - A limb
≥ 2^BITSturned the column identity into a congruence mod BN254's field (#63). A typedBignumorfp!input now range-checks its limbs when it's read;fp!(unchecked_input …)skips that for code that checks its inputs itself, as the curve macros do. Limbs a circuit takes as[Field; N]still needrange_check_limbs, as the crate docs say.
- The remainder's bound
- Two soundness holes in
witness_begin()/witness_end()regions, each letting a prover make a valid proof of a statement the circuit rejects. No shipped circuit hit either (every digest is unchanged).- A
Fieldcomparison (==,!=,lt, …) made in a region lost its rows but was still trusted as a 0-or-1bool, so a branch or select on it after the region could take any value (#59). It now keeps its rows, as native integer ops do. - An arm of a witness branch that panicked inside a region left the region open, and every constraint after the branch was dropped (#58). Each arm now starts in the region state the branch was reached in, and a region that would straddle a branch is refused.
- A
- Malformed input is an error, not a panic: a row-file window index out of range, a malformed or wrongly laid out row stream, a proving key whose lengths overflow, and an MSM work item or accelerator result of the wrong size or with points that don't decode.
xarkfound a directory named*.ptauas a powers-of-tau file; it now looks at files only. A crate whosename = "…"line ends in a comment got the comment in its build directory's name.xark check --inputsrefused a circuit with witness-only scratch variables no constraint references (thesecp256k1_ecdsaexample's GLV decomposition) as under-constrained, whilexark checkpassed it. Such a variable changes no row and no output, so it is ignored, as the test harness already did.- The generated TypeScript client runs in Node's own ESM loader. It imported its schema as
./cube.schema, with no extension, which only a bundler resolves (Node:ERR_MODULE_NOT_FOUND). The schema is now inlined:xark clientwrites one file,<circuit>.ts, and no longer a<circuit>.schema.ts(an old one can be deleted). - Outside a browser, a client's
prover(from),verifier(from)andready(from)given a path or afile:URL say to pass the files' bytes, and show thereadFileSynccalls that do it. A path was refused as "relative, … pass an absolute URL" (even an absolute one), and afile:URL failed with "fetch failed". The runtime still only fetches, so it has no Node-only code. - The next steps
xark setupandxark clientprint can be followed as written:- setup always writes
inputs.example.jsonand says to replace its placeholders, instead of a runnable-looking--inputs '{"x": "<field>"}'that failed with "is not a decimal or 0x-hex number". A placeholder left in is now named: "still the placeholder "" frominputs.example.json". - client's
prover(…)hint and the generated client's docs point at the build's directory, named after the package, not the circuit (target/xark/my-cube/, nottarget/xark/cube/). - setup says how it made the key and where to find a multi-party ceremony.
- setup always writes
- A
#[circuit]array parameter's length may be aconst:Private<[Field; DEPTH]>failed with "array lengths must be integer literals". The circuit is the one the literal gives (examples/merklenow usesconst DEPTH, same digest). A generic entry (fn c<const N: usize>) is refused with a pointer to aconstor a generic helper; its generics used to be dropped silently. - Two
#[circuit]functions in one crate fail with "the crate has 2 #[circuit] functions (src/lib.rs:2, …); xark builds one circuit per crate", not a clash of the internal__xark_main/__XARK_ENTRYsymbols. The rule is now documented. - The
xarkcrate docs said^onFieldis exponentiation. It is boolean XOR, but it didn't check that its operands are 0 or 1, sox ^ Field::from(3u8)built and constrained3 - 5x, notx³. The example now usesx.pow(3)and is compiled as a doctest.^now checks each operand is a bit: free when the compiler already knows it is one (a bit ofto_bits, a XOR/AND/OR of bits, a constant 0 or 1), one row otherwise. A constant other than 0 or 1 is a build error that points touNorto_bitsfor bitwise XOR and topowfor a power.^=and^with an integer literal work too.Field::xorstays unchecked. No example's rows change. xark buildchecks that thecircuit.xbcit writes expands to exactly the circuit it lowered, and fails before writing anything if not. The check used to run only in xark's own tests, so a compaction bug on a user's circuit would have shipped silently. It adds 0–15% to a build (1.8s of 12s onsecp256r1_ecdsa).Field::to_bits::<N>of a constant takes the bits of its field element. A constant abovep/2(e.g.2^253 - 1) is stored as a negative integer, so it failed to build with "does not fit in N bits", and in a witness branch it ruled the branch out, so honest witnesses taking it were rejected.xark ceremony verifyandfinalizecheck the whole of the shipped keys, not just δ. They took any α, β, γ and public-input points, so a coordinator could shipγ = δ(which lets anyone prove anything) behind an honest contribution chain and have it markedproduction_safe. They now recompute the keysinitmade from the circuit, the.ptau(a new required--ptau-file) and the phase-2 seed, whichinitrecords incircuit_meta.json, and require the shipped keys to be those with only δ changed, by exactly the chain.baseline_delta_g1.binis checked against them too. A ceremony begun with an older xark (no recorded seed) can't be checked: start it again.- Native integer arithmetic inside a
witness_begin()/witness_end()region is constrained. It used to be free there likeFieldops, so an integer computed in the region was trusted afterwards with no range proof (au32quotient could be3⁻¹ mod p, proving1 = 3·q). And because the optimizer may merge integer code across the region's ends, a value recomputed after the region could be the region's unconstrained one. No example or gadget circuit changes. - A circuit with a
u128input beside a narrower integer input (struct { x: u8, z: u128 }, or two parameters) no longer crashes the build with "index out of bounds". proveStreamingwithoutoptions.r1csproves with the rows its key was made for, asprovedoes. Aminimizedkey (whichxark setuppicks for some circuits) used to fail there while plainproveworked. A push-driven proof (beginStreamingProof,proveFromStream) still needsr1csfor such a key.- A client function taking or returning a type alias (
type Address = Hash), or a path to a type (xark_hash::Hash), reaches the generated client. It used to be skipped with a warning, because the client read each type as written; it now reads the type'sInput::TYPE. xark exportno longer needs a proof. Without one, or with one made for another key, it writes the verifier crate without its self-test (and says why in the second case). A proof named with--proofmust still verify.xark-verifierno longer turns onstatic-syscallsby default. An SBPFv3 build is byte-identical without it (the v3 target sets it), and an SBPFv0 build now works with the default features, where it used to build a.sothe loader rejects.xark ceremony finalizerecords what the keys were made from, asxark setupdoes:num_constraints(was 0),ptau_source(was null),r1cs_formandqap_domain_size. A ceremony begun with an older xark still finalizes, without the constraint count or the.ptauname.- A circuit's generated test function (
zkyc_circuit(...)incargo test) looks for the build wherexark buildwrites it, under the package's name: a crate namedmy-circuit(asxark init my-circuitmakes it) said "has not been built". xark ceremony contribute,verifyandfinalizeon a directory that isn't a ceremony (a typo) say so and how to start one, instead of "No such file or directory (os error 2)"; a damaged ceremony key names the file.- Builds of one crate at once (an editor's
xark checkbesidexark buildin a terminal) no longer fail with "reading …/.wasm: No such file or directory": each holds the build directory until it has read its.wasm. require_eqaccepts an integer or decimal string on either side (require_eq(7u64, x)compiles).- The verifier docs no longer suggest
verify_strictmakes proof bytes safe as a replay or dedup key: Groth16 proofs are re-randomizable. They now say to put replay protection in the public inputs (a nullifier, nonce or signer). xark setupandxark ceremony contributewrite their files under temporary names and swap them in at the end, so an interruption can't leave a new dev key beside metadata marking it production-safe, or keys the ceremony's chain doesn't explain.ceremony contributerefuses a finalized ceremony, andceremony initrefuses a directory holding one unless given--force.xark export --outrefuses to overwrite files it didn't generate (it could replace your own crate'sCargo.tomlandsrc/lib.rs).xark build,test,checkandprofilefind the crate from inside it, as cargo does, and every command reports a mistyped path (no such directory: …) instead of building the current directory or passing it tocargo testas a filter.xark initrefuses namescargo newrefuses and suggests one that works, names the crate after the last path component, and makes a crate that passes its ownxark test.xark testpasses its arguments tocargo testas given (xark test . -- --list).xark provewith a proving key older than the circuit says to runxark setupagain, and a proof that fails its self-check says whether the inputs don't satisfy the circuit or the key is for another one (ProveError::Unsatisfied).- A missing input is named (
missing inputresult``), an out-of-rangeuNinput is named before solving, and a whole number written as a JSON float (`1e3`) is accepted. xark verifyreports a public-input count mismatch as such, and suggestsxark proveonly whenpublic_inputs.binis missing.- Errors in a circuit crate's tests show in an editor:
xark check --message-format=json(rust-analyzer's command) runscargo check --all-targetsfirst. xark doctorwarns when thexarkthatcargo testand rust-analyzer run is a different version, and says what it's for.xark cleanno longer follows symlinks and skipsnode_modules.- Solving a circuit multiplied out every
A·B = Crow, so two 500-term sides made 250,000 terms (a 12k-constraint Grumpkin circuit took 27 GB and 80 s); such rows are factored through a helper variable (0.7 GB, about 2 s). xark_test_harness::compile_filebuilds debug notes and variable names only when it writes the JSON views:grumpkin_ipa_fold's tests went from 34 GB and 106 s to 3.6 GB and 7 s.- A circuit importing
Fieldby name (use xark::{Field, …}) no longer gets anunused importwarning on host builds. - Smaller fixes to messages and
--help:xark ceremonydocuments its flags, default artifact paths are given astarget/xark/<name>/…, the builds that other commands run don't printxark build's next-step hint, andxark setupsays a key needs xark's provers only for a mixed-radix QAP domain.
What's Changed
- feat: circuit
bool— comparison operators and witnessif-mux lowering by @dhl in #8 - fix(dx): verifier loadability, export crate, and input UX by @L0STE in #10
- feat: xark-wasm by @dhl in #9
- formal: Lean proofs over the rows the compiler emits by @L0STE in #37
- deprecate nightly compiler by @deanmlittle in #31
- feat(bignum): Bignum up to 32 limbs (RSA-2048 and wider) by @lgalabru in #36
- Bump @vitest/mocker from 3.2.7 to 5.1.0 in /clients/check in the npm_and_yarn group across 1 directory by @dependabot[bot] in #46
- build: crates/lang and crates/macros track the workspace version by @dhl in #48
- Release workflow by @dhl in #50
- Prove check speedups by @deanmlittle in #53
- soundness in tests, not prove by @deanmlittle in #54
- CI in minutes: caches from master, every long job in shards, the soundness gate over compiled rows by @L0STE in #52
- a faster witness solve by @deanmlittle in #55
- docs for 0.3 by @deanmlittle in #56
- export takes any key and says how it was made by @deanmlittle in #57
- regions: comparisons keep their rows, and a branch arm can't leave one open by @deanmlittle in #60
- setup has no --insecure-dev-mode by @deanmlittle in #61
- fixes for the open soundness and robustness reports by @deanmlittle in #74
- inputs, fp! and setup: fixes from the pre-0.3 sweep by @deanmlittle in #75
New Contributors
- @deanmlittle made their first contribution in #31
- @lgalabru made their first contribution in #36
- @dependabot[bot] made their first contribution in #46
Full Changelog: https://github.com/blueshift-gg/xark/commits/v0.3.0