Build

The guest program and verifying a batch yourself

What the zkVM guest checks, the 104 bytes it commits, how the program verifies the proof, and how to recompute a batch's hashes yourself.

Every proven batch carries a proof that one small Rust program ran on that batch and accepted its clearing. This page describes that program, what its proof binds, and how to check a batch from your own machine with nothing but the API and SHA-256.

The guest

The guest is a Rust program for the SP1 zkVM. It reads three values, runs one function, and commits its result:

Rust
pub fn main() {
    let records = sp1_zkvm::io::read::<Vec<InputRecord>>();
    let state = sp1_zkvm::io::read::<BatchState>();
    let result = sp1_zkvm::io::read::<BatchResult>();
    let public_values = check(&records, &state, &result).expect("clearing refused");
    sp1_zkvm::io::commit_slice(&public_values.to_bytes());
}

check is the function of the clearing crate that tests the four conditions. The solver calls the same function before it posts a clearing, and the program uses the same crate to move pairs and settle orders. If check refuses, the guest panics and no proof exists.

What it reads

records: Vec of InputRecord

Placeorder, sell, buy, amount, limit
An order placed in the batch, or a remainder moved into it: the order's 32-byte address, the two token indexes as u16, the amount as u64 and the limit as u128.
Cancelorder
An order cancelled before the batch sealed.

state: BatchState

batch_idu64
The batch's number.
band_bpsu16
The price band.
clearing_fee_bpsu16
The clearing fee.
tokensVec of TokenState
Each batch token's index and last proven price, ascending by index.
pairsVec of PairState
Each batch pair: its index, its two tokens, fee, tick spacing, square-root price, tick, active liquidity and initialized ticks with their net liquidity.

result: BatchResult

batch_idu64
The batch's number.
pricesVec of TokenPriceResult
For each batch token: its index, its cleared price and the clearing fee its buyers pay.
fillsVec of FillFraction
The fill fraction of each rationed direction: sell index, buy index, fraction.

What it commits

104 bytes, the public values:

Text
batch_id: u64 LE  ||  input_hash: [u8; 32]  ||  state_hash: [u8; 32]  ||  result_hash: [u8; 32]

Each hash is SHA-256 over the value's fields in a fixed order, integers little-endian.

Text
input_hash:   h = sha256("una/batch" || batch_id: u64)
              for each record, in order:
                Place:   h = sha256(h || 0x01 || order: 32 bytes || sell: u16 || buy: u16 || amount: u64 || limit: u128)
                Cancel:  h = sha256(h || 0x02 || order: 32 bytes)

state_hash:   sha256(batch_id: u64 || band_bps: u16 || clearing_fee_bps: u16
                || token count: u8 || for each token: index: u16, last_price: u128
                || pair count: u8  || for each pair: pair_index: u16, x: u16, y: u16, fee_bps: u16,
                     tick_spacing: u16, sqrt_price: u128, tick: i32, liquidity: u128,
                     tick count: u8, for each tick: tick: i32, liquidity_net: i128)

result_hash:  sha256(batch_id: u64
                || price count: u8 || for each token: index: u16, price: u128, fee: u64
                || fill count: u8  || for each fill: sell: u16, buy: u16, fraction: u64)

The program computes the same three on chain. It folds each record into the batch's input hash as the order is placed or cancelled, computes the state hash from the live token and pair accounts when the clearing is posted, and computes the result hash from the posted prices, fees and fractions.

What the proof binds

prove_batch takes the 260-byte SP1 Groth16 proof and verifies it with Solana's pairing syscalls against two public inputs:

Public inputValueWhat it fixes
Firstsp1_vkey_hash from the program's ConfigWhich guest program ran. A guest built from different source has a different hash.
SecondSHA-256 of the 104 public values, with its top three bits clearedWhich batch, which input, which state and which result the guest accepted.

The program does not take the public values from the sender. It builds them from the batch account: the batch's number, the input hash it accumulated, the state hash it computed at clearing, and the result hash recomputed from the stored prices, fees and fractions. A proof verifies only if the guest accepted exactly the clearing the program has already settled orders against.

