Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

On-Chain ZK Verification

Learning objective: Compile guards and state invariants into ZK circuits, commit state with Merkle trees, and verify Petri net execution on-chain.

Chapter 13 showed how petrigen compiles Petri net topology into gnark circuits and how graph connectivity determines strategic value. This chapter covers the rest of the pipeline: guards become arithmetic constraints, state is committed via Merkle trees, invariants become circuit constraints, and proofs are verified on-chain by smart contracts. The compiler stages are go-pflow’s zkcompile package; the contracts are petri-pilot’s ZkOde and the ZKHoldem contract generated by pflow-rs. Nothing in this chapter was re-run for it; where a number is derived rather than read from the code, the text says so.

Guard Compilation

Chapter 4 introduced guards — boolean expressions that add conditions beyond simple token availability. A guard like balances[from] >= amount on a transfer transition means: even if the input places have tokens, the transition only fires when the guard is satisfied.

In a ZK circuit, guards become arithmetic constraints. The GuardCompiler in go-pflow (zkcompile/guard.go) transforms guard expressions into the constraint IR that the gnark code generator consumes.

Boolean Logic as Field Arithmetic

ZK circuits operate over a finite field. There are no if statements, no booleans, no branches. Everything is multiplication and addition over integers mod a prime. The compiler transforms each logical operation:

AND: A && B becomes A * B. Both must be 1 for the product to be 1.

OR: A || B becomes A + B - A * B. At least one must be 1.

NOT: !A becomes 1 - A. The operand must be boolean (0 or 1).

These formulas compute a value; they do not by themselves constrain it. In the current compiler the constraints come from comparisons, each of which is asserted unconditionally and then returns the constant 1, and the value of the guard as a whole is never asserted to equal 1 (Compile discards it). A conjunction of comparisons, like the ERC-20 guard balances[from] >= amount && to != address(0) that guard_test.go compiles, is therefore enforced exactly. A comparison under || is enforced as though it stood alone, and !revoked adds only the check that revoked is 0 or 1, so disjunction and negation are not yet enforced.

Comparisons as Range Checks

The more subtle transformations handle comparisons:

Greater-or-equal: left >= right becomes:

  1. Compute diff = left - right
  2. Assert diff is non-negative with a range check

Non-negativity in a finite field is tricky — every field element is technically positive. The trick from Chapter 12 applies: require diff to fit in a fixed number of bits. The generated code asserts diff <= 2^64 - 1 (api.AssertIsLessOrEqual in zkcompile/gnark.go), which gnark implements by bit decomposition. If the original value was negative, it wraps to a huge field element that won’t fit in 64 bits, and the check fails.

Strict greater-than: left > right reduces to left - right - 1 >= 0.

Equality: left == right is a direct AssertIsEqual constraint.

Inequality: left != right requires proving the inverse exists. The compiler introduces a witness inv and constrains (left - right) * inv = 1. This is satisfiable only when left - right is non-zero — zero has no multiplicative inverse in a field.

State Access and Merkle Proofs

Guards often reference state: balances[alice] >= amount. The compileIndexExpr function handles map lookups by registering a state read. Each state read becomes a Merkle proof obligation — the prover must demonstrate that the claimed value actually exists in the committed state tree.

For nested maps like allowances[owner][spender], the compiler generates composite key hashing: key = Poseidon(owner, spender). The resulting key looks up a single leaf in the Merkle tree. The excerpt below has its error checks trimmed:

func (c *GuardCompiler) compileIndexExpr(idx *guard.IndexExpr) *Expr {
    // Check for nested index (e.g., allowances[owner][spender])
    if innerIdx, ok := idx.Object.(*guard.IndexExpr); ok {
        return c.compileNestedIndex(innerIdx, idx.Index)
    }

    // Simple index: place[key]
    placeIdent, _ := idx.Object.(*guard.Identifier)
    keyIdent, _ := idx.Index.(*guard.Identifier)

    // Register state read — triggers Merkle proof generation
    witness := c.witnesses.AddStateRead(placeIdent.Name, []string{keyIdent.Name})
    return VarExpr(witness.Name)
}

The guard compiler doesn’t verify Merkle proofs itself. It registers what state needs to be proven, and the pipeline (zkcompile/pipeline.go) hands those reads to the Merkle proof compiler, which generates the verification constraints.

Merkle State Commitment

