Skip to content

starkware-libs/stwo-cairo

Repository files navigation

Stwo Cairo

A production Circle STARK prover and verifier for the Cairo CPU architecture.

Cairo CI License: Apache-2.0 Rust: nightly-2025-06-23 Scarb: 2.15.0

Overview · Production status · Architecture · Quick start · Building & testing · Security · References


Overview

Stwo Cairo is a Circle STARK prover and verifier for the Cairo CPU — the zero-knowledge virtual machine that powers Starknet and the broader StarkWare proving stack. It produces succinct, non-interactive proofs of correct Cairo execution and verifies them in two complementary settings:

  • a Rust verifier for off-chain checks, embedded use, and CI; and
  • a Cairo verifier (the same logic written in the Cairo language) that runs inside the Cairo VM — enabling recursive proving, on-chain verification, and proof aggregation pipelines.

The cryptography is built on the stwo core proof system: a generic, AIR-agnostic Circle STARK implementation over the Mersenne-31 field. This repository contributes the Cairo-specific Algebraic Intermediate Representation (AIR) — the constraint system, lookup arguments, and witness generators that encode every Cairo opcode and built-in into algebraic form.

Production status

Important

Stwo Cairo is production software. It runs at scale inside StarkWare's SHARP (SHARed Prover) infrastructure, where it secures Starknet and other systems that rely on STARK-validated Cairo execution. Proofs generated by this prover are settled on Ethereum L1 and trusted by production users today.

This is not a research artifact, a demo, or a work in progress. The codebase is actively maintained by StarkWare's prover engineering team, gated by an extensive CI matrix, and reviewed under the soundness-critical change protocol described in AGENTS.md. The proving system itself (stwo) is the next-generation successor to StarkWare's earlier StarkEx/Stone provers.

Why Circle STARKs

Stwo proves Cairo execution using Circle STARKs (Habök, Haböck, Levit, Papini, Polydouri, Yarom 2024), a STARK variant that operates over the Mersenne-31 prime field (\mathbb{F}_p) with (p = 2^{31} - 1). The construction replaces the multiplicative subgroups used by classical FRI with the circle group (C(\mathbb{F}_p) = {(x, y) \in \mathbb{F}_p^2 : x^2 + y^2 = 1}), enabling FFT-style operations on a field whose modulus matches a single machine word.

The practical consequences:

  • CPU-friendly arithmetic. All hot-path field operations on the prover and verifier reduce to 32-bit integer multiplies and Mersenne reductions — no 64-bit or 256-bit modular reductions on the critical path.
  • SIMD-native witness generation. The prover uses a portable-SIMD backend and rayon-based parallelism; the M31 field was chosen so that field operations vectorize cleanly.
  • Small proofs, fast verification. Standard configuration targets 96 bits of conjectured soundness at competitive proof sizes; the recursive Cairo verifier executes in a bounded number of Cairo steps.
  • Recursion-ready. Because the verifier itself is implemented in Cairo, proofs can verify proofs, enabling aggregation and on-chain settlement.

See the STWO Whitepaper for the full protocol specification.

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│  Cairo program                                                      │
└─────────────────────────────┬───────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  cairo-vm 3.2.0  →  execution trace (steps + memory + builtins)     │
└─────────────────────────────┬───────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  stwo-cairo-adapter  →  ProverInput (per-opcode / per-builtin)      │
└─────────────────────────────┬───────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  stwo-cairo-prover  →  witness generation, AIR constraint           │
│                          evaluation, FRI commitment, Fiat-Shamir    │
│  cairo-air          →  Cairo CPU AIR  (69+ components)              │
│  stwo (upstream)    →  Circle STARK proof system                    │
└─────────────────────────────┬───────────────────────────────────────┘
                              │
                              ▼
                       CairoProof (JSON / Cairo-serde / binary)
                              │
                ┌─────────────┴─────────────┐
                ▼                           ▼
   ┌─────────────────────────┐   ┌────────────────────────────────┐
   │ Rust verifier            │   │ Cairo verifier                 │
   │ (off-chain, CI, native)  │   │ (recursive, on-chain-bound)    │
   │ cairo-air::verifier      │   │ stwo_cairo_verifier (Cairo)    │
   └─────────────────────────┘   └────────────────────────────────┘

Workspace layout

Path Language Purpose
stwo_cairo_prover/ Rust Native prover + Rust reference verifier
  crates/adapter Rust Converts cairo-vm execution traces into prover input
  crates/cairo-air Rust Soundness-critical — Cairo CPU AIR: components, constraints, lookups
  crates/prover Rust Witness generation and proof construction
  crates/common Rust Shared types and preprocessed columns
  crates/cairo-serialize Rust Cairo-compatible (felt-array) proof serialization
  crates/dev_utils Rust prove, verify, run_and_prove, get_execution_resources binaries
stwo_cairo_verifier/ Cairo Cairo-language verifier for recursive proving
  crates/cairo_verifier Cairo Executable entry point — verifies a CairoProof
  crates/cairo_air Cairo Soundness-critical — Cairo CPU AIR in Cairo
  crates/verifier_core Cairo Soundness-critical — fields, VCS, channel, PCS, FRI
  crates/constraint_framework Cairo Constraint evaluation framework
  crates/bounded_int Cairo Bounded-integer primitives

