# `hfhss` Security & Threat Model

This document states—without magical thinking or marketing inflation—what `hfhss` (`Dark-PoUW`, `LPN-PoUW`, two-plane malicious 3PC, `C127^(7)` leveled Matrix-FHE, `BonsaiAuditReceipt`, and 3-custodian `ErasureReceipt`) **actually** guarantees, which attacks it defeats, and which physical or metadata boundaries remain outside cryptography.

---

## 1. Parties, Trust Assumptions, and Adversarial Model

| Role | What It Sees | Adversarial Assumption | Failure Mode |
|---|---|---|---|
| **Client / Prompt Owner** | Own prompt tokens, final decrypted output (after `MAC2` / `Settled`), sequence lengths | Honest for own privacy; untrusted during episode ingest (checked via `NotBits`, `NotGradientStep`, `LossNotReduced`) | Malformed inputs rejected before mutating shared state |
| **Untrusted GPU Miner / Worker** | Encrypted activations (`B` mod `Q` or LPN-masked `X'` mod `M31`), public `PTQ1_0` weights `W` (Tier 1) or encrypted weights `ct(W)` (Tier 2), public headers & commitments | **Actively malicious** (may forge outputs, inject crafted noise, mine shortcuts like stacked-`H` / `H_128` / permutations, or collude with up to 1 custodian) | Rejected **before decryption** (`Settled`, `WinningTileProof`, `SingleColumnPtq1Proof`) and slashed on-chain |
| **3 Custodians (`C0, C1, C2`)** | Replicated/additive secret shares (`1`-of-`3` view on lattice/3PC; genuine `3`-of-`3` OS-entropy shares + independent `alpha_i : B61Ext5` in `verifiable_unlearn.rs`) | **At most one corrupt custodian** for lattice/3PC confidentiality & soundness; **up to two corrupt custodians** for `verifiable_unlearn.rs` episode erasure & live-state MAC soundness | Fail-closed abort with soundness `< 2^-121.97` (`Ext2` MACs) / `< 2^-123` (`LPN-PoUW`) / `< 2^-182` (`p61 * M61`) / `< 2^-304` (`B61Ext5` erasure) |
| **Public Verifier / On-Chain Program (`dreggference`)** | Public `BonsaiAuditReceipt` (`DPWT`, `688 B` / `1,072 B` `ErasureReceipt`, `PTJ1` `198 B` job + `PTC1` `1,205 B` / `1,160 B` single-column `PTQ1_0` dispute witness, `Settled` / `MAC2` commitments) | Zero trusted hardware; verifies purely from registered `Ptq1WeightTree` roots, committee pubkeys, and prior state commitments | Rejects invalid receipts, forged column dots, mismatched roots, and offline receipt forgeries |
| **Network Observer** | Packet sizes, round counts, timing, sequence/batch dimensions (`T`, `K`, `N`) | Passive or active network eavesdropper | Sees **metadata** (lengths & timing) unless fixed-bucket padding is enabled (§4) |

---

## 2. `IND-CPA^D` (Li–Micciancio) & Active CCA / Malformed-Ciphertext Oracles

Lattice homomorphic encryption schemes are **not** `IND-CCA` secure out of the box, and exposing decrypted outputs to untrusted parties creates two distinct key-recovery channels:

### 2.1 Why Unverified Approximate CKKS Fails (`IND-CPA^D`)

In approximate CKKS, decryption returns `m + e` directly, where `e` is a linear function of the secret key `s` and the evaluation error polynomial (`e = c_0 + c_1 s - m`). As demonstrated by Li and Micciancio (CRYPTO 2022) and formalized further by Choe–Kang–Stehlé (ePrint 2026/2546), an adversary who learns `m + e` for honestly evaluated ciphertexts extracts noisy linear equations over `s`, recovering the secret key in minutes unless the decryption output is flooded with super-polynomial or differential-privacy noise `sigma_flood >> sigma_err`.

### 2.2 Why Unverified Exact BFV / BGV / Compact-MLWE Fails Under Active CCA Probing

Even when an *honest* ciphertext decrypts with zero error (`round((Delta * m + e) / Delta) = m`), an **actively malicious** server or miner can turn decryption into a **reaction / decryption-failure oracle**:
- The server crafts a malformed ciphertext or perturbs an output residue (`Y5 + delta`, or adds a biased error `e*`) to push the phase `Delta * m + e` right onto the rounding boundary `+-Delta / 2` (or `+-Delta / 4` in 3-party rounding).
- Observing whether the client/custodians accept, abort, or emit a shifted integer output leaks 1 bit of a half-space inequality on the secret key `s` (mechanized in `lean/Hfhss/CryptanalysisFalsifiers.lean` as `zero_error_halfspace_leakage`). Repeating ~`O(d)` adaptive queries recovers the secret key.
- Similarly, heuristic message bounds (such as applying a probabilistic sub-Gaussian Bernstein bound to *activations* `X`, which are structured and can align with weight columns!) allow an adversarial or deep-layer correlated input to overflow the `joint_round` window and cause silent decryption wraps.