The proof's first 4 bytes are the first 4 bytes of the SHA-256 of the Groth16 verifying key in Config, so a proof made for another verifying key is refused before any pairing. A proof that fails any of this raises InvalidProof.

prove_batch with a real Groth16 proof uses 180,087 compute units, measured in the program's test of the fixture batch.

Verify a batch yourself

Three levels, each stronger than the last.

1. Recompute the hashes

The API returns a batch's hashes, its input records, and the state and result its solver published. This script recomputes all three hashes from the data and compares them with what the chain holds.

TypeScript
import { createHash } from 'node:crypto'
import { createUnaClient, fromBase58 } from '@una/sdk'

const client = createUnaClient(process.env.UNA_API_URL ?? 'https://api.una.markets')
const id = process.argv[2]!

const sha256 = (...parts: Uint8Array[]) => {
  const h = createHash('sha256')
  for (const p of parts) h.update(p)
  return new Uint8Array(h.digest())
}
// Little-endian integers of a fixed width.
const le = (value: bigint | number | string, bytes: number) => {
  const out = new Uint8Array(bytes)
  let v = BigInt(value)
  for (let i = 0; i < bytes; i++, v >>= 8n) out[i] = Number(v & 0xffn)
  return out
}
const hex = (b: Uint8Array) => Buffer.from(b).toString('hex')

const batch = await client.batch(id)
const input = await client.batchInput(id)

// 1. The input hash: start from the batch's number, fold every record in order.
let inputHash = sha256(new TextEncoder().encode('una/batch'), le(id, 8))
for (const r of input.records) {
  inputHash =
    r.type === 'place'
      ? sha256(inputHash, Uint8Array.of(1), fromBase58(r.order), le(r.sellToken, 2), le(r.buyToken, 2), le(r.amount, 8), le(r.limitQ64, 16))
      : sha256(inputHash, Uint8Array.of(2), fromBase58(r.order))
}
console.log('input hash ', hex(inputHash), hex(inputHash) === batch.inputHash ? 'matches' : 'DIFFERS')

// 2. The result hash: the posted prices and fees, then the fill fractions.
const prices = [...batch.prices].sort((a, b) => a.tokenIndex - b.tokenIndex)
const fills = [...batch.fills].sort((a, b) => a.sellTokenIndex - b.sellTokenIndex || a.buyTokenIndex - b.buyTokenIndex)
const resultHash = sha256(
  le(id, 8),
  Uint8Array.of(prices.length),
  ...prices.flatMap((p) => [le(p.tokenIndex, 2), le(p.priceQ64, 16), le(p.feeAmount, 8)]),
  Uint8Array.of(fills.length),
  ...fills.flatMap((f) => [le(f.sellTokenIndex, 2), le(f.buyTokenIndex, 2), le(f.phiQ63, 8)]),
)
console.log('result hash', hex(resultHash), hex(resultHash) === batch.resultHash ? 'matches' : 'DIFFERS')

// 3. The state hash: the state the solver published, hashed field by field.
const { state } = await client.batchState(id)
const stateHash = sha256(
  le(id, 8),
  le(state.bandBps, 2),
  le(state.clearingFeeBps, 2),
  Uint8Array.of(state.tokens.length),
  ...state.tokens.flatMap((t) => [le(t.index, 2), le(t.lastPriceQ64, 16)]),
  Uint8Array.of(state.pairs.length),
  ...state.pairs.flatMap((p) => [
    le(p.pairIndex, 2), le(p.tokenX, 2), le(p.tokenY, 2), le(p.feeBps, 2), le(p.tickSpacing, 2),
    le(p.sqrtPriceQ64, 16), le(BigInt.asUintN(32, BigInt(p.tick)), 4), le(p.liquidity, 16),
    Uint8Array.of(p.ticks.length),
    ...p.ticks.flatMap((k) => [le(BigInt.asUintN(32, BigInt(k.tick)), 4), le(BigInt.asUintN(128, BigInt(k.liquidityNet)), 16)]),
  ]),
)
console.log('state hash ', hex(stateHash), hex(stateHash) === batch.stateHash ? 'matches' : 'DIFFERS')