The Cairo AIR currently encodes 69+ components spanning every Cairo opcode (add, mul, call, ret, jmp, jnz, assert_eq, blake_compress, qm31_add_mul, …) and every built-in (Pedersen, Poseidon, Bitwise, Range-check, EC-op, Add-mod, Mul-mod). Component definitions live under stwo_cairo_prover/crates/cairo-air/src/components/.

Generated code

Files marked // This file was created by the AIR team. are generated by the stwo-air-infra tooling (the canonical source of truth for AIR constraints and witness layouts). Do not hand-edit them — changes will be overwritten on the next regeneration. Submit AIR changes upstream.

Quick start

Prerequisites

  • Rust — the prover uses the nightly toolchain pinned in rust-toolchain.toml. rustup will install it automatically on first build. Other crates target stable Rust 1.89.0.
  • Scarb 2.15.0 + Starknet Foundry 0.33.0 — for the Cairo verifier. Install via asdf using the pinned versions in .tool-versions:
    asdf plugin add scarb && asdf plugin add starknet-foundry
    asdf install

Prove and verify a Cairo program

From stwo_cairo_prover/:

# 1. Build the dev binaries with native CPU optimization.
RUSTFLAGS="-C target-cpu=native -C opt-level=3" \
    cargo build --release --bin run_and_prove --bin verify

# 2. Execute a Cairo program, generate a proof, and verify it.
./target/release/run_and_prove \
    --program test_data/test_prove_verify_all_opcode_components/compiled.json \
    --proof_path /tmp/proof.json \
    --verify

# 3. (Optional) Re-verify the proof standalone with the Rust verifier.
./target/release/verify \
    --proof_path /tmp/proof.json \
    --channel_hash blake2s

Default proving parameters target 96 bits of conjectured soundness (pow_bits = 26, log_blowup_factor = 1, n_queries = 70); override with --params_json.

Verify a proof inside Cairo (recursive)

The Cairo verifier is itself a Cairo executable. From stwo_cairo_verifier/:

# Run the verifier as a Cairo program over a previously generated proof.
scarb --profile proving execute \
    --package stwo_cairo_verifier \
    --features qm31_opcode \
    --print-resource-usage \
    --output none \
    --arguments-file /tmp/proof.serde.json

This is the same code path used to produce proofs of proofs — a Cairo program that verifies a Stwo Cairo proof can itself be proven, yielding a recursive proof tree. See stwo_cairo_verifier/README.md for profiling instructions (cairo-profiler, scarb-burn flamegraphs, scoped Sierra traces).

Programmatic use

use stwo_cairo_prover::prover::{prove_cairo, ProverParameters};
use stwo::core::vcs_lifted::blake2_merkle::Blake2sMerkleChannel;

let prover_input = /* obtained from stwo-cairo-adapter */;
let proof = prove_cairo::<Blake2sMerkleChannel>(prover_input, ProverParameters::default())?;

Building & testing

Rust prover (stwo_cairo_prover/)

# Standard test suite (custom profile, single-threaded for stack safety).
RUST_MIN_STACK=4194304 RUSTFLAGS="-C target-cpu=native" \
    cargo nextest run --cargo-profile witness-opt-1 --features=slow-tests -j 1

# Clippy with -D warnings across all crates and features.
scripts/clippy.sh

# Formatting.
scripts/rust_fmt.sh --check

# Wasm targets (enforced in CI).
RUSTFLAGS='--cfg getrandom_backend="custom"' cargo check \
    --target wasm64-unknown-unknown -Z build-std=std,panic_abort \
    --package stwo-cairo-prover --release

cargo check --package cairo-air --no-default-features \
    --target wasm32-unknown-unknown --release

Cairo verifier (stwo_cairo_verifier/)

# Format and lint (CI runs `--deny-warnings`).
scarb fmt --check
scarb lint --features=qm31_opcode --deny-warnings

# Tests run as a feature matrix per package in CI; locally pick any combo.
scarb test --features=qm31_opcode --package stwo_cairo_verifier
scarb test --features=poseidon252_verifier --package stwo_verifier_core

CI gates

Every pull request runs the full matrix in .github/workflows/cairo-ci.yaml:

  • scarb-fmt / scarb-lint — Cairo formatting and lints, --deny-warnings
  • scarb-test — Cairo verifier tests across 4 packages × 5 feature combinations
  • run-tests — full Rust nextest suite with slow-tests
  • cairo-prover-wasmwasm64 build of the prover
  • cairo-air-wasmwasm32, no_std build of cairo-air
  • crates-stable — verifies non-prover crates compile on stable Rust 1.89.0
  • format / clippy / cargo-lock / typos — repository hygiene
  • merge-gatekeeper — required-checks gate

No check may be bypassed, weakened, or made non-blocking. The repository's contributor protocol (see AGENTS.md and CLAUDE.md) treats every gate as load-bearing for soundness.

Verifier configuration