### 2.3 Exact Mitigations Across Every `hfhss` Substrate

`hfhss` eliminates both attack surfaces using four concrete mechanisms tailored to each datapath:

1. **Exact `M31` `LPN-PoUW` (`crates/dark-pouw/src/{lpn_mask,lpn_pouw}.rs`) — Zero Noise, Zero Rounding:**
   - Operates over exact integers in the Mersenne prime field `GF(M31)` (`M31 = 2^31 - 1`) with **zero lattice noise and zero rounding step**. There is no decryption-failure boundary to probe.
   - Each of the three modeled pairs has four private probes. Under independent uniform sampling, a fixed wrong result passes an unseen pair's checks with probability at most `M31^-4 < 2^-123`. A failed probe retires the settlement key.
   - The Rust reference verifier holds all three probe sets and receives raw `Y`. It supplies a masked vector to custodian 0's correction calculation. A host that runs the verifier can inspect `Y` and the probes. Protection against compromise of that host requires separating the pair keys and the check across processes.

2. **Tier-1 `Dark-PoUW` Compact-MLWE (`crates/dark-pouw/src/{bonsai_ternary_pouw,private_finetune,proof_freivalds}.rs` & `llama-dark-pouw`):**
   - **Verify-Before-Decrypt (`Settled` / `settled_ct`):** Before custodians ever touch secret shares `S_p` or hints `U_p = S_p W`, the public verifier checks the exact integer quotient-lift identity `B_c W = Y_c + Q Z_wrap` over `Z` via hard range checks plus Fiat-Shamir Freivalds probes modulo `p61` and `M61` (`<= 2^-182` under `Standard128`; `2` probes mod `p61` `<= 2^-121.9` under `Everyday80` whenever `2 * total_bound < p61`, automatically activating `M61` when `2 * total_bound >= p61` such as `Q_6, K = 17408, L = 127`). Because `distributed_decrypt5` / `cmlwe_decrypt_3pc_settled` accepts **only** a type-checked `Settled` token bound to `(B_c, W, dims, root)`, a malicious miner **cannot inject crafted noise into the decryption input**.
   - **Deterministic Cauchy–Schwarz / Hölder message bounds (zero `bern_m` heuristic):** `plan_base_round` (`private_finetune.rs`) and `choose_params_3pc_weight` (`llama-dark-pouw`) apply Bernstein sub-Gaussian tails **strictly to the i.i.d. zero-mean LWE noise `E W`** (`<= 2^-80` per entry / `<= 2^-64` union for `Standard128`; `<= 2^-52` / `<= 2^-36` union for `Everyday80`), while bounding `|X_t . W_j| <= min(||X_t||_2 ||W_j||_2, ||X_t||_inf ||W_j||_1) <= m_bias` **deterministically** before encryption (`cmlwe_row_admissible` / `BaseRoundPlan`). Aligned or adversarial activations that could wrap `joint_round` are refused before encryption.
   - **Exact 3-party smudging-free rounding & per-weight durable sample caps:** All live Bonsai/Tier-1 3PC decryption paths (`bonsai_ternary_pouw.rs`, `compact_mlwe.rs`, `subring_ct_pt.rs`, `private_finetune.rs`) route through zero-dealer networked `NetworkedExt2Custodian` (`threshold_decrypt.rs`, `ePrint 2025/1781`) to round into verified `F_p61` shares without opening any plaintext phase or raw LWE noise (the legacy semi-honest `JointRoundParams::round_entry` twins are deleted). Every encryption key struct (`Pt6SecretKey`, `Pt6CustodianKeys`, `CompactMlweKey`, `Mlwe5Key`, `FlexBaseKey`, `c127_ctct_lora::SecretKey`, `ring_fhe::SecretKey`, `TmClientKey`, plus co-held custodians) persists row counts on disk via `RowLedger` in the configured ledger directory (default `$XDG_STATE_HOME/hfhss/rows`, or `$HOME/.local/state/hfhss/rows`) so restarts never reset `SAMPLE_CAP`. Provision a stable directory and preserve it with the key.
   - **Threshold decryption and MPC rounding.** Each role checks the owner-authorized Q5 settlement, bounded public operands and agreement on the job before using its local hints. The network protocol authenticates peer frames, refreshes its tapes with three committed OS contributions and records nonces durably. An interrupted run retires the local pair-key epoch. The worst truncation opening per element has distance at most `2^-67` for Q5 and `2^-60` for PT6. Repeated openings compose. The local reference and the network protocol have different preprocessing assumptions.