Chapter 12 committed state with a flat MiMC hash: feed all place values into a single hash and publish the result. That chapter derives 330 constraints per element absorbed, so the 33-place ZK tic-tac-toe marking costs about constraints per hash. That is affordable for a small net.

But real applications have thousands or millions of state entries. An ERC-20 token has one balance per address. A workflow system has one case state per process instance. Flat hashing doesn’t scale.

From Flat Hash to Merkle Tree

A Merkle tree organizes state as leaves and hashes pairs up to a single root:

            root
           /    \
        h01      h23
       /   \    /   \
     h0    h1  h2    h3
     |     |   |     |
   leaf0 leaf1 leaf2 leaf3

To prove a single value, the prover provides the leaf and the sibling hashes along the path to the root — hashes instead of . The compiler fixes the depth at 20 (MerkleProofDepth in zkcompile/merkle.go), which supports (~1 million) leaves with 20 hashes up the path plus one for the leaf.

Poseidon or MiMC

The Merkle compiler’s constraint IR names its hash Poseidon, a ZK-friendly hash usually cheaper in circuits than MiMC. The IR constraint is marked as a placeholder in merkle.go, though, and the gnark code generator currently lowers every Poseidon constraint to a two-input MiMC call (mimcHash in gnark.go). As generated today, then, each hash in a Merkle proof is a MiMC hash of two elements, constraints by Chapter 12’s derivation. go-pflow’s research outline estimates about 182 constraints for a Poseidon call; that is an estimate, not a count taken from a compiled circuit.

Verification in the Circuit

The Merkle proof verification algorithm in the circuit (CompileProof in merkle.go):

  1. Compute the leaf hash: leaf = Poseidon(key, value)
  2. Walk up the tree: at each level, select left/right based on the path index, then hash the pair
  3. Assert the computed root equals the committed state root

The path selection uses the same no-branching pattern as transition selection — arithmetic multiplexing:

left  = pathIndex * sibling + (1 - pathIndex) * current
right = pathIndex * current + (1 - pathIndex) * sibling
hash  = Poseidon(left, right)

Each level adds one hash, a boolean check on the path index and the two selections; the leaf adds one more hash and the root one equality. A proof is therefore 21 two-input hashes plus 61 small constraints. With the MiMC the generator emits, that is about constraints per state access; with Poseidon at the outline’s estimate it would be about . Both figures are derived, not measured. Every state access costs one proof, but the circuit does not grow with the number of entries in the tree.

The pipeline proves reads against the pre-state root only. It declares a public post-state root but generates no constraints for writing the new values into the tree, so proving the updated root is not yet part of the generated circuit.

Nested Maps

For data structures like allowances[owner][spender], the compiler hashes the key pair into a single composite key:

compositeKey = Poseidon(owner, spender)
leaf = Poseidon(compositeKey, value)

This flattens nested maps into a single Merkle tree. The prover includes the raw keys and the composite key hash in the witness, and the circuit verifies the key composition.

State Invariants in Circuits

Chapter 2 introduced P-invariants — weighted sums of places that remain constant across all firings. In its three-place chain, never changes: tokens are neither created nor destroyed, only moved.

Offline, an invariant is something you check. Compiled into a proof circuit as a constraint, it becomes something the prover cannot get around: no valid proof exists for a step that breaks it. go-pflow’s InvariantCompiler (zkcompile/invariant.go) generates these constraints. It is exercised on its own by invariant_test.go (mint, transfer and burn against sum(balances) == totalSupply, and an NFT supply bound), but Pipeline.Compile does not yet call it: the pipeline passes no invariant constraints to the code generator.

Conservation Laws

Consider an ERC-20 token with the invariant sum(balances) == totalSupply. In a ZK circuit, we can’t iterate over all balances — the circuit doesn’t know how many accounts exist. Instead, we verify the invariant differentially:

Untouched balances don’t change, so their deltas are zero. The circuit only needs to verify that the changes to touched balances sum to the change in total supply. Condensed from CompileConservation:

func (c *InvariantCompiler) CompileConservation(
    sumPlace string,
    totalPlace string,
    transitions []StateTransition,
) []*Constraint {
    // Sum deltas for the summed place (e.g., balances)
    var sumDeltaExpr *Expr
    for _, t := range transitions {
        if t.Place == sumPlace {
            delta := SubExpr(VarExpr(t.PostVar), VarExpr(t.PreVar))
            if sumDeltaExpr == nil {
                sumDeltaExpr = delta
            } else {
                sumDeltaExpr = AddExpr(sumDeltaExpr, delta)
            }
        }
    }

    // Find delta for total place (e.g., totalSupply); 0 if untouched.
    // ...

    // Conservation: delta(total) == sum(deltas)
    return []*Constraint{{
        Type:  Equal,
        Left:  totalDeltaExpr,
        Right: sumDeltaExpr,
        Tag:   fmt.Sprintf("conservation: delta(%s) == sum(delta(%s))", totalPlace, sumPlace),
    }}
}