The Cairo verifier supports a configurable hash and packing strategy via Scarb features. Tests are run across a curated subset of valid combinations.

Feature Effect
qm31_opcode Use the QM31 Cairo opcode for verifier speed (requires Cairo VM support)
poseidon252_verifier Use Poseidon over the BN254 scalar field for Merkle/channel hashing (suited for on-chain settlement on Ethereum)
blake_outputs_packing Pack verifier outputs for Blake-channel proofs
poseidon_outputs_packing Pack verifier outputs for Poseidon-channel proofs

Prover-side, the channel hash is selected at proof generation time:

--channel_hash Backend
blake2s Blake2s over field outputs (default)
blake2s_m31 Blake2s with M31-aware lifting
poseidon252 Poseidon over BN254 — for Ethereum L1 verification

Security & soundness

This codebase implements cryptographic protocol logic whose correctness is strictly load-bearing: an accepted invalid proof, or a rejected valid one, is a protocol-level failure with no recovery path.

Security model

  • Soundness. The construction follows the Circle STARK protocol of Habök et al. 2024. Default parameters target 96 bits of conjectured soundness against the FRI list-decoding regime. The verifier additionally enforces an interaction-phase proof-of-work (INTERACTION_POW_BITS).
  • Zero-knowledge. Stwo Cairo is a transparent STARK; the protocol is not zero-knowledge by default. (The proof reveals no execution data beyond the declared public input.)
  • Trusted setup. None. The system is fully transparent — no toxic waste, no MPC ceremony.
  • Post-quantum. STARK soundness rests on collision-resistance of the underlying hash function; the construction is post-quantum-plausible.

Audit and review

Stwo Cairo is deployed by StarkWare into production proving infrastructure (SHARP). Soundness-critical changes follow the protocol documented in AGENTS.md:

  1. Identify the paper section or stwo core component governing the logic.
  2. State the invariant the change must preserve and how it preserves it.
  3. Identify the test that verifies the invariant.
  4. Obtain explicit human review before merge.

The following directories are designated soundness-critical and require math-reviewer sign-off:

  • stwo_cairo_prover/crates/cairo-air/src/components/
  • stwo_cairo_verifier/crates/cairo_air/
  • stwo_cairo_verifier/crates/verifier_core/{fields,vcs,channel,pcs.cairo}
  • stwo_cairo_verifier/crates/constraint_framework/
  • stwo_cairo_prover/crates/cairo-serialize/

Responsible disclosure

Suspected vulnerabilities, soundness gaps, or paper-implementation divergences must not be reported as public GitHub issues. Contact StarkWare's security team — see https://www.starkware.co/ for current channels.

Performance

The prover is engineered as production infrastructure:

  • Portable SIMD witness generation (std::simd) with M31-vectorized hot paths.
  • Parallel trace generation and FRI commitment via rayon.
  • Streaming trace adaptation from cairo-vm with bounded memory.
  • Wasm-deployable — both wasm32 (verifier-side) and wasm64 (prover-side) targets are CI-enforced.

For profiling proof generation use tracing (every major phase is instrumented with spans). For profiling the Cairo verifier, stwo_cairo_verifier/README.md covers cairo-profiler, scarb-burn, and cairo-execute --run-profiler scoped workflows including flamegraph and pprof output.

References

Papers

  • Cairo CPU architecture. Goldberg, Papini, Riabzev. Cairo — a Turing-complete STARK-friendly CPU architecture. IACR ePrint 2021/1063, 2021.
  • Circle STARKs. Habök, Levit, Papini, Polydouri, Yarom. Circle STARKs. IACR ePrint 2024/278, 2024.
  • STWO whitepaper. Stwo_Whitepaper.llm.md in the upstream stwo repository.
  • FRI. Ben-Sasson, Bentov, Horesh, Riabzev. Fast Reed–Solomon Interactive Oracle Proofs of Proximity. ICALP, 2018.

Related repositories

Contributing

Contributions are welcome — bug reports, performance improvements, test coverage, documentation, and verifier optimizations. Before submitting changes, please read:

  • AGENTS.md — roles, soundness-critical change protocol, escalation format.
  • CLAUDE.md — codebase invariants, operational boundaries, the priority contract (soundness > production quality > performance).

Do not modify constraint definitions, field arithmetic, FRI parameters, the Fiat-Shamir channel, verifier logic, or the commitment scheme without explicit human approval and a documented mathematical justification. Do not edit files marked as AIR-generated — submit changes to stwo-air-infra instead.

License

Licensed under the Apache License, Version 2.0. See the license field in each crate's Cargo.toml. By contributing, you agree that your contributions will be licensed under the same terms.

Acknowledgments

Built by the StarkWare prover team and contributors. Stwo Cairo stands on the shoulders of years of STARK research — the Cairo architecture, the FRI protocol, the Mersenne-31 / Circle STARK construction, and the production lessons from earlier StarkWare provers (StarkEx, Stone). The recursive Cairo verifier is made possible by the Cairo language compiler (starkware-libs/cairo) and the broader Starknet ecosystem.

About

Prove Cairo programs with the blazing-fast S-two prover, powered by the cryptographic breakthrough of Circle STARKs.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors