[feat] ed25519-pokos: Proof of Knowledge of Seed (POKOS) for Ed25519 (#10)

* init pokos

* fix soundness bug

* update doc

* fix

* simplification

* refactor

* add docs

* clean up

* ci

* Update experimental/ed25519-pokos/readme.md

Co-authored-by: Sam Kim <skim13@cs.stanford.edu>

---------

Co-authored-by: Sam Kim <skim13@cs.stanford.edu>
This commit is contained in:
zz-sol 2026-04-08 10:24:32 -04:00 committed by GitHub
parent bccf7e13c0
commit 0f7379cc05
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 4239 additions and 5 deletions

422
Cargo.lock generated
View file

@ -8,7 +8,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e33f6a175ec6a9e0aca777567f9ff7c3deefc255660df887e7fa3585e9801d8"
dependencies = [
"num-bigint",
"num-bigint 0.3.3",
"num-integer",
"num-traits",
]
@ -245,7 +245,7 @@ dependencies = [
"clap",
"criterion-plot",
"is-terminal",
"itertools",
"itertools 0.10.5",
"num-traits",
"once_cell",
"oorandom",
@ -266,7 +266,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
dependencies = [
"cast",
"itertools",
"itertools 0.10.5",
]
[[package]]
@ -402,6 +402,29 @@ dependencies = [
"zeroize",
]
[[package]]
name = "ed25519-pokos"
version = "0.1.0"
dependencies = [
"bincode",
"p3-air",
"p3-challenger",
"p3-commit",
"p3-dft",
"p3-field",
"p3-fri",
"p3-keccak",
"p3-koala-bear",
"p3-matrix",
"p3-merkle-tree",
"p3-symmetric",
"p3-uni-stark",
"rand 0.9.2",
"serde",
"sha2 0.11.0",
"solana-ed25519",
]
[[package]]
name = "ed25519-zebra"
version = "4.2.0"
@ -637,6 +660,15 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@ -677,6 +709,15 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.29"
@ -700,6 +741,16 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.46"
@ -730,6 +781,275 @@ version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "p3-air"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0141a56ed9924ce0265e7e91cd29bbcd230262744b7a7f0c448bfbf212f73182"
dependencies = [
"p3-field",
"p3-matrix",
]
[[package]]
name = "p3-challenger"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20e42ba74a49c08c6e99f74cd9b343bfa31aa5721fea55079b18e3fd65f1dcbc"
dependencies = [
"p3-field",
"p3-maybe-rayon",
"p3-monty-31",
"p3-symmetric",
"p3-util",
"tracing",
]
[[package]]
name = "p3-commit"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "498211e7b9a0f8366b410b4a9283ae82ff2fc91f473b1c5816aa6e90e74b125d"
dependencies = [
"itertools 0.14.0",
"p3-challenger",
"p3-dft",
"p3-field",
"p3-matrix",
"p3-util",
"serde",
]
[[package]]
name = "p3-dft"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e63fa5eb1bd12a240089e72ae3fe10350944d9c166d00a3bfd2a1794db65cf5c"
dependencies = [
"itertools 0.14.0",
"p3-field",
"p3-matrix",
"p3-maybe-rayon",
"p3-util",
"spin",
"tracing",
]
[[package]]
name = "p3-field"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ebfdb6ef992ae64e9e8f449ac46516ffa584f11afbdf9ee244288c2a633cdf4"
dependencies = [
"itertools 0.14.0",
"num-bigint 0.4.6",
"p3-maybe-rayon",
"p3-util",
"paste",
"rand 0.9.2",
"serde",
"tracing",
]
[[package]]
name = "p3-fri"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0236da9bb191391b4d1f6e090988227d5da27055a006953aa456f34b683be436"
dependencies = [
"itertools 0.14.0",
"p3-challenger",
"p3-commit",
"p3-dft",
"p3-field",
"p3-interpolation",
"p3-matrix",
"p3-maybe-rayon",
"p3-util",
"rand 0.9.2",
"serde",
"thiserror",
"tracing",
]
[[package]]
name = "p3-interpolation"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d877565a94a527c89459fc8ccb0eb58769d8c86456575d1315a1651bd24616d"
dependencies = [
"p3-field",
"p3-matrix",
"p3-maybe-rayon",
"p3-util",
]
[[package]]
name = "p3-keccak"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d57334537d10316e0f1cda622f0a5b3239f219a5dcd2a95ea87e41e00df6a92"
dependencies = [
"p3-field",
"p3-symmetric",
"p3-util",
"tiny-keccak",
]
[[package]]
name = "p3-koala-bear"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5113f50002c56006685b7d7ae12db568150aa1d4bfb092b883d64ece20138042"
dependencies = [
"p3-challenger",
"p3-field",
"p3-monty-31",
"p3-poseidon2",
"p3-symmetric",
"rand 0.9.2",
]
[[package]]
name = "p3-matrix"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5542f96504dae8100c91398fb1e3f5ec669eb9c73d9e0b018a93b5fe32bad230"
dependencies = [
"itertools 0.14.0",
"p3-field",
"p3-maybe-rayon",
"p3-util",
"rand 0.9.2",
"serde",
"tracing",
"transpose",
]
[[package]]
name = "p3-maybe-rayon"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e5669ca75645f99cd001e9d0289a4eeff2bc2cd9dc3c6c3aaf22643966e83df"
dependencies = [
"rayon",
]
[[package]]
name = "p3-mds"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "038763af23df9da653065867fd85b38626079031576c86fd537097e5be6a0da0"
dependencies = [
"p3-dft",
"p3-field",
"p3-symmetric",
"p3-util",
"rand 0.9.2",
]
[[package]]
name = "p3-merkle-tree"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d93625a3041effddc72ee2511c919f710b7f91fd0f9931ab8a70aeba586fd6e"
dependencies = [
"itertools 0.14.0",
"p3-commit",
"p3-field",
"p3-matrix",
"p3-maybe-rayon",
"p3-symmetric",
"p3-util",
"rand 0.9.2",
"serde",
"thiserror",
"tracing",
]
[[package]]
name = "p3-monty-31"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a981d60da3d8cbf8561014e2c186068578405fd69098fa75b43d4afb364a47"
dependencies = [
"itertools 0.14.0",
"num-bigint 0.4.6",
"p3-dft",
"p3-field",
"p3-matrix",
"p3-maybe-rayon",
"p3-mds",
"p3-poseidon2",
"p3-symmetric",
"p3-util",
"paste",
"rand 0.9.2",
"serde",
"spin",
"tracing",
"transpose",
]
[[package]]
name = "p3-poseidon2"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "903b73e4f9a7781a18561c74dc169cf03333497b57a8dd02aaeb130c0f386599"
dependencies = [
"p3-field",
"p3-mds",
"p3-symmetric",
"p3-util",
"rand 0.9.2",
]
[[package]]
name = "p3-symmetric"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cd788f04e86dd5c35dd87cad29eefdb6371d2fd5f7664451382eeacae3c3ed0"
dependencies = [
"itertools 0.14.0",
"p3-field",
"serde",
]
[[package]]
name = "p3-uni-stark"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68d409704a8cbdb6c77f6b83a05c6b16a3c8a2c00d880146fa34181977a0d3ac"
dependencies = [
"itertools 0.14.0",
"p3-air",
"p3-challenger",
"p3-commit",
"p3-dft",
"p3-field",
"p3-matrix",
"p3-maybe-rayon",
"p3-util",
"serde",
"thiserror",
"tracing",
]
[[package]]
name = "p3-util"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "663b16021930bc600ecada915c6c3965730a3b9d6a6c23434ccf70bfc29d6881"
dependencies = [
"serde",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@ -739,6 +1059,12 @@ dependencies = [
"base64ct",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkcs8"
version = "0.10.2"
@ -998,7 +1324,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2aef88cb4ddb3b1c83beff963f9197607dac780cc39a09f19c041dacbb0b6a5"
dependencies = [
"addchain",
"num-bigint",
"num-bigint 0.3.3",
"num-integer",
"num-traits",
"proc-macro2",
@ -1070,6 +1396,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "semver"
version = "1.0.27"
@ -1196,6 +1528,15 @@ dependencies = [
"zeroize",
]
[[package]]
name = "spin"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.7.3"
@ -1206,6 +1547,12 @@ dependencies = [
"der",
]
[[package]]
name = "strength_reduce"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
[[package]]
name = "subtle"
version = "2.6.1"
@ -1253,6 +1600,35 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
@ -1263,6 +1639,44 @@ dependencies = [
"serde_json",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
[[package]]
name = "transpose"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
dependencies = [
"num-integer",
"strength_reduce",
]
[[package]]
name = "typenum"
version = "1.19.0"

View file

@ -1,7 +1,8 @@
[workspace]
members = [
"curve25519/curve25519-cuda",
"curve25519/solana-ed25519",
"curve25519/solana-ed25519",
"experimental/ed25519-pokos",
]
resolver = "2"

View file

@ -0,0 +1,23 @@
[package]
name = "ed25519-pokos"
version = "0.1.0"
edition = "2024"
[dependencies]
bincode.workspace = true
curve25519.workspace = true
p3-air = "0.4.2"
p3-challenger = "0.4.2"
p3-commit = "0.4.2"
p3-dft = { version = "0.4.2", features = ["parallel"] }
p3-field = "0.4.2"
p3-fri = "0.4.2"
p3-keccak = "0.4.2"
p3-koala-bear = "0.4.2"
p3-matrix = "0.4.2"
p3-merkle-tree = "0.4.2"
p3-symmetric = "0.4.2"
p3-uni-stark = { version = "0.4.2", features = ["parallel"] }
rand = { version = "0.9", features = ["small_rng"] }
serde = { version = "1.0", features = ["derive"] }
sha2.workspace = true

View file

@ -0,0 +1,38 @@
use std::time::Instant;
use ed25519_pokos::{
Seed, deserialize_proof, gen_pokos, private_seed_chain, serialize_proof, verify_pokos,
};
fn main() -> Result<(), String> {
let seed: Seed = [7_u8; 32];
let proving_start = Instant::now();
let proof = gen_pokos(seed)?;
let proving_time = proving_start.elapsed();
let verification_start = Instant::now();
verify_pokos(&proof).map_err(|err| format!("verification failed: {err:?}"))?;
let verification_time = verification_start.elapsed();
let encoded = serialize_proof(&proof);
let decoded = deserialize_proof(&encoded).map_err(|err| format!("decode failed: {err:?}"))?;
verify_pokos(&decoded).map_err(|err| format!("round-trip verification failed: {err:?}"))?;
println!("commit_of_seed: {:02x?}", proof.statement.commit_of_seed);
println!("hash_of_sk: {:02x?}", proof.statement.hash_of_sk);
println!("proving_time_ms: {}", proving_time.as_millis());
println!("verification_time_ms: {}", verification_time.as_millis());
println!(
"air_trace_rows: {}",
private_seed_chain::ACTIVE_AIR_TRACE_ROWS
);
println!(
"air_trace_cols: {}",
private_seed_chain::ACTIVE_AIR_TRACE_COLS
);
println!("proof_bytes: {}", encoded.len());
println!("verification: ok");
Ok(())
}

View file

@ -0,0 +1,165 @@
# Ed25519 Proof of Knowledge of Seed (POKOS)
This crate is an experimental implementation testing (post-quantum) Proof of Knowledge (PoK) on an Ed25519 seed (see https://eprint.iacr.org/2025/1368). It constructs a zero-knowledge proof that a prover knows a seed used to derive an Ed25519 secret key—without revealing the seed or the key itself.
This mechanism is useful for seamless blockchain migration, specifically on networks like Solana that natively rely on Ed25519 for account authentication. Because accounts are intrinsically tied to these public keys, a traditional transition to post-quantum signatures would require users to transfer assets and state to entirely new addresses. However, because EdDSA keys are deterministically derived from a seed (per RFC 8032), that seed can act as a reusable witness in a Post-Quantum Non-Interactive Zero-Knowledge (PQ-NIZK) proof. This allows a user to authorize a new quantum-safe key under their original on-chain identity, protecting dormant accounts and avoiding the friction of a network-wide asset migration even if the legacy public key has already been exposed.
The goal is not simply to prove knowledge of an Ed25519 secret key. The seed, or a commitment to it, is intended to be reused in a separate protocol that derives post-quantum keys from the same root. Consequently, the proof must constrain the entire seed derivation path, rather than merely validating the final Ed25519 key material.
## Protocol shape
The public statement is `(commit_of_seed, hash_of_sk)`. The prover holds the
secret `seed` and proves the following derivation chain in zero knowledge:
```
commit_of_seed = SHA512("ed25519-pokos/commit/v1" || seed)
prf_output = SHA512("ed25519-pokos/derive-sk/v1" || seed)
sk_seed = prf_output[0..32]
hash_of_sk = SHA512("ed25519-pokos/hash-sk/v1" || sk_seed)
```
Each domain label is zero-padded to 32 bytes, then concatenated with the
32-byte payload to form a single 64-byte message hashed in one SHA-512 block.
All three SHA-512 evaluations are proved by a single Plonky3 STARK over the
SHA-512 compression function. The outer proof envelope is then signed by the
Ed25519 key derived from `sk_seed`, binding the proof to the key owner without
exposing either the seed or the secret key.
## Security tradeoff
This is a **temporary** construction. It does not prove `sk → pk` inside the
circuit; that link is enforced externally by the Ed25519 signature over the
proof transcript.
- The ZK proof ties `seed → sk`.
- The Ed25519 signature ties `sk → pk`.
This is weaker than a fully end-to-end statement because the linkage to `pk` is
not proven inside the circuit — it is enforced by an external signature.
In the pre-quantum setting this is sufficient: only the legitimate owner of `sk`
can produce a valid signature. In a post-quantum setting, once an adversary can
recover `sk` from `pk`, the signature no longer adds meaningful security. At
that point the temporary authentication layer becomes unnecessary anyway, and the
system can rely on the revealed `sk` directly.
This construction should be read as a temporary engineering compromise, not as
the ideal final statement.
## Fully sound version
The fully sound end-to-end statement would use these public inputs:
- `commit_of_seed`
- `pk`
And prove:
- `commit_of_seed` commits to some seed
- the seed is transformed into the Ed25519 secret key `sk` by the specified PRF
- the corresponding Ed25519 public key derived from `sk` is exactly `pk`
This directly binds the seed commitment to the Ed25519 public key inside the
proof, with no external signature required.
## Why the fully sound version is not used here
The main bottleneck is proving Ed25519 group operations inside the circuit under
emulated arithmetic. Our proof-of-concept for the fully end-to-end version
exceeds **1 billion gates**. The dominant cost is in-circuit elliptic-curve
arithmetic for the `sk → pk` derivation.
By contrast, this construction avoids that expensive step: instead of proving
`sk → pk` in circuit it exposes `hash_of_sk` and delegates the `sk → pk` link
to an external Ed25519 signature. The result is far more practical:
| Construction | Proof size (default settings) |
|---|---|
| This crate (temporary) | ~401 KB |
| Fully end-to-end | not yet practical |
## Crate layout
```
src/
lib.rs — public types, constants, and re-exports
prover.rs — key derivation, statement assembly, proof generation
verifier.rs — STARK verification, Ed25519 auth check, serialization
private_seed_chain.rs — public witness/layout types for the three-segment chain
sha512/ — Plonky3 AIR, trace builder, constraints, proof API
air.rs — Sha512RoundAir (implements the Plonky3 Air trait)
circuit.rs — Sha512Circuit: reference hash, block compression, trace gen
private_seed_chain.rs — STARK prover/verifier for the seed chain
proof_api/ — STARK config, FRI settings, serialization
```
The `prover` and `verifier` modules are intentionally separated so that a
verifier binary need not link any prover code.
## Wire format
`serialize_proof` / `deserialize_proof` produce a versioned byte sequence:
```
[magic: 8 bytes "EPKOS001"]
[commit_of_seed: 64 bytes]
[hash_of_sk: 64 bytes]
[sha512_proof_len: 8 bytes big-endian u64] [sha512_proof: N bytes]
[authentication_key: 32 bytes]
[authentication_signature: 64 bytes]
```
## Usage
```rust
use ed25519_pokos::{Seed, gen_pokos, verify_pokos, serialize_proof, deserialize_proof};
// ── Prover ──────────────────────────────────────────────────────────────────
let seed: Seed = [7_u8; 32];
let proof = gen_pokos(seed)?;
// Inspect the public statement without running the verifier:
println!("commit_of_seed: {:02x?}", proof.statement.commit_of_seed);
println!("hash_of_sk: {:02x?}", proof.statement.hash_of_sk);
// Serialize for transport:
let proof_bytes = serialize_proof(&proof);
// ── Verifier (can run in a separate process / binary) ─────────────────────
let proof = deserialize_proof(&proof_bytes)?;
verify_pokos(&proof)?;
# Ok::<(), String>(())
```
Run the bundled example:
```bash
cargo run --release -p ed25519-pokos --example gen_verify_pokos
```
Sample output (fixed seed `[7u8; 32]`, timings vary by machine):
```
commit_of_seed: [01, ff, 79, 8a, 05, 6f, b4, a4, 25, 13, 16, d5, 9e, a3, fe, 21, e9, 1e, 56, dd, 6b, cb, 69, db, 03, dd, 27, f2, 06, 8d, 9a, a2, ca, c0, cc, f2, 6f, d3, 9f, 4c, cb, ac, 00, 8a, d8, c1, c0, 70, f8, 51, d2, c4, 64, b0, e7, bb, de, 4f, 86, bb, 0e, 2f, e1, dc]
hash_of_sk: [52, 5c, 52, 0a, 8a, 61, bf, 28, df, 5b, a5, 4e, 31, fe, 53, 2d, 43, 3a, 35, 91, 5d, 6e, 78, 71, 4f, 01, 4c, de, c7, d8, 5f, 48, 9e, 91, a4, 3a, c9, be, 1b, ce, 63, a1, 15, 79, 84, 14, b4, ef, 06, c6, ec, c9, 60, 78, 0a, 52, 0c, ff, 48, d8, 75, fd, 6a, 67]
proving_time_ms: 55
verification_time_ms: 13
air_trace_rows: 512
air_trace_cols: 1076
proof_bytes: 400848
verification: ok
```
The trace shape and proof envelope bytes are stable unless the AIR or the
default `Sha512ProofSettings` change.
## Current implementation status
- The STARK proves all three SHA-512 relations in a single concatenated
three-segment proof.
- The authentication key and signature use the Ed25519 implementation in this
repo (`curve25519` crate).
- The `sk → pk` link is **not** proved inside the circuit; it remains external
and is enforced by the Ed25519 signature over the proof statement.
- The proof settings (`Sha512ProofSettings`) are configurable, but the
verifier enforces minimum security thresholds and rejects proofs produced
with weaker parameters.

View file

@ -0,0 +1,463 @@
//! Proof of Knowledge of Seed (POKOS) for Ed25519.
//!
//! This crate proves, in zero knowledge, that the prover knows a seed that was used
//! to derive an Ed25519 secret key — without revealing the seed or the key itself.
//! The proof covers the full SHA-512 derivation chain and is authenticated with an
//! Ed25519 signature from the derived key.
//!
//! # Protocol shape
//!
//! The public statement is `(commit_of_seed, hash_of_sk)`. The prover holds the
//! secret `seed` and proves the following chain in zero knowledge:
//!
//! ```text
//! commit_of_seed = SHA512(domain_commit || seed)
//! prf_output = SHA512(domain_derive || seed)
//! sk_seed = prf_output[0..32]
//! hash_of_sk = SHA512(domain_hash_sk || sk_seed)
//! ```
//!
//! All three SHA-512 evaluations are proved by a single Plonky3 STARK over the
//! SHA-512 compression function. The outer envelope is then signed by the Ed25519
//! key derived from `sk_seed`, binding the proof to the key owner without exposing
//! either the seed or the secret key.
//!
//! # Security note
//!
//! This is a *temporary* construction. It does not prove `sk -> pk` inside the
//! circuit; that link is enforced externally by the Ed25519 signature. A fully
//! sound end-to-end statement would expose `pk` as a public input and prove the
//! complete chain `seed -> sk -> pk` in circuit. That stronger version is deferred
//! because in-circuit Ed25519 group operations currently exceed practical circuit
//! sizes. See [`readme.md`](../readme.md) for the full design discussion.
//!
//! # Quick start
//!
//! ```rust,ignore
//! use ed25519_pokos::{Seed, gen_pokos, verify_pokos, serialize_proof, deserialize_proof};
//!
//! let seed: Seed = [7_u8; 32];
//!
//! // Prover side
//! let proof = gen_pokos(seed)?;
//! let bytes = serialize_proof(&proof);
//!
//! // Verifier side
//! let proof = deserialize_proof(&bytes)?;
//! verify_pokos(&proof)?;
//! # Ok::<(), String>(())
//! ```
use curve25519::ed_sigs::{Signature, VerificationKeyBytes};
use sha2::{Digest, Sha512};
// ─── Byte-length constants ────────────────────────────────────────────────────
/// Byte length of a SHA-512 digest (64 bytes = 512 bits).
pub const SHA512_DIGEST_LEN: usize = 64;
/// Byte length of an Ed25519 seed (32 bytes).
pub const ED25519_SEED_LEN: usize = 32;
/// Byte length of an Ed25519 compressed public key (32 bytes).
pub const ED25519_PUBLIC_KEY_LEN: usize = 32;
/// Byte length of an Ed25519 signature (64 bytes).
pub const ED25519_SIGNATURE_LEN: usize = 64;
// ─── SHA-512 block-layout constants ──────────────────────────────────────────
/// Byte length of a domain-separation prefix within a fixed seed-chain block.
///
/// Each SHA-512 block in the seed chain is structured as
/// `domain[0..32] || payload[0..32] || SHA-512 padding`.
/// This constant names the domain portion's length.
pub const DOMAIN_LEN: usize = 32;
/// Total byte length of the message before padding (`domain || payload`).
///
/// Equals `DOMAIN_LEN + ED25519_SEED_LEN` = 64 bytes.
pub const FIXED_MESSAGE_LEN: usize = DOMAIN_LEN + ED25519_SEED_LEN;
/// Number of 64-bit words in a single 128-byte SHA-512 input block (= 16).
pub const FIXED_BLOCK_WORDS: usize = 16;
/// Word index within the block where the 32-byte payload begins.
///
/// The payload (seed or sk_seed) is stored as four 64-bit words at positions
/// 4..7 of the block word array (bytes 32..63).
pub const PAYLOAD_WORD_START: usize = 4;
/// Number of 64-bit words occupied by the 32-byte payload (= 4).
pub const PAYLOAD_WORD_COUNT: usize = 4;
/// Word index of the SHA-512 message-length field within the fixed block.
///
/// SHA-512 padding places the 64-bit big-endian bit-length in the last word
/// of the 128-byte block (word index 15, bytes 120..127).
pub const LENGTH_WORD_INDEX: usize = 15;
// ─── Domain-separation labels ─────────────────────────────────────────────────
/// Domain prefix used when hashing the seed to produce `commit_of_seed`.
const COMMIT_OF_SEED_DOMAIN: [u8; DOMAIN_LEN] = domain32(b"ed25519-pokos/commit/v1");
/// Domain prefix used in the PRF step that derives `sk_seed` from the seed.
const DERIVE_SK_DOMAIN: [u8; DOMAIN_LEN] = domain32(b"ed25519-pokos/derive-sk/v1");
/// Domain prefix used when hashing `sk_seed` to produce `hash_of_sk`.
const HASH_OF_SK_DOMAIN: [u8; DOMAIN_LEN] = domain32(b"ed25519-pokos/hash-sk/v1");
/// Domain prefix for the authentication transcript signed by the derived key.
const AUTH_TRANSCRIPT_DOMAIN: &[u8] = b"ed25519-pokos/auth-transcript/v1";
/// Magic bytes at the start of a serialized [`SeedChainProofEnvelope`].
///
/// "EPKOS001" — Ed25519 POKOS format version 1.
const PROOF_FORMAT_MAGIC: &[u8; 8] = b"EPKOS001";
pub mod private_seed_chain;
pub mod prover;
mod sha512;
pub mod verifier;
// ─── Type aliases ─────────────────────────────────────────────────────────────
/// A 32-byte Ed25519 seed.
pub type Seed = [u8; ED25519_SEED_LEN];
/// A 64-byte SHA-512 digest.
pub type DigestBytes = [u8; SHA512_DIGEST_LEN];
/// A SHA-512 digest of a seed, used as the public commitment.
///
/// Computed as `SHA512(COMMIT_OF_SEED_DOMAIN || seed)`.
pub type CommitOfSeedDigest = DigestBytes;
/// A SHA-512 digest of a derived Ed25519 secret key seed.
///
/// Computed as `SHA512(HASH_OF_SK_DOMAIN || sk_seed)`.
pub type HashOfSkDigest = DigestBytes;
// ─── Public types ─────────────────────────────────────────────────────────────
/// The public statement proved by a [`SeedChainProofEnvelope`].
///
/// Both fields are SHA-512 digests that are computable from the private `seed`
/// alone. Together they form the statement: "I know a seed such that
/// `commit_of_seed` and `hash_of_sk` were computed from it via the prescribed
/// derivation chain."
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SeedChainStatement {
/// `SHA512(COMMIT_OF_SEED_DOMAIN || seed)` — public commitment to the seed.
pub commit_of_seed: CommitOfSeedDigest,
/// `SHA512(HASH_OF_SK_DOMAIN || sk_seed)` — public commitment to the derived key.
pub hash_of_sk: HashOfSkDigest,
}
/// All secret material derived from a seed during proof generation.
///
/// This struct is produced by [`derive_secret_key_material`] and is the
/// prover's private witness. Fields are intentionally not `Copy` or
/// `zeroize`d here — callers are responsible for handling them with
/// appropriate care.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DerivedSecretKeyMaterial {
/// Full output of `SHA512(DERIVE_SK_DOMAIN || seed)`. The first 32 bytes
/// become `sk_seed`; the remaining 32 bytes are currently unused.
pub prf_output: DigestBytes,
/// First 32 bytes of `prf_output`, used as the Ed25519 signing seed.
pub sk_seed: Seed,
/// `SHA512(HASH_OF_SK_DOMAIN || sk_seed)` — the `hash_of_sk` public value.
pub hash_of_sk: DigestBytes,
/// Ed25519 verification key (public key) derived from `sk_seed`.
pub authentication_key: VerificationKeyBytes,
}
/// A sealed (serialized) Plonky3 STARK proof for the three-segment SHA-512 chain.
///
/// The `sealed_proof` bytes are the full STARK proof bundle produced by the
/// Plonky3 prover. The format is internal to this crate; use
/// [`serialize_proof`] / [`deserialize_proof`] to transport the outer envelope.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Sha512ProofBundle {
/// Raw bytes of the serialized Plonky3 STARK proof.
pub sealed_proof: Vec<u8>,
}
/// A complete, self-contained proof envelope for the POKOS statement.
///
/// This type bundles all three components a verifier needs:
/// 1. The public statement (`commit_of_seed`, `hash_of_sk`).
/// 2. The STARK proof that the statement was honestly derived from some hidden seed.
/// 3. An Ed25519 signature from the derived key, binding the proof to the key owner.
///
/// Use [`gen_pokos`] to produce an envelope and [`verify_pokos`] to check it.
/// For wire transport, see [`serialize_proof`] and [`deserialize_proof`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SeedChainProofEnvelope {
/// The public outputs of the seed-chain derivation.
pub statement: SeedChainStatement,
/// The STARK proof for the three SHA-512 steps in the derivation chain.
pub sha512_proof: Sha512ProofBundle,
/// Ed25519 verification key corresponding to the signing key derived from `sk_seed`.
pub authentication_key: VerificationKeyBytes,
/// Ed25519 signature over the `authentication_transcript` of `statement`,
/// produced by the signing key derived from `sk_seed`.
pub authentication_signature: Signature,
}
/// Errors returned by [`verify_pokos`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VerifyError {
/// The STARK proof for the SHA-512 seed-chain is invalid or does not match
/// the public statement.
InvalidSkDerivationProof,
/// The Ed25519 signature over the proof transcript is invalid. Either the
/// signature bytes are malformed or the signature was made with a different key.
AuthenticationSignatureInvalid,
}
/// Errors returned by [`deserialize_proof`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeserializeError {
/// The byte slice ends before all expected fields have been read.
Truncated,
/// The leading magic bytes do not match `PROOF_FORMAT_MAGIC`.
InvalidMagic,
/// The Ed25519 signature bytes are structurally invalid.
InvalidSignature,
/// The byte slice contains extra data after the last expected field.
TrailingBytes,
}
pub use prover::{commit_of_seed, derive_secret_key_material, gen_pokos, statement_from_seed};
pub use verifier::{deserialize_proof, serialize_proof, verify_pokos};
// ─── Crate-internal helpers ───────────────────────────────────────────────────
/// Computes a raw SHA-512 digest of `message`.
fn sha512(message: &[u8]) -> DigestBytes {
let digest = Sha512::digest(message);
let mut bytes = [0_u8; SHA512_DIGEST_LEN];
bytes.copy_from_slice(&digest);
bytes
}
/// Pads a byte-string label to a 32-byte domain-separation prefix.
///
/// Copies `label` into the first `label.len()` bytes of a zero-filled
/// `[u8; 32]`. Panics at compile time if `label.len() > 32`.
const fn domain32(label: &[u8]) -> [u8; DOMAIN_LEN] {
let mut out = [0_u8; DOMAIN_LEN];
let mut i = 0;
while i < label.len() {
out[i] = label[i];
i += 1;
}
out
}
/// Builds the single padded 128-byte SHA-512 block for a fixed-layout seed-chain segment.
///
/// The block layout is:
/// ```text
/// [domain: 32 bytes] [payload: 32 bytes] [0x80] [zeros] [bit_length: 8 bytes]
/// ```
/// `payload` must be exactly [`ED25519_SEED_LEN`] (32) bytes.
///
/// The resulting block is a valid, fully padded SHA-512 message that fits in
/// exactly one block, which is the structural invariant the AIR relies on.
pub(crate) fn fixed_single_block(domain: &[u8; DOMAIN_LEN], payload: &[u8]) -> [u8; 128] {
assert_eq!(
payload.len(),
ED25519_SEED_LEN,
"fixed seed-chain block expects a 32-byte payload"
);
let mut block = [0_u8; 128];
block[..DOMAIN_LEN].copy_from_slice(domain);
block[DOMAIN_LEN..FIXED_MESSAGE_LEN].copy_from_slice(payload);
block[FIXED_MESSAGE_LEN] = 0x80;
block[120..128].copy_from_slice(&((FIXED_MESSAGE_LEN as u64) * 8).to_be_bytes());
block
}
/// Parses a 128-byte SHA-512 block into 16 big-endian 64-bit words.
pub(crate) fn block_words(block: [u8; 128]) -> [u64; FIXED_BLOCK_WORDS] {
let mut words = [0_u64; FIXED_BLOCK_WORDS];
for (i, chunk) in block.chunks_exact(8).enumerate() {
words[i] = u64::from_be_bytes(chunk.try_into().expect("chunk size"));
}
words
}
/// Concatenates a 32-byte domain prefix and an arbitrary payload into one message.
///
/// Used by the prover to form the input to each domain-separated SHA-512 call
/// before passing it to the standard `sha2` crate (outside the circuit).
pub(crate) fn encode_domain_message(domain: &[u8; DOMAIN_LEN], payload: &[u8]) -> Vec<u8> {
let mut message = Vec::with_capacity(FIXED_MESSAGE_LEN);
message.extend_from_slice(domain);
message.extend_from_slice(payload);
message
}
/// Builds the transcript that the authentication signature covers.
///
/// Layout:
/// ```text
/// AUTH_TRANSCRIPT_DOMAIN || 0x00 || commit_of_seed[64] || hash_of_sk[64]
/// ```
/// The `0x00` byte acts as a length delimiter between the domain string
/// and the two fixed-length fields.
pub(crate) fn authentication_transcript(statement: SeedChainStatement) -> Vec<u8> {
let mut transcript =
Vec::with_capacity(AUTH_TRANSCRIPT_DOMAIN.len() + 1 + SHA512_DIGEST_LEN * 2);
transcript.extend_from_slice(AUTH_TRANSCRIPT_DOMAIN);
transcript.push(0);
transcript.extend_from_slice(&statement.commit_of_seed);
transcript.extend_from_slice(&statement.hash_of_sk);
transcript
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_seed() -> Seed {
[7_u8; ED25519_SEED_LEN]
}
#[test]
fn round_trip_proof_verifies() {
let proof = gen_pokos(sample_seed()).unwrap();
assert_eq!(verify_pokos(&proof), Ok(()));
}
#[test]
fn proof_serialization_round_trip() {
let proof = gen_pokos(sample_seed()).unwrap();
let encoded = serialize_proof(&proof);
let decoded = deserialize_proof(&encoded).unwrap();
assert_eq!(decoded, proof);
assert_eq!(verify_pokos(&decoded), Ok(()));
}
#[test]
fn rejects_wrong_commitment() {
let mut proof = gen_pokos(sample_seed()).unwrap();
proof.statement.commit_of_seed[0] ^= 1;
assert_eq!(
verify_pokos(&proof),
Err(VerifyError::InvalidSkDerivationProof)
);
}
#[test]
fn rejects_wrong_authentication_key() {
let mut proof = gen_pokos(sample_seed()).unwrap();
let other_seed = [9_u8; ED25519_SEED_LEN];
proof.authentication_key = derive_secret_key_material(other_seed).authentication_key;
assert_eq!(
verify_pokos(&proof),
Err(VerifyError::AuthenticationSignatureInvalid)
);
}
#[test]
fn rejects_tampered_sha512_proof() {
let mut proof = gen_pokos(sample_seed()).unwrap();
proof.sha512_proof.sealed_proof[0] ^= 1;
assert_eq!(
verify_pokos(&proof),
Err(VerifyError::InvalidSkDerivationProof)
);
}
#[test]
fn active_path_depends_only_on_sealed_proof() {
let proof = gen_pokos(sample_seed()).unwrap();
let encoded = serialize_proof(&proof);
let decoded = deserialize_proof(&encoded).unwrap();
assert_eq!(verify_pokos(&decoded), Ok(()));
}
#[test]
fn rejects_broken_signature() {
let mut proof = gen_pokos(sample_seed()).unwrap();
let mut sig_bytes = proof.authentication_signature.to_bytes();
sig_bytes[0] ^= 1;
proof.authentication_signature = Signature::from_slice(&sig_bytes).unwrap();
assert_eq!(
verify_pokos(&proof),
Err(VerifyError::AuthenticationSignatureInvalid)
);
}
#[test]
fn rejects_invalid_serialized_magic() {
let proof = gen_pokos(sample_seed()).unwrap();
let mut encoded = serialize_proof(&proof);
encoded[0] ^= 1;
assert_eq!(
deserialize_proof(&encoded),
Err(DeserializeError::InvalidMagic)
);
}
#[test]
fn rejects_trailing_bytes() {
let proof = gen_pokos(sample_seed()).unwrap();
let mut encoded = serialize_proof(&proof);
encoded.push(0);
assert_eq!(
deserialize_proof(&encoded),
Err(DeserializeError::TrailingBytes)
);
}
#[test]
fn rejects_overflowing_sha512_bundle_length() {
let mut encoded = Vec::new();
encoded.extend_from_slice(PROOF_FORMAT_MAGIC);
encoded.extend_from_slice(&[0_u8; SHA512_DIGEST_LEN]);
encoded.extend_from_slice(&[0_u8; SHA512_DIGEST_LEN]);
encoded.extend_from_slice(&u64::MAX.to_be_bytes());
assert_eq!(
deserialize_proof(&encoded),
Err(DeserializeError::Truncated)
);
}
#[test]
fn fixed_block_layout_is_stable() {
let seed = sample_seed();
let block = fixed_single_block(&COMMIT_OF_SEED_DOMAIN, &seed);
let words = block_words(block);
let mut expected_word = [0_u8; 8];
expected_word.copy_from_slice(&COMMIT_OF_SEED_DOMAIN[..8]);
assert_eq!(words[0], u64::from_be_bytes(expected_word));
let payload_words = &words[PAYLOAD_WORD_START..PAYLOAD_WORD_START + PAYLOAD_WORD_COUNT];
for (i, word) in payload_words.iter().enumerate() {
let mut expected = [0_u8; 8];
expected.copy_from_slice(&seed[i * 8..(i + 1) * 8]);
assert_eq!(*word, u64::from_be_bytes(expected));
}
assert_eq!(words[8], 0x8000_0000_0000_0000);
assert_eq!(words[LENGTH_WORD_INDEX], (FIXED_MESSAGE_LEN as u64) * 8);
}
}

View file

@ -0,0 +1,211 @@
//! Public types and helpers describing the three-segment SHA-512 seed chain.
//!
//! The seed chain is the computation proved by the STARK:
//!
//! ```text
//! Segment 0 (Commit): SHA512(COMMIT_OF_SEED_DOMAIN || seed) → commit_of_seed
//! Segment 1 (Derive): SHA512(DERIVE_SK_DOMAIN || seed) → prf_output (sk_seed = prf_output[0..32])
//! Segment 2 (HashSk): SHA512(HASH_OF_SK_DOMAIN || sk_seed) → hash_of_sk
//! ```
//!
//! Each segment is a single-block SHA-512 evaluation with the same fixed layout:
//! 32 bytes of domain label followed by 32 bytes of payload, padded to 128 bytes.
//!
//! The types in this module describe this layout at the *witness* level (before the
//! STARK circuit is involved). They are shared with the inner
//! `sha512/private_seed_chain.rs` STARK layer (which re-exports
//! [`PrivateSeedChainPublic`] and imports [`PrivateSeedChainWitness`] and
//! [`segment_block`] from here) so that each type is defined in exactly one place.
use crate::{
COMMIT_OF_SEED_DOMAIN, DERIVE_SK_DOMAIN, DOMAIN_LEN, DigestBytes, FIXED_BLOCK_WORDS,
FIXED_MESSAGE_LEN, HASH_OF_SK_DOMAIN, PAYLOAD_WORD_COUNT, PAYLOAD_WORD_START, Seed,
block_words, fixed_single_block, sha512,
};
/// Number of real SHA-512 segments in the seed chain (commit, derive, hash_sk).
pub const ACTIVE_SEGMENT_COUNT: usize = 3;
/// Number of segments after padding to the next power of two for the AIR.
pub const ACTIVE_PADDED_SEGMENT_COUNT: usize = ACTIVE_SEGMENT_COUNT.next_power_of_two();
/// Total number of AIR trace rows for the padded seed chain
/// (`ACTIVE_PADDED_SEGMENT_COUNT × 128`).
pub const ACTIVE_AIR_TRACE_ROWS: usize = 128 * ACTIVE_PADDED_SEGMENT_COUNT;
/// Number of columns in the AIR trace.
pub const ACTIVE_AIR_TRACE_COLS: usize = 1076;
/// Identifies which of the three seed-chain segments a layout or constraint belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SegmentKind {
/// The commit segment: `SHA512(COMMIT_OF_SEED_DOMAIN || seed)`.
Commit,
/// The derive segment: `SHA512(DERIVE_SK_DOMAIN || seed)`.
Derive,
/// The hash-of-sk segment: `SHA512(HASH_OF_SK_DOMAIN || sk_seed)`.
HashSk,
}
/// The prover's private witness for the seed chain.
///
/// Both fields are secret; only the public outputs derived from them are
/// exposed in the [`SeedChainStatement`](crate::SeedChainStatement).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PrivateSeedChainWitness {
/// The original 32-byte secret seed.
pub seed: Seed,
/// The first 32 bytes of `SHA512(DERIVE_SK_DOMAIN || seed)`, used as the
/// Ed25519 signing seed.
pub sk_seed: Seed,
}
/// The public outputs of the seed chain, visible to the verifier.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PrivateSeedChainPublic {
/// `SHA512(COMMIT_OF_SEED_DOMAIN || seed)`.
pub commit_of_seed: DigestBytes,
/// `SHA512(HASH_OF_SK_DOMAIN || sk_seed)`.
pub hash_of_sk: DigestBytes,
}
/// The fully expanded block layout for a single seed-chain segment.
///
/// This captures both the domain/payload metadata and the concrete word
/// decomposition used by the AIR trace builder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FixedSegmentLayout {
/// Which segment this layout corresponds to.
pub kind: SegmentKind,
/// The 32-byte domain-separation prefix for this segment.
pub domain: [u8; DOMAIN_LEN],
/// The four 64-bit words of the 32-byte payload (words 4..7 of the block).
pub payload_words: [u64; PAYLOAD_WORD_COUNT],
/// All 16 big-endian 64-bit words of the full padded 128-byte block.
pub block_words: [u64; FIXED_BLOCK_WORDS],
}
/// Computes the public outputs from a private witness without running the STARK.
///
/// Useful for tests and for building the expected public values before proof
/// generation or verification.
pub fn public_from_witness(witness: PrivateSeedChainWitness) -> PrivateSeedChainPublic {
PrivateSeedChainPublic {
commit_of_seed: sha512(&segment_message(SegmentKind::Commit, witness.seed)),
hash_of_sk: sha512(&segment_message(SegmentKind::HashSk, witness.sk_seed)),
}
}
/// Builds the single padded 128-byte SHA-512 block for a segment payload.
///
/// This is the exact fixed-layout block consumed by the SHA-512 AIR:
/// 32 bytes of domain, 32 bytes of payload, then standard single-block SHA-512
/// padding out to 128 bytes.
pub fn segment_block(kind: SegmentKind, payload: Seed) -> [u8; 128] {
fixed_single_block(&segment_domain(kind), &payload)
}
/// Builds the full [`FixedSegmentLayout`] for a given segment kind and payload.
///
/// Computes the padded 128-byte block, then extracts the 16 block words and
/// the 4 payload words from it.
pub fn segment_layout(kind: SegmentKind, payload: Seed) -> FixedSegmentLayout {
let block = segment_block(kind, payload);
let block_words = block_words(block);
let payload_words = core::array::from_fn(|i| block_words[PAYLOAD_WORD_START + i]);
FixedSegmentLayout {
kind,
domain: segment_domain(kind),
payload_words,
block_words,
}
}
/// Builds the 64-byte pre-padding message `domain || payload` for a segment.
pub fn segment_message(kind: SegmentKind, payload: Seed) -> [u8; FIXED_MESSAGE_LEN] {
let mut message = [0_u8; FIXED_MESSAGE_LEN];
message[..DOMAIN_LEN].copy_from_slice(&segment_domain(kind));
message[DOMAIN_LEN..].copy_from_slice(&payload);
message
}
/// Returns the 32-byte domain-separation prefix for `kind`.
pub fn segment_domain(kind: SegmentKind) -> [u8; DOMAIN_LEN] {
match kind {
SegmentKind::Commit => COMMIT_OF_SEED_DOMAIN,
SegmentKind::Derive => DERIVE_SK_DOMAIN,
SegmentKind::HashSk => HASH_OF_SK_DOMAIN,
}
}
/// Encodes a 32-byte `payload` as four 64-bit big-endian words.
///
/// These are words 4..7 of the SHA-512 input block — the words the AIR
/// treats as the private payload.
pub fn payload_words(payload: Seed) -> [u64; PAYLOAD_WORD_COUNT] {
core::array::from_fn(|i| {
let mut bytes = [0_u8; 8];
bytes.copy_from_slice(&payload[i * 8..(i + 1) * 8]);
u64::from_be_bytes(bytes)
})
}
/// Returns the SHA-512 message-length word for the fixed 64-byte message.
///
/// SHA-512 encodes the bit-length of the original message in the last word of
/// the padded block. For a 64-byte message this is `64 × 8 = 512`.
pub fn length_word() -> u64 {
(FIXED_MESSAGE_LEN as u64) * 8
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
ED25519_SEED_LEN, FIXED_BLOCK_WORDS, LENGTH_WORD_INDEX, derive_secret_key_material,
};
fn sample_seed() -> Seed {
[7_u8; ED25519_SEED_LEN]
}
#[test]
fn segment_layout_payload_words_are_stable() {
let seed = sample_seed();
let layout = segment_layout(SegmentKind::Commit, seed);
assert_eq!(layout.payload_words, payload_words(seed));
assert_eq!(layout.block_words[LENGTH_WORD_INDEX], length_word());
}
#[test]
fn public_outputs_match_existing_derivation() {
let seed = sample_seed();
let derived = derive_secret_key_material(seed);
let witness = PrivateSeedChainWitness {
seed,
sk_seed: derived.sk_seed,
};
let public = public_from_witness(witness);
assert_eq!(public.commit_of_seed, crate::commit_of_seed(seed));
assert_eq!(public.hash_of_sk, derived.hash_of_sk);
}
#[test]
fn all_segments_share_fixed_block_shape() {
let seed = sample_seed();
let derived = derive_secret_key_material(seed);
let layouts = [
segment_layout(SegmentKind::Commit, seed),
segment_layout(SegmentKind::Derive, seed),
segment_layout(SegmentKind::HashSk, derived.sk_seed),
];
for layout in layouts {
assert_eq!(layout.block_words.len(), FIXED_BLOCK_WORDS);
assert_eq!(layout.block_words[LENGTH_WORD_INDEX], length_word());
assert_eq!(layout.block_words[8], 0x8000_0000_0000_0000);
}
}
}

View file

@ -0,0 +1,113 @@
//! Prover-side entry points for the POKOS proof envelope.
//!
//! This module is responsible for everything the *prover* does:
//!
//! 1. **Key derivation** — [`derive_secret_key_material`] computes the
//! full SHA-512 derivation chain from a `seed`, producing the PRF output,
//! the Ed25519 signing seed (`sk_seed`), and the public hash of that seed.
//! 2. **Statement assembly** — [`statement_from_seed`] and the private
//! `statement_from_derived` helper turn derivation output into the
//! [`SeedChainStatement`] that the STARK proof is bound to.
//! 3. **Proof generation** — [`gen_pokos`] orchestrates the STARK prover
//! and wraps everything into a [`SeedChainProofEnvelope`] signed by the
//! derived Ed25519 key.
use crate::sha512::prove_private_seed_chain;
use crate::{
COMMIT_OF_SEED_DOMAIN, DERIVE_SK_DOMAIN, DerivedSecretKeyMaterial, DigestBytes,
ED25519_SEED_LEN, HASH_OF_SK_DOMAIN, Seed, SeedChainProofEnvelope, SeedChainStatement,
Sha512ProofBundle, authentication_transcript, encode_domain_message, sha512,
};
use curve25519::ed_sigs::{SigningKey, VerificationKeyBytes};
/// Computes the public seed commitment: `SHA512(COMMIT_OF_SEED_DOMAIN || seed)`.
///
/// This is the value published as `commit_of_seed` in the [`SeedChainStatement`].
/// It binds the proof to a specific seed without revealing it.
pub fn commit_of_seed(seed: Seed) -> DigestBytes {
sha512(&encode_domain_message(&COMMIT_OF_SEED_DOMAIN, &seed))
}
/// Derives all secret material from `seed`.
///
/// Executes the full SHA-512 derivation chain:
///
/// ```text
/// prf_output = SHA512(DERIVE_SK_DOMAIN || seed)
/// sk_seed = prf_output[0..32]
/// hash_of_sk = SHA512(HASH_OF_SK_DOMAIN || sk_seed)
/// auth_key = Ed25519 verification key for sk_seed
/// ```
///
/// The returned [`DerivedSecretKeyMaterial`] is the prover's private witness.
/// It should be treated as sensitive and not persisted beyond the proof
/// generation call.
pub fn derive_secret_key_material(seed: Seed) -> DerivedSecretKeyMaterial {
let prf_output = sha512(&encode_domain_message(&DERIVE_SK_DOMAIN, &seed));
let mut sk_seed = [0_u8; ED25519_SEED_LEN];
sk_seed.copy_from_slice(&prf_output[..ED25519_SEED_LEN]);
let hash_of_sk = sha512(&encode_domain_message(&HASH_OF_SK_DOMAIN, &sk_seed));
let authentication_key = VerificationKeyBytes::from(&SigningKey::from(sk_seed));
DerivedSecretKeyMaterial {
prf_output,
sk_seed,
hash_of_sk,
authentication_key,
}
}
/// Computes the public [`SeedChainStatement`] from a seed.
///
/// This is a convenience wrapper that calls [`derive_secret_key_material`] and
/// [`commit_of_seed`] and packs the results into a statement. Useful when a
/// caller needs the public outputs without running the full proof.
pub fn statement_from_seed(seed: Seed) -> SeedChainStatement {
statement_from_derived(seed, &derive_secret_key_material(seed))
}
/// Generates a complete [`SeedChainProofEnvelope`] for `seed`.
///
/// This is the main prover entry point. It:
/// 1. Derives all secret key material from `seed` (one pass through the chain).
/// 2. Assembles the public [`SeedChainStatement`].
/// 3. Runs the Plonky3 STARK prover over the three-segment SHA-512 AIR.
/// 4. Signs the authentication transcript with the derived Ed25519 key.
/// 5. Returns the fully assembled [`SeedChainProofEnvelope`].
///
/// # Errors
///
/// Returns `Err(String)` if the STARK prover fails (e.g. internal Plonky3
/// error) or if the proof settings do not meet the minimum verifier policy.
pub fn gen_pokos(seed: Seed) -> Result<SeedChainProofEnvelope, String> {
let derived = derive_secret_key_material(seed);
let statement = statement_from_derived(seed, &derived);
let signing_key = SigningKey::from(derived.sk_seed);
let transcript = authentication_transcript(statement);
Ok(SeedChainProofEnvelope {
statement,
sha512_proof: prove_sha512_bundle(seed)?,
authentication_key: derived.authentication_key,
authentication_signature: signing_key.sign(&transcript),
})
}
/// Builds a [`SeedChainStatement`] from an already-derived witness, avoiding a
/// redundant call to [`derive_secret_key_material`].
fn statement_from_derived(seed: Seed, derived: &DerivedSecretKeyMaterial) -> SeedChainStatement {
SeedChainStatement {
commit_of_seed: commit_of_seed(seed),
hash_of_sk: derived.hash_of_sk,
}
}
/// Runs the Plonky3 STARK prover over the three-segment SHA-512 seed chain and
/// returns the sealed proof bytes as a [`Sha512ProofBundle`].
pub(crate) fn prove_sha512_bundle(seed: Seed) -> Result<Sha512ProofBundle, String> {
let sealed = prove_private_seed_chain(seed)?;
Ok(Sha512ProofBundle {
sealed_proof: sealed.sealed_proof,
})
}

View file

@ -0,0 +1,665 @@
//! Plonky3 AIR definition for the SHA-512 compression circuit.
//!
//! This module stitches together the column layout ([`columns`]), constraint logic
//! ([`constraints`]), and trace-building utilities ([`trace_builder`]) into a single
//! [`Sha512RoundAir`] that Plonky3 can prove and verify.
//!
//! ## Trace layout (128 rows × `AIR_WIDTH` columns)
//!
//! | Row range | Role |
//! |-----------|------|
//! | 0 – 79 | One SHA-512 compression round per row |
//! | 80 | Post-round-80 working state (before feed-forward); public values are bound here |
//! | 81 – 127 | Padding rows — degenerate register-shift rows with W = K = 0 |
//!
//! ## Public values
//!
//! The active PoKOS seed-chain statement exposes 16 public values:
//! the 8 pre-feed-forward words for the commit segment followed by the 8
//! pre-feed-forward words for the hash-of-sk segment. The verifier reconstructs
//! each SHA-512 digest externally by adding the standard initial state word-wise
//! modulo 2⁶⁴, so the AIR does **not** constrain the feed-forward addition.
//!
//! ## Preprocessed trace
//!
//! An instance-specific preprocessed trace is committed separately from the main trace.
//! It carries:
//! * The initial working state (a..h) — constant across all rows, used for boundary binding.
//! * The round constant K[i] for each round row.
//! * W[0..15] for the initial 16 rows (before the schedule recurrence takes over).
//! * Selector columns controlling which constraint groups and seed-chain roles are active.
//!
//! The active seed-chain-specific trace assembly is split into `air/seed_chain.rs` so this file
//! can stay focused on the generic SHA-512 round AIR and base trace layout.
#[path = "air/columns.rs"]
mod columns;
#[path = "air/constraints.rs"]
mod constraints;
#[path = "air/seed_chain.rs"]
mod seed_chain;
#[path = "air/trace_builder.rs"]
mod trace_builder;
use p3_air::{
Air, AirBuilder, AirBuilderWithPublicValues, BaseAir, BaseAirWithPublicValues, PairBuilder,
};
use p3_field::PrimeCharacteristicRing;
use p3_koala_bear::KoalaBear;
use p3_matrix::Matrix;
use p3_matrix::dense::RowMajorMatrix;
use super::circuit::Sha512Circuit;
use super::constants::{INITIAL_STATE, K};
use super::ops::{bb, big_sigma0, big_sigma1, ch, maj, small_sigma0, small_sigma1};
use super::trace::BlockTrace;
use columns::*;
use constraints::*;
use trace_builder::*;
/// The Plonky3 AIR for SHA-512 block compression.
///
/// `Sha512RoundAir` implements the [`Air`] trait and holds the instance-specific
/// preprocessed trace. The preprocessed trace commits to the initial working state,
/// the 80 round constants, the fixed block words, and selector metadata. This
/// allows the STARK verifier to confirm that the prover used the correct
/// instance without re-running the full witness construction.
///
/// ## Construction
///
/// ```ignore
/// use sha512_circuit::Sha512Circuit;
/// use sha512_circuit::Sha512RoundAir;
///
/// let initial_state = sha512_circuit::INITIAL_STATE;
/// let block = [0u8; 128];
/// let preprocessed = Sha512Circuit::build_plonky3_preprocessed_trace_from_instance(
/// &initial_state, &block,
/// );
/// let air = Sha512RoundAir::new(preprocessed);
/// ```
///
/// In practice you will not construct this directly — the [`prove_single_block`](crate::prove_single_block)
/// family of functions handle it for you.
#[derive(Clone, Debug)]
pub struct Sha512RoundAir {
preprocessed: RowMajorMatrix<KoalaBear>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PrivateSeedChainBlocks {
pub(crate) commit: [u8; 128],
pub(crate) derive: [u8; 128],
pub(crate) hash_sk: [u8; 128],
}
impl Sha512RoundAir {
/// Creates a new [`Sha512RoundAir`] from a precomputed preprocessed trace.
///
/// The `preprocessed` matrix must have been produced by
/// [`Sha512Circuit::build_plonky3_preprocessed_trace_from_instance`] for the same
/// `(initial_state, block)` pair that will be proved / verified.
pub fn new(preprocessed: RowMajorMatrix<KoalaBear>) -> Self {
Self { preprocessed }
}
}
impl BaseAir<KoalaBear> for Sha512RoundAir {
fn width(&self) -> usize {
AIR_WIDTH
}
fn preprocessed_trace(&self) -> Option<RowMajorMatrix<KoalaBear>> {
Some(self.preprocessed.clone())
}
}
impl BaseAirWithPublicValues<KoalaBear> for Sha512RoundAir {
fn num_public_values(&self) -> usize {
16
}
}
impl<AB> Air<AB> for Sha512RoundAir
where
AB: AirBuilderWithPublicValues<F = KoalaBear> + PairBuilder,
{
fn eval(&self, builder: &mut AB) {
let main = builder.main();
let prep = builder.preprocessed();
let local = main.row_slice(0).expect("window has local row");
let next = main.row_slice(1).expect("window has next row");
let local_prep = prep
.row_slice(0)
.expect("window has local preprocessed row");
for limb in 0..LIMBS_PER_WORD {
// Bind K exactly as a 64-bit value, not just modulo the base field.
builder.assert_zero(
local_prep[PREP_ROUND_SELECTOR_COL].clone()
* (local[limb_col(WORD_K, limb)].clone()
- local_prep[limb_col(WORD_K, limb)].clone()),
);
}
for limb in 0..LIMBS_PER_WORD {
// Bind W[0..15] exactly as 64-bit words from the instance.
builder.assert_zero(
local_prep[PREP_FIXED_INIT_W_SELECTOR_COL].clone()
* (local[limb_col(WORD_W, limb)].clone()
- local_prep[limb_col(WORD_W, limb)].clone()),
);
}
for (word_idx, row_sel) in [
(0_usize, local_prep[PREP_PAYLOAD_WORD0_SELECTOR_COL].clone()),
(1_usize, local_prep[PREP_PAYLOAD_WORD1_SELECTOR_COL].clone()),
(2_usize, local_prep[PREP_PAYLOAD_WORD2_SELECTOR_COL].clone()),
(3_usize, local_prep[PREP_PAYLOAD_WORD3_SELECTOR_COL].clone()),
] {
let seed_or_sk_sel = local_prep[PREP_SEGMENT_HASH_SELECTOR_COL].clone();
for limb in 0..LIMBS_PER_WORD {
let seed_limb = local[private_seed_limb_col(word_idx, limb)].clone();
let sk_limb = local[private_sk_limb_col(word_idx, limb)].clone();
let expected = seed_limb.clone() * (AB::Expr::ONE - seed_or_sk_sel.clone())
+ sk_limb.clone() * seed_or_sk_sel.clone();
builder.assert_zero(
row_sel.clone() * (local[limb_col(WORD_W, limb)].clone() - expected),
);
}
}
for limb in 0..LIMBS_PER_WORD {
builder.assert_zero(
(AB::Expr::ONE - local_prep[PREP_ROUND_SELECTOR_COL].clone())
* local[limb_col(WORD_W, limb)].clone(),
);
}
constrain_private_sk_from_derive_final(
builder,
&local,
&local_prep,
local_prep[PREP_DERIVE_FINAL_SELECTOR_COL].clone().into(),
);
let block_start_sel = local_prep[PREP_BLOCK_START_SELECTOR_COL].clone();
for word in WORD_A..=WORD_H {
for limb in 0..LIMBS_PER_WORD {
builder.assert_zero(
block_start_sel.clone()
* (local[limb_col(word, limb)].clone()
- local_prep[limb_col(word, limb)].clone()),
);
}
}
let public: [AB::PublicVar; 16] = core::array::from_fn(|i| builder.public_values()[i]);
let commit_final_sel = local_prep[PREP_COMMIT_FINAL_SELECTOR_COL].clone();
let hash_final_sel = local_prep[PREP_HASH_FINAL_SELECTOR_COL].clone();
for i in 0..8 {
builder.assert_zero(
commit_final_sel.clone()
* (public[i].into() - pack_word_from_limbs::<AB>(&local, i)),
);
builder.assert_zero(
hash_final_sel.clone()
* (public[8 + i].into() - pack_word_from_limbs::<AB>(&local, i)),
);
}
let round_sel = local_prep[PREP_ROUND_SELECTOR_COL].clone();
for (word, base) in [
(WORD_A, BIT_A_BASE),
(WORD_B, BIT_B_BASE),
(WORD_C, BIT_C_BASE),
(WORD_E, BIT_E_BASE),
(WORD_F, BIT_F_BASE),
(WORD_G, BIT_G_BASE),
] {
for bit in 0..64 {
builder.assert_zero(
round_sel.clone()
* (local[base + bit].clone() * (AB::Expr::ONE - local[base + bit].clone())),
);
}
builder.assert_zero(
round_sel.clone()
* (pack_word_from_limbs::<AB>(&local, word) - pack_bits::<AB>(&local, base)),
);
for limb in 0..LIMBS_PER_WORD {
let mut limb_expr = AB::Expr::ZERO;
for bit in 0..16 {
let bit_col = base + limb * 16 + bit;
limb_expr += local[bit_col].clone() * KoalaBear::from_u32(1 << bit);
}
builder.assert_zero(
round_sel.clone() * (local[limb_col(word, limb)].clone() - limb_expr),
);
}
}
for limb in 0..LIMBS_PER_WORD {
let mut sigma0_limb = AB::Expr::ZERO;
let mut sigma1_limb = AB::Expr::ZERO;
let mut ch_limb = AB::Expr::ZERO;
let mut maj_limb = AB::Expr::ZERO;
for bit in 0..16 {
let bit_idx = limb * 16 + bit;
let a = local[BIT_A_BASE + bit_idx].clone();
let b = local[BIT_B_BASE + bit_idx].clone();
let c = local[BIT_C_BASE + bit_idx].clone();
let e = local[BIT_E_BASE + bit_idx].clone();
let f = local[BIT_F_BASE + bit_idx].clone();
let g = local[BIT_G_BASE + bit_idx].clone();
let sigma0 = xor3_expr::<AB>(
local[BIT_A_BASE + ((bit_idx + 28) % 64)].clone().into(),
local[BIT_A_BASE + ((bit_idx + 34) % 64)].clone().into(),
local[BIT_A_BASE + ((bit_idx + 39) % 64)].clone().into(),
);
let sigma1 = xor3_expr::<AB>(
local[BIT_E_BASE + ((bit_idx + 14) % 64)].clone().into(),
local[BIT_E_BASE + ((bit_idx + 18) % 64)].clone().into(),
local[BIT_E_BASE + ((bit_idx + 41) % 64)].clone().into(),
);
let ch_expr = e.clone() * f.clone() + (AB::Expr::ONE - e) * g.clone();
let ab = a.clone() * b.clone();
let ac = a.clone() * c.clone();
let bc = b.clone() * c.clone();
let abc = a * b * c;
let maj_expr = ab + ac + bc - abc * KoalaBear::TWO;
let bit_weight = KoalaBear::from_u32(1 << bit);
sigma0_limb += sigma0 * bit_weight;
sigma1_limb += sigma1 * bit_weight;
ch_limb += ch_expr * bit_weight;
maj_limb += maj_expr * bit_weight;
}
builder.assert_zero(
round_sel.clone() * (local[limb_col(WORD_SIGMA0, limb)].clone() - sigma0_limb),
);
builder.assert_zero(
round_sel.clone() * (local[limb_col(WORD_SIGMA1, limb)].clone() - sigma1_limb),
);
builder.assert_zero(
round_sel.clone() * (local[limb_col(WORD_CH, limb)].clone() - ch_limb),
);
builder.assert_zero(
round_sel.clone() * (local[limb_col(WORD_MAJ, limb)].clone() - maj_limb),
);
}
for src in 0..RANGE_SOURCES {
let mut packed = AB::Expr::ZERO;
for bit in 0..RANGE_BITS_PER_SOURCE {
let b = local[range_bit_col(src, bit)].clone();
builder.assert_bool(b.clone());
packed += b * KoalaBear::from_u32(1 << bit);
}
builder.assert_eq(local[range_source_col(src)].clone(), packed);
}
for (lag, base) in [(1_usize, LAG1_BIT_BASE), (14_usize, LAG14_BIT_BASE)] {
for bit in 0..64 {
builder.assert_bool(local[base + bit].clone());
}
for limb in 0..LIMBS_PER_WORD {
let mut packed = AB::Expr::ZERO;
for bit in 0..16 {
packed += local[base + limb * 16 + bit].clone() * KoalaBear::from_u32(1 << bit);
}
builder.assert_eq(local[lag_limb_col(lag, limb)].clone(), packed);
}
}
let mut global_transition = builder.when_transition();
for word in 0..4 {
for limb in 0..LIMBS_PER_WORD {
global_transition.assert_eq(
next[private_seed_limb_col(word, limb)].clone(),
local[private_seed_limb_col(word, limb)].clone(),
);
global_transition.assert_eq(
next[private_sk_limb_col(word, limb)].clone(),
local[private_sk_limb_col(word, limb)].clone(),
);
}
}
let mut transition_window = builder.when_transition();
let mut transition =
transition_window.when(local_prep[PREP_TRANSITION_SELECTOR_COL].clone());
constrain_add_5_limbs(
&mut transition,
&local,
[WORD_H, WORD_SIGMA1, WORD_CH, WORD_K, WORD_W],
WORD_T1,
CARRY_T1_BASE,
);
constrain_add_2_limbs(
&mut transition,
&local,
WORD_SIGMA0,
WORD_MAJ,
WORD_T2,
CARRY_T2_BASE,
);
constrain_add_2_limbs_across_rows(
&mut transition,
&local,
&next,
WORD_T1,
WORD_T2,
WORD_A,
CARRY_A_BASE,
);
constrain_add_2_limbs_across_rows(
&mut transition,
&local,
&next,
WORD_D,
WORD_T1,
WORD_E,
CARRY_E_BASE,
);
for limb in 0..LIMBS_PER_WORD {
transition.assert_eq(
next[limb_col(WORD_B, limb)].clone(),
local[limb_col(WORD_A, limb)].clone(),
);
transition.assert_eq(
next[limb_col(WORD_C, limb)].clone(),
local[limb_col(WORD_B, limb)].clone(),
);
transition.assert_eq(
next[limb_col(WORD_D, limb)].clone(),
local[limb_col(WORD_C, limb)].clone(),
);
transition.assert_eq(
next[limb_col(WORD_F, limb)].clone(),
local[limb_col(WORD_E, limb)].clone(),
);
transition.assert_eq(
next[limb_col(WORD_G, limb)].clone(),
local[limb_col(WORD_F, limb)].clone(),
);
transition.assert_eq(
next[limb_col(WORD_H, limb)].clone(),
local[limb_col(WORD_G, limb)].clone(),
);
}
for lag in 0..LAG_COUNT {
for limb in 0..LIMBS_PER_WORD {
let expected = if lag == 0 {
local[limb_col(WORD_W, limb)].clone()
} else {
local[lag_limb_col(lag - 1, limb)].clone()
};
transition.assert_eq(next[lag_limb_col(lag, limb)].clone(), expected);
}
}
let sched_sel = local_prep[PREP_ROUND_SELECTOR_COL].clone()
* (AB::Expr::ONE - local_prep[PREP_FIXED_INIT_W_SELECTOR_COL].clone())
* (AB::Expr::ONE - local_prep[PREP_PAYLOAD_WORD_SELECTOR_COL].clone());
constrain_schedule_recurrence(&mut transition, &local, sched_sel);
let mut last = builder.when_last_row();
for word in WORD_W..WORD_COUNT {
for limb in 0..LIMBS_PER_WORD {
last.assert_eq(local[limb_col(word, limb)].clone(), KoalaBear::ZERO);
}
}
for col in CARRY_T1_BASE..BIT_A_BASE {
last.assert_eq(local[col].clone(), KoalaBear::ZERO);
}
}
}
fn pack_word_from_limbs<AB: AirBuilder<F = KoalaBear>>(row: &[AB::Var], word: usize) -> AB::Expr {
let two16 = KoalaBear::from_u32(1 << 16);
let two32 = KoalaBear::from_u64(1_u64 << 32);
let two48 = KoalaBear::from_u64(1_u64 << 48);
row[limb_col(word, 0)].clone()
+ row[limb_col(word, 1)].clone() * two16
+ row[limb_col(word, 2)].clone() * two32
+ row[limb_col(word, 3)].clone() * two48
}
impl Sha512Circuit {
/// Builds the instance-specific preprocessed trace matrix.
///
/// The preprocessed trace has the same dimensions as the main trace
/// (128 rows × `AIR_WIDTH` columns) but only a small subset of columns are
/// populated. All other cells are zero. Populated columns:
///
/// * `limb_col(WORD_K, ..)` — round constant K\[i\] limbs in rows 0..80; zero in rows 80..127.
/// * `limb_col(WORD_W, ..)` — W\[i\] limbs in rows 0..15.
/// * `limb_col(WORD_A..WORD_H, ..)` — initial state limbs, constant across all rows;
/// the first-row boundary constraint uses these to bind the main trace.
/// * `PREP_ROUND_SELECTOR_COL` — 1 in rows 0..79, 0 elsewhere.
/// * `PREP_INIT_W_SELECTOR_COL` — 1 in rows 0..15, 0 elsewhere.
/// * `PREP_BLOCK_START_SELECTOR_COL` — 1 on row 0 (block start), 0 elsewhere.
/// * `PREP_TRANSITION_SELECTOR_COL` — 1 in rows 0..126, 0 on row 127.
/// * `PREP_FINAL_SELECTOR_COL` — 1 in row 80 only.
///
/// # Panics
///
/// Panics internally if the 128-byte block cannot be parsed into 64-bit words
/// (should not occur for valid inputs).
pub fn build_plonky3_preprocessed_trace_from_instance(
initial_state: &[u64; 8],
block: &[u8; 128],
) -> RowMajorMatrix<KoalaBear> {
let mut values = vec![KoalaBear::ZERO; TRACE_ROWS * AIR_WIDTH];
let block_words: [u64; 16] = core::array::from_fn(|i| {
let start = i * 8;
u64::from_be_bytes(block[start..start + 8].try_into().expect("word size is 8"))
});
for row in 0..TRACE_ROWS {
let dst = &mut values[row * AIR_WIDTH..(row + 1) * AIR_WIDTH];
for limb in 0..LIMBS_PER_WORD {
let k = if row < 80 { K[row] } else { 0 };
dst[limb_col(WORD_K, limb)] =
KoalaBear::from_u16(((k >> (16 * limb)) & 0xffff) as u16);
let w = if row < 16 { block_words[row] } else { 0 };
dst[limb_col(WORD_W, limb)] =
KoalaBear::from_u16(((w >> (16 * limb)) & 0xffff) as u16);
}
dst[PREP_ROUND_SELECTOR_COL] = KoalaBear::from_bool(row < 80);
dst[PREP_INIT_W_SELECTOR_COL] = KoalaBear::from_bool(row < 16);
dst[PREP_FIXED_INIT_W_SELECTOR_COL] = KoalaBear::from_bool(row < 16);
dst[PREP_BLOCK_START_SELECTOR_COL] = KoalaBear::from_bool(row == 0);
dst[PREP_TRANSITION_SELECTOR_COL] = KoalaBear::from_bool(row + 1 < TRACE_ROWS);
dst[PREP_FINAL_SELECTOR_COL] = KoalaBear::from_bool(row == 80);
for (offset, value) in initial_state.iter().copied().enumerate() {
let word = WORD_A + offset;
for limb in 0..LIMBS_PER_WORD {
let limb_value = ((value >> (16 * limb)) & 0xffff) as u16;
dst[limb_col(word, limb)] = KoalaBear::from_u16(limb_value);
}
}
}
RowMajorMatrix::new(values, AIR_WIDTH)
}
/// Builds the full AIR witness (main trace) from a [`BlockTrace`].
///
/// Produces a 128-row × `AIR_WIDTH`-column [`RowMajorMatrix`] in KoalaBear.
///
/// ## Row structure
///
/// * **Rows 0–79** (round rows): For each SHA-512 round `i`, fills in the
/// 16-bit limb decompositions for all tracked words (a..h, W, K, Σ0, Σ1, Ch, Maj, T1, T2),
/// carry values for each limb-wise addition (T1, T2, A, E,
/// and schedule), 64-bit Boolean decompositions for bitwise operations, and the
/// corresponding range-proof bit columns.
///
/// * **Row 80** (final state row): Contains only the 8 working-state limbs
/// (`round_states[80]`) together with the lag history
/// for the schedule, and degenerate "padding helpers" (W = K = 0, all carry /
/// bit columns zeroed). This row's words are bound to the 8 public values by
/// the `PREP_FINAL_SELECTOR_COL` constraint.
///
/// * **Rows 81–127** (padding rows): Degenerate rows that extend the trace to
/// the required power-of-two length (128). The register-shift transition
/// constraints still hold here (b ← a, etc.), but W = K = 0 and all non-state
/// helper columns are zero.
///
/// ## Column groups
///
/// | Group | Column range | Purpose |
/// |-------|-------------|---------|
/// | Limbs | 0–63 | 4 × 16-bit decomposition per word |
/// | Carries | 64–79 | Per-limb carries for T1, T2, A, E additions |
/// | Lag limbs | 80–143 | Previous 16 W values, 4 limbs each |
/// | Sched carries | 144–147 | Carries for the W recurrence |
/// | Bits | 148–531 | 64-bit Boolean decompositions for a,b,c,e,f,g |
/// | Lag sigma bits | 532–659 | 64-bit decomposition for lag1 and lag14 |
/// | Range bits | 660–1043 | 16-bit range proofs for D/H/W/K/T1/T2 limbs |
/// | Carry bits | 1044–1075 | Minimal-width carry bit decompositions |
pub fn build_plonky3_air_trace(trace: &BlockTrace) -> RowMajorMatrix<KoalaBear> {
let mut values = Vec::with_capacity(TRACE_ROWS * AIR_WIDTH);
let mut lags = [0_u64; LAG_COUNT];
for (i, &constant) in K.iter().enumerate() {
let s = trace.round_states[i];
let word = trace.words[i];
let sigma0 = big_sigma0(s[0]);
let sigma1 = big_sigma1(s[4]);
let choose = ch(s[4], s[5], s[6]);
let majority = maj(s[0], s[1], s[2]);
let t1 = s[7]
.wrapping_add(sigma1)
.wrapping_add(choose)
.wrapping_add(constant)
.wrapping_add(word);
let t2 = sigma0.wrapping_add(majority);
let (_, carry_t1) = add_with_carries_5(s[7], sigma1, choose, constant, word);
let (_, carry_t2) = add_with_carries_2(sigma0, majority);
let (_, carry_a) = add_with_carries_2(t1, t2);
let (_, carry_e) = add_with_carries_2(s[3], t1);
let sched_carries = if i >= 16 {
let w2 = trace.words[i - 2];
let w7 = trace.words[i - 7];
let w15 = trace.words[i - 15];
let w16 = trace.words[i - 16];
let (_, carries) = add_with_carries_4(small_sigma1(w2), w7, small_sigma0(w15), w16);
carries
} else {
[0; LIMBS_PER_WORD]
};
let mut row = [KoalaBear::ZERO; AIR_WIDTH];
let words = [
s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], word, constant, sigma0, sigma1,
choose, majority, t1, t2,
];
for (w, &value) in words.iter().enumerate() {
set_word_limbs(&mut row, w, value);
}
set_lag_words(&mut row, &lags);
set_lag_sigma_bits(&mut row, &lags);
set_helper_bits(&mut row);
set_carries(&mut row, CARRY_T1_BASE, carry_t1);
set_carries(&mut row, CARRY_T2_BASE, carry_t2);
set_carries(&mut row, CARRY_A_BASE, carry_a);
set_carries(&mut row, CARRY_E_BASE, carry_e);
set_carries(&mut row, SCHED_CARRY_BASE, sched_carries);
set_carry_bits(&mut row);
set_range_bits(&mut row);
values.extend(row);
advance_lags(&mut lags, word);
}
let mut row80 = [KoalaBear::ZERO; AIR_WIDTH];
let s = trace.round_states[80];
let words = [s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]];
for (w, &value) in words.iter().enumerate() {
set_word_limbs(&mut row80, w, value);
}
set_lag_words(&mut row80, &lags);
set_lag_sigma_bits(&mut row80, &lags);
set_helper_bits(&mut row80);
seed_padding_helpers(&mut row80);
set_carry_bits(&mut row80);
set_range_bits(&mut row80);
values.extend(row80);
advance_lags(&mut lags, 0);
let mut state = trace.round_states[80];
for row_idx in SHA_ROUNDS_PLUS_INIT..TRACE_ROWS {
let next_state = [
state[7],
state[0],
state[1],
state[2],
state[3].wrapping_add(state[7]),
state[4],
state[5],
state[6],
];
let mut row = [KoalaBear::ZERO; AIR_WIDTH];
let words = [
next_state[0],
next_state[1],
next_state[2],
next_state[3],
next_state[4],
next_state[5],
next_state[6],
next_state[7],
];
for (w, &value) in words.iter().enumerate() {
set_word_limbs(&mut row, w, value);
}
set_lag_words(&mut row, &lags);
set_lag_sigma_bits(&mut row, &lags);
set_helper_bits(&mut row);
if row_idx != TRACE_ROWS - 1 {
seed_padding_helpers(&mut row);
}
set_carry_bits(&mut row);
set_range_bits(&mut row);
values.extend(row);
advance_lags(&mut lags, 0);
state = next_state;
}
RowMajorMatrix::new(values, AIR_WIDTH)
}
pub(crate) fn build_private_seed_chain_air_bundle(
blocks: &PrivateSeedChainBlocks,
) -> MessageAirBundle {
seed_chain::build_private_seed_chain_air_bundle(blocks)
}
}
pub(crate) struct MessageAirBundle {
pub(crate) main: RowMajorMatrix<KoalaBear>,
pub(crate) preprocessed: RowMajorMatrix<KoalaBear>,
pub(crate) final_public_values: [KoalaBear; 16],
pub(crate) degree_bits: usize,
}
pub(crate) use columns::{
LIMBS_PER_WORD, PREP_BLOCK_START_SELECTOR_COL, PREP_COMMIT_FINAL_SELECTOR_COL,
PREP_DERIVE_FINAL_SELECTOR_COL, PREP_FINAL_SELECTOR_COL, PREP_FIXED_INIT_W_SELECTOR_COL,
PREP_HASH_FINAL_SELECTOR_COL, PREP_INIT_W_SELECTOR_COL, PREP_PAYLOAD_WORD_SELECTOR_COL,
PREP_PAYLOAD_WORD0_SELECTOR_COL, PREP_PAYLOAD_WORD1_SELECTOR_COL,
PREP_PAYLOAD_WORD2_SELECTOR_COL, PREP_PAYLOAD_WORD3_SELECTOR_COL, PREP_ROUND_SELECTOR_COL,
PREP_SEGMENT_COMMIT_SELECTOR_COL, PREP_SEGMENT_DERIVE_SELECTOR_COL,
PREP_SEGMENT_HASH_SELECTOR_COL, PREP_TRANSITION_SELECTOR_COL, WORD_A, WORD_K, WORD_W, limb_col,
};
#[cfg(test)]
pub(crate) use columns::{
LIMB_BASE_FOR_TESTS, LIMBS_PER_WORD_FOR_TESTS, PREP_COMMIT_FINAL_SELECTOR_COL_FOR_TESTS,
PREP_DERIVE_FINAL_SELECTOR_COL_FOR_TESTS, PREP_FIXED_INIT_W_SELECTOR_COL_FOR_TESTS,
PREP_HASH_FINAL_SELECTOR_COL_FOR_TESTS, PREP_PAYLOAD_WORD_SELECTOR_COL_FOR_TESTS,
PREP_SEGMENT_COMMIT_SELECTOR_COL_FOR_TESTS, PREP_SEGMENT_DERIVE_SELECTOR_COL_FOR_TESTS,
PREP_SEGMENT_HASH_SELECTOR_COL_FOR_TESTS, PRIVATE_SEED_LIMB_BASE_FOR_TESTS,
PRIVATE_SK_LIMB_BASE_FOR_TESTS, WORD_W_FOR_TESTS,
};

View file

@ -0,0 +1,365 @@
//! Column index constants and helper functions for the SHA-512 AIR trace.
//!
//! The main AIR trace has `AIR_WIDTH` columns per row. This module defines a name for
//! every column (or column group) and provides accessor functions that compute the
//! concrete column index from logical identifiers (word index, limb index, bit index,
//! etc.).
//!
//! ## Column layout (in order)
//!
//! ```text
//! ┌─ Limbs ────────────────────────── cols 0 – 63 ──────────────────────────────────────┐
//! │ 16 words × 4 limbs (16-bit each) = 64 columns │
//! ├─ Carries ───────────────────────────────────────────────────────────────────────────┤
//! │ Carry_T1 (4), Carry_T2 (4), Carry_A (4), Carry_E (4) = 16 columns │
//! ├─ Lags ──────────────────────────────────────────────────────────────────────────────┤
//! │ 16 previous W values (ring buffer), stored as 4 limbs each = 64 columns │
//! ├─ Schedule carries ──────────────────────────────────────────────────────────────────┤
//! │ 4 carries for W recurrence = 4 columns │
//! ├─ Bit decompositions ────────────────────────────────────────────────────────────────┤
//! │ 64 bits × {A, B, C, E, F, G} = 384 columns │
//! │ 64 bits × {lag1, lag14} = 128 columns │
//! ├─ Range-proof bits ──────────────────────────────────────────────────────────────────┤
//! │ RANGE_SOURCES sources × 16 bits each (D/H/W/K/T1/T2 limbs) │
//! ├─ Carry bits ────────────────────────────────────────────────────────────────────────┤
//! │ Minimal-width carry bit decompositions (T1=3 bits, T2/A/E=1 bit, sched=2 bits) │
//! ├─ Preprocessed columns (at the tail — shared with the preprocessed trace) ───────────┤
//! │ PREP_BLOCK_START_SELECTOR_COL — 1 at block-start rows, 0 elsewhere │
//! │ PREP_TRANSITION_SELECTOR_COL — 1 where row-to-next transition is enforced │
//! │ PREP_ROUND_SELECTOR_COL — 1 in rounds 0..79, 0 elsewhere │
//! │ PREP_INIT_W_SELECTOR_COL — 1 in rows 0..15, 0 elsewhere │
//! │ PREP_FINAL_SELECTOR_COL — 1 in row 80 only │
//! │ PREP_SEGMENT_* selectors — fixed-role metadata for the seed-chain AIR │
//! └─────────────────────────────────────────────────────────────────────────────────────┘
//! ```
// ─── Trace dimensions ────────────────────────────────────────────────────────
/// Total number of rows in the AIR trace (must be a power of two).
///
/// Rows 0–79 are the 80 SHA-512 compression rounds.
/// Row 80 holds the post-round working state and the public value bindings.
/// Rows 81–127 are degenerate padding rows.
pub(super) const TRACE_ROWS: usize = 128;
/// First row index that is not a real SHA-512 round (row 80 = final state, rows 81+ = padding).
pub(super) const SHA_ROUNDS_PLUS_INIT: usize = 81;
// ─── Logical word ids ────────────────────────────────────────────────────────
/// Logical word id for working variable `a`.
pub(crate) const WORD_A: usize = 0;
/// Logical word id for working variable `b` (equals previous round's `a`).
pub(super) const WORD_B: usize = 1;
/// Logical word id for working variable `c` (equals previous round's `b`).
pub(super) const WORD_C: usize = 2;
/// Logical word id for working variable `d` (equals previous round's `c`).
pub(super) const WORD_D: usize = 3;
/// Logical word id for working variable `e`.
pub(super) const WORD_E: usize = 4;
/// Logical word id for working variable `f` (equals previous round's `e`).
pub(super) const WORD_F: usize = 5;
/// Logical word id for working variable `g` (equals previous round's `f`).
pub(super) const WORD_G: usize = 6;
/// Logical word id for working variable `h` (equals previous round's `g`).
pub(super) const WORD_H: usize = 7;
/// Logical word id for current message schedule word W[i].
pub(crate) const WORD_W: usize = 8;
/// Logical word id for round constant K[i].
pub(crate) const WORD_K: usize = 9;
/// Logical word id for Σ0(a).
pub(super) const WORD_SIGMA0: usize = 10;
/// Logical word id for Σ1(e).
pub(super) const WORD_SIGMA1: usize = 11;
/// Logical word id for Ch(e, f, g).
pub(super) const WORD_CH: usize = 12;
/// Logical word id for Maj(a, b, c).
pub(super) const WORD_MAJ: usize = 13;
/// Logical word id for T1.
pub(super) const WORD_T1: usize = 14;
/// Logical word id for T2.
pub(super) const WORD_T2: usize = 15;
/// Total number of logical words tracked in limbs.
pub(super) const WORD_COUNT: usize = 16;
// ─── Limb columns ────────────────────────────────────────────────────────────
/// Number of 16-bit limbs per 64-bit word.
pub(crate) const LIMBS_PER_WORD: usize = 4;
/// First column of the limb section.
///
/// Limbs are stored as `LIMB_BASE + word * LIMBS_PER_WORD + limb` where `limb ∈ 0..4`
/// with limb 0 being the least significant 16 bits. Use [`limb_col`] to compute.
pub(super) const LIMB_BASE: usize = 0;
// ─── Carry columns ───────────────────────────────────────────────────────────
/// First carry column for the T1 = h + Σ1(e) + Ch + K + W limb-wise addition.
///
/// Four consecutive columns, one per limb (least to most significant).
pub(super) const CARRY_T1_BASE: usize = WORD_COUNT * LIMBS_PER_WORD;
/// First carry column for the T2 = Σ0(a) + Maj limb-wise addition.
pub(super) const CARRY_T2_BASE: usize = CARRY_T1_BASE + LIMBS_PER_WORD;
/// First carry column for the new-`a` addition: A = T1 + T2 (cross-row).
pub(super) const CARRY_A_BASE: usize = CARRY_T2_BASE + LIMBS_PER_WORD;
/// First carry column for the new-`e` addition: E = d + T1 (cross-row).
pub(super) const CARRY_E_BASE: usize = CARRY_A_BASE + LIMBS_PER_WORD;
// ─── Lag columns (message schedule history) ──────────────────────────────────
/// Number of previous W values tracked in the lag ring buffer.
///
/// The SHA-512 schedule recurrence references W[i−2], W[i−7], W[i−15], and W[i−16],
/// so the circuit needs to remember the last 16 W values.
pub(super) const LAG_COUNT: usize = 16;
/// First column of the lag-word limb section.
///
/// Each lag word is also decomposed into 4 × 16-bit limbs for range-proof purposes.
/// Use [`lag_limb_col`] to compute.
pub(super) const LAG_LIMB_BASE: usize = CARRY_E_BASE + LIMBS_PER_WORD;
// ─── Schedule carry columns ───────────────────────────────────────────────────
/// First carry column for the 4-operand message schedule recurrence addition.
///
/// The recurrence W[i] = σ1(W[i−2]) + W[i−7] + σ0(W[i−15]) + W[i−16] requires
/// four carry columns (one per 16-bit limb).
pub(super) const SCHED_CARRY_BASE: usize = LAG_LIMB_BASE + LAG_COUNT * LIMBS_PER_WORD;
// ─── Bit-decomposition columns ────────────────────────────────────────────────
/// First bit column for the Boolean decomposition of `a`.
pub(super) const BIT_A_BASE: usize = SCHED_CARRY_BASE + LIMBS_PER_WORD;
/// First bit column for the Boolean decomposition of `b`.
pub(super) const BIT_B_BASE: usize = BIT_A_BASE + 64;
/// First bit column for the Boolean decomposition of `c`.
pub(super) const BIT_C_BASE: usize = BIT_B_BASE + 64;
/// First bit column for the Boolean decomposition of `e`.
pub(super) const BIT_E_BASE: usize = BIT_C_BASE + 64;
/// First bit column for the Boolean decomposition of `f`.
pub(super) const BIT_F_BASE: usize = BIT_E_BASE + 64;
/// First bit column for the Boolean decomposition of `g`.
pub(super) const BIT_G_BASE: usize = BIT_F_BASE + 64;
// ─── Range-proof columns ─────────────────────────────────────────────────────
/// Words whose limbs are range-proved through the generic 16-bit range-bit section.
///
/// Limbs of `A,B,C,E,F,G` are constrained directly from their 64-bit Boolean
/// decompositions in the AIR, so they are excluded from this set.
pub(super) const RANGED_WORDS: [usize; 6] = [WORD_D, WORD_H, WORD_W, WORD_K, WORD_T1, WORD_T2];
/// Number of range-proof sources contributed by word limbs.
pub(super) const RANGED_WORD_SOURCES: usize = RANGED_WORDS.len() * LIMBS_PER_WORD;
/// Number of 16-bit values that receive a generic range proof (selected word limbs only).
pub(super) const RANGE_SOURCES: usize = RANGED_WORD_SOURCES;
/// Number of Boolean bits allocated per range-proof source (= 16, covering 0..65535).
pub(super) const RANGE_BITS_PER_SOURCE: usize = 16;
/// First bit column for the Boolean decomposition of lag word W[i-2] (lag index 1).
pub(super) const LAG1_BIT_BASE: usize = BIT_G_BASE + 64;
/// First bit column for the Boolean decomposition of lag word W[i-15] (lag index 14).
pub(super) const LAG14_BIT_BASE: usize = LAG1_BIT_BASE + 64;
/// First column of the range-proof bit section.
pub(super) const RANGE_BIT_BASE: usize = LAG14_BIT_BASE + 64;
/// First column of carry-bit decomposition section.
pub(super) const CARRY_BIT_BASE: usize = RANGE_BIT_BASE + RANGE_SOURCES * RANGE_BITS_PER_SOURCE;
/// First carry-bit column for T1 carry limbs (3 bits per limb).
pub(super) const CARRY_T1_BIT_BASE: usize = CARRY_BIT_BASE;
/// First carry-bit column for T2 carry limbs (1 bit per limb).
pub(super) const CARRY_T2_BIT_BASE: usize = CARRY_T1_BIT_BASE + LIMBS_PER_WORD * 3;
/// First carry-bit column for A carry limbs (1 bit per limb).
pub(super) const CARRY_A_BIT_BASE: usize = CARRY_T2_BIT_BASE + LIMBS_PER_WORD;
/// First carry-bit column for E carry limbs (1 bit per limb).
pub(super) const CARRY_E_BIT_BASE: usize = CARRY_A_BIT_BASE + LIMBS_PER_WORD;
/// First carry-bit column for schedule carry limbs (2 bits per limb).
pub(super) const CARRY_SCHED_BIT_BASE: usize = CARRY_E_BIT_BASE + LIMBS_PER_WORD;
/// First seed-chain segment selector: 1 on commit segment rows, 0 elsewhere.
pub(crate) const PREP_SEGMENT_COMMIT_SELECTOR_COL: usize =
CARRY_SCHED_BIT_BASE + LIMBS_PER_WORD * 2;
/// 1 on derive segment rows, 0 elsewhere.
pub(crate) const PREP_SEGMENT_DERIVE_SELECTOR_COL: usize = PREP_SEGMENT_COMMIT_SELECTOR_COL + 1;
/// 1 on hash-of-sk segment rows, 0 elsewhere.
pub(crate) const PREP_SEGMENT_HASH_SELECTOR_COL: usize = PREP_SEGMENT_DERIVE_SELECTOR_COL + 1;
/// 1 on row 80 of the commit segment, 0 elsewhere.
pub(crate) const PREP_COMMIT_FINAL_SELECTOR_COL: usize = PREP_SEGMENT_HASH_SELECTOR_COL + 1;
/// 1 on row 80 of the derive segment, 0 elsewhere.
pub(crate) const PREP_DERIVE_FINAL_SELECTOR_COL: usize = PREP_COMMIT_FINAL_SELECTOR_COL + 1;
/// 1 on row 80 of the hash-of-sk segment, 0 elsewhere.
pub(crate) const PREP_HASH_FINAL_SELECTOR_COL: usize = PREP_DERIVE_FINAL_SELECTOR_COL + 1;
/// 1 on rows 4..7 of each seed-chain segment, where W carries the private payload.
pub(crate) const PREP_PAYLOAD_WORD_SELECTOR_COL: usize = PREP_HASH_FINAL_SELECTOR_COL + 1;
/// 1 on fixed W[0..15] rows except payload rows, for the seed-chain AIR.
pub(crate) const PREP_FIXED_INIT_W_SELECTOR_COL: usize = PREP_PAYLOAD_WORD_SELECTOR_COL + 1;
/// 1 only on row 4 of each seed-chain segment.
pub(crate) const PREP_PAYLOAD_WORD0_SELECTOR_COL: usize = PREP_FIXED_INIT_W_SELECTOR_COL + 1;
/// 1 only on row 5 of each seed-chain segment.
pub(crate) const PREP_PAYLOAD_WORD1_SELECTOR_COL: usize = PREP_PAYLOAD_WORD0_SELECTOR_COL + 1;
/// 1 only on row 6 of each seed-chain segment.
pub(crate) const PREP_PAYLOAD_WORD2_SELECTOR_COL: usize = PREP_PAYLOAD_WORD1_SELECTOR_COL + 1;
/// 1 only on row 7 of each seed-chain segment.
pub(crate) const PREP_PAYLOAD_WORD3_SELECTOR_COL: usize = PREP_PAYLOAD_WORD2_SELECTOR_COL + 1;
/// Hidden witness columns holding the 32-byte seed as four 64-bit words.
///
/// These indices belong to the main trace only. The preprocessed trace reuses the
/// same column index space with different semantics in the tail selector region.
pub(super) const PRIVATE_SEED_LIMB_BASE: usize = PREP_PAYLOAD_WORD3_SELECTOR_COL + 1;
/// Hidden witness columns holding the 32-byte derived sk_seed as four 64-bit words.
pub(super) const PRIVATE_SK_LIMB_BASE: usize = PRIVATE_SEED_LIMB_BASE + 4 * LIMBS_PER_WORD;
/// Total number of columns in the AIR trace (main and preprocessed share the same width).
pub(super) const AIR_WIDTH: usize = PRIVATE_SK_LIMB_BASE + 4 * LIMBS_PER_WORD;
// ─── Preprocessed selector columns (at the tail of the shared column space) ──
/// Preprocessed selector: 1 on the first row of each real block segment, 0 elsewhere.
///
/// Note that preprocessed selectors intentionally reuse the shared AIR column index
/// space instead of reserving disjoint indices from the main-trace-only witness area.
pub(crate) const PREP_BLOCK_START_SELECTOR_COL: usize = AIR_WIDTH - 5;
/// Preprocessed selector: 1 when transition constraints are active for this row.
///
/// This is set on rows whose `next` row belongs to the same real block segment.
pub(crate) const PREP_TRANSITION_SELECTOR_COL: usize = AIR_WIDTH - 4;
/// Preprocessed selector: 1 for rows 0..79 (active SHA-512 rounds), 0 elsewhere.
///
/// Guards constraints that only apply during real compression rounds (e.g. Σ0/Σ1
/// bit decomposition checks, T1/T2 addition constraints).
pub(crate) const PREP_ROUND_SELECTOR_COL: usize = AIR_WIDTH - 3;
/// Preprocessed selector: 1 for rows 0..15 (initial W words from the block), 0 elsewhere.
///
/// Binds the W column to the preprocessed W[0..15] values during the first 16 rows.
pub(crate) const PREP_INIT_W_SELECTOR_COL: usize = AIR_WIDTH - 2;
/// Preprocessed selector: 1 only on row 80 (final working state), 0 elsewhere.
///
/// Binds the 8 public values to the working-state columns on this row.
pub(crate) const PREP_FINAL_SELECTOR_COL: usize = AIR_WIDTH - 1;
// ─── Index accessor functions ─────────────────────────────────────────────────
/// Returns the column index for `limb` (0–3, LSB first) of `word` (0–15).
pub(crate) fn limb_col(word: usize, limb: usize) -> usize {
LIMB_BASE + word * LIMBS_PER_WORD + limb
}
/// Returns the column index for `limb` (0–3) of lag word `lag`.
pub(super) fn lag_limb_col(lag: usize, limb: usize) -> usize {
LAG_LIMB_BASE + lag * LIMBS_PER_WORD + limb
}
/// Returns the **column** index of range-proof source `source`.
///
/// Maps logical source indices to selected word limbs (`D/H/W/K/T1/T2`) in the
/// concrete column that holds the 16-bit value being range-proved. Used by the
/// constraint system to assert `source_col == Σ bit_col[source][k] * 2^k`.
pub(super) fn range_source_col(source: usize) -> usize {
if source < RANGED_WORD_SOURCES {
let word_idx = source / LIMBS_PER_WORD;
let limb = source % LIMBS_PER_WORD;
limb_col(RANGED_WORDS[word_idx], limb)
} else {
unreachable!("range sources only include selected word limbs");
}
}
/// Returns the column index for bit `bit` (0 = LSB) of range-proof source `source`.
pub(super) fn range_bit_col(source: usize, bit: usize) -> usize {
RANGE_BIT_BASE + source * RANGE_BITS_PER_SOURCE + bit
}
/// Returns the number of carry bits allocated for `carry_col`.
pub(super) fn carry_bit_width(carry_col: usize) -> usize {
if (CARRY_T1_BASE..CARRY_T2_BASE).contains(&carry_col) {
3
} else if (CARRY_T2_BASE..LAG_LIMB_BASE).contains(&carry_col) {
1
} else if (SCHED_CARRY_BASE..BIT_A_BASE).contains(&carry_col) {
2
} else {
unreachable!("carry_col is out of carry column ranges");
}
}
/// Returns the carry-bit column index for bit `bit` of `carry_col`.
pub(super) fn carry_bit_col(carry_col: usize, bit: usize) -> usize {
if (CARRY_T1_BASE..CARRY_T2_BASE).contains(&carry_col) {
CARRY_T1_BIT_BASE + (carry_col - CARRY_T1_BASE) * 3 + bit
} else if (CARRY_T2_BASE..CARRY_A_BASE).contains(&carry_col) {
CARRY_T2_BIT_BASE + (carry_col - CARRY_T2_BASE) + bit
} else if (CARRY_A_BASE..CARRY_E_BASE).contains(&carry_col) {
CARRY_A_BIT_BASE + (carry_col - CARRY_A_BASE) + bit
} else if (CARRY_E_BASE..LAG_LIMB_BASE).contains(&carry_col) {
CARRY_E_BIT_BASE + (carry_col - CARRY_E_BASE) + bit
} else if (SCHED_CARRY_BASE..BIT_A_BASE).contains(&carry_col) {
CARRY_SCHED_BIT_BASE + (carry_col - SCHED_CARRY_BASE) * 2 + bit
} else {
unreachable!("carry_col is out of carry column ranges");
}
}
pub(super) fn private_seed_limb_col(word: usize, limb: usize) -> usize {
PRIVATE_SEED_LIMB_BASE + word * LIMBS_PER_WORD + limb
}
pub(super) fn private_sk_limb_col(word: usize, limb: usize) -> usize {
PRIVATE_SK_LIMB_BASE + word * LIMBS_PER_WORD + limb
}
// ─── Test re-exports ──────────────────────────────────────────────────────────
#[cfg(test)]
pub(crate) const WORD_W_FOR_TESTS: usize = WORD_W;
#[cfg(test)]
pub(crate) const LIMB_BASE_FOR_TESTS: usize = LIMB_BASE;
#[cfg(test)]
pub(crate) const LIMBS_PER_WORD_FOR_TESTS: usize = LIMBS_PER_WORD;
#[cfg(test)]
pub(crate) const PREP_SEGMENT_COMMIT_SELECTOR_COL_FOR_TESTS: usize =
PREP_SEGMENT_COMMIT_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_SEGMENT_DERIVE_SELECTOR_COL_FOR_TESTS: usize =
PREP_SEGMENT_DERIVE_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_SEGMENT_HASH_SELECTOR_COL_FOR_TESTS: usize = PREP_SEGMENT_HASH_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_COMMIT_FINAL_SELECTOR_COL_FOR_TESTS: usize = PREP_COMMIT_FINAL_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_DERIVE_FINAL_SELECTOR_COL_FOR_TESTS: usize = PREP_DERIVE_FINAL_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_HASH_FINAL_SELECTOR_COL_FOR_TESTS: usize = PREP_HASH_FINAL_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_PAYLOAD_WORD_SELECTOR_COL_FOR_TESTS: usize = PREP_PAYLOAD_WORD_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PREP_FIXED_INIT_W_SELECTOR_COL_FOR_TESTS: usize = PREP_FIXED_INIT_W_SELECTOR_COL;
#[cfg(test)]
pub(crate) const PRIVATE_SEED_LIMB_BASE_FOR_TESTS: usize = PRIVATE_SEED_LIMB_BASE;
#[cfg(test)]
pub(crate) const PRIVATE_SK_LIMB_BASE_FOR_TESTS: usize = PRIVATE_SK_LIMB_BASE;