3. **Tier-2 Leveled `C127^(7)` Matrix-FHE (`crates/dark-pouw/src/{c127_ctct_lora,private_finetune}.rs`):**
   - **Exact integer CRT decoding (`54`-bit & `30`-bit RNS):** Private LoRA encodes integer activations and adapters via exact CRT primes (`[31751, 28703, 27941]` at 30-bit) with `>= 26` bits of measured noise headroom (`61.7–62.5b` max noise vs. `88.9b` ceiling at `K = 17,408, r = 32`), so honest decryption recovers the **exact integer** `(X A B)` with zero approximate CKKS error `e` exposed.
   - **Noise flooding where approximate/threshold decryptions occur:** When approximate CKKS outputs or threshold partial decryptions must be exposed to external parties, `ActiveFhe.lean` mechanizes unconditional total-variation-distance (TVD) smudging bounds (`shiftMass_eq_l1_half_of_supported`, 40-bit uniform flooding at `Q_PT6`).
   - **Ephemeral per-session client keys & pre-decrypt verification:** Deployments MUST rotate `C127^(7)` client keys per session (and strictly honor `C127_SAMPLE_CAP = 2^25` via `RowLedger` — never reusing a long-lived approximate CKKS key across interactive decryption oracles without flooding) and verify the ciphertext product before decryption. The verifier draws private Freivalds probes after receiving the ciphertext tensor. It checks every slot and component of each RNS plane before trusted relinearization and output decoding. Repetitions give at least 128 bits against a fixed wrong tensor under independent uniform probes. Historical GPU timings predate this verifier.

4. **Malicious Two-Plane 3PC (`crates/dark-3pc-core/`, `Ext2(p61) x Ext2(m61)`):**
   - Consolidated into one shared audited crate (`crates/dark-3pc-core/`) imported by `dark-pouw`, `bonsai27b_full_layer0_3proc`, `dark_custodiand`, `dark_attention_3proc`, `sarvam_moe_3proc`, and `rss_weights_3proc` (eliminating copy-pasted multi-binary drift): bounded-frame `Mesh`, canonical `< P61`/`< M61` `Result` decoding, PRG-padded zero tests, symmetric AES-128-CTR pair-seeded PRG streams across both `p61` and `m61`, wrap-free `rns_trunc`, `Ext2`-challenged `rnsspline`, and compile-time `#[cfg(feature = "fault-injection")]` gating.
   - Upgrades two-plane `Zm` MACs to `Ext2(p61) x Ext2(m61)` (single independent MAC-key guess probability `< 2^-121.97` for single-limb zero-divisor deviations `(0, delta_m)` and `(delta_p, 0)`, while keeping base wire elements at `16 B/elem`).
   - Uses `RHOS` pair-seeded client input masking, zero-`Delta`-leak `MAC2` output authentication, guard-bucket `spline_v2`, and wrap-free `rns_trunc` (`K = 119`, `< 2^-70` statistical privacy at `vb <= 48`).
   - **Open 3PC caveats (documented honestly):** Legacy `--trunc-bits --dealer-free` splines retain the older dual check; Mode B can leak ~1 bit through a data-dependent abort; and on values inside a range check's slack zone a corrupt dealer can still shift the threshold (`notes/bonsai27b-3proc-malicious.md`). Use default TwoPlane `Ext2` `rns_trunc` for production security.

---

## 3. Explicit Security Profiles: `Standard128` vs. `Everyday80`

`Standard128` (`DPW_SECURITY=128`) is the **default** everywhere. `Everyday80` (`DPW_SECURITY=80`) is an **explicit opt-in** profile sized to `>= 90.2` classical AND `>= 80.5` quantum Core-SVP at quantum sieving exponent `0.265` against one corrupt custodian. At exponent `0.257` only the 5-plane row stays above 80 bits (`>= 80.9`); the 4- and 6-plane rows are certified at `78.3` and `78.8`. Every figure in the table is a proved lower bound, not the higher Python point estimate (interval-certified in Lean 4 under `lean/Hfhss/ConcreteSecurity/Shipped/` and `lean-real/HfhssReal/Rows.lean`, and cross-checked via `validation/lean_concrete_security_diff.py` over primal uSVP, dual, primal-hybrid, and ePrint 2026/2117 probability-ordered dual hybrid, `m <= 2^16` rows/key):