This is Chapter 2’s P-invariant argument applied to differences: if is the same before and after a step, then , and only the places the step touched contribute non-zero terms.

Non-Negativity

Token counts can’t go negative. The CompileNonNegative function adds range checks on every touched place’s post-transition value:

func (c *InvariantCompiler) CompileNonNegative(
    place string,
    transitions []StateTransition,
) []*Constraint {
    var constraints []*Constraint
    for _, t := range transitions {
        if t.Place == place {
            constraints = append(constraints,
                RangeConstraint(VarExpr(t.PostVar),
                    fmt.Sprintf("%s[%v] >= 0", place, t.Keys)))
        }
    }
    return constraints
}

In the generated circuit this is the same 64-bit range check the guard compiler uses, the trick Chapter 12 used for enabledness checks. If a balance would go negative, the field element wraps to a huge value that fails the range check.

Boundedness

Some places have capacity limits; an NFT’s supply of each token ID, for instance, is at most 1, which is the case TestInvariantCompiler_Bounded compiles. The CompileBounded function constrains post-values to not exceed a maximum, again by a range check on the difference:

// max - post >= 0
diff := c.witnesses.AddComputed(fmt.Sprintf("bound_%s", t.PostVar))
constraints = append(constraints,
    EqualConstraint(
        VarExpr(diff.Name),
        SubExpr(ConstExpr(maxValue), VarExpr(t.PostVar)),
        fmt.Sprintf("%s[%v] <= %s", place, t.Keys, maxValue),
    ),
    RangeConstraint(VarExpr(diff.Name), "bounded check"),
)

From Schema to Constraints

CompileFromSchema reads invariants from the model schema, but its parser (parseSchemaConstraint) recognises only two shapes:

sum(balances) == totalSupply    → Conservation constraint
balances >= 0                   → Non-negative constraint

Any other expression, an upper bound such as votes <= maxVotes included, is skipped; a bound has to be compiled by calling CompileBounded directly.

Each invariant adds one to three constraints to the IR: one equality for conservation, one range check for non-negativity, an equality and a range check for a bound. In R1CS the equalities are cheap and each 64-bit range check costs on the order of the bit width; no compiled count is recorded. Once such a constraint is in a circuit, a step that violates it has no valid proof.

On-Chain Verification

Generating proofs locally is useful for peer-to-peer verification — one player proves to another that a move is valid. But for applications with shared state — token transfers, governance, auctions — the proof needs to be verified where the state lives: on a blockchain.

State Root Chaining

petri-pilot’s ZkOde contract (solidity/src/ZkOde.sol) maintains a chain of state roots. The genesis root, the MiMC hash of the initial marking, is a constructor argument. Each submitted proof’s pre-state root (public input 0) must equal the stored root, and after the proof verifies the contract advances to the next root:

Genesis: stateRoot₀ = MiMC(initial_marking)

Step 1: proof₁ has preRoot = stateRoot₀; contract stores stateRoot₁
Step 2: proof₂ has preRoot = stateRoot₁; contract stores stateRoot₂
  ...
Step n: proofₙ has preRoot = stateRootₙ₋₁; contract stores stateRootₙ

The contract rejects any proof whose pre-state root doesn’t match:

if (preRoot != currentStateRoot) {
    revert InvalidStateChain(currentStateRoot, preRoot);
}

A proof made against an old root reverts, so steps cannot be replayed or reordered. Which root comes next is a separate question. The contract advances to nextStateRoot, an argument the prover passes alongside the proof; in the tic-tac-toe deployment it is the board after the chosen move, while the proof’s own post-state (public input 1) is the state after one ODE step. The verifier never sees nextStateRoot, so that link of the chain rests on the contract’s onlyProver restriction, not on the proof.

The ZkOde Contract

The contract’s state:

