Skip to content
Writing

· 4 min read

Verifying Groth16 proofs on Solana, end to end

From a circom circuit to an Anchor program that checks the proof on-chain: the pipeline, the byte-level gotchas, and the design choices that keep a privacy protocol safe.

Jose Rai

Senior software engineer

Zero-knowledge proofs let a program accept a claim without seeing the data behind it. On Solana that used to be impractical, but the alt_bn128 syscalls changed that: a Groth16 proof can now be verified inside a normal transaction. This is the pipeline I use for privacy protocols, from circuit to on-chain check, and the details that cost me the most time.

The shape of the problem

A privacy pool has to answer one question on withdrawal: does this person own one of the deposits in the pool, and have they not withdrawn it before? The proof has to say yes without saying which deposit.

Each deposit stores a commitment, Poseidon(secret, nullifier), as a leaf in an on-chain Merkle tree. To withdraw, the user proves in zero knowledge that they know a secret and nullifier whose commitment is in the tree under a known root, and reveals only a hash of the nullifier. The program records that nullifier hash, so the same deposit can never be spent twice.

The circuit

I write the circuit in circom with Poseidon hashing, because Poseidon is cheap inside a SNARK where SHA-256 is not. The circuit has three jobs:

  • Recompute the commitment from the private secret and nullifier.
  • Walk the Merkle path and check it ends at the public root.
  • Output the nullifier hash as a public signal.

Everything the program has to trust goes into the public signals: the root, the nullifier hash, the recipient, the relayer and the fee. If the recipient weren't a public input, anyone watching pending transactions could copy the proof and redirect the funds. Binding it into the proof makes the proof useless for any other recipient.

circom
template Withdraw(levels) {
    signal input root;
    signal input nullifierHash;
    signal input recipient;   // bound into the proof
    signal input relayer;
    signal input fee;

    signal input secret;
    signal input nullifier;
    signal input pathElements[levels];
    signal input pathIndices[levels];

    component commitment = Poseidon(2);
    commitment.inputs[0] <== secret;
    commitment.inputs[1] <== nullifier;

    component nh = Poseidon(1);
    nh.inputs[0] <== nullifier;
    nh.out === nullifierHash;

    component tree = MerkleTreeChecker(levels);
    tree.leaf <== commitment.out;
    tree.root <== root;
    for (var i = 0; i < levels; i++) {
        tree.pathElements[i] <== pathElements[i];
        tree.pathIndices[i] <== pathIndices[i];
    }

    // Square the public-only inputs so they stay constrained.
    signal recipientSquare <== recipient * recipient;
    signal relayerSquare <== relayer * relayer;
    signal feeSquare <== fee * fee;
}

The trusted setup has two phases: a reusable Powers of Tau ceremony, then a circuit-specific phase 2. Every change to the circuit means a new phase 2 and a new verifying key, so I ship the circuit, the key and the program together as one versioned release.

From snarkjs to Solana bytes

snarkjs produces proofs and keys as JSON full of decimal strings. The on-chain verifier wants fixed-size big-endian byte arrays, and this encoding step is where most bugs live:

  • Field elements are 32 bytes, big-endian. A Solana public key is 32 bytes too, but it can be larger than the BN254 field modulus, so reduce or hash it into the field before it becomes a public input, and do exactly the same on-chain.
  • G2 points (proof B and parts of the verifying key) need their coordinate pairs in the order the verifier expects, which isn't the order snarkjs prints them in.
  • The verifier expects proof A negated. Forget that and you get a proof that verifies in snarkjs and fails on-chain every single time.

I ended up writing a small Rust-to-WASM converter for this, so the same code runs in the browser SDK, in Node scripts and in tests. Generating the Rust verifying key straight from snarkjs output, instead of copying numbers by hand, removed a whole class of mismatches.

Verifying in the program

On-chain I use the groth16-solana crate, which wraps the alt_bn128 syscalls. The withdraw instruction checks the root, verifies the proof, then records the nullifier:

rust
use anchor_lang::prelude::*;
use groth16_solana::groth16::Groth16Verifier;

pub fn withdraw(
    ctx: Context<Withdraw>,
    proof_a: [u8; 64],
    proof_b: [u8; 128],
    proof_c: [u8; 64],
    root: [u8; 32],
    nullifier_hash: [u8; 32],
    fee: u64,
) -> Result<()> {
    let tree = ctx.accounts.tree.load()?;
    require!(tree.is_known_root(&root), MixerError::UnknownRoot);

    let public_inputs = [
        root,
        nullifier_hash,
        to_field(&ctx.accounts.recipient.key()),
        to_field(&ctx.accounts.relayer.key()),
        u64_to_field(fee),
    ];

    let mut verifier = Groth16Verifier::new(
        &proof_a, &proof_b, &proof_c, &public_inputs, &VERIFYING_KEY,
    )
    .map_err(|_| MixerError::InvalidProof)?;
    verifier.verify().map_err(|_| MixerError::InvalidProof)?;

    // `nullifier` is created with `init`, so a second withdrawal with the
    // same nullifier hash fails before any funds move.
    ctx.accounts.nullifier.spent_at = Clock::get()?.unix_timestamp;

    // ...pay out the amount minus the fee, and the fee to the relayer
    Ok(())
}

Two design choices matter here. First, the program keeps a short history of recent roots instead of only the latest, so a proof generated a few seconds before someone else's deposit still verifies. Second, nullifiers are PDAs seeded by the nullifier hash. Anchor's init constraint fails if the account already exists, which turns double-spend protection into something the runtime enforces rather than a lookup I could get wrong.

Costs and limits

A Groth16 verification fits in one transaction, but it isn't cheap in compute, so withdrawals request a higher compute unit limit and the rest of the instruction stays lean. The Merkle tree is the bigger design question. With 24 levels, I store it zero-copy and keep only the filled subtrees and a root history on-chain. The full set of leaves lives in an indexer that rebuilds the tree from program events and serves Merkle paths to clients.

What I'd tell my past self

  • Test the full path, circuit to on-chain, with the real verifying key from day one. Unit tests on each half can both pass while the whole thing fails.
  • Treat the verifying key, the circuit and the program as one release. A mismatch isn't a bug you patch later; it's a redeploy.
  • Put everything the program trusts into public inputs. If it isn't in the proof, an attacker can change it.
  • Plan the off-chain side early. Proofs need Merkle paths, and those come from an indexer you can rebuild from scratch.

ZK on Solana is practical now, and the building blocks are well understood. Most of the work isn't cryptography. It's careful plumbing between a circuit, a byte format and a program that has to be right the first time.