| Substrate / Planes | `Standard128` (`DPW_SECURITY=128`, default) | `Everyday80` (`DPW_SECURITY=80`, explicit opt-in) |
|---|---|---|
| **Compact-MLWE `4` planes (`Q_4 ~ 2^31.65`)** | `D = 2560` (`>= 241.7b` cl / `>= 212.7b` qu) | `D = 1216` (`>= 90.2b` cl / `>= 80.5b` qu, `>= 78.3b` qu at `0.257`; `L = 1` for `K <= 6144`) |
| **Compact-MLWE `5` planes (`Q_5 ~ 2^39.49`)** | `D = 2560` (`>= 186.0b` cl / `>= 164.8b` qu; `L <= 12`) | `D = 1536` (`>= 93.1b` cl / `>= 83.2b` qu, `>= 80.9b` qu at `0.257`; `L = 16`, `11.86 GiB/cust`) |
| **Compact-MLWE `6` planes (`Q_6 ~ 2^47.32`)** | `D = 2560` (`>= 148.3b` cl / `>= 132.2b` qu; `L = 127`) | `D = 1792` (`>= 90.5b` cl / `>= 81.0b` qu, `>= 78.8b` qu at `0.257`; `L = 127`, `13.84 GiB/cust`) |
| **`C127^(7)` 30-bit Private LoRA (`QP ~ 2^120`)** | `n = 512, N = 9216` (`>= 247.0b` cl / `>= 215.6b` qu at `0.257`) | `n = 256, N = 4608` (`>= 95.0b` cl / `>= 83.2b` qu at `0.257`; 1 key at `K=17408`) |
| **Pre-decrypt settlement** | Dual-prime `p61^5 x M61^3` (`<= 2^-182`) | 2-probe `p61` (`<= 2^-121.9`) if `2*bound < p61`, else dual `p61 x M61` |
| **Recommended use** | High-value / long-lived confidentiality, harvest-now-decrypt-later resistance | Ephemeral low-latency interactive sessions where `>= 80b` quantum / `>= 90b` classical security suffices |

---

## 3.1 Zero-custodian mode (open weights, no committee)

`crates/dark-pouw/src/zero_custodian_pouw.rs` removes the custodians for public weights. The client holds an ephemeral ternary `S`, an independent ternary RLWE key, and nothing else long-lived. Parameters: `Q_RLWE = 1 + 8192·333·Q5` (prime, `DELTA_RLWE·Q5 = Q_RLWE − 1`), RLWE errors uniform on `[−2^13, 2^13]`, `Standard128` `D = 2560, n = 4096`, `Everyday80` `D = 1536, n = 2048`. The mask-layer RLWE estimate comes from `validation/concrete_lattice_estimator.py` (point estimate: about `110` classical / `97` quantum bits at `n = 2048`, about `277` / `244` at `n = 4096`); it is **not** Lean-certified, which is why the `2048` ring is used only with the `Everyday80` profile. The LWE layer reuses the certified `planes5` / `ev80Planes5` rows.

- **Verify before decrypt.** `ZcSession::decrypt` accepts only a product settlement token and a mask settlement token whose statements are bound to this session's upload digests, the layer record and the query. Both checks are functions of public values (`B`, the uploaded `b^`, `W`, the hint, the answer), so the verdict is available to the miner without any secret; there is no accept/reject that depends on `sk` or `S` (ePrint 2026/3039). `rejects_selective_failure_perturbations_before_the_rlwe_key_is_read` runs eleven perturbations, including shifts that would move one decrypted entry by one message unit and a tampered public mask, and asserts the key is never read. Lean: `mask_reaction_none_of_reject`, `mask_wrong_answer_accept_count` (`≤ q^(n−1)` of `q^n` probes accept a wrong answer, for any adversary choice that depends on the secret).
- **Client sketch (`ClientSettledSketch`).** A client holding `W` once can keep `V_W = W·R mod p61` for `4` secret probe columns (`K×4` words, plus `R`, `N×4` words) and settle the product as `B·V_W = (Y + Q5·Z)·R` without reading `W` (state `0.72 MB` at `5120×17408`, one-row check `0.23 ms` measured); it retires itself on the first mismatch. The token is valid for that client only. The mask relation has no such sketch: a per-slot check needs the hint-times-probe table (`D·5·n` words per probe, about `125 MB` for `Everyday80`), so mask settlement reads the hint.
- **Limits.** One `S` meets each layer's `A` once and at most `2^24` columns in total. The session upload is `114 MiB` (`Everyday80`) or `381 MiB` (`Standard128`) per row. Weights are public: this mode hides `X` and `X·W`, nothing about the model.

## 4. Metadata Leakage: Sequence Lengths, Token Counts & Padding Recommendations

**Cryptographic encryption and 3PC hide prompt *content*, NOT prompt or response *lengths*.**