contract ZkOde {
    IVerifier public verifier;
    address public prover;
    uint256 public currentStateRoot;
    uint256 public stepCount;
    uint256 public immutable numTransitions;
    bool public enforceOptimal;

    struct Step {
        uint256 preRoot;
        uint256 postRoot;
        uint256 nextRoot;
        uint256 stepSize;
        uint256 chosenTransition;
        uint256 timestamp;
    }

    mapping(uint256 => Step) public steps;
}

The verifier is a gnark-generated Groth16 verifier, reached through a small adapter contract that converts the call into gnark’s flat argument format (solidity/DEPLOY.md). submitStep passes its arguments to _verifyAndRecord, which checks the chain, verifies the proof, records the step and advances the root. An excerpt, with the optimal-play check and the event omitted:

function _verifyAndRecord(
    uint256[8] calldata proof,
    uint256[] calldata publicInputs,
    uint256 chosenTransition,
    uint256 nextStateRoot
) internal {
    require(publicInputs.length >= 3 + numTransitions, "insufficient public inputs");

    uint256 preRoot = publicInputs[0];
    uint256 postRoot = publicInputs[1];
    uint256 stepSize = publicInputs[2];

    // Verify state chain: preRoot must match current state
    if (preRoot != currentStateRoot) {
        revert InvalidStateChain(currentStateRoot, preRoot);
    }

    // ... chosen-transition bounds check and optimal-play check ...

    // Verify the ZK proof
    uint256[2] memory a = [proof[0], proof[1]];
    uint256[2][2] memory b = [[proof[2], proof[3]], [proof[4], proof[5]]];
    uint256[2] memory c = [proof[6], proof[7]];

    bool valid = verifier.verifyProof(a, b, c, publicInputs);
    if (!valid) revert InvalidProof();

    // Record step
    steps[stepCount] = Step({
        preRoot: preRoot,
        postRoot: postRoot,
        nextRoot: nextStateRoot,
        stepSize: stepSize,
        chosenTransition: chosenTransition,
        timestamp: block.timestamp
    });

    // Chain on the discrete post-move board, not the ODE post-state
    currentStateRoot = nextStateRoot;
    stepCount++;
}

petri-pilot’s solidity/test/ZkOde.t.sol covers this contract with a stub verifier, the optimal-play rule, and the real Groth16 verifier behind the adapter (17 tests in three suites, per DEPLOY.md; not re-run here).

Optimal Play Enforcement

For game applications, the contract can enforce that the chosen transition has the highest value among all transitions. Public inputs 3 onward carry one value per transition, which the proof binds: the rate constants in the cascade circuit, and the nine heatmap scores in the tic-tac-toe circuit (DeployHeatmap.s.sol configures 12 public inputs: pre-root, post-root, step size and nine scores). The contract checks that no other transition has a higher value:

if (enforceOptimal) {
    uint256 chosenRate = publicInputs[3 + chosenTransition];
    for (uint256 t = 0; t < numTransitions; t++) {
        uint256 rate = publicInputs[3 + t];
        if (rate > chosenRate) {
            revert NotOptimalPlay(
                chosenTransition, chosenRate, t, rate);
        }
    }
}

The contract holds no game rules and no board; it compares numbers that the proof binds to the circuit. Ties pass, since only a strictly higher value reverts. Whether the highest value is the best move is a property of the scoring, which Chapter 13 derives from topology; the contract does not check that.

Batch Submission

For applications with many steps per session (a full game, a sequence of workflow transitions), submitting proofs one at a time pays the fixed cost of a transaction for every step. The submitBatchSteps function accepts arrays of proofs and processes them in order:

function submitBatchSteps(
    uint256[8][] calldata proofs,
    uint256[][] calldata publicInputsBatch,
    uint256[] calldata chosenTransitions,
    uint256[] calldata nextStateRoots
) external onlyProver {
    require(proofs.length == publicInputsBatch.length, "length mismatch");
    require(proofs.length == chosenTransitions.length, "transitions length mismatch");
    require(proofs.length == nextStateRoots.length, "nextStateRoots length mismatch");
    for (uint256 i = 0; i < proofs.length; i++) {
        _verifyAndRecord(proofs[i], publicInputsBatch[i], chosenTransitions[i], nextStateRoots[i]);
    }
}

Gas Costs

No gas measurement of submitStep is checked into the repository. An estimate can be derived from the EVM’s prices for the BN254 precompiles (EIP-1108) and for storage (EIP-2929):

OperationGas (derived)
Groth16 pairing check, 4 pairings: 181,000
Public-input combination: one scalar multiplication (6,000) and one addition (150) per input30,750 for 5 inputs; 73,800 for 12
Step record: six fields in a fresh storage slot each, at 22,100 for a zero-to-non-zero writeup to 132,600
currentStateRoot and stepCount updatesabout 10,000

That puts a step at roughly 350,000 gas for the five-input cascade and 400,000 for the twelve-input tic-tac-toe circuit, before the 21,000 base cost of a transaction and its calldata. What that costs in money depends on the chain’s gas price at the time.

Deployed Contracts

Foundry’s broadcast logs in petri-pilot’s solidity/broadcast/ record two deployments on Base Sepolia (testnet, chain 84532):

DeploymentVerifierZkOdeTransitionsOptimal
Cascade (3-place)0xA675...0x2084...2Yes
TTT Heatmap (33-place)0x97a6...0xF5d9...9Yes

Both were deployed with enforceOptimal set, so the TTT contract rejects a move whose score is lower than another transition’s. That falls short of a trustless game in two ways already described: only the deployer’s prover address can submit steps, and the board root the contract advances to is not bound by the proof.

ZK Hold’em: Topology-Derived Payouts

The poker hand analysis net from Chapter 13 produces hand strength values from its topology, in which the drain counts encode how common each hand is. pflow-rs’s zk_holdem.rs example carries those values into a game contract as payout multipliers. Run with --export-solidity, it renders a ZKHoldem contract from the template render_holdem_contract in pflow-zk-arkworks/src/solidity_export.rs. Its proofs come from a different stack from ZkOde’s: arkworks Groth16 over BN254 with Poseidon state roots. The contract adds three poker-specific mechanisms.

Commit-reveal shuffle. The example shuffles the deck with Fisher-Yates driven by a seeded linear congruential generator (shuffle_deck) and publishes a Poseidon commitment to the seed; the contract stores it through commitShuffle. At showdown the house reveals the seed, so anyone can recompute the commitment and the cards off-chain. The generated revealAndSettle does not yet do either check itself: its body says the Poseidon check and the card derivation are left for production, and it takes both hand ranks as arguments. A claimTimeout function is meant to close a game the house abandons; as generated, its 100-block timeout counts from block 0 rather than from showdown, so it does not yet enforce a reveal window.

State root chaining per action. Each game action — deal, check, bet, call, fold — fires a transition on a reduced heads-up game net (build_game_net: 18 places, 16 transitions — not the Chapter 10 model) and produces a Groth16 proof. playerAction and houseAction require the proof’s pre-state root to equal the stored root and then store its post-state root, so here, unlike in ZkOde, every link of the chain is bound by a proof.

Topology-derived bonus payouts. The winner takes the pot plus a bonus proportional to the integer reduction value of their hand. The example rounds Chapter 13’s values, , to integers and writes them into the contract:

uint256[9] private HAND_STRENGTH = [
    uint256(1), 1, 2, 3, 4, 6, 8, 16, 32
];
// Index: 0=HC, 1=Pair, 2=2P, 3=3K, 4=Str, 5=Flush, 6=FH, 7=4K, 8=SF

uint256 bonus = HAND_STRENGTH[playerRank] * SMALL_BLIND;

The array values are that rounding of the closed form (32, 16, 8, 6.4, 4, 2.7, 2, 1.3, 1), derived rather than re-run. A straight flush win pays 32 times the small blind as bonus, a pair 1 time. As Chapter 13 notes, the ordering went into the net with the drain counts, which were chosen by hand from the combination counts. The net does not discover the payout schedule; it gives a mechanical, inspectable path from the frequency table to the multipliers, which is what makes the schedule auditable.

The example’s house plays a deterministic strategy based on hand strength and pot odds, so it could in principle be checked on-chain. The generated contract does not check it: houseAction accepts any action that comes with a valid transition proof.

Combinatorial vs. Continuous

The circuits in this chapter and the last fall into two modes, and the choice affects both the circuit design and how the results should be read.

Combinatorial Mode

Games, workflows, governance, token standards.

The state space is finite and discrete. Tic-tac-toe has at most 5,478 reachable board states. A workflow has a bounded number of case states. An ERC-20 has integer balances.

In these systems, the topology and discrete scoring are sufficient. The ODE provides a continuous picture of token flow, useful for intuition and as a heatmap, but when it comes time to decide, you discretize. The heatmap scoring that drives move selection in tic-tac-toe is discrete: count win lines, evaluate threats, pick the best move. There is no continuous quantity being modeled.