View file

@ -0,0 +1,231 @@
use p3_air::AirBuilder;
use p3_field::PrimeCharacteristicRing;
use p3_koala_bear::KoalaBear;
use super::columns::{LAG1_BIT_BASE, LAG14_BIT_BASE};
use super::columns::{
LIMBS_PER_WORD, SCHED_CARRY_BASE, WORD_A, WORD_W, carry_bit_col, carry_bit_width, lag_limb_col,
limb_col, private_sk_limb_col,
};
pub(super) fn constrain_add_5_limbs<AB: AirBuilder<F = KoalaBear>>(
builder: &mut AB,
row: &[AB::Var],
ops: [usize; 5],
out: usize,
carry_base: usize,
) {
let two16 = KoalaBear::from_u32(1 << 16);
let mut carry_in = AB::Expr::ZERO;
for limb in 0..LIMBS_PER_WORD {
let carry_out = row[carry_base + limb].clone();
constrain_carry_max::<AB>(builder, row, carry_base + limb, 4);
let sum = row[limb_col(ops[0], limb)].clone()
+ row[limb_col(ops[1], limb)].clone()
+ row[limb_col(ops[2], limb)].clone()
+ row[limb_col(ops[3], limb)].clone()
+ row[limb_col(ops[4], limb)].clone()
+ carry_in;
let rhs = row[limb_col(out, limb)].clone() + carry_out.clone() * two16;
builder.assert_eq(sum, rhs);
carry_in = carry_out.into();
}
}
pub(super) fn constrain_add_2_limbs<AB: AirBuilder<F = KoalaBear>>(
builder: &mut AB,
row: &[AB::Var],
lhs: usize,
rhs: usize,
out: usize,
carry_base: usize,
) {
let two16 = KoalaBear::from_u32(1 << 16);
let mut carry_in = AB::Expr::ZERO;
for limb in 0..LIMBS_PER_WORD {
let carry_out = row[carry_base + limb].clone();
constrain_carry_max::<AB>(builder, row, carry_base + limb, 1);
let sum = row[limb_col(lhs, limb)].clone() + row[limb_col(rhs, limb)].clone() + carry_in;
let expected = row[limb_col(out, limb)].clone() + carry_out.clone() * two16;
builder.assert_eq(sum, expected);
carry_in = carry_out.into();
}
}
pub(super) fn constrain_add_2_limbs_across_rows<AB: AirBuilder<F = KoalaBear>>(
builder: &mut AB,
local: &[AB::Var],
next: &[AB::Var],
lhs: usize,
rhs: usize,
out_next: usize,
carry_base: usize,
) {
let two16 = KoalaBear::from_u32(1 << 16);
let mut carry_in = AB::Expr::ZERO;
for limb in 0..LIMBS_PER_WORD {
let carry_out = local[carry_base + limb].clone();
constrain_carry_max::<AB>(builder, local, carry_base + limb, 1);
let sum =
local[limb_col(lhs, limb)].clone() + local[limb_col(rhs, limb)].clone() + carry_in;
let expected = next[limb_col(out_next, limb)].clone() + carry_out.clone() * two16;
builder.assert_eq(sum, expected);
carry_in = carry_out.into();
}
}
pub(super) fn constrain_schedule_recurrence<B: AirBuilder<F = KoalaBear>>(
builder: &mut B,
row: &[B::Var],
selector: B::Expr,
) {
let two16 = KoalaBear::from_u32(1 << 16);
let mut carry_in = B::Expr::ZERO;
for limb in 0..LIMBS_PER_WORD {
let sigma1_limb = pack_small_sigma1_limb::<B>(row, limb);
let sigma0_limb = pack_small_sigma0_limb::<B>(row, limb);
let lag7_limb = row[lag_limb_col(6, limb)].clone();
let lag16_limb = row[lag_limb_col(15, limb)].clone();
let carry_out = row[SCHED_CARRY_BASE + limb].clone();
constrain_carry_max::<B>(builder, row, SCHED_CARRY_BASE + limb, 3);
let sum = sigma1_limb + lag7_limb + sigma0_limb + lag16_limb + carry_in;
let expected = row[limb_col(WORD_W, limb)].clone() + carry_out.clone() * two16;
builder.assert_zero(selector.clone() * (sum - expected));
carry_in = carry_out.into();
}
}
pub(super) fn constrain_private_sk_from_derive_final<AB: AirBuilder<F = KoalaBear>>(
builder: &mut AB,
row: &[AB::Var],
prep_row: &[AB::Var],
selector: AB::Expr,
) {
let two16 = KoalaBear::from_u32(1 << 16);
for (word_idx, carry_base) in [
(0_usize, super::columns::CARRY_T1_BASE),
(1_usize, super::columns::CARRY_T2_BASE),
(2_usize, super::columns::CARRY_A_BASE),
(3_usize, super::columns::CARRY_E_BASE),
] {
let mut carry_in = AB::Expr::ZERO;
for limb in 0..LIMBS_PER_WORD {
let carry_out = row[carry_base + limb].clone();
constrain_carry_max::<AB>(builder, row, carry_base + limb, 1);
let sum = row[limb_col(WORD_A + word_idx, limb)].clone()
+ prep_row[limb_col(WORD_A + word_idx, limb)].clone()
+ carry_in;
let expected =
row[private_sk_limb_col(word_idx, limb)].clone() + carry_out.clone() * two16;
builder.assert_zero(selector.clone() * (sum - expected));
carry_in = carry_out.into();
}
}
}
pub(super) fn constrain_carry_max<AB: AirBuilder<F = KoalaBear>>(
builder: &mut AB,
row: &[AB::Var],
carry_col: usize,
max: u32,
) {
let width = carry_bit_width(carry_col);
let mut packed = AB::Expr::ZERO;
for bit in 0..width {
let b = row[carry_bit_col(carry_col, bit)].clone();
builder.assert_bool(b.clone());
packed += b * KoalaBear::from_u32(1 << bit);
}
builder.assert_eq(row[carry_col].clone(), packed);
match max {
1 => {}
3 => {}
4 => {
let b0 = row[carry_bit_col(carry_col, 0)].clone();
let b1 = row[carry_bit_col(carry_col, 1)].clone();
let b2 = row[carry_bit_col(carry_col, 2)].clone();
builder.assert_zero(b2 * (b1 + b0));
}
_ => unreachable!("unsupported carry bound"),
}
}
pub(super) fn pack_bits<AB: AirBuilder<F = KoalaBear>>(
row: &[AB::Var],
bit_base: usize,
) -> AB::Expr {
let mut acc = AB::Expr::ZERO;
for i in (0..64).rev() {
acc = acc * KoalaBear::TWO + row[bit_base + i].clone();
}
acc
}
pub(super) fn xor2_expr<AB: AirBuilder<F = KoalaBear>>(x: AB::Expr, y: AB::Expr) -> AB::Expr {
x.clone() + y.clone() - (x * y) * KoalaBear::TWO
}
pub(super) fn xor3_expr<AB: AirBuilder<F = KoalaBear>>(
x: AB::Expr,
y: AB::Expr,
z: AB::Expr,
) -> AB::Expr {
xor2_expr::<AB>(xor2_expr::<AB>(x, y), z)
}
fn pack_small_sigma0_limb<B: AirBuilder<F = KoalaBear>>(row: &[B::Var], limb: usize) -> B::Expr {
let mut out = B::Expr::ZERO;
for bit in 0..16 {
let b = small_sigma0_bit::<B>(row, limb * 16 + bit);
out += b * KoalaBear::from_u32(1 << bit);
}
out
}
fn pack_small_sigma1_limb<B: AirBuilder<F = KoalaBear>>(row: &[B::Var], limb: usize) -> B::Expr {
let mut out = B::Expr::ZERO;
for bit in 0..16 {
let b = small_sigma1_bit::<B>(row, limb * 16 + bit);
out += b * KoalaBear::from_u32(1 << bit);
}
out
}
fn small_sigma0_bit<B: AirBuilder<F = KoalaBear>>(row: &[B::Var], bit: usize) -> B::Expr {
xor3_expr::<B>(
lag_bit_expr::<B>(row, 14, (bit + 1) % 64),
lag_bit_expr::<B>(row, 14, (bit + 8) % 64),
if bit + 7 < 64 {
lag_bit_expr::<B>(row, 14, bit + 7)
} else {
B::Expr::ZERO
},
)
}
fn small_sigma1_bit<B: AirBuilder<F = KoalaBear>>(row: &[B::Var], bit: usize) -> B::Expr {
xor3_expr::<B>(
lag_bit_expr::<B>(row, 1, (bit + 19) % 64),
lag_bit_expr::<B>(row, 1, (bit + 61) % 64),
if bit + 6 < 64 {
lag_bit_expr::<B>(row, 1, bit + 6)
} else {
B::Expr::ZERO
},
)
}
fn lag_bit_expr<B: AirBuilder<F = KoalaBear>>(row: &[B::Var], lag: usize, bit: usize) -> B::Expr {
let base = match lag {
1 => LAG1_BIT_BASE,
14 => LAG14_BIT_BASE,
_ => unreachable!("only lag=1 and lag=14 are bit-addressed in schedule sigmas"),
};
row[base + bit].clone().into()
}