// 4. The public values: the 104 bytes the proof commits to.
const publicValues = hex(le(id, 8)) + hex(inputHash) + hex(stateHash) + hex(resultHash)
console.log('public values', publicValues === batch.publicValuesHex ? 'match' : 'DIFFER')

// 5. What the Groth16 proof was verified against: sha256 of those bytes with its top three bits cleared.
const digest = sha256(Buffer.from(publicValues, 'hex'))
digest[0]! &= 0x1f
console.log('second public input', hex(digest))
console.log('proof transaction', batch.proofSignature ?? 'none yet')
Shell
node --experimental-strip-types verify.ts 20

Run on a proven batch, it prints:

Text
input hash  3be83e8e2480ba88fed2a7e45febd2fc9f98144fcf741757d0be9d25be44cee1 matches
result hash 2f750af48a9332fd24617f4a3605cd4ef9bfda4e4cde51cd0a9c4c06ddf9bdb0 matches
state hash  0bea35355aa231cd0e5aff91f6c71b440bfff2542596db031b468b7d6d9da2cf matches
public values match
second public input 0e044037a0aaa068bf6baeee2bcc3f0ddad96bb7e9348942cff25600d458a3c3
proof transaction <the signature of the batch's prove_batch transaction>

Each record in batchInput carries the signature of the transaction that folded it, so every order in the input can be traced to the transaction that placed it. The state comes from batchState, which the API serves only when it hashes to the batch's state_hash on chain, and the script checks that hash again itself.

2. Read it from the chain

The API is a convenience. The same values sit in the batch's own account, at the address derived from the seeds "batch" and the batch's number as a u64 little-endian, under the program. Its fields hold input_hash, state_hash, result_hash, the prices, fees and fill fractions, and status, which is 3 for a proven batch.

The proof itself is in the prove_batch transaction, linked from the batch's page and returned as proofSignature. That transaction succeeded only because the program's verifier accepted the proof against the public values above. The 260 bytes of the proof are the instruction's argument.

3. Run the guest

The strongest check is to run the guest on a batch yourself. The guest's source is 14 lines over the clearing crate. Its prover host, una-prove, takes a batch as a JSON file, executes the guest on it, proves it, and verifies the proof:

Shell
cargo run --release --manifest-path guest/prove/Cargo.toml -- tests/fixtures/batch-input.json batch-proof.json

It prints the guest's cycle count, the proving time and the verification key hash of the guest it built:

Text
cycles=140942
prove_secs=141 vkey_hash=0x00e3fb2f3aa537041c24cec56443c21fad8f5f91e1eeba6b5b0d0543f0711fa3

Those are the figures for the fixture batch, proven as SP1 5.2.4 Groth16 on a CPU. The vkey_hash it prints is what to compare with sp1_vkey_hash in the program's Config: when they are equal, the program accepts proofs of the guest you just built and of no other.

The batch file has four fields:

batch-input.json

input_recordsarray
The records, in fold order, as Place and Cancel objects.
stateBatchState
The state the clearing was solved against.
resultBatchResult
The posted clearing.
public_values_hexhex, 104 bytes
The public values expected. una-prove stops if the guest commits anything else.

For a batch on chain, the same three values come from the API: client.batchInput(id) returns the records, and client.batchState(id) returns the state and the result, each already checked against the batch's hashes by the script above. Written into a file of this shape, they are what una-prove runs the guest on. A guest that accepts them commits the batch's own public values.

The fixture batch has two tokens and one pair. One order sells 200,000,000 atoms of token 0 for token 1, another sells 12,000,000,000 atoms of token 1 for token 0, and the pair holds liquidity of 50,000,000,000 between ticks 45,650 and 46,450. The pair's fee is 5 basis points and the clearing fee 10. It clears with token 1 priced 3.09% above its last proven price, inside a band of 500 basis points, with no fill fractions: both orders fill in full, and the pair moves from tick 46,054 to tick 45,755. What a position earns works through its numbers.

Where next