The “mass-action kinetics” framing is a useful metaphor that lets you apply ODE machinery, but the strategic information is graph-theoretic.

What the ZK circuit proves: the discrete state transition was valid — correct inputs consumed, correct outputs produced, guard conditions met. The ODE step is optional — it enriches the public output with heatmap scores but isn’t necessary for correctness.

Rate derivation: auto-derive from topology, by Chapter 13’s count of win transitions reachable through each move’s unique outputs.

Continuous Mode

Chemical kinetics, population ecology, epidemiology, economic models.

The state genuinely evolves in continuous time. Concentrations rise and fall. Populations oscillate. Epidemics peak and decay. The trajectory carries information — you care about when concentrations peak, in what order, and how fast.

In these systems, the topology tells you what can happen, but the ODE tells you what happens first. A chemical cascade where reaction A peaks before reaction B produces a different product mix than one where B peaks first, even if the topology is identical.

What the ZK circuit proves: the ODE integration was computed correctly. petri-pilot’s zk-ode circuit recomputes the seven stages of a Tsit5 step, the mass-action rates and the stoichiometry-weighted derivatives in fixed point and constrains the result. The circuit is compiled against fixed topology constants: the three-place cascade A → B → C in zk-ode/topology.go, and a separate 33-place tic-tac-toe topology for the heatmap circuit. Another net needs new constants, a recompile and a new verifier (DEPLOY.md).

Rate derivation: bring domain-specific rates. They encode physical properties (activation energies, birth/death rates, transmission coefficients) that topology cannot capture.

Fixed-Point Arithmetic for Continuous Mode

ZK circuits operate over finite fields — integers mod a prime. There are no floating-point numbers. zk-ode/fixedpoint.go uses fixed-point arithmetic with a scale factor over the BN254 scalar field:

This gives 18 decimal digits after the point, using only integer operations that ZK circuits handle natively. In the circuit, FixMul takes the quotient and remainder from a prover hint and constrains , so every product is truncated, and a long integration can drift from a floating-point run by the accumulated truncation.

The Pipeline Supports Both

CombinatorialContinuous
RatesAuto-derived from topologySpecified in model
ODE stepOptional (enriches output)Essential (proves trajectory)
ScoringDiscrete win/block detectionRate-weighted heatmap
Circuit focusState transition validityIntegration correctness
ExamplesTTT, Hold’em, workflows, ERC-20The A → B → C cascade

Epidemic and population models fit the continuous column on paper; none has been compiled to a ZK ODE circuit. petri-pilot’s zkgen command (cmd/petri-pilot/zkgen.go) generates a ZK ODE circuit package from a model file, with an optional scoring configuration for the tic-tac-toe heatmap.

Putting It Together

The compilation pipeline from this chapter and Chapter 13, combined with the circuit fundamentals from Chapter 12, creates a complete system for verifiable Petri net execution:

  1. Define the model in JSON — places, transitions, arcs, guards, invariants
  2. Generate circuits — petrigen turns topology into constants and guards into constraints; zkcompile’s guard and Merkle stages handle map-valued state, and its invariant compiler is not yet wired into that pipeline
  3. Derive rates from graph connectivity — or specify domain-specific rates
  4. Prove transitions locally — the prover generates a Groth16 proof that the state changed correctly
  5. Verify — off-chain in milliseconds (Chapter 12’s typical figure, not benchmarked here), or on-chain for a few hundred thousand gas (derived above)

The model is the specification, and each proof attests that one step followed it.

Two games now carry topology-derived values into a proof system:

GameWhat is recoveredHowNet
Tic-Tac-ToePosition value: center=4, corner=3, edge=2Count of win transitions reachable from each move33 places, 35 transitions (ZK variant)
Hold’emHand ranking: SF=32, 4K=16, …, HC=1Equilibrium of an analysis net, normalised and rounded18 places, 113 transitions (analysis net)

The two differ in where the game knowledge enters. Tic-tac-toe’s values are counted from the game’s own win transitions; Hold’em’s come from a separate analysis net whose drain counts encode the hand-frequency table, so the poker knowledge enters as data. They also use different proof stacks: the tic-tac-toe circuits are gnark Groth16 over BN254 with MiMC state roots (Chapter 12), the Hold’em example arkworks Groth16 over BN254 with Poseidon roots. In both, the circuit is compiled from the net’s topology and contains no game-specific code.