View file

@ -0,0 +1,150 @@
use p3_field::PrimeCharacteristicRing;
use p3_koala_bear::KoalaBear;
use p3_matrix::Matrix;
use p3_matrix::dense::RowMajorMatrix;
use super::{
AIR_WIDTH, INITIAL_STATE, LIMBS_PER_WORD, MessageAirBundle, PREP_BLOCK_START_SELECTOR_COL,
PREP_COMMIT_FINAL_SELECTOR_COL, PREP_DERIVE_FINAL_SELECTOR_COL, PREP_FINAL_SELECTOR_COL,
PREP_FIXED_INIT_W_SELECTOR_COL, PREP_HASH_FINAL_SELECTOR_COL, PREP_INIT_W_SELECTOR_COL,
PREP_PAYLOAD_WORD_SELECTOR_COL, PREP_PAYLOAD_WORD0_SELECTOR_COL,
PREP_PAYLOAD_WORD1_SELECTOR_COL, PREP_PAYLOAD_WORD2_SELECTOR_COL,
PREP_PAYLOAD_WORD3_SELECTOR_COL, PREP_ROUND_SELECTOR_COL, PREP_SEGMENT_COMMIT_SELECTOR_COL,
PREP_SEGMENT_DERIVE_SELECTOR_COL, PREP_SEGMENT_HASH_SELECTOR_COL, PREP_TRANSITION_SELECTOR_COL,
PrivateSeedChainBlocks, SHA_ROUNDS_PLUS_INIT, Sha512Circuit, TRACE_ROWS, WORD_A, WORD_K,
WORD_W, bb, limb_col, set_private_seed_chain_derive_final_carries,
set_private_seed_chain_words,
};
pub(super) fn build_private_seed_chain_air_bundle(
blocks: &PrivateSeedChainBlocks,
) -> MessageAirBundle {
let seed_words = payload_words(blocks.commit);
let derive_seed_words = payload_words(blocks.derive);
let sk_words = payload_words(blocks.hash_sk);
debug_assert_eq!(
seed_words, derive_seed_words,
"commit and derive blocks must carry the same seed payload"
);
let segments = [
(INITIAL_STATE, blocks.commit),
(INITIAL_STATE, blocks.derive),
(INITIAL_STATE, blocks.hash_sk),
];
let real_segment_count = segments.len();
let segment_count = real_segment_count.next_power_of_two().max(1);
let total_rows = segment_count * TRACE_ROWS;
let degree_bits = total_rows.trailing_zeros() as usize;
debug_assert_eq!(1_usize << degree_bits, total_rows);
let mut main_values = vec![KoalaBear::ZERO; total_rows * AIR_WIDTH];
let mut prep_values = vec![KoalaBear::ZERO; total_rows * AIR_WIDTH];
let mut final_public_values = [KoalaBear::ZERO; 16];
for row in 0..total_rows {
let dst_base = row * AIR_WIDTH;
let row_slice: &mut [KoalaBear] = &mut main_values[dst_base..dst_base + AIR_WIDTH];
let row_array: &mut [KoalaBear; AIR_WIDTH] = row_slice.try_into().expect("row width");
set_private_seed_chain_words(row_array, seed_words, sk_words);
}
for (seg, (state, block)) in segments.iter().copied().enumerate() {
let trace = Sha512Circuit::compress_block(&state, &block);
let main = Sha512Circuit::build_plonky3_air_trace(&trace);
let prep = Sha512Circuit::build_plonky3_preprocessed_trace_from_instance(&state, &block);
for row in 0..TRACE_ROWS {
let dst_base = (seg * TRACE_ROWS + row) * AIR_WIDTH;
let src_main = main.row_slice(row).expect("main row exists");
let src_prep = prep.row_slice(row).expect("prep row exists");
main_values[dst_base..dst_base + AIR_WIDTH].copy_from_slice(&src_main);
let row_slice: &mut [KoalaBear] = &mut main_values[dst_base..dst_base + AIR_WIDTH];
let row_array: &mut [KoalaBear; AIR_WIDTH] = row_slice.try_into().expect("row width");
set_private_seed_chain_words(row_array, seed_words, sk_words);
for word in WORD_A..WORD_A + 8 {
for limb in 0..LIMBS_PER_WORD {
prep_values[dst_base + limb_col(word, limb)] = src_prep[limb_col(word, limb)];
}
}
for limb in 0..LIMBS_PER_WORD {
prep_values[dst_base + limb_col(WORD_K, limb)] = src_prep[limb_col(WORD_K, limb)];
}
if row < 16 && !(4..8).contains(&row) {
for limb in 0..LIMBS_PER_WORD {
prep_values[dst_base + limb_col(WORD_W, limb)] =
src_prep[limb_col(WORD_W, limb)];
}
}
prep_values[dst_base + PREP_BLOCK_START_SELECTOR_COL] = KoalaBear::from_bool(row == 0);
prep_values[dst_base + PREP_TRANSITION_SELECTOR_COL] =
KoalaBear::from_bool(row + 1 < TRACE_ROWS && row != 80);
prep_values[dst_base + PREP_ROUND_SELECTOR_COL] = KoalaBear::from_bool(row < 80);
prep_values[dst_base + PREP_FINAL_SELECTOR_COL] =
KoalaBear::from_bool(seg + 1 == real_segment_count && row == 80);
prep_values[dst_base + PREP_SEGMENT_COMMIT_SELECTOR_COL] =
KoalaBear::from_bool(seg == 0);
prep_values[dst_base + PREP_SEGMENT_DERIVE_SELECTOR_COL] =
KoalaBear::from_bool(seg == 1);
prep_values[dst_base + PREP_SEGMENT_HASH_SELECTOR_COL] = KoalaBear::from_bool(seg == 2);
prep_values[dst_base + PREP_COMMIT_FINAL_SELECTOR_COL] =
KoalaBear::from_bool(seg == 0 && row == 80);
prep_values[dst_base + PREP_DERIVE_FINAL_SELECTOR_COL] =
KoalaBear::from_bool(seg == 1 && row == 80);
prep_values[dst_base + PREP_HASH_FINAL_SELECTOR_COL] =
KoalaBear::from_bool(seg == 2 && row == 80);
// Fixed 32-byte-domain || 32-byte-payload layout:
// rows 4..7 carry the private payload words W[4..7].
prep_values[dst_base + PREP_INIT_W_SELECTOR_COL] =
KoalaBear::from_bool(row < 16 && !(4..8).contains(&row));
prep_values[dst_base + PREP_PAYLOAD_WORD_SELECTOR_COL] =
KoalaBear::from_bool((4..8).contains(&row));
prep_values[dst_base + PREP_FIXED_INIT_W_SELECTOR_COL] =
KoalaBear::from_bool(row < 16 && !(4..8).contains(&row));
prep_values[dst_base + PREP_PAYLOAD_WORD0_SELECTOR_COL] =
KoalaBear::from_bool(row == 4);
prep_values[dst_base + PREP_PAYLOAD_WORD1_SELECTOR_COL] =
KoalaBear::from_bool(row == 5);
prep_values[dst_base + PREP_PAYLOAD_WORD2_SELECTOR_COL] =
KoalaBear::from_bool(row == 6);
prep_values[dst_base + PREP_PAYLOAD_WORD3_SELECTOR_COL] =
KoalaBear::from_bool(row == 7);
if seg == 1 && row == 80 {
set_private_seed_chain_derive_final_carries(
row_array,
trace.round_states[80],
INITIAL_STATE,
);
}
}
if seg == 0 {
final_public_values[..8].copy_from_slice(&trace.round_states[80].map(bb));
}
if seg == 2 {
final_public_values[8..].copy_from_slice(&trace.round_states[80].map(bb));
}
}
debug_assert!(total_rows >= SHA_ROUNDS_PLUS_INIT);
MessageAirBundle {
main: RowMajorMatrix::new(main_values, AIR_WIDTH),
preprocessed: RowMajorMatrix::new(prep_values, AIR_WIDTH),
final_public_values,
degree_bits,
}
}
fn payload_words(block: [u8; 128]) -> [u64; 4] {
core::array::from_fn(|i| {
let start = 32 + i * 8;
u64::from_be_bytes(block[start..start + 8].try_into().expect("payload word"))
})
}

View file

@ -0,0 +1,229 @@
use p3_field::{PrimeCharacteristicRing, PrimeField32};
use p3_koala_bear::KoalaBear;
use super::columns::{
AIR_WIDTH, BIT_A_BASE, BIT_B_BASE, BIT_C_BASE, BIT_E_BASE, BIT_F_BASE, BIT_G_BASE,
CARRY_A_BASE, CARRY_E_BASE, CARRY_T1_BASE, CARRY_T2_BASE, LAG_COUNT, LAG_LIMB_BASE,
LIMBS_PER_WORD, RANGE_BITS_PER_SOURCE, RANGE_SOURCES, SCHED_CARRY_BASE, WORD_A, WORD_B, WORD_C,
WORD_CH, WORD_E, WORD_F, WORD_G, WORD_K, WORD_MAJ, WORD_SIGMA0, WORD_SIGMA1, WORD_T1, WORD_T2,
WORD_W, carry_bit_col, carry_bit_width, lag_limb_col, limb_col, private_seed_limb_col,
private_sk_limb_col, range_bit_col, range_source_col,
};
use super::columns::{LAG1_BIT_BASE, LAG14_BIT_BASE};
pub(super) fn set_word_limbs(row: &mut [KoalaBear; AIR_WIDTH], word: usize, value: u64) {
let limbs = u64_to_limbs(value);
for (i, limb) in limbs.into_iter().enumerate() {
row[limb_col(word, i)] = KoalaBear::from_u16(limb);
}
}
pub(super) fn set_lag_words(row: &mut [KoalaBear; AIR_WIDTH], lags: &[u64; LAG_COUNT]) {
for (lag, value) in lags.iter().copied().enumerate() {
let limbs = u64_to_limbs(value);
for (limb, limb_value) in limbs.into_iter().enumerate() {
row[lag_limb_col(lag, limb)] = KoalaBear::from_u16(limb_value);
}
}
}
pub(super) fn set_carries(
row: &mut [KoalaBear; AIR_WIDTH],
base: usize,
carries: [u16; LIMBS_PER_WORD],
) {
for (i, carry) in carries.into_iter().enumerate() {
row[base + i] = KoalaBear::from_u16(carry);
}
}
pub(super) fn set_range_bits(row: &mut [KoalaBear; AIR_WIDTH]) {
for source in 0..RANGE_SOURCES {
let value_col = range_source_col(source);
let x = row[value_col].as_canonical_u32();
for bit in 0..RANGE_BITS_PER_SOURCE {
row[range_bit_col(source, bit)] = KoalaBear::from_bool(((x >> bit) & 1) == 1);
}
}
}
pub(super) fn set_carry_bits(row: &mut [KoalaBear; AIR_WIDTH]) {
for carry_col in CARRY_T1_BASE..LAG_LIMB_BASE {
let width = carry_bit_width(carry_col);
let x = row[carry_col].as_canonical_u32();
for bit in 0..width {
row[carry_bit_col(carry_col, bit)] = KoalaBear::from_bool(((x >> bit) & 1) == 1);
}
}
for carry_col in SCHED_CARRY_BASE..BIT_A_BASE {
let width = carry_bit_width(carry_col);
let x = row[carry_col].as_canonical_u32();
for bit in 0..width {
row[carry_bit_col(carry_col, bit)] = KoalaBear::from_bool(((x >> bit) & 1) == 1);
}
}
}
pub(super) fn advance_lags(lags: &mut [u64; LAG_COUNT], word: u64) {
for i in (1..LAG_COUNT).rev() {
lags[i] = lags[i - 1];
}
lags[0] = word;
}
pub(super) fn seed_padding_helpers(row: &mut [KoalaBear; AIR_WIDTH]) {
let h = decode_word_from_inline(row, 7);
let d = decode_word_from_inline(row, 3);
let t1 = h;
let t2 = 0_u64;
let (_, carry_t1) = add_with_carries_5(h, 0, 0, 0, 0);
let (_, carry_t2) = add_with_carries_2(0, 0);
let (_, carry_a) = add_with_carries_2(t1, t2);
let (_, carry_e) = add_with_carries_2(d, t1);
set_word_limbs(row, WORD_W, 0);
set_word_limbs(row, WORD_K, 0);
set_word_limbs(row, WORD_SIGMA0, 0);
set_word_limbs(row, WORD_SIGMA1, 0);
set_word_limbs(row, WORD_CH, 0);
set_word_limbs(row, WORD_MAJ, 0);
set_word_limbs(row, WORD_T1, t1);
set_word_limbs(row, WORD_T2, 0);
set_helper_bits(row);
set_carries(row, CARRY_T1_BASE, carry_t1);
set_carries(row, CARRY_T2_BASE, carry_t2);
set_carries(row, CARRY_A_BASE, carry_a);
set_carries(row, CARRY_E_BASE, carry_e);
set_carries(row, SCHED_CARRY_BASE, [0; LIMBS_PER_WORD]);
}
pub(super) fn set_helper_bits(row: &mut [KoalaBear; AIR_WIDTH]) {
for (word, base) in [
(WORD_A, BIT_A_BASE),
(WORD_B, BIT_B_BASE),
(WORD_C, BIT_C_BASE),
(WORD_E, BIT_E_BASE),
(WORD_F, BIT_F_BASE),
(WORD_G, BIT_G_BASE),
] {
let value = decode_word_from_inline(row, word);
for i in 0..64 {
row[base + i] = KoalaBear::from_bool(((value >> i) & 1) == 1);
}
}
}
pub(super) fn set_lag_sigma_bits(row: &mut [KoalaBear; AIR_WIDTH], lags: &[u64; LAG_COUNT]) {
for i in 0..64 {
row[LAG1_BIT_BASE + i] = KoalaBear::from_bool(((lags[1] >> i) & 1) == 1);
row[LAG14_BIT_BASE + i] = KoalaBear::from_bool(((lags[14] >> i) & 1) == 1);
}
}
pub(super) fn set_private_seed_chain_words(
row: &mut [KoalaBear; AIR_WIDTH],
seed_words: [u64; 4],
sk_words: [u64; 4],
) {
for word in 0..4 {
let seed_limbs = u64_to_limbs(seed_words[word]);
let sk_limbs = u64_to_limbs(sk_words[word]);
for limb in 0..LIMBS_PER_WORD {
row[private_seed_limb_col(word, limb)] = KoalaBear::from_u16(seed_limbs[limb]);
row[private_sk_limb_col(word, limb)] = KoalaBear::from_u16(sk_limbs[limb]);
}
}
}
pub(super) fn set_private_seed_chain_derive_final_carries(
row: &mut [KoalaBear; AIR_WIDTH],
derive_round_state: [u64; 8],
initial_state: [u64; 8],
) {
for (word_idx, carry_base) in [
(0_usize, CARRY_T1_BASE),
(1_usize, CARRY_T2_BASE),
(2_usize, CARRY_A_BASE),
(3_usize, CARRY_E_BASE),
] {
let (_, carries) =
add_with_carries_2(derive_round_state[word_idx], initial_state[word_idx]);
set_carries(row, carry_base, carries);
}
set_carry_bits(row);
}
fn u64_to_limbs(value: u64) -> [u16; LIMBS_PER_WORD] {
[
(value & 0xffff) as u16,
((value >> 16) & 0xffff) as u16,
((value >> 32) & 0xffff) as u16,
((value >> 48) & 0xffff) as u16,
]
}
fn decode_word_from_inline(row: &[KoalaBear; AIR_WIDTH], word: usize) -> u64 {
let mut out = 0_u64;
for limb in 0..LIMBS_PER_WORD {
let x = row[limb_col(word, limb)].as_canonical_u32();
out |= u64::from(x) << (16 * limb);
}
out
}
pub(super) fn add_with_carries_2(a: u64, b: u64) -> (u64, [u16; LIMBS_PER_WORD]) {
add_with_carries(&[u64_to_limbs(a), u64_to_limbs(b)])
}
pub(super) fn add_with_carries_4(a: u64, b: u64, c: u64, d: u64) -> (u64, [u16; LIMBS_PER_WORD]) {
add_with_carries(&[
u64_to_limbs(a),
u64_to_limbs(b),
u64_to_limbs(c),
u64_to_limbs(d),
])
}
pub(super) fn add_with_carries_5(
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
) -> (u64, [u16; LIMBS_PER_WORD]) {
add_with_carries(&[
u64_to_limbs(a),
u64_to_limbs(b),
u64_to_limbs(c),
u64_to_limbs(d),
u64_to_limbs(e),
])
}
/// Limb-wise addition of `operands` with carry propagation.
///
/// Returns `(sum mod 2^64, per-limb carries)`. Each carry is the value carried
/// into the next 16-bit limb after summing all operand limbs at that position.
fn add_with_carries(operands: &[[u16; LIMBS_PER_WORD]]) -> (u64, [u16; LIMBS_PER_WORD]) {
let mut out = [0_u16; LIMBS_PER_WORD];
let mut carries = [0_u16; LIMBS_PER_WORD];
let mut carry = 0_u32;
for i in 0..LIMBS_PER_WORD {
let sum: u32 = operands.iter().map(|o| u32::from(o[i])).sum::<u32>() + carry;
out[i] = (sum & 0xffff) as u16;
carry = sum >> 16;
carries[i] = carry as u16;
}
(limbs_to_u64(out), carries)
}
fn limbs_to_u64(limbs: [u16; LIMBS_PER_WORD]) -> u64 {
u64::from(limbs[0])
| (u64::from(limbs[1]) << 16)
| (u64::from(limbs[2]) << 32)
| (u64::from(limbs[3]) << 48)
}

View file