Without traffic shaping, an untrusted miner, custodian, or passive network observer directly observes:
1. **Prompt token count `T_prompt`** (exact prefill row count, or padded tile `M = ceil(T_prompt / TM) * TM`).
2. **Generated token count `T_gen`** (number of decode iterations before the session closes — leaking stop-token `<eos>` position and approximate answer length).
3. **MTP speculative acceptance cadence** (variable draft-accept lengths can correlate with output entropy/predictability).

### Recommended Production Mitigations

Deployments requiring resistance to length-based side channels (e.g., medical, legal, or financial queries where short vs. long answers leak a sensitive yes/no verdict) SHOULD enforce **fixed-bucket padding**:
- **Prompt length buckets:** Pad `T_prompt` at the client to a small public set of fixed buckets—e.g. `{64, 256, 1024, 4096}` (all exact multiples of `TM = 16` and `r = 128`)—using encrypted padding tokens whose attention mask is applied inside the encrypted/3PC attention layer.
- **Output length buckets:** Commit to a fixed output bucket `T_out in {64, 256, 512, 1024}` before starting decode. Once the client reconstructs `<eos>`, the client continues submitting dummy encrypted decode steps until `T_out` tokens are reached, preventing stop-token timing leakage.
- **Constant-rate MTP or fixed batching:** When hiding entropy patterns matters, either run fixed-size decode batches across multiplexed sessions or disable variable-length speculative early exit.

---

## 5. Honest `ErasureReceipt` Threat Model (Zero Magical Thinking)

**Hard physical truth:** *No cryptographic protocol can prove that a single dishonest machine did not copy its own RAM to disk, take a VM snapshot, or exfiltrate its memory over a side channel before zeroizing its buffers.* Any system claiming a "cryptographic proof that one server deleted your data" is selling theater.

### 5.1 3-of-3 Additive Custody, Independent `B61Ext5` MACs, and Erasure Receipts

In `crates/dark-pcg-custody/src/verifiable_unlearn.rs`, episodic fast-weight memory `(U_e, V_e)` and offset-binary bit-planes `beta` are split across **three independent custodians** using **genuine 3-of-3 OS-entropy additive secret sharing** over `F_p61` (delivered privately per custodian), authenticated under **independent per-custodian OS-entropy MAC key shares** `alpha_i : B61Ext5` (`p61^5 > 2^304`) via pairwise post-quantum RLWE 1-out-of-2 base OTs and forward-ratcheted OT-extension `B61Ext5` COPEe / Beaver correlations with the KOS15 correlation check (`crates/dark-pcg-custody/src/ole.rs`, with zero replicated pair seeds). A receiver that deviates in the extension passes that check only by guessing bits of the sender's `delta` (`c` bits with probability `2^-c`); any abort in `INGEST_COMMIT`, `QUERY` or `REVOKE` zeroizes the realm and poisons its id, so a wrong guess cannot be retried against the same keys. When episode `e*` is revoked, the custodians delete `[U_{e*}], [V_{e*}]`, subtract them from the live factor aggregates `([agg_U], [agg_V])`, add interactive 3-party OS-entropy zero-sum refresh shares `rho_0 + rho_1 + rho_2 = 0` (`Mesh::zero_sum_avec`) to every surviving share (immediately zeroizing pre-erasure shares and temporaries on drop), commit to the new state, run a live-state SPDZ MAC check, and emit an attested `ErasureReceipt`.

This proves **two concrete, non-magical guarantees** (matching `lean/Hfhss/ErasureHonestModel.lean`):

1. **1- and 2-corrupt live-state unlearning consistency (anti-lazy / anti-stale guarantee):**
   - Even if up to **two** custodians collude to leave episode `e*` inside the live shared fast-weight adapter (or replay pre-revocation shares), the lone honest custodian's independent unknown `alpha_h : B61Ext5` causes the live-state SPDZ MAC check (`sum(pi[*][3]) = 0`) to reject with probability `1 - p61^-5 > 1 - 2^-304`, refusing to sign and destroying the realm (`two_corrupt_lazy_or_stale_custodians_still_caught_by_independent_alpha`).
   - Verified post-revocation live queries are mathematically identical to a twin world in which episode `e*` was never ingested (`revoke_matches_twin_world_and_forgets_only_the_target`).

2. **2-corrupt RAM-snapshot unrecoverability (1-of-3 honest deletion):**
   - Because each custodian receives only its own 3-of-3 share `(u_i, v_i)` (never pair seeds) and overwrites/zeroizes its pre-erasure share during `REVOKE`, **even two colluding custodians holding both pre- and post-erasure RAM snapshots** (plus post-erasure shares) hold zero mutual information about the erased episode (`two_corrupt_pre_and_post_snapshots_cannot_reconstruct_erased_episode`, matching `one_honest_custodian_erasure_it_unrecoverable` and `two_corrupt_full_view_hides_erased_target`; `uniform_zero_sum_refresh_hides_target_share` is the 1-corrupt refresh statement, and `two_corrupt_view_plus_honest_pre_share_determines_target` shows the 2-corrupt claim needs the honest custodian's pre-erasure share to be gone).
   - **Honest physical boundaries:** Compromising all **3-of-3** pre-erasure snapshots (`three_corrupt_snapshots_recover_target`) or simultaneously capturing all 3 pre- and post-revocation shares (`all_three_pre_and_post_determine_target`) recovers the episode. Standalone `silent_pcg.rs::CustodianPcg` (2-of-3 replicated GGM stream, not used by `verifiable_unlearn.rs`) remains a 1-corrupt primitive (`replicated_cnf_two_corrupt_recovers_target`).

### 5.2 Closing Standalone Offline `ErasureReceipt` Forgery

Earlier versions checked only the unauthenticated `688 B` algebraic core (`sum(pi) == 0` plus unkeyed `TurboSHAKE256` transcript tags). Because `sum_{i=0}^2 pi[i][k] = 0` is linear, any third party with no custodian keys could fabricate a standalone receipt offline by choosing arbitrary `pi[0], pi[1]`, setting `pi[2][k] = -(pi[0][k] + pi[1][k])` for `k in {0, 1, 3}`, and recomputing the unkeyed tags.

`verifiable_unlearn.rs` closes this forgery in place:
- Every `ErasureReceipt` (`1,072 B` binary = `688 B` `dreggference-wire` algebraic core + `96 B` `prev_commits` + `96 B` Ed25519 pubkeys + `192 B` Ed25519 signatures) chains explicitly from the pre-revocation state commitments `prev_commits` to the distinct refreshed `commits` (`commits[i] != prev_commits[i]`).
- Honest custodians **refuse to sign** if the live-state SPDZ MAC or delta check fails (`!ok => [0u8; 64]`).
- `ErasureReceipt::verify(scope, expected_custodians, expected_prev_commits)` enforces: (i) full algebraic core check, (ii) exact `prev_commits` chain equality and state transition, (iii) exact 3-of-3 committee match against `expected_custodians`, and (iv) strict Ed25519 verification (`verify_strict`, rejecting small-order/malleable signatures) over `TurboSHAKE256(0x23; "dreggference/erasure-attest/v4" || program || job_id || realm || target || prev_commits || commits || H(core_688))`, the digest `dreggference-wire` verifies.
- The unauthenticated algebraic helper is explicitly renamed `verify_algebraic_core_only()` with a security warning and tested against offline zero-sum forgery (`rejects_offline_forged_zero_sum_erasure_receipt`).

---

Per-block rank screens eliminate simple shortcuts. A signed Hadamard transform can pass these screens and still support fast multiplication. Governance must authenticate the registered model root independently of the miner. Registration checks for repeated effective tiles across output columns.

## 6. Honest Audit-Receipt Boundary (`hfhss -> dreggference`)

`crates/dark-pouw/src/pouw_receipt.rs` bridges an `hfhss` inference session to `dreggference` on Solana SBF with **zero synthetic lattice-SNARK wrapper theater**. We state the exact proof boundary cleanly:
- **What proves all 401 Bonsai-27B matmuls:** Off-chain / 3-custodian pre-decrypt `Settled` (`p61 * M61` / `M31` Freivalds), `Ext2` `MAC2` checks across all nonlinear layers, and `PTQ1_0`-native `WinningTileProof`s (with structural admissibility: full rank `>= 127`, all 12 off-diagonal `32 x 32` ranks `>= 24`, `16 x 16` Kronecker unfolding rank `>= 12`).
- **What `BonsaiAuditReceipt` bundles and `dreggference` verifies natively on Solana SBF:**
  1. **`DPWT` (`WinningTileProof` + `Ptq1WeightOpening`):** Verifies the winning tile and rejects stacked-`H`, permutation, low-rank shift, and Kronecker-structured weight blocks against the registered `Ptq1WeightTree` root.
  2. **`SingleColumnPtq1Proof` (`dreggference-col-dispute` **`PTJ1`** / **`PTC1`**, `198 B` job, `136 B` ix-0 `root || n || m || row_tree_root || claimant || source_job`, `32 B` ix-1 `output_tree_root`, `1,205 B` `PTC1` cache holding the `40`-tile `1,160 B = 1.13 KiB` column opening at `K = 5120`):** Objective single-column fraud dispute authenticating one full `K = 5120` column against `Ptq1WeightTree`, opening the `SHA-256` `Bc-i40` row Merkle tree and `Yq5` output Merkle tree, and checking exact `dot(B_c[row_t], W[:, j]) mod Q5` (slashing on any mismatch: `job[140] = 2, job[141] = 3`).
  3. **`ErasureReceipt` (`688 B` algebraic core + `1,072 B` 3-custodian strict Ed25519-attested, `prev_commits`-chained envelope):** Verifies live-state unlearning consistency anchored to the assigned committee and prior state commitments.
  4. **Session Commitment Statement (`BonsaiAuditStatement`, `256 B`):** Deterministically binds all eight session commitments (`model_ptq1_root`, `prompt_commitment`, `response_commitment`, `winning_tile_digest`, `settled_digest`, `mac2_root`, `erasure_receipt_digest`, `col_dispute_job_digest`). `BonsaiAuditReceipt` deliberately carries **no** vacuous prover-chosen `OLAB` / outer-SNARK wrapper; computational integrity comes directly from `Settled` + `Ext2 MAC2` + `DPWT` + `PTJ1` single-column fraud proofs + attested `ErasureReceipt`.

The erasure owner can pin the three Ed25519 keys before setup with `PlasticOwner::connect_pinned`. The local `connect` convenience method trusts keys learned over the initial Unix sockets. Setup and ingest signatures bind the role, operation, realm, episode, prior head and reply before the owner advances the chain.

The Rust registrar and browser verifier project the complete Kronecker unfolding and check rank on both disjoint column halves. For a rank-one unfolding plus 13 changed entries, one half has rank at most seven. These structural tests do not establish a lower bound on evaluation cost for arbitrary registered weights.


The standalone column-dispute fixture uses a 137-byte tagged initialization instruction. Its final 32 argument bytes identify the source job. The account stores that address at bytes 166 through 197. Run `validation/check_col_dispute_sbf.py` with the program checkout and receipt export directory to check both accounts in LiteSVM.

Build `dark-pouw` with `--features fault-injection` to run the daemon or Bonsai runner with diagnostic deviations or weakened checks. Their default binaries reject these switches before opening sockets. The nonlinear daemon accepts DNL4 by default. Operators of legacy integrations can explicitly enable DNL2 and DNL3 with `--allow-legacy-dnl`. In extension mode, the two field coordinates use independent sacrifice masks. Each spline batch checks its residuals under independent projections. The per-check MAC bound is distinct from the probability of any failure across multiple sessions.


### Settled Q5 terminal service

`crates/dark-pouw/src/threshold_service.rs` runs terminal decryption as three custodian daemons and one owner client. The processes can sit on separate hosts and talk over TCP, or on one host over Unix sockets in an owner-private directory. The same handshake and framing apply to both.

**What each process holds.**

| Process | Holds | Never holds |
| --- | --- | --- |
| Custodian `i` | Its Ed25519 identity, its two pair keys, the hints `U_{i,j} = S_{i,j} W` it derives from them, its per-session `Ext2` MAC key shares, its journal and row ledger | The third pair key, another custodian's hints or MAC key shares |
| Owner client | The owner identity, the ciphertext `(A, B_c)`, the miner's product, the released plaintext | Any pair key, hint or MAC key share |
| Miner | `B_c`, `W`, its product `(Y, Z)` | Any key material, any plaintext |

The three custodians learn the released plaintext, as before: this is a terminal service. No single process, including the client, holds enough to decrypt alone.

**Channels.** Every connection starts with an ephemeral X25519 exchange. Both ends sign the transcript with Ed25519 identities that the other end pins in its configuration, and the directional AES-256-GCM-SIV frame keys come from the shared secret and the transcript. The transcript names both roles. Between two custodians it also names the session, and the pair key enters the key derivation, so a link is bound to one session and to the pair that owns it. When a session starts, the pair links are rekeyed from the handshake key, the pair key and the session nonce. A frame read before authentication is capped at 256 bytes. A daemon serves at most 32 connections at once and gives a handshake ten seconds.

This handshake is assembled in this repository from `curve25519-dalek`, `ed25519-dalek` and `aes-gcm-siv`. It is not the Noise framework, it has no external review, and it hides neither the roles nor the session identifier from a network observer.

**Wire format.** The job header is 124 bytes: `Q5J1`, the job identifier, key identifier and nonce (32 bytes each), `rows`, `k`, `n` and `delta_bits` as `u32`, and `m_bias` as `u64`, little-endian. A custodian checks the header against its provisioned key and shape and against the cap `rows * (2560 + k + 2 n) <= 2^23` before it allocates anything for the body. That cap admits 197 rows per session at `5120 x 17408` and 108 rows at `5120 x 34816`. The body follows in frames of at most 1 MiB, each with the single length the header implies: `A` (`rows x 2560`) and `B_c` (`rows x k`) as little-endian signed 40-bit residues, then `rows * n` product entries of a signed 64-bit `Y` and a signed 32-bit `Z`. A frame of any other length ends the session. The service parses no JSON from the network. Job files are the header followed by `A` and `B_c`; product files are `Q5P1` followed by the entries; weight files are `Q5W1`, `k`, `n`, the `PTQ1_0` blocks and one scale byte per block.

**Order of checks.** Each custodian settles the lift (`settle_q5_lift`) on the bytes it received and reads its remaining row budget. The three then connect for this session, exchange their verdicts and compare a digest of the settled statement. Only after all three agree does a custodian reserve the nonce, charge the rows and read its hints. A rejected product, a mismatched statement or an exhausted budget therefore leaves the nonce unused and the ledger unchanged at every custodian. Rounding runs in batches of at most `2^15` outputs on the one session, which keeps the largest protocol frame (816 bytes per output) under half of the 64 MiB frame cap, and every batch is MAC-checked before its plaintext is opened.

**Durable state.** A custodian's state directory holds, per set of pair keys, one file per used nonce, an in-flight marker and the count of rows charged against the 65,536-row limit. All three survive a daemon restart. An abort or crash after reservation leaves the marker in place: that key then refuses every later session and needs replacement pair keys and hints. Protect each custodian's configuration, identity and state from the other roles and from rollback. A restored older state directory would accept a used nonce again.

**Running it.** Create each identity on its own host, exchange the printed verifying keys, and give each custodian a mode-0600 configuration:

```sh
dark_custodiand --threshold-identity identity.json        # prints the verifying key
dark_custodiand --threshold-q5 --config custodian.json    # prints READY once it listens
bonsai27b_full_layer0_3proc --threshold-client --config client.json \
  --job job.q5j --product product.q5p --out plaintext.bin
```

A custodian configuration has `custodian` (0, 1 or 2), `listen` and `peers` (`tcp://host:port` or `unix:/path`), `identity` (path), `custodian_keys` and `owner_key` (verifying keys), `pair_keys` (by peer, own entry zero), `key_id`, `weights` (path) and `state_dir`. A client configuration has `custodians`, `identity` and `custodian_keys`. Both binaries provide all three entry points.

**What is tested.** `crates/dark-pouw/tests/threshold_service_tcp.rs` and `validation/threshold_service.py` start three daemon processes on loopback TCP with a `5120 x 384` `PTQ1_0` weight and six-row jobs. They check the exact integer result against the cleartext `X W` (also for a `256 x 8448` weight whose output spans two rounding batches), rejection of a changed `Y` or `Z` entry and of two conflicting statements with nothing spent, refusal of unauthenticated bytes and of an unpinned client identity, replay rejection and the row cap across daemon restarts, and, in a `fault-injection` build, abort on a custodian that corrupts a hint share, one MAC plane, a Beaver triple or its final share.

`python3 validation/threshold_service.py target/release --shape 8 5120 17408` runs the same checks at the Bonsai width `5120 x 17408`; one eight-row release took 21.6 s with all three daemons and the client on one laptop.

**What remains open.** The tests run all processes on one machine; no measurement on separate hosts or under packet loss exists. The `5120 x 34816` width has not been run. Sessions on one key run one at a time, and a daemon that fails mid-session locks its key. There is no key rotation or re-provisioning protocol: pair keys and identities are placed by the operator. The privacy bounds assume at most one corrupt custodian, honest owner inputs, an admissible message and absolute noise at most one quarter of the scale. A corrupt custodian can always force an abort. There is no UC proof for this implementation.

# Run once for each id, concurrently with the collector.
dark_custodiand --threshold-q5 --custodian "$id" --dir "$socket_dir" --job "$job" \
  --product "$product" --pair-keys "$local_keys" --state-dir "$persistent_state"
```

Both binaries support the custodian entry point. The collector prints the plaintext JSON array after three matching replies. Local OS access control protects the client endpoint. Directional AES-256-GCM-SIV keys authenticate and encrypt inter-custodian frames. Each accepted session requires a fresh owner nonce. Custodians check the lift and agree on the statement before reserving that nonce. Rejected preflight leaves the nonce available. Each local key directory persists the total number of rows charged against the 65,536-row limit. An abort or crash after reservation requires replacement pair keys and corresponding encryption hints. The privacy bounds assume at most one corrupt custodian, honest owner inputs, an admissible message and absolute noise at most one quarter of the scale.