@ -0,0 +1,91 @@
use super::constants::K;
use super::ops::{big_sigma0, big_sigma1, ch, maj, small_sigma0, small_sigma1};
use super::trace::BlockTrace;
/// SHA-512 witness and trace builder for the PoKOS seed-chain AIR.
///
/// `Sha512Circuit` is a namespace (a zero-sized struct with only associated functions)
/// that groups two layers of functionality:
///
/// 1. **Block-level witness** — [`compress_block`](Sha512Circuit::compress_block) runs
/// a single 128-byte block compression and records every intermediate value in a
/// [`BlockTrace`], which is the prover's witness.
///
/// 2. **AIR trace generation** — [`build_plonky3_air_trace`](Sha512Circuit::build_plonky3_air_trace)
/// and [`build_plonky3_preprocessed_trace_from_instance`](Sha512Circuit::build_plonky3_preprocessed_trace_from_instance)
/// convert a `BlockTrace` into the column matrices consumed by Plonky3.
///
/// This crate no longer exposes a generic public SHA-512 API; the active consumer is the
/// internal PoKOS seed-chain proof path.
pub struct Sha512Circuit;
impl Sha512Circuit {
/// Runs one SHA-512 block compression and records the full execution trace.
///
/// Given an 8-word chaining `state` and a 128-byte `block`, this function:
///
/// 1. Parses `block` into 16 big-endian 64-bit words W[0..15].
/// 2. Expands the message schedule to W[0..79] using the σ0/σ1 recurrence.
/// 3. Executes 80 rounds of the SHA-512 compression function, recording the
/// working state `[a,b,c,d,e,f,g,h]` after each round.
/// 4. Applies the feed-forward addition: `output[i] = state[i] + working[i]` (mod 2⁶⁴).
///
/// # Returns
///
/// A [`BlockTrace`] containing:
/// * `words` — the full 80-word message schedule.
/// * `round_states` — working state at each of the 81 boundaries (before round 0
/// through after round 79).
///
/// The `BlockTrace` is the prover's witness and is consumed by
/// [`build_plonky3_air_trace`](Sha512Circuit::build_plonky3_air_trace).
pub fn compress_block(state: &[u64; 8], block: &[u8; 128]) -> BlockTrace {
let mut words = [0_u64; 80];
for (i, chunk) in block.chunks_exact(8).enumerate() {
words[i] = u64::from_be_bytes(chunk.try_into().expect("word size is 8"));
}
for i in 16..80 {
words[i] = small_sigma1(words[i - 2])
.wrapping_add(words[i - 7])
.wrapping_add(small_sigma0(words[i - 15]))
.wrapping_add(words[i - 16]);
}
let mut round_states = [[0_u64; 8]; 81];
round_states[0] = *state;
let mut a = state[0];
let mut b = state[1];
let mut c = state[2];
let mut d = state[3];
let mut e = state[4];
let mut f = state[5];
let mut g = state[6];
let mut h = state[7];
for i in 0..80 {
let t1 = h
.wrapping_add(big_sigma1(e))
.wrapping_add(ch(e, f, g))
.wrapping_add(K[i])
.wrapping_add(words[i]);
let t2 = big_sigma0(a).wrapping_add(maj(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
round_states[i + 1] = [a, b, c, d, e, f, g, h];
}
BlockTrace {
words,
round_states,
}
}
}

View file

@ -0,0 +1,109 @@
/// The SHA-512 initial hash values (IV).
///
/// These are the first 64 bits of the fractional parts of the square roots of the first
/// eight prime numbers, as specified in FIPS 180-4 §5.3.5.
///
/// Use this as the `initial_state` for the first block of a fresh SHA-512 computation.
/// When chaining blocks (e.g. in [`crate::prove_message`]), the output state of each block
/// becomes the input state of the next block; callers do not need to supply `INITIAL_STATE`
/// for subsequent blocks directly — the multi-block API handles chaining automatically.
pub const INITIAL_STATE: [u64; 8] = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179,
];
/// The 80 SHA-512 round constants K[0..79].
///
/// These are the first 64 bits of the fractional parts of the cube roots of the first
/// eighty prime numbers, as specified in FIPS 180-4 §4.2.3.
///
/// Each constant is consumed by one compression round: round `i` uses `K[i]` when
/// computing T1 = h + Σ1(e) + Ch(e,f,g) + K[i] + W[i].
pub(crate) const K: [u64; 80] = [
0x428a2f98d728ae22,
0x7137449123ef65cd,
0xb5c0fbcfec4d3b2f,
0xe9b5dba58189dbbc,
0x3956c25bf348b538,
0x59f111f1b605d019,
0x923f82a4af194f9b,
0xab1c5ed5da6d8118,
0xd807aa98a3030242,
0x12835b0145706fbe,
0x243185be4ee4b28c,
0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f,
0x80deb1fe3b1696b1,
0x9bdc06a725c71235,
0xc19bf174cf692694,
0xe49b69c19ef14ad2,
0xefbe4786384f25e3,
0x0fc19dc68b8cd5b5,
0x240ca1cc77ac9c65,
0x2de92c6f592b0275,
0x4a7484aa6ea6e483,
0x5cb0a9dcbd41fbd4,
0x76f988da831153b5,
0x983e5152ee66dfab,
0xa831c66d2db43210,
0xb00327c898fb213f,
0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2,
0xd5a79147930aa725,
0x06ca6351e003826f,
0x142929670a0e6e70,
0x27b70a8546d22ffc,
0x2e1b21385c26c926,
0x4d2c6dfc5ac42aed,
0x53380d139d95b3df,
0x650a73548baf63de,
0x766a0abb3c77b2a8,
0x81c2c92e47edaee6,
0x92722c851482353b,
0xa2bfe8a14cf10364,
0xa81a664bbc423001,
0xc24b8b70d0f89791,
0xc76c51a30654be30,
0xd192e819d6ef5218,
0xd69906245565a910,
0xf40e35855771202a,
0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8,
0x1e376c085141ab53,
0x2748774cdf8eeb99,
0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63,
0x4ed8aa4ae3418acb,
0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc,
0x78a5636f43172f60,
0x84c87814a1f0ab72,
0x8cc702081a6439ec,
0x90befffa23631e28,
0xa4506cebde82bde9,
0xbef9a3f7b2c67915,
0xc67178f2e372532b,
0xca273eceea26619c,
0xd186b8c721c0c207,
0xeada7dd6cde0eb1e,
0xf57d4f7fee6ed178,
0x06f067aa72176fba,
0x0a637dc5a2c898a6,
0x113f9804bef90dae,
0x1b710b35131c471b,
0x28db77f523047d84,
0x32caab7b40c72493,
0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c,
0x4cc5d4becb3e42b6,
0x597f299cfc657e2a,
0x5fcb6fab3ad6faec,
0x6c44198c4a475817,
];

View file

@ -0,0 +1,34 @@
//! Internal SHA-512 AIR and proof helpers for the `ed25519-pokos` seed-chain statement.
//!
//! The active proof path is the dedicated private seed-chain construction used to prove:
//! - `commit_of_seed = SHA512(domain_commit || seed)`
//! - `sk_seed = SHA512(domain_derive || seed)[0..32]`
//! - `hash_of_sk = SHA512(domain_hash_sk || sk_seed)`
//!
//! Witness types ([`PrivateSeedChainPublic`], `PrivateSeedChainWitness`) and block
//! helpers (`segment_block`) are defined in the outer `crate::private_seed_chain`
//! module and imported here, so each type has exactly one definition.
//!
//! [`Sha512Circuit`] and the AIR submodules provide the trace-generation and
//! constraint machinery; [`private_seed_chain`] wires them into the Plonky3
//! prover and verifier.
mod air;
mod circuit;
mod constants;
mod ops;
mod private_seed_chain;
mod proof_api;
mod trace;
pub use circuit::Sha512Circuit;
pub use constants::INITIAL_STATE;
pub(crate) use proof_api::{
Sha512ProofSettings, Sha512SegmentChainProof, Sha512StarkConfig,
deserialize_segment_chain_proof, serialize_segment_chain_proof,
};
pub(crate) use private_seed_chain::{
PrivateSeedChainPublic, SealedPrivateSeedChainProof, prove_private_seed_chain,
verify_private_seed_chain_statement,
};

View file

@ -0,0 +1,88 @@
//! SHA-512 bitwise and rotation helper functions.
//!
//! Each function here corresponds directly to a named operation in FIPS 180-4 §4.1.3.
//! They operate on bare `u64` values and are used both by the reference SHA-512
//! implementation ([`crate::sha512::Sha512Circuit`]) and by the AIR trace builder to
//! populate witness columns.
use p3_field::PrimeCharacteristicRing;
use p3_koala_bear::KoalaBear;
/// Converts a `u64` scalar into a KoalaBear field element.
///
/// KoalaBear's modulus is 2³¹ − 2²⁴ + 1, so the value is reduced modulo p. This is
/// used throughout the trace builder to store 64-bit words (and derived values) inside
/// the field-valued trace matrix.
pub(crate) fn bb(x: u64) -> KoalaBear {
KoalaBear::from_u64(x)
}
/// SHA-512 Choose function — Ch(x, y, z).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// Ch(x, y, z) = (x AND y) XOR (NOT x AND z)
/// ```
/// For each bit position, the output bit equals `y` if the corresponding bit of `x` is 1,
/// and `z` otherwise. Used in computing T1 each round.
pub(crate) fn ch(x: u64, y: u64, z: u64) -> u64 {
(x & y) ^ ((!x) & z)
}
/// SHA-512 Majority function — Maj(x, y, z).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z)
/// ```
/// For each bit position, the output bit equals 1 if at least two of the three
/// corresponding input bits are 1 (majority vote). Used in computing T2 each round.
pub(crate) fn maj(x: u64, y: u64, z: u64) -> u64 {
(x & y) ^ (x & z) ^ (y & z)
}
/// SHA-512 upper-case Sigma-0 — Σ0(x).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// Σ0(x) = ROTR²⁸(x) XOR ROTR³⁴(x) XOR ROTR³⁹(x)
/// ```
/// Applied to the working variable `a` to produce the `sigma0` term that feeds into T2.
pub(crate) fn big_sigma0(x: u64) -> u64 {
x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39)
}
/// SHA-512 upper-case Sigma-1 — Σ1(x).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// Σ1(x) = ROTR¹⁴(x) XOR ROTR¹⁸(x) XOR ROTR⁴¹(x)
/// ```
/// Applied to the working variable `e` to produce the `sigma1` term that feeds into T1.
pub(crate) fn big_sigma1(x: u64) -> u64 {
x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41)
}
/// SHA-512 lower-case sigma-0 — σ0(x).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// σ0(x) = ROTR¹(x) XOR ROTR⁸(x) XOR SHR⁷(x)
/// ```
/// Used in the message schedule expansion:
/// W[i] = σ1(W[i−2]) + W[i−7] + σ0(W[i−15]) + W[i−16] (for 16 ≤ i < 80)
pub(crate) fn small_sigma0(x: u64) -> u64 {
x.rotate_right(1) ^ x.rotate_right(8) ^ (x >> 7)
}
/// SHA-512 lower-case sigma-1 — σ1(x).
///
/// Defined in FIPS 180-4 §4.1.3 as:
/// ```text
/// σ1(x) = ROTR¹⁹(x) XOR ROTR⁶¹(x) XOR SHR⁶(x)
/// ```
/// Used in the message schedule expansion:
/// W[i] = σ1(W[i−2]) + W[i−7] + σ0(W[i−15]) + W[i−16] (for 16 ≤ i < 80)
pub(crate) fn small_sigma1(x: u64) -> u64 {
x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6)
}

View file

@ -0,0 +1,408 @@
use super::{
INITIAL_STATE, Sha512Circuit, Sha512ProofSettings, Sha512SegmentChainProof, Sha512StarkConfig,
air::{MessageAirBundle, PrivateSeedChainBlocks, Sha512RoundAir},
deserialize_segment_chain_proof,
proof_api::{meets_minimum_verifier_policy, setup_config, validate_settings_for_proving},
serialize_segment_chain_proof,
};
use crate::{
Seed, derive_secret_key_material,
private_seed_chain::{PrivateSeedChainWitness, SegmentKind, segment_block},
};
use p3_field::PrimeCharacteristicRing;
use p3_uni_stark::{prove_with_preprocessed, setup_preprocessed, verify_with_preprocessed};
pub(crate) use crate::private_seed_chain::PrivateSeedChainPublic;
/// All data needed to run the Plonky3 prover for one seed chain.
///
/// `air_bundle` is always present. `public` and `blocks` are only available
/// in test builds, where they are used to check AIR trace correctness.
pub(crate) struct PrivateSeedChainBundle {
#[cfg(test)]
pub(crate) public: PrivateSeedChainPublic,
#[cfg(test)]
pub(crate) blocks: PrivateSeedChainBlocks,
pub(crate) air_bundle: MessageAirBundle,
}
/// A serialized Plonky3 STARK proof for the private seed chain, ready for transport.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SealedPrivateSeedChainProof {
pub(crate) sealed_proof: Vec<u8>,
}
/// Constructs the [`PrivateSeedChainBundle`] (AIR traces + public values) for `seed`.
///
/// This builds the witness, the three padded SHA-512 blocks, and the full
/// main + preprocessed Plonky3 trace matrices, but does **not** run the prover.
/// Call [`prove_private_seed_chain`] to also produce the STARK proof.
pub(crate) fn build_private_seed_chain_bundle(seed: Seed) -> PrivateSeedChainBundle {
let witness = witness_from_seed(seed);
let blocks = blocks_from_witness(witness);
let air_bundle = Sha512Circuit::build_private_seed_chain_air_bundle(&blocks);
PrivateSeedChainBundle {
#[cfg(test)]
public: crate::private_seed_chain::public_from_witness(witness),
#[cfg(test)]
blocks,
air_bundle,
}
}
/// Proves the private seed chain for `seed` using the default [`Sha512ProofSettings`].
///
/// Returns a [`SealedPrivateSeedChainProof`] on success, or a string error if
/// the prover fails or the settings fail policy validation.
pub(crate) fn prove_private_seed_chain(seed: Seed) -> Result<SealedPrivateSeedChainProof, String> {
prove_private_seed_chain_with_settings(seed, Sha512ProofSettings::default())
}
/// Proves the private seed chain for `seed` with explicit `settings`.
///
/// Validates that `settings` meet the minimum verifier policy before running
/// the prover. Returns an error if validation fails or if the Plonky3 prover
/// encounters an internal error.
///
/// The resulting [`SealedPrivateSeedChainProof`] contains only the Plonky3
/// proof bytes and the settings. The preprocessed commitment is embedded
/// inside the Plonky3 proof structure and is validated implicitly during
/// verification: the verifier independently reconstructs the expected VK from
/// `verifier_template_blocks()` and passes it to `verify_with_preprocessed`.
pub(crate) fn prove_private_seed_chain_with_settings(
seed: Seed,
settings: Sha512ProofSettings,
) -> Result<SealedPrivateSeedChainProof, String> {
let bundle = build_private_seed_chain_bundle(seed);
validate_settings_for_proving(settings)?;
let config = setup_config(settings);
let air = Sha512RoundAir::new(bundle.air_bundle.preprocessed.clone());
let (preprocessed_prover_data, _) =
setup_preprocessed::<Sha512StarkConfig, _>(&config, &air, bundle.air_bundle.degree_bits)
.ok_or_else(|| {
"failed to setup preprocessed data for private seed-chain proof".to_string()
})?;
let proof = prove_with_preprocessed(
&config,
&air,
bundle.air_bundle.main,
&bundle.air_bundle.final_public_values,
Some(&preprocessed_prover_data),
);
let sealed_proof = serialize_segment_chain_proof(&Sha512SegmentChainProof { proof, settings })?;
Ok(SealedPrivateSeedChainProof { sealed_proof })
}
/// Verifies a sealed seed-chain proof against `public` using the default settings.
///
/// Returns `true` if and only if:
/// - the proof deserializes successfully,
/// - the proof was produced with the default [`Sha512ProofSettings`],
/// - the verifier's independently reconstructed preprocessed VK (from
/// zero-payload template blocks) matches the commitment in the proof, and
/// - the Plonky3 STARK proof is valid for the given public values.
pub(crate) fn verify_private_seed_chain_statement(
bundle: &SealedPrivateSeedChainProof,
public: PrivateSeedChainPublic,
) -> bool {
verify_private_seed_chain_statement_with_settings(
bundle,
public,
Sha512ProofSettings::default(),
)
}
/// Verifies a sealed seed-chain proof against `public` with explicit `settings`.
///
/// Fails fast (returns `false`) if:
/// - `settings` do not meet the minimum verifier policy,
/// - the proof was produced with different settings than supplied here, or
/// - the Plonky3 verifier rejects the proof.
///
/// The preprocessed commitment check is performed inside Plonky3: the verifier
/// reconstructs the expected VK from `verifier_template_blocks()` (zero-payload
/// blocks with the correct domain structure) and passes it to
/// `verify_with_preprocessed`, which enforces that the prover's committed
/// preprocessed trace matches.
pub(crate) fn verify_private_seed_chain_statement_with_settings(
bundle: &SealedPrivateSeedChainProof,
public: PrivateSeedChainPublic,
settings: Sha512ProofSettings,
) -> bool {
if !meets_minimum_verifier_policy(settings) {
return false;
}
let Ok(proof) = deserialize_segment_chain_proof(&bundle.sealed_proof) else {
return false;
};
if proof.settings != settings {
return false;
}
let config = setup_config(settings);
let air_bundle =
Sha512Circuit::build_private_seed_chain_air_bundle(&verifier_template_blocks());
let air = Sha512RoundAir::new(air_bundle.preprocessed.clone());
let Some((_, expected_vk)) =
setup_preprocessed::<Sha512StarkConfig, _>(&config, &air, air_bundle.degree_bits)
else {
return false;
};
let public_values = public_values_from_statement(public);
verify_with_preprocessed(
&config,
&air,
&proof.proof,
&public_values,
Some(&expected_vk),
)
.is_ok()
}
fn witness_from_seed(seed: Seed) -> PrivateSeedChainWitness {
PrivateSeedChainWitness {
seed,
sk_seed: derive_secret_key_material(seed).sk_seed,
}
}
pub(crate) fn public_values_from_statement(
public: PrivateSeedChainPublic,
) -> [p3_koala_bear::KoalaBear; 16] {
let mut values = [p3_koala_bear::KoalaBear::ZERO; 16];
// The proof exposes the pre-feed-forward SHA-512 round state at row 80, while the public
// statement exposes the post-feed-forward digest. Reconstruct the former by subtracting the
// standard initial chaining value word-by-word modulo 2^64.
for (i, chunk) in public.commit_of_seed.chunks_exact(8).take(8).enumerate() {
let digest_word = u64::from_be_bytes(chunk.try_into().expect("commit digest word"));
values[i] = super::ops::bb(digest_word.wrapping_sub(INITIAL_STATE[i]));
}
for (i, chunk) in public.hash_of_sk.chunks_exact(8).take(8).enumerate() {
let digest_word = u64::from_be_bytes(chunk.try_into().expect("hash-of-sk digest word"));
values[8 + i] = super::ops::bb(digest_word.wrapping_sub(INITIAL_STATE[i]));
}
values
}
fn verifier_template_blocks() -> PrivateSeedChainBlocks {
let zero = [0_u8; 32];
PrivateSeedChainBlocks {
commit: segment_block(SegmentKind::Commit, zero),
derive: segment_block(SegmentKind::Derive, zero),
hash_sk: segment_block(SegmentKind::HashSk, zero),
}
}
fn blocks_from_witness(witness: PrivateSeedChainWitness) -> PrivateSeedChainBlocks {
PrivateSeedChainBlocks {
commit: segment_block(SegmentKind::Commit, witness.seed),
derive: segment_block(SegmentKind::Derive, witness.seed),
hash_sk: segment_block(SegmentKind::HashSk, witness.sk_seed),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sha512::air::{
PREP_COMMIT_FINAL_SELECTOR_COL_FOR_TESTS, PREP_DERIVE_FINAL_SELECTOR_COL_FOR_TESTS,
PREP_FIXED_INIT_W_SELECTOR_COL_FOR_TESTS, PREP_HASH_FINAL_SELECTOR_COL_FOR_TESTS,
PREP_PAYLOAD_WORD_SELECTOR_COL_FOR_TESTS, PREP_SEGMENT_COMMIT_SELECTOR_COL_FOR_TESTS,
PREP_SEGMENT_DERIVE_SELECTOR_COL_FOR_TESTS, PREP_SEGMENT_HASH_SELECTOR_COL_FOR_TESTS,
PRIVATE_SEED_LIMB_BASE_FOR_TESTS, PRIVATE_SK_LIMB_BASE_FOR_TESTS,
};
use p3_field::PrimeCharacteristicRing;
use p3_field::PrimeField32;
use p3_matrix::Matrix;
fn sample_seed() -> Seed {
[7_u8; 32]
}
#[test]
fn sealed_proof_round_trip_verifies() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let sealed = prove_private_seed_chain(sample_seed()).unwrap();
assert!(verify_private_seed_chain_statement(&sealed, bundle.public));
}
#[test]
fn sealed_proof_rejects_tampered_bytes() {
let mut sealed = prove_private_seed_chain(sample_seed()).unwrap();
sealed.sealed_proof[0] ^= 1;
let public = build_private_seed_chain_bundle(sample_seed()).public;
assert!(!verify_private_seed_chain_statement(&sealed, public));
}
#[test]
fn statement_verifier_accepts_valid_public_statement() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let sealed = prove_private_seed_chain(sample_seed()).unwrap();
assert!(verify_private_seed_chain_statement(&sealed, bundle.public));
}
#[test]
fn statement_verifier_rejects_wrong_commitment() {
let mut public = build_private_seed_chain_bundle(sample_seed()).public;
let sealed = prove_private_seed_chain(sample_seed()).unwrap();
public.commit_of_seed[0] ^= 1;
assert!(!verify_private_seed_chain_statement(&sealed, public));
}
#[test]
fn statement_verifier_rejects_wrong_hash_of_sk() {
let mut public = build_private_seed_chain_bundle(sample_seed()).public;
let sealed = prove_private_seed_chain(sample_seed()).unwrap();
public.hash_of_sk[0] ^= 1;
assert!(!verify_private_seed_chain_statement(&sealed, public));
}
#[test]
fn air_bundle_final_digest_matches_public_hash() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let trace = Sha512Circuit::compress_block(&INITIAL_STATE, &bundle.blocks.hash_sk);
let mut digest = [0_u8; 64];
for (i, chunk) in digest.chunks_exact_mut(8).enumerate() {
let word = INITIAL_STATE[i].wrapping_add(trace.round_states[80][i]);
chunk.copy_from_slice(&word.to_be_bytes());
}
assert_eq!(digest, bundle.public.hash_of_sk);
}
#[test]
fn prover_and_verifier_preprocessed_commitments_match() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let config = setup_config(Sha512ProofSettings::default());
let prover_air = Sha512RoundAir::new(bundle.air_bundle.preprocessed.clone());
let (_, prover_vk) = setup_preprocessed::<Sha512StarkConfig, _>(
&config,
&prover_air,
bundle.air_bundle.degree_bits,
)
.unwrap();
let verifier_bundle =
Sha512Circuit::build_private_seed_chain_air_bundle(&verifier_template_blocks());
let verifier_air = Sha512RoundAir::new(verifier_bundle.preprocessed);
let (_, verifier_vk) = setup_preprocessed::<Sha512StarkConfig, _>(
&config,
&verifier_air,
verifier_bundle.degree_bits,
)
.unwrap();
assert_eq!(prover_vk.commitment, verifier_vk.commitment);
}
#[test]
fn air_bundle_marks_seed_chain_roles() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let prep = &bundle.air_bundle.preprocessed;
let row = |r: usize| prep.row_slice(r).unwrap();
let commit_row0 = row(0);
let derive_row0 = row(128);
let hash_row0 = row(256);
assert_eq!(
commit_row0[PREP_SEGMENT_COMMIT_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
derive_row0[PREP_SEGMENT_DERIVE_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
hash_row0[PREP_SEGMENT_HASH_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
row(80)[PREP_COMMIT_FINAL_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
row(208)[PREP_DERIVE_FINAL_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
row(336)[PREP_HASH_FINAL_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
row(4)[PREP_PAYLOAD_WORD_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
assert_eq!(
row(0)[PREP_FIXED_INIT_W_SELECTOR_COL_FOR_TESTS],
p3_koala_bear::KoalaBear::ONE
);
}
#[test]
fn preprocessed_trace_hides_payload_w_words() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let prep = &bundle.air_bundle.preprocessed;
for absolute_row in [4_usize, 5, 6, 7, 132, 133, 134, 135, 260, 261, 262, 263] {
let row = prep.row_slice(absolute_row).unwrap();
for limb in 0..4 {
assert_eq!(
row[crate::sha512::air::LIMB_BASE_FOR_TESTS
+ crate::sha512::air::WORD_W_FOR_TESTS
* crate::sha512::air::LIMBS_PER_WORD_FOR_TESTS
+ limb],
p3_koala_bear::KoalaBear::ZERO
);
}
}
}
#[test]
fn main_trace_carries_private_seed_and_sk_words() {
let bundle = build_private_seed_chain_bundle(sample_seed());
let main = &bundle.air_bundle.main;
let row = main.row_slice(0).unwrap();
let seed = sample_seed();
for (word_idx, bytes) in seed.chunks_exact(8).enumerate() {
let expected_seed = u64::from_be_bytes(bytes.try_into().unwrap());
let expected_sk = u64::from_be_bytes(
bundle.blocks.hash_sk[32 + word_idx * 8..40 + word_idx * 8]
.try_into()
.unwrap(),
);
let mut actual_seed = 0_u64;
let mut actual_sk = 0_u64;
for limb in 0..4 {
actual_seed |= u64::from(
row[PRIVATE_SEED_LIMB_BASE_FOR_TESTS + word_idx * 4 + limb].as_canonical_u32(),
) << (16 * limb);
actual_sk |= u64::from(
row[PRIVATE_SK_LIMB_BASE_FOR_TESTS + word_idx * 4 + limb].as_canonical_u32(),
) << (16 * limb);
}
assert_eq!(actual_seed, expected_seed);
assert_eq!(actual_sk, expected_sk);
}
}
#[test]
fn statement_public_values_match_air_bundle() {
let bundle = build_private_seed_chain_bundle(sample_seed());
assert_eq!(
public_values_from_statement(bundle.public),
bundle.air_bundle.final_public_values
);
}
}

View file

@ -0,0 +1,124 @@
use p3_challenger::{HashChallenger, SerializingChallenger32};
use p3_commit::ExtensionMmcs;
use p3_dft::Radix2DitParallel;
use p3_field::extension::BinomialExtensionField;
use p3_fri::{FriParameters, TwoAdicFriPcs};
use p3_keccak::Keccak256Hash;
use p3_koala_bear::KoalaBear;
use p3_merkle_tree::MerkleTreeMmcs;
use p3_symmetric::{CompressionFunctionFromHasher, SerializingHasher};
use p3_uni_stark::{Proof, StarkConfig};
use serde::{Deserialize, Serialize};
mod segment_chain;
pub(crate) use segment_chain::{
Sha512SegmentChainProof, deserialize_segment_chain_proof, serialize_segment_chain_proof,
};
pub type Val = KoalaBear;
type ByteHash = Keccak256Hash;
type FieldHash = SerializingHasher<ByteHash>;
type MyCompress = CompressionFunctionFromHasher<ByteHash, 2, 32>;
type ValMmcs = MerkleTreeMmcs<Val, u8, FieldHash, MyCompress, 32>;
type Challenge = BinomialExtensionField<Val, 4>;
type ChallengeMmcs = ExtensionMmcs<Val, Challenge, ValMmcs>;
type Challenger = SerializingChallenger32<Val, HashChallenger<u8, ByteHash, 32>>;
type Dft = Radix2DitParallel<Val>;
type Pcs = TwoAdicFriPcs<Val, Dft, ValMmcs, ChallengeMmcs>;
const MIN_VERIFIER_LOG_FINAL_POLY_LEN: usize = 4;
const MIN_VERIFIER_LOG_BLOWUP: usize = 3;
const MIN_VERIFIER_NUM_QUERIES: usize = 2;
const MIN_VERIFIER_COMMIT_POW_BITS: usize = 1;
const MIN_VERIFIER_QUERY_POW_BITS: usize = 1;
const MAX_INNER_PROOF_BYTES: usize = 16 * 1024 * 1024;
/// Concrete Plonky3 STARK configuration used by this crate.
pub type Sha512StarkConfig = StarkConfig<Pcs, Challenge, Challenger>;
/// A serialisable Plonky3 STARK proof under [`Sha512StarkConfig`].
pub type Sha512StarkProof = Proof<Sha512StarkConfig>;
/// FRI and transcript parameters for the STARK prover and verifier.
///
/// Both prover and verifier must use identical settings.
///
/// Defaults are a stronger production-oriented profile for this crate, not an audited policy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sha512ProofSettings {
/// Log2 of FRI blowup factor.
pub log_blowup: usize,
/// Log2 of FRI final polynomial length.
pub log_final_poly_len: usize,
/// Number of FRI queries.
pub num_queries: usize,
/// Commit-phase proof-of-work bits.
pub commit_proof_of_work_bits: usize,
/// Query-phase proof-of-work bits.
pub query_proof_of_work_bits: usize,
/// Seed for the Fiat-Shamir transcript challenger.
pub rng_seed: u64,
}
impl Default for Sha512ProofSettings {
fn default() -> Self {
Self {
log_blowup: 3,
log_final_poly_len: 5,
num_queries: 28,
commit_proof_of_work_bits: 16,
query_proof_of_work_bits: 16,
rng_seed: 1,
}
}
}
/// Constructs a [`Sha512StarkConfig`] from the given `settings`.
///
/// Instantiates the FRI/Merkle parameters, the DFT, and the Fiat-Shamir
/// challenger. Both prover and verifier must call this with identical
/// `settings` for the proof to verify.
pub(crate) fn setup_config(settings: Sha512ProofSettings) -> Sha512StarkConfig {
let byte_hash = ByteHash {};
let field_hash = FieldHash::new(byte_hash);
let compress = MyCompress::new(byte_hash);
let val_mmcs = ValMmcs::new(field_hash, compress);
let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
let fri_params = FriParameters {
log_blowup: settings.log_blowup,
log_final_poly_len: settings.log_final_poly_len,
num_queries: settings.num_queries,
commit_proof_of_work_bits: settings.commit_proof_of_work_bits,
query_proof_of_work_bits: settings.query_proof_of_work_bits,
mmcs: challenge_mmcs,
};
let pcs = Pcs::new(Dft::default(), val_mmcs, fri_params);
let challenger = Challenger::from_hasher(settings.rng_seed.to_le_bytes().to_vec(), byte_hash);
Sha512StarkConfig::new(pcs, challenger)
}
/// Returns `true` if `settings` satisfy all minimum security thresholds the
/// verifier enforces.
///
/// The verifier rejects proofs whose settings are weaker than the minimums
/// defined by the `MIN_VERIFIER_*` constants, regardless of whether the proof
/// is otherwise structurally valid.
pub(crate) fn meets_minimum_verifier_policy(settings: Sha512ProofSettings) -> bool {
settings.log_final_poly_len >= MIN_VERIFIER_LOG_FINAL_POLY_LEN
&& settings.log_blowup >= MIN_VERIFIER_LOG_BLOWUP
&& settings.num_queries >= MIN_VERIFIER_NUM_QUERIES
&& settings.commit_proof_of_work_bits >= MIN_VERIFIER_COMMIT_POW_BITS
&& settings.query_proof_of_work_bits >= MIN_VERIFIER_QUERY_POW_BITS
}
/// Validates `settings` for use as prover inputs.
///
/// Returns `Err` if the settings do not meet the minimum verifier policy,
/// preventing the prover from producing a proof that the verifier would
/// immediately reject.
pub(crate) fn validate_settings_for_proving(settings: Sha512ProofSettings) -> Result<(), String> {
if !meets_minimum_verifier_policy(settings) {
return Err("proof settings do not meet minimum verifier policy".to_string());
}
Ok(())
}

View file

@ -0,0 +1,84 @@
use bincode::Options;
use serde::{Deserialize, Serialize};
use super::{MAX_INNER_PROOF_BYTES, Sha512ProofSettings, Sha512StarkProof};
/// Maximum byte size accepted for a full serialized [`Sha512SegmentChainProof`].
///
/// This guards against allocation-based DoS attacks when deserializing
/// untrusted proof bytes.
const MAX_SEGMENT_CHAIN_PROOF_BYTES: usize = 64 * 1024 * 1024;
/// A Plonky3 STARK proof for the multi-segment seed chain, together with the
/// settings under which it was produced.
///
/// The `settings` are stored alongside the proof so that the verifier can
/// confirm it is checking the proof under the same parameters the prover used.
pub struct Sha512SegmentChainProof {
/// The raw Plonky3 proof.
pub proof: Sha512StarkProof,
/// FRI and PoW parameters used when producing this proof.
pub settings: Sha512ProofSettings,
}
/// Wire-serializable form of [`Sha512SegmentChainProof`].
///
/// The inner proof is first serialized to bytes independently so that its
/// length can be bounded before the outer envelope is deserialized.
#[derive(Serialize, Deserialize)]
struct SerializableSegmentChainProof {
proof_bytes: Vec<u8>,
settings: Sha512ProofSettings,
}
/// Serializes a [`Sha512SegmentChainProof`] to bytes using bincode.
///
/// The inner proof is serialized first; if it exceeds [`MAX_INNER_PROOF_BYTES`]
/// the call returns an error. The outer envelope is checked against
/// [`MAX_SEGMENT_CHAIN_PROOF_BYTES`] after wrapping.
pub fn serialize_segment_chain_proof(proof: &Sha512SegmentChainProof) -> Result<Vec<u8>, String> {
let proof_bytes = bincode::serialize(&proof.proof).map_err(|e| e.to_string())?;
if proof_bytes.len() > MAX_INNER_PROOF_BYTES {
return Err("inner segment-chain proof exceeds configured size limit".to_string());
}
let serializable = SerializableSegmentChainProof {
proof_bytes,
settings: proof.settings,
};
let bytes = bincode::serialize(&serializable).map_err(|e| e.to_string())?;
if bytes.len() > MAX_SEGMENT_CHAIN_PROOF_BYTES {
return Err("serialized segment-chain proof exceeds configured size limit".to_string());
}
Ok(bytes)
}
/// Deserializes a [`Sha512SegmentChainProof`] from bytes.
///
/// Enforces size limits at both the outer and inner envelope levels before
/// any allocation-heavy deserialization begins. Uses `reject_trailing_bytes`
/// to ensure there are no stray bytes in the input.
pub fn deserialize_segment_chain_proof(bytes: &[u8]) -> Result<Sha512SegmentChainProof, String> {
if bytes.len() > MAX_SEGMENT_CHAIN_PROOF_BYTES {
return Err("serialized segment-chain proof exceeds configured size limit".to_string());
}
let bincode_opts = bincode::DefaultOptions::new()
.with_fixint_encoding()
.reject_trailing_bytes()
.with_limit(MAX_SEGMENT_CHAIN_PROOF_BYTES as u64);
let serializable: SerializableSegmentChainProof =
bincode_opts.deserialize(bytes).map_err(|e| e.to_string())?;
if serializable.proof_bytes.len() > MAX_INNER_PROOF_BYTES {
return Err("inner segment-chain proof exceeds configured size limit".to_string());
}
let inner_opts = bincode::DefaultOptions::new()
.with_fixint_encoding()
.reject_trailing_bytes()
.with_limit(MAX_INNER_PROOF_BYTES as u64);
let proof: Sha512StarkProof = inner_opts
.deserialize(&serializable.proof_bytes)
.map_err(|e| e.to_string())?;
Ok(Sha512SegmentChainProof {
proof,
settings: serializable.settings,
})
}

View file

@ -0,0 +1,37 @@
/// Full execution witness for one SHA-512 block compression.
///
/// `BlockTrace` captures every intermediate value produced during the compression of a
/// single 128-byte message block. It is produced by [`crate::sha512::Sha512Circuit::compress_block`]
/// and consumed by [`crate::sha512::Sha512Circuit::build_plonky3_air_trace`] to populate
/// the AIR witness matrix.
///
/// ## Lifecycle
///
/// 1. The prover calls `compress_block` to obtain a `BlockTrace`.
/// 2. The `BlockTrace` is passed to `build_plonky3_air_trace`, which lays out all witness
/// columns (working state words, limb decompositions, carry bits, etc.).
/// 3. The resulting [`p3_matrix::dense::RowMajorMatrix`] is handed to the Plonky3 prover.
///
/// ## Verification without a STARK
///
#[derive(Clone, Debug)]
pub struct BlockTrace {
/// The expanded message schedule W[0..79].
///
/// * W[0..15] — parsed directly from the 128-byte block (big-endian, 8 bytes per word).
/// * W[16..79] — derived via the recurrence
/// `W[i] = σ1(W[i−2]) + W[i−7] + σ0(W[i−15]) + W[i−16]` (mod 2⁶⁴).
pub words: [u64; 80],
/// Working state snapshots at every round boundary, indexed 0 through 80.
///
/// * `round_states[0]` equals the input chaining state (the state before any rounds).
/// * `round_states[i+1]` is the state immediately after applying round `i`.
/// * `round_states[80]` is the working state after all 80 rounds, **before**
/// the feed-forward addition.
///
/// The AIR binds `round_states[80]` as the 8 public values of the proof.
/// The verifier then reconstructs the post-feed-forward digest as
/// `initial_state + round_states[80]` (component-wise, mod 2⁶⁴).
pub round_states: [[u64; 8]; 81],
}

View file

@ -0,0 +1,191 @@
//! Verifier-side entry points for the POKOS proof envelope.
//!
//! Verification is split into two independent layers, either of which can
//! reject the proof:
//!
//! 1. **STARK verification** — checks the Plonky3 proof against the public
//! statement `(commit_of_seed, hash_of_sk)`. A valid proof guarantees
//! that the prover knew a seed that produced both values via the prescribed
//! SHA-512 derivation chain.
//!
//! 2. **Ed25519 authentication** — checks the signature over the
//! `authentication_transcript` against `authentication_key`. A valid
//! signature guarantees that the holder of the Ed25519 key derived from
//! `sk_seed` authorized this specific proof.
//!
//! Both checks must pass for [`verify_pokos`] to return `Ok(())`.
use crate::sha512::{
PrivateSeedChainPublic, SealedPrivateSeedChainProof, verify_private_seed_chain_statement,
};
use crate::{
DeserializeError, ED25519_PUBLIC_KEY_LEN, ED25519_SIGNATURE_LEN, PROOF_FORMAT_MAGIC,
SeedChainProofEnvelope, SeedChainStatement, Sha512ProofBundle, VerifyError,
authentication_transcript,
};
use curve25519::ed_sigs::{Signature, VerificationKey, VerificationKeyBytes};
/// Verifies a [`SeedChainProofEnvelope`].
///
/// Performs two checks in order:
/// 1. Verifies the STARK proof against the public statement.
/// 2. Verifies the Ed25519 signature over the authentication transcript.
///
/// # Errors
///
/// - [`VerifyError::InvalidSkDerivationProof`] if the STARK proof is invalid
/// or does not match `proof.statement`.
/// - [`VerifyError::AuthenticationSignatureInvalid`] if the Ed25519 signature
/// is invalid or was made with a different key.
pub fn verify_pokos(proof: &SeedChainProofEnvelope) -> Result<(), VerifyError> {
verify_sha512_bundle(&proof.sha512_proof, proof.statement)?;
let transcript = authentication_transcript(proof.statement);
let verification_key = VerificationKey::try_from(proof.authentication_key)
.map_err(|_| VerifyError::AuthenticationSignatureInvalid)?;
verification_key
.verify(&proof.authentication_signature, &transcript)
.map_err(|_| VerifyError::AuthenticationSignatureInvalid)
}
/// Serializes a [`SeedChainProofEnvelope`] to bytes.
///
/// Wire format (big-endian lengths):
/// ```text
/// [magic: 8]
/// [commit_of_seed: 64]
/// [hash_of_sk: 64]
/// [sha512_proof_len: 8] [sha512_proof: N]
/// [authentication_key: 32]
/// [authentication_signature: 64]
/// ```
///
/// The serialized form is self-describing: the magic bytes identify the
/// format version, and all variable-length fields are prefixed with their
/// 64-bit big-endian byte count.
pub fn serialize_proof(proof: &SeedChainProofEnvelope) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(PROOF_FORMAT_MAGIC);
bytes.extend_from_slice(&proof.statement.commit_of_seed);
bytes.extend_from_slice(&proof.statement.hash_of_sk);
bytes.extend_from_slice(&(proof.sha512_proof.sealed_proof.len() as u64).to_be_bytes());
bytes.extend_from_slice(&proof.sha512_proof.sealed_proof);
bytes.extend_from_slice(proof.authentication_key.as_ref());
bytes.extend_from_slice(&proof.authentication_signature.to_bytes());
bytes
}
/// Deserializes a [`SeedChainProofEnvelope`] from bytes produced by [`serialize_proof`].
///
/// # Errors
///
/// - [`DeserializeError::InvalidMagic`] if the leading bytes are not
/// `EPKOS001`.
/// - [`DeserializeError::Truncated`] if the byte slice ends before all fields
/// have been read, or if a length prefix points past the end of the slice.
/// - [`DeserializeError::InvalidSignature`] if the Ed25519 signature bytes are
/// structurally invalid.
/// - [`DeserializeError::TrailingBytes`] if there are extra bytes after the
/// last expected field.
pub fn deserialize_proof(bytes: &[u8]) -> Result<SeedChainProofEnvelope, DeserializeError> {
let mut cursor = Cursor::new(bytes);
if cursor.read_exact(PROOF_FORMAT_MAGIC.len())? != *PROOF_FORMAT_MAGIC {
return Err(DeserializeError::InvalidMagic);
}
let statement = SeedChainStatement {
commit_of_seed: cursor.read_array()?,
hash_of_sk: cursor.read_array()?,
};
let sha512_proof = Sha512ProofBundle {
sealed_proof: cursor.read_vec()?,
};
let authentication_key =
VerificationKeyBytes::from(cursor.read_array::<ED25519_PUBLIC_KEY_LEN>()?);
let signature_bytes = cursor.read_array::<ED25519_SIGNATURE_LEN>()?;
let authentication_signature =
Signature::from_slice(&signature_bytes).map_err(|_| DeserializeError::InvalidSignature)?;
if !cursor.is_at_end() {
return Err(DeserializeError::TrailingBytes);
}
Ok(SeedChainProofEnvelope {
statement,
sha512_proof,
authentication_key,
authentication_signature,
})
}
/// Verifies the Plonky3 STARK proof inside `bundle` against the public `statement`.
///
/// Returns `Ok(())` if the proof is valid; `Err(VerifyError::InvalidSkDerivationProof)`
/// otherwise.
fn verify_sha512_bundle(
bundle: &Sha512ProofBundle,
statement: SeedChainStatement,
) -> Result<(), VerifyError> {
let verified = verify_private_seed_chain_statement(
&SealedPrivateSeedChainProof {
sealed_proof: bundle.sealed_proof.clone(),
},
PrivateSeedChainPublic {
commit_of_seed: statement.commit_of_seed,
hash_of_sk: statement.hash_of_sk,
},
);
if verified {
Ok(())
} else {
Err(VerifyError::InvalidSkDerivationProof)
}
}
/// Minimal forward-only byte reader used during deserialization.
struct Cursor<'a> {
bytes: &'a [u8],
offset: usize,
}
impl<'a> Cursor<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes, offset: 0 }
}
fn read_exact(&mut self, len: usize) -> Result<Vec<u8>, DeserializeError> {
let end = self
.offset
.checked_add(len)
.ok_or(DeserializeError::Truncated)?;
if end > self.bytes.len() {
return Err(DeserializeError::Truncated);
}
let slice = self.bytes[self.offset..end].to_vec();
self.offset = end;
Ok(slice)
}
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializeError> {
if self.offset + N > self.bytes.len() {
return Err(DeserializeError::Truncated);
}
let mut out = [0_u8; N];
out.copy_from_slice(&self.bytes[self.offset..self.offset + N]);
self.offset += N;
Ok(out)
}
fn read_u64(&mut self) -> Result<u64, DeserializeError> {
Ok(u64::from_be_bytes(self.read_array()?))
}
fn read_vec(&mut self) -> Result<Vec<u8>, DeserializeError> {
let len = self.read_u64()? as usize;
self.read_exact(len)
}
fn is_at_end(&self) -> bool {
self.offset == self.bytes.len()
}
}