---
id: go-zenon-v1-pq-implementation-spec
title: "go-zenon-v1 Post-Quantum Validator Implementation Spec (ZNN-IMP-PQ-V1 · v4 Verified)"
sidebar_label: "go-zenon-v1 PQ Implementation Spec"
sidebar_position: 5
---

# `0x3639/go-zenon-v1` Post-Quantum Validator Implementation Spec (`ZNN-IMP-PQ-V1` · `v4`)

:::info Review Draft & Direct LLM Agent Input (`ZNN-SPEC-PHASE1-v4` Aligned)
- **Status:** `v4 VERIFIED REVIEW DRAFT` (source-audited against `0x3639/go-zenon-v1@1c6e3d8..ff9496a`, `zenon-rs`, and live `go1.27.1`, incorporating Round-4 findings `R4-01..R4-09`).
- **Target Codebase:** [`0x3639/go-zenon-v1`](https://github.com/0x3639/go-zenon-v1) (`CGO_ENABLED=0`, `Go 1.27+`).
- **Standalone LLM File:** [`/raw/post-quantum/go-zenon-v1-pq-implementation-spec.md`](pathname:///raw/post-quantum/go-zenon-v1-pq-implementation-spec.md) (feed directly to an AI coding agent alongside the `go-zenon-v1` repository).
- **Normative References:** [0x02 Addresses & AuthRegistry (#14)](/docs/post-quantum/addresses-and-key-derivation) · [AccountBlock v2 & H_inc Rules](/docs/post-quantum/account-blocks-and-pk-caching) · [Two-Lane Plasma & SporkMask](/docs/post-quantum/dynamic-plasma-and-dos) · [Day-1 PoKoS & Complete Sunset](/docs/post-quantum/ed25519-pokos-seed-rescue) · [Go 1.27+ Blueprint](/docs/roadmap/go-zenon-v1-master-blueprint).
:::

## 1. Purpose, Scope & Hard Invariants

This specification is a **byte-exact, file-anchored engineering blueprint** for upgrading the [`0x3639/go-zenon-v1`](https://github.com/0x3639/go-zenon-v1) full node and Pillar validator to full Post-Quantum capability **prior to** the Phase 1B Meta-DAG consensus swap.

### 1.1 In-Scope Deliverables (This Upgrade Series)
1. **Toolchain & PQ Cryptographic Core (`L0`):** Upgrade `go.mod` to `go 1.27.0`+, wire `crypto/mldsa` (`ML-DSA-44`, FIPS 204) with mandatory startup `AssertMLDSAReady()` KAT (`GOFIPS140 != v1.0.0`), non-separable key/alg-bound signing transcript **`boundDigest32` (`R4-01`)**, full pure-Go (`CGO_ENABLED=0`) `FN-DSA-512` keygen + signing + `0`-FPU integer-NTT verification (`fn-dsa v0.3` `32B` seed `R4-09`), pure-Keccak `SLH-DSA-SHAKE-128s` (FIPS 205), transitional `AlgHybridEdMLDSA44` (`0x81`), PQ `SLIP-0010` KDF, and true **`2^-128` QROM (`2^-256` classical RBR)** pure-`SHA3-256` `WHIR-SHA3-v1` zero-alloc verifier (`<= 8,000` Keccak perms `R4-04`).
2. **Phase 1A State & Account Layer (`Spork #9: StateRootSpork` + `Spork #10: PQAccountsSpork`):**
   - Domain-separated (`[0x00]` leaf / `[0x01]` internal) `smt-v1` depth-256 `SHA3-256` Sparse Merkle Tree committing `Momentum.StateRoot` on **`Momentum v3`** (`R4-07`).
   - **`AccountBlock v2`** preserving the exact `306-byte` `ComputeHash()` preimage while adding `ProofWitness` (tag `24`), `EquiXSolution` (tag `25`), witness-separated `[0x11]` persistence (`R4-07`), length-framed `(Hash, WitnessCommitment)` gossip dedup (`C03`), and `InvalidWitnessPenalty` peer scoring.
   - `20-byte` `0x02` PQ user addresses (`z1q{2,f,g,t}...`) + fail-closed `{0x00, 0x02}` sender class allowlist; `0x81` forbidden on unregistered `0x00` Path-C reveals (`R4-01`).
   - **`AuthRegistryContract` (`Embedded #14`, `z1qxemdeddedxauthxxxxxxxxxxxxxxxxx2a36sk`)**: `RotateKey`, `RescueWithPoKoS`, `PrecommitKey`, `UpgradeHybridToPureMLDSA44`, exact `179-byte` `GenesisHash`-bound PoP, `expectedRotationNonce` (`ErrAuthNonceOverflow`), **`ctx.InclusionHeight() + 1` promotion (`R4-03`)**, and **`O(1)` `GenesisReceive`- & producer-aware `pubKey_A`-bound `Ed25519-PoKoS` (`AuthRegistry[0x03]` + `AccountStore[0x0a]` + `ByHeight(1..2)` `R4-02`)**.
   - `AccountStore[0x09]` public-key caching + `32 B` `pubKeyHash` RAM pinning in `HotStateCache`.
   - `uint64 SporkMask` widening (preserving Phase 0 `0x1f` bits `0..4` verbatim), stateless `WitnessPlasma`, two-stage `Equi-X` verification, and `1`-slot/Momentum `PoKoS` anti-starvation in `ContentSelector`.
   - **`LegacyDposV1` PQ Pillar production & seal verification** supporting both in-place rotated `0x00` Pillars and native `0x02` producer addresses on `Momentum v3`.
3. **PQ P2P Transport (`v1.1` / `Phase 1A`):** `X25519MLKEM768` TLS 1.3 + `/znn/tls-pq/1.0.0` `ML-DSA-44` host identity in `internal/p2p/libp2p`, disabling classical `noise.ID` at `Spork #14`.
4. **Stake-Coordinated Hard-Fork Governance & Complete Classical Sunset (`Spork #14: LegacyCryptoSunsetSpork`):**
   - On-chain **`>= 85%` active-stake `MaxProtocolVersion` readiness across `2` consecutive epochs** + `HardForkEnforcementDelay = 8,640` (`24h`) for `Sporks #9..#14`.
   - Era-separated **`InclusionMomentumHeight` (`H_inc`)** enforcement across **both** user blocks and `GenerateEmbeddedReceive` (`DEEZ-B02, R4-03`), plus `Version = 2` upgrade on embedded `ContractReceive`/`ContractSend` blocks (`R4-03`).
   - Complete embedded-contract sunset (`BridgeContract` ECDSA, `SwapContract`, `Pillar.RegisterLegacy`, zero-stranded-funds `PtlcContract` `{0,1,2}` drain with `DeletePtlcReclaimLock`) + **`SunsetAnchorCheckpoint`** (`MaxPreCRQCBitcoinHeight`, `DEEZ-B11, B12, R4-09`).

### 1.2 Explicitly Out of Scope (Deferred to Subsequent Specs)
* Phase 1B `Mahi-Mahi` / `Steelhead` Meta-DAG consensus, `M=4,096` voting shares, `HashRand-PQ` (`M_coin = 256`) coin, `Momentum v4` (`1.0 s`), `MomentumPQQC`, and `H_fork` `10x` height rescaling.
* Phase 1C `SettlementContract (#13)` `Zeno` domains (`d_wasm`, `d_zvm`, `d_accounts`) — only the reserved `SettlementContract` address constant is pinned here.
* Phase 1D `d_btc` SPV bridge and `ChannelContract (#15)` (`z1qxemdeddedxchannelxxxxxxxxxxxxxxr7xsx2`).

### 1.3 Non-Negotiable Engineering Invariants for the Implementing LLM
1. **Zero CGo in Production (`CGO_ENABLED=0`):** Every cryptographic keygen/signer/verifier, `Equi-X` solver/verifier, `WHIR-SHA3-v1` verifier, and trie implementation MUST compile and pass tests with `CGO_ENABLED=0` across `linux/amd64`, `linux/arm64` (Raspberry Pi 5), and `darwin/arm64` (using `CGO_ENABLED=1` solely when running `go test -race` `C05`).
2. **100% Phase 0 Alphanet Replay Parity:** For every Momentum `H` where `Spork #9` and `Spork #10` are inactive, `AccountBlock.ComputeHash()`, `AccountBlock.ChangesHash`, `Momentum.ComputeHash()`, `Momentum.ChangesHash`, Protobuf, RLP, JSON, and all 74 existing `vmerr` verdicts MUST remain **bit-for-bit identical** to `go-zenon-v1@1c6e3d8`. Never write `[0x09]`, `[0x0a]`, or `[0x11]` witness sidecars when `SporkBitPQAccounts` is inactive!
3. **Acyclic `L0–L9` Layering:** Preserve `go-zenon-v1`'s strict package DAG (`common/crypto` → `types/trie/storage` → `codec/nom/wallet/p2p` → `pow` → `chain` → `consensus` → `vm` → `protocol` → `pillar/rpc` → `node/cmd`). No upward imports or import cycles.
4. **Fail-Closed Parsing & Zero Panics:** Every wire decoder, signature verifier, ABI unpacker, and STARK verifier MUST validate lengths against frame bounds before allocating and return typed sentinel errors—never panic on hostile bytes.
5. **No Speculative `TODO` Stubs on Consensus Paths:** Every consensus check must be completely implemented and tested.

---

## 2. Ordered PR Implementation Graph (`PR-PQ-01` → `PR-PQ-08`)

Implement and verify strictly in topological order so both `CGO_ENABLED=1 go test -race ./...` and `CGO_ENABLED=0 go test ./...` stay green after every single PR:

```mermaid
flowchart TD
    P1["PR-PQ-01 · L0 Go 1.27+ & PQ Crypto<br/>crypto/mldsa KAT, boundDigest32, full fn-dsa v0.3, SLH-DSA, 2^-128 QROM WHIR"]
    P2["PR-PQ-02 · L0-L1 Params, uint64 Sporks, 0x02 Addr & 0x00/0x01 smt-v1<br/>params.go, spork.go, address.go (#14 AuthRegistry), trie/smtcore"]
    P3["PR-PQ-03 · L2 Wire Codecs, [0x11] Witness Sidecar & Dedup<br/>AccountBlock v2 (tags 24..25), Momentum v3 (tag 14), WitnessCommitment"]
    P4["PR-PQ-04 · L3-L4 WitnessPlasma, Equi-X & AccountStore [0x09/0x0a]<br/>uint64 SporkMask, equix.go, spork_index.go, HotStateCache 32B hash"]
    P5["PR-PQ-05 · L5-L6 AuthRegistry #14, H_inc VM/Verifiers & PQ DPoS Seals<br/>O(1) exposure resolver, postPromoStore, InclusionHeight, Version=2 descendants"]
    P6["PR-PQ-06 · L6-L8 >=85% Spork Gate, Pillar Worker & Phase 1E Sunset<br/>spork.go, pillar/worker+selector, Bridge/Swap/PTLC sunset, SunsetAnchor"]
    P7["PR-PQ-07 · L2/L8/L9 PQ P2P (/znn/tls-pq/1.0.0), Wallet, RPC & znnd<br/>libp2p X25519MLKEM768+MLDSA44, PQKeyPair, embedded.auth.*, AssertMLDSAReady"]
    P8["PR-PQ-08 · Full Conformance, Fuzzing & Gate Qualification<br/>G1, G7, G9, ZP-Q16..Q20, ZP-Q23..Q30 + Alphanet replay"]

    P1 --> P2 --> P3 --> P4 --> P5 --> P6 --> P7 --> P8
```

---

## 3. Critical `go-zenon-v1` Codebase Landmines (`10` Verified Traps — Read Before Editing!)

Direct source audit of `go-zenon-v1` uncovered **10 concrete landmines** (`#1..#7` from `v3` + `#8..#10` uncovered in Round 4 `R4-02, R4-03, R4-07`) that will break compilation, sync, or consensus if missed:

| # | Exact File & Line in `go-zenon-v1` | Existing Behavior | Required `v4` PQ Fix |
|:---:|---|---|---|
| **1** | `internal/vm/verifier/momentum.go:384,388` (`wrapIfBodyTampered`) | Hardcodes `len(blk.PublicKey) > 32 \|\| len(blk.Signature) > 64` to classify body tampering. | Replace with `ExceedsMaxWitnessBounds(blk)` (`v1`: `32/64`; `v2`: exact per-`algID` lengths + `ProofWitness <= 131,072` + `EquiXSolution <= 16`). |
| **2** | `internal/consensus/engine/legacy_dpos.go:281-305` (`VerifyMomentumProducer`) | Hardcodes `len(m.PublicKey) == 32` and derives `producerAddr := types.PubKeyToAddress(m.PublicKey)`. | Resolve `expectedProducer` from `ElectionData` for `(tick, m.TimestampUnix)`, then match `m.PublicKey` against `AuthRegistry(expectedProducer)` (Path A), `DerivePQAddress` (`0x02`), or `PubKeyToAddress` (`0x00` pre-sunset). |
| **3** | `internal/vm/verifier/momentum.go:468` & `account_block.go` | Evaluates spork masks exclusively at `blk.MomentumAcknowledged.Height` (`H_ack`). | Split heights (`DEEZ-B02`): evaluate `Version == 2` permission, `AuthRegistry` active key, and `SporkBitLegacyCryptoSunset` (`#14`) strictly at **`InclusionMomentumHeight` (`H_inc`)**, never `H_ack`! |
| **4** | `internal/chain/account_store.go:67-84` & `genesis/builder.go:188` | Writes outside `[0x00..0x02]` enter `AccountBlock.ChangesHash`; Genesis `Height = 1` `GenesisReceive` has `len(PublicKey) == 0`! | Write `[0x09]`/`[0x0a]` **ONLY when `SporkBitPQAccounts` is active at `H_inc`**. Resolve legacy exposure in `O(1)` via `AuthRegistry[0x03]` + `[0x0a]` + `GenesisReceive`-aware `ByHeight(1..2)` (`R4-02`). For `v2` blocks, store stripped body + `WitnessCommitment` in `[0x02]` and raw witness in `[0x11]` (`R4-07`)! |
| **5** | `internal/vm/supervisor/registry.go:19,225` (`ContractRegistry`) | Stores fixed `[32]map[types.Address]*compiledContract` indexed by 5-bit `uint8`. | Replace with a `uint64`-keyed cache compiling each normalized `uint64` mask on demand while fast-pathing `normMask <= 0x1f` into `[32]`. |
| **6** | `internal/common/params.go:51,260,612` & tests | Tests index `cfg.ImplementedSporks[0..7]` directly and assert `len(EmbeddedContractsList()) == 12`. | **Preserve exact indices `0..7`!** Append `#9, #10, #14` at `[8..10]` (`[11]SporkDef`) and add `types.EmbeddedContractsForSporkMask(mask uint64)`. |
| **7** | `internal/pillar/worker.go:197` (`NewPillarWorker`) | Hardcodes `len(cfg.ProducerKey.Public) != 32 \|\| len(cfg.ProducerKey.Private) != 64`. | Accept unified `wallet.Signer` / `*wallet.PQKeyPair` (`AlgID in {0x00, 0x01, 0x02, 0x03}`) signing `boundDigest32` on `Momentum v3`. |
| **8** | `internal/vm/supervisor/momentum_vm.go:167,191` (`ApplyMomentum`, **`R4-03`**) | Executes `m.Content` blocks against `evalStore := parentStore` (ignoring `momOverlay`!). | After Step-0 `AuthRegistry` promotion on `momOverlay`, construct read-only `postPromoStore` over `momOverlay` as `evalStore` so blocks in `m.Content` see keys promoted at `m.Height`! Record `0x00` Momentum producer keys in `AuthRegistry[0x03]` *after* `m.Content` so producer `AccountBlock.ChangesHash`es never diverge (`R4-02`)! |
| **9** | `internal/vm/supervisor/vm.go:671-687` (`GenerateEmbeddedReceive`, **`R4-03`**) | Rewinds `ctx.momentumStore`, `ctx.frontierMomentum`, and `ctx.sporkHeight` to `targetMA` (`H_ack`)! | Pass `inclusionHeight` (`m.Height`) and `inclusionStore` (`momStore`) into `GenerateEmbeddedReceive`! Phase 0 contracts keep `targetMA` snapshot reads, while **`Spork #14` sunset checks and `AuthRegistry` methods MUST read `ctx.InclusionHeight()` and `ctx.InclusionMomentumStore()`**! |
| **10** | `internal/vm/supervisor/vm.go:758,813` & `pillar/updater.go` (**`R4-03`**) | Hardcodes `dblock.Version = cfg.AccountBlockVersion` (`1`) on `ContractSend` descendants, refunds, and `ContractReceive`s! | When `SporkBitPQAccounts` (`#10`) is active at `H_inc`, emit **`Version = 2`** on all generated `ContractReceive` and `ContractSend` blocks so `Spork #14` (`Require Version == 2`) never bricks embedded contracts! |

---

## 4. Detailed Package-by-Package Implementation Spec

### `PR-PQ-01` — Layer 0: `Go 1.27+` Toolchain & `internal/crypto` PQ Primitives

#### 4.1.1 Toolchain, `boundDigest32` & Startup Self-Test (`go.mod`, `internal/crypto/pq_wire.go`)
* Bump `go.mod`: `go 1.27.0` (verified on `go1.27.1`). Maintain `CGO_ENABLED=0`.
* Create `internal/crypto/pq_wire.go` with exact algorithm IDs, wire sizes, and non-separable key-bound digest construction (`R4-01`):

```go title="internal/crypto/pq_wire.go"
package crypto

import (
	"bytes"
	"crypto/mldsa"
	"crypto/sha3"
	"encoding/hex"
)

const (
	AlgEd25519         uint8 = 0x00 // Legacy RFC 8032 (disabled at H_inc >= H_sunset)
	AlgMLDSA44         uint8 = 0x01 // FIPS 204 (Go 1.27+ stdlib crypto/mldsa)
	AlgFNDSA512        uint8 = 0x02 // Draft FIPS 206 (pinned fn-dsa v0.3 32B seed, 0-FPU verify)
	AlgSLHDSA128s      uint8 = 0x03 // FIPS 205 (SLH-DSA-SHAKE-128s pure Keccak)
	AlgXMSSShake22     uint8 = 0x04 // SP 800-208 (reserved for Phase 1B validator emergency)
	AlgProofWHIRSha3V1 uint8 = 0x10 // Pure-SHA3-256 WHIR-SHA3-v1 STARK (true 2^-128 QROM)
	AlgHybridEdMLDSA44 uint8 = 0x81 // Transitional Ed25519 AND ML-DSA-44 (0x02 or AuthRegistry only; disabled at H_sunset)

	Ed25519PubKeySize     = 32
	Ed25519SigSize        = 64
	MLDSA44PubKeySize     = mldsa.MLDSA44PublicKeySize // 1312
	MLDSA44SigSize        = mldsa.MLDSA44SignatureSize // 2420
	FNDSA512PubKeySize    = 897
	FNDSA512SigSize       = 666
	SLHDSA128sPubKeySize  = 32
	SLHDSA128sSigSize     = 7856
	HybridPubKeySize      = Ed25519PubKeySize + MLDSA44PubKeySize // 1344
	HybridSigSize         = Ed25519SigSize + MLDSA44SigSize       // 2484

	WireEd25519PubSize    = 1 + Ed25519PubKeySize    // 33
	WireEd25519SigSize    = 1 + Ed25519SigSize       // 65
	WireMLDSA44PubSize    = 1 + MLDSA44PubKeySize    // 1313
	WireMLDSA44SigSize    = 1 + MLDSA44SigSize       // 2421
	WireFNDSA512PubSize   = 1 + FNDSA512PubKeySize   // 898
	WireFNDSA512SigSize   = 1 + FNDSA512SigSize      // 667
	WireSLHDSA128sPubSize = 1 + SLHDSA128sPubKeySize // 33
	WireSLHDSA128sSigSize = 1 + SLHDSA128sSigSize    // 7857
	WireHybridPubSize     = 1 + HybridPubKeySize     // 1345
	WireHybridSigSize     = 1 + HybridSigSize        // 2485

	MaxSingleProofWitnessBytes = 131_072 // 128 KiB hard cap per AccountBlock
	EquiXSolutionSize          = 16      // 8 x uint16 little-endian indices

	DomainAccountBlockV2 = "zenon-ab:v2"
	DomainMomentumV3     = "zenon-mom:v3"
	DomainAuthPopV3      = "zenon-auth-pop:v3"
	DomainPQAddressV1    = "zenon-pq-addr:v1"
	DomainPQSLIP0010V1   = "zenon-pq-slip0010:v1"
	DomainTLSExporterV1  = "zenon-tls-pq-auth:v1"
)

// BoundSigningDigest computes SHA3-256(domainCtx || [0x00] || [algID] || SHA3-256(pubWire)[32] || msg[32]),
// binding both algID and the complete public key (including both halves of 0x81) to prevent
// hybrid stripping (0x81->0x00) and third-party key-splicing ransomware (0x00->0x81) (R4-01).
func BoundSigningDigest(domainCtx string, pubWire []byte, msg []byte) [32]byte {
	pubHash := sha3.Sum256(pubWire)
	h := sha3.New256()
	_, _ = h.Write([]byte(domainCtx))
	_, _ = h.Write([]byte{0x00, pubWire[0]})
	_, _ = h.Write(pubHash[:])
	_, _ = h.Write(msg)
	var out [32]byte
	_, _ = h.Read(out[:])
	return out
}
```

* **Unified Signing & Verification Rules (`R4-01`):**
  * For every `v2` `AccountBlock`, PQ `v3` `Momentum`, and `AuthPopV3` signature, compute `digest := BoundSigningDigest(domainCtx, pubWire, msg)`:
    * `0x01` (`ML-DSA-44`): `mldsa.Verify(pk, digest[:], rawSig, &mldsa.Options{Context: domainCtx}) == nil`.
    * `0x00` (`Ed25519` inside `v2`): `VerifyEd25519(edPub, digest[:], edSig)` (legacy `v1` `AccountBlock` / `v1..v2` `Momentum` continue signing raw `Hash[:]` unchanged!).
    * `0x02` (`FN-DSA-512`, `internal/crypto/fndsa512_v03.go`): full pure-Go `CGO_ENABLED=0` implementation of pinned `fn-dsa v0.3` (`32-byte` seed NTRU keygen + deterministic/emulated-binary64 signing + `0`-FPU integer-NTT `mod 12289` verification `R4-09`) over `digest[:]` with context `domainCtx`.
    * `0x03` (`SLH-DSA-SHAKE-128s`, `internal/crypto/slhdsa.go`): pure-Go FIPS 205 `SLH-DSA-SHAKE-128s` (`crypto/sha3.NewSHAKE256()`) over `digest[:]` with context `domainCtx`.
    * `0x81` (`AlgHybridEdMLDSA44`): returns `true` **iff BOTH** `VerifyEd25519(edPub, digest[:], edSig)` **AND** `VerifyMLDSA44(mldsaPub, digest[:], mldsaSig, domainCtx)` succeed (where `digest` commits to `[0x81] || edPub || mldsaPub`!).
  * **`AssertMLDSAReady()`** (`cmd/znnd/main.go`, `cmd/libznn`): verifies both the low-level `SignMLDSA44Deterministic` KAT (`621b16f8e3e2c7c064aec7ab540f1f64b1d1665feef964f07c6cded92d99f33b`) and the `BoundSigningDigest` KAT (`b7444ca31c5c802bd2cdc7f3fd5c76d1e2bce8655bfd44dd96a099e26c8608cf` over `SHA3-256("zenon-v4-bound-ab-kat")`), panicking fail-closed if `GOFIPS140=v1.0.0` disables `crypto/mldsa`.
* **PQ `SLIP-0010` Derivation (`internal/crypto/slip0010.go`, `R4-09`):**
  * Master HMAC key `"zenon-pq-slip0010:v1"`, hardened path `m / 44' / 73404' / 1' / <algID>' / <accountIndex>'`:
    * `0x01`: `mldsa.NewPrivateKey(mldsa.MLDSA44(), leaf.Key[:])` (`32 B`)
    * `0x02`: `SHA3_256("zenon-fndsa512-keygen:v1" || leaf.Key[:])` (`32 B` seed -> `fn-dsa v0.3` keygen `R4-09`)
    * `0x03`: `SHAKE256("zenon-slhdsa128s-keygen:v1" || leaf.Key[:], 48)` -> FIPS 205 `(SK.seed[16], SK.prf[16], PK.seed[16])`
* **True `2^-128` QROM `WHIR-SHA3-v1` Verifier (`internal/crypto/zkverify/whir_sha3_v1.go`, `R4-04`):**
  * Enforce hard pre-check bounds: `len(proofWire) <= 131_072`, `proofWire[0] == 0x10`, `foldingRounds <= 6`, `totalMerkleQueries <= 320`, **`keccakPerms <= 8,000`** (`<= 3.5 ms` on Cortex-A76 without `FEAT_SHA3`), **`32-bit` Fiat-Shamir PoW grinding** + `>= 224-bit` classical query security + `256-bit` extension field (`<= 2^-128` QROM soundness), `100%` `FIPS-202 SHA3-256`/`SHAKE256`, `0` heap allocations inside `arena *[262144]byte`.
  * `R_PoKoS` (`circuitId = 0x01`) public-input digest:
    ```text
    publicInputsDigest = SHA3_256(
      "zenon-pokos-pi:v3" ||
      genesisHash[32] ||
      be_u64(chainIdentifier) ||
      targetAddress[20] ||
      hasExposedPK[1] ||       // 0x00 (authenticated UNEXPOSED) or 0x01 (authenticated EXPOSED)
      expectedPubKeyA[32] ||   // [32]byte{0} iff hasExposedPK==0; exact 32B Ed25519 PK iff 1
      popDigest[32]            // SHA3-256 of exact 179B zenon-auth-pop:v3 preimage
    )
    ```

---

### `PR-PQ-02` — Layers 0–1: Params, `SporkId`s, `0x02` Addresses, Embedded `#14` & Domain-Separated `smt-v1`

#### 4.2.1 `internal/types/spork.go` & `internal/common/params.go`
* **Canonical Spork IDs:** `StateRootSpork = SporkId{31: 0x09}` (`Bit 8`), `PQAccountsSpork = SporkId{31: 0x0a}` (`Bit 9`, implies `Bit 8`), `LegacyCryptoSunsetSpork = SporkId{31: 0x0e}` (`Bit 13`, implies `Bits 9, 8`).
* Keep `ImplementedSporks[0..7]` in exact existing order, extending to `[11]SporkDef`.
* Add to `ProtocolParamsConfig`: `AccountBlockVersionV2 (2)`, `MomentumVersionV3 (3)`, `HardForkEnforcementDelay (8_640)`, `HardForkReadinessStakeBps (8_500)`, `HardForkReadinessEpochs (2)`, `Phase1AMaxBasePlasmaInMomentum (16_800_000)`, `Phase1AMaxProofWitnessBytes (524_288)`, and `SunsetAnchorCheckpoint` (`Height`, `MomentumHash`, `StateRoot`, `CommitteeHash`, `BitcoinAnchorHeight`, `MaxPreCRQCBitcoinHeight` `R4-09`).

#### 4.2.2 `internal/types/address.go`
* Add `PQUserAddrByte = 0x02`, `DerivePQAddress`, `IsPQUserAddress`, `IsAllowedUserSenderClass` (`{0x00, 0x02}`), `SettlementContract` (`z1qxemdeddedxsettlementxxxxxxxxxxxh5rx6j`), `AuthRegistryContract` (`z1qxemdeddedxauthxxxxxxxxxxxxxxxxx2a36sk`), and `EmbeddedContractsForSporkMask(mask uint64)`.

#### 4.2.3 Domain-Separated `smt-v1` Sparse Merkle Tree (`internal/trie/smtcore/`, `R4-07` Fix)
* Implement depth-256 binary `SHA3-256` Sparse Merkle Tree with **explicit RFC-6962-style leaf/internal domain separation (`R4-07`)**:
  * `EmptyHash = [32]byte{0}` at all 256 levels.
  * `LeafPath(logicalKey) = SHA3-256(logicalKey)` (32 bytes, MSB-first bit walk).
  * **`LeafHash(path[32], value) = SHA3-256([0x00] || path[32] || value)`** (prevents `32B`-value leaves from colliding with `64B` internal nodes!).
  * **`InternalHash(left[32], right[32]) = EmptyHash` if `left == 0 && right == 0`, else `SHA3-256([0x01] || left[32] || right[32])`**.
  * **Compact Proof Wire (`SMTProof`, `<= 1.2 KB`):** `[32B nonEmptyBitmap] || [k * 32B nonEmptySiblings]` walking all 256 levels deterministically.
  * **Committed Keys:** All live keys in `MomentumChanges` excluding `[0x00, 0x01, 0x02]`, persisted under Pebble namespace `[0x10] || nodeHash[32]` outside `MomentumChanges`.

---

### `PR-PQ-03` — Layer 2: `AccountBlock v2`, `[0x11]` Witness Sidecar, `Momentum v3` & Gossip Dedup

#### 4.3.1 `internal/nom/account_block.go` & `[0x11]` Witness Sidecar (`R4-07` Fix)
* Add `ProofWitness []byte` (Proto tag `24`; RLP elem `23`) and `EquiXSolution []byte` (Proto tag `25`; RLP elem `24`). Keep `306-byte` `ComputeHash()` unchanged!
* **Witness-Separated `[0x02]` vs `[0x11]` Storage (`R4-07` Fix):**
  * For `Version == 1`: `buildStoredAccountPatch` (`account_pool.go:1009`) keeps `b.SerializeProto()` in `[0x02] || be_u64(height)` unchanged (`100%` Phase 0 `Momentum.ChangesHash` parity!).
  * For `Version == 2`: `[0x02] || be_u64(height)` stores `b.SerializeStrippedBodyProto()` (omitting `PublicKey`, `Signature`, `ProofWitness`, `EquiXSolution` and appending tag `26` `WitnessCommitment[32]`), while raw witness bytes are persisted in Pebble namespace **`[0x11] || b.Hash[32]`** (outside `MomentumChanges`) so `14`-day witness compaction never alters `Momentum.ChangesHash`!

#### 4.3.2 `internal/nom/momentum.go`
* Add `StateRoot types.Hash` (`Proto` tag `14`, `RLP` optional elem `14`); `Version >= 3` `ComputeHash()` hashes `208 B` (`StateRoot` at `176..208`); update `snapshotHashPreimage` in `verifier/momentum.go:56-85`.

#### 4.3.3 Zero-Copy Frame Caps, Witness Validation & `(Hash, WitnessCommitment)` Dedup (`M02, C03`)
* Keep `go-zenon-v1`'s zero-copy slice-bounded decoders (`MaxMsgSize = 10 MiB` P2P, `MaxHTTPBodySize = 5 MiB` RPC, `MaxDescendantDepth = 10,000`), enforce `ValidateAccountBlockWitnessCaps` immediately post-decode (`PublicKey` in `{0,33,898,1313,1345}`, `Signature` in `{0,65,667,2421,2485,7857}`, `ProofWitness <= 131,072` only to `AuthRegistry`/`Settlement`, `EquiXSolution` in `{0,16}`), charge `InvalidWitnessPenalty = 512` in `budget.go`, and key `TxMsg` broadcast/seen caches by `(block.Hash, WitnessCommitment)`.

---

### `PR-PQ-04` — Layers 3–4: `uint64 SporkMask`, `WitnessPlasma`, `Equi-X` & `AccountStore[0x09]/[0x0a]`

* Widen `type SporkMask uint64` preserving Phase 0 `0x1f` bits `0..4` verbatim; register `AuthRegistryContract` (`0xeb35f142`, `0x60c3b470`, `0x3a1c6df1`, `0xe2043a81`) and `Pillar` (`0xc807dc32`, `0x0cf340ef`) at `EmbeddedSimplePlasma (52,500)`; implement `WitnessPlasma` and two-stage `Equi-X` (`internal/pow/equix.go`).
* Add `KeyAccountCachedPublicKey = 0x09` and `KeyAccountLegacyEd25519PK = 0x0a` in `account_store.go`; pin only `32B` `SHA3-256(pubWire)` in `HotStateCache`; widen `SporkIndex` with downward closure (`LegacyCryptoSunset => PQAccounts => StateRoot`).

---

### `PR-PQ-05` — Layers 5–6: `AuthRegistry (#14)`, `O(1)` Exposure Resolver & `H_inc` Supervisor Fixes (`R4-01..R4-03`)

#### 4.5.1 New Error Sentinels (`internal/vm/vmerr/errors.go`)
Preserve all 74 existing verdicts verbatim and append `ErrABUnsupportedAddressClass`, `ErrABLegacyCryptoDisabled`, `ErrABPublicKeyMustBeCached`, `ErrABWitnessBoundsInvalid`, `ErrABProofWitnessInvalid`, `ErrMStateRootMismatch`, `ErrMProofWitnessTooBig`, `ErrAuthStaleGeneration`, `ErrAuthNonceOverflow`, `ErrAuthPendingRotationExists`, `ErrAuthInvalidPop`, `ErrAuthTargetAlreadyPQ`, `ErrAuthAddressDerivationMismatch`, `ErrAuthUnknownExposure`, `ErrAuthInvalidPoKoS`, `ErrSporkReadinessNotMet`.

#### 4.5.2 `AuthRegistryContract (#14)` & `O(1)` Legacy Exposure Resolver (`R4-02, R4-03` Fix)
* **Storage Layout inside `[0x04]`:**
  * `PrefixAuthRecord = 0x01`: `[0x01] || targetAddr[20]` → ABI `authRecord`
  * `PrefixPendingIndex = 0x02`: `[0x02] || be_u64(pendingEffectiveHeight) || targetAddr[20]` → `be_u64(1)`
  * **`PrefixExternalEd25519Reveal = 0x03` (`R4-02`):** `[0x03] || addr[20]` → `pk32[32]`, populated ONLY for non-`AccountBlock` `Ed25519` signature reveals (`Momentum` `0x00` producer keys & `PtlcContract` `PointTypeEd25519` unlocks — `< 250` entries total = `< 15 KiB`!). At `H_spork10` Step 0, seed `[0x03]` from the `<= 150` historical Pillar producer/PTLC reveals (`< 1 ms`), and after `m.Content` in each `Momentum`, record any unrotated `0x00` `m.PublicKey` into `[0x03]` (never mutating `AccountStore(producer)`, avoiding `AccountBlock.ChangesHash` conflicts!).
* **Execution Context (`R4-03`):** All 4 `AuthRegistry` methods execute against **`ctx.InclusionMomentumStore()`** (`momStore`, seeing live intra-Momentum writes!) and compute **`pendingEffectiveHeight = ctx.InclusionHeight() + 1`** (NEVER `targetMA.Height + 1`!). Enforce `rec.RotationNonce < math.MaxUint64` (`ErrAuthNonceOverflow`).
* **`ResolveLegacyEd25519Exposure(ms, targetAddress)` inside `RescueWithPoKoS` (`O(1)`, `R4-02`):**
  1. Check `AuthRegistry[0x03 || targetAddress]` and `AccountStore(targetAddress)[0x0a]`: if found (asserting `PubKeyToAddress(pk32) == targetAddress`; mismatch fails closed), return `(hasExposedPK = 1, pk32)`.
  2. Else inspect `hh = acct.Identifier()`:
     * `hh.Height == 0`: return `(0, [32]byte{0})`.
     * `hh.Height == 1`: load `blk1 := acct.ByHeight(1)`. If `blk1 == nil`, return `ErrAuthUnknownExposure`! If `blk1.BlockType == BlockTypeGenesisReceive`, return `(0, [32]byte{0})`; else return `(1, blk1.PublicKey[0:32])`.
     * `hh.Height >= 2`: load `blk1 := acct.ByHeight(1)`; if `blk1 != nil && blk1.BlockType != BlockTypeGenesisReceive`, return `(1, blk1.PublicKey[0:32])`; else load `blk2 := acct.ByHeight(2)` (returning `ErrAuthUnknownExposure` if `nil`, else `(1, blk2.PublicKey[0:32])`).

#### 4.5.3 `MomentumVM`, `GenerateEmbeddedReceive` & Verifiers (`R4-01, R4-03` Fix)
* **`momentum_vm.go` (`Landmine #8`):** Run Step-0 `AuthRegistry` promotion on `momOverlay`, then construct `postPromoStore` over `momOverlay` as `evalStore` for `m.Content`! After `m.Content` succeeds and before `MomentumChanges()`, if `SporkBitPQAccounts` is active and `len(m.PublicKey) == 32` (`0x00` unrotated producer), stage `AuthRegistry[0x03 || expectedProducer] = m.PublicKey` if absent.
* **`vm.go` (`Landmines #9 & #10`):** Pass `inclusionHeight` (`m.Height`) and `inclusionStore` (`momStore`) into `GenerateEmbeddedReceive`; emit `AccountBlock.Version = 2` on all generated `ContractReceive` (`AutoReceiver`) and `ContractSend` descendants/refunds whenever `SporkBitPQAccounts` is active at `H_inc`!
* **`account_block.go` (`R4-01`):** On Path C (`First Reveal`), **forbid `algID == 0x81` when `Address[0] == 0x00`** (`Address[0] == 0x00` Path C permits ONLY `algID == 0x00` pre-sunset; `0x81` requires `0x02` address derivation or `AuthRegistry` PoP!). Verify all `v2` signatures over `BoundSigningDigest`.

---

### `PR-PQ-06` — Layers 6–8: `>= 85%` Spork Gate, Pillar Worker & Phase 1E Sunset (`R4-03, R4-09`)

* Enforce `>= 85%` active-stake 2-epoch `MaxProtocolVersion` readiness + `HardForkEnforcementDelay = 8,640` (`24h`) in `Spork.ActivateSpork`.
* Enforce Phase 1E sunset (`Bridge`, `Swap`, `Pillar.RegisterLegacy`, `PTLC {0..2}`) at **`H_inc >= H_sunset`** inside BOTH `ApplySend` and `ReceiveBlock` (`ctx.InclusionHeight()` `R4-03`). In post-expiry `Ptlc.Reclaim(id)`, call **both `DeletePtlcInfo` and `DeletePtlcReclaimLock`** (`R4-03`).
* Enforce `SunsetAnchorCheckpoint` (`Height`, `MomentumHash`, `StateRoot`, `MaxPreCRQCBitcoinHeight` `R4-09`) in `downloader.go` and `reorg.go`.

---

### `PR-PQ-07` — Layers 2, 8 & 9: `/znn/tls-pq/1.0.0`, PQ Wallet, RPC & `znnd` Startup KAT

* Register `/znn/tls-pq/1.0.0` (`X25519MLKEM768` + `ML-DSA-44` exporter binding), disable `noise.ID` at `Spork #14`, add `PQKeyPair` (`SignAccountBlockV2` / `SignMomentumV3` using `BoundSigningDigest`), expose `embedded.auth.*` + `ledger.getStateProof` RPCs, and call `crypto.AssertMLDSAReady()` at `znnd` startup.

---

### `PR-PQ-08` — Mandatory Verification Matrix & Qualification Gates (`C05` + `R4-01..R4-09`)

Every PR MUST pass **both** `CGO_ENABLED=1 go test -race ./...` and `CGO_ENABLED=0 go test ./...` (`C05`) plus:

| Gate | Exact Test Suite in `go-zenon-v1` | Pass Criterion |
|:---:|---|---|
| **`G1`** | `internal/crypto/pq_kat_test.go`, `pq_address_test.go`, `pq_codec_test.go` | Matches `Go 1.27` `ML-DSA-44` low-level (`621b16f8...`) & `BoundSigningDigest` (`b7444ca3...`) KATs, `z1qgyf208a5...`, `179 B` PoP, `[0x00]/[0x01]` `smt-v1`, `[0x11]` witness sidecars, and 100% Phase 0 replay parity. |
| **`G7` / `ZP-Q16` / `ZP-Q27`** | `internal/vm/contracts/auth/auth_test.go`, `pq_verifier_test.go` | Rejects `0x81->0x00` stripping & `0x00->0x81` ransomware (`R4-01`), tests `postPromoStore` `evalStore` + `ctx.InclusionMomentumStore()` intra-Momentum reveals (`R4-03`), `GenesisReceive` `H=1` unexposed vs `H=2` exposed + Pillar `[0x03]` `PoKoS` (`R4-02`), and `ErrAuthNonceOverflow`. |
| **`ZP-Q17` / `ZP-Q30`** | `internal/pow/pq_plasma_test.go`, `internal/storage/pruner_pq_test.go` | Phase 0 `0x1f` parity, per-suite `WitnessPlasma` monotonicity, `1` reserved `PoKoS` slot, and `100%` `Momentum.ChangesHash` replay across days `15..30` after `[0x11]` `14`-day witness compaction (`R4-07`). |
| **`G9` / `ZP-Q19`** | `internal/crypto/pq_fuzz_test.go`, `equix_test.go`, `pq_tls_test.go` | Zero panics under `go test -fuzz` on `ML-DSA-44`, pure-Go `fn-dsa v0.3` (`0` FPU instructions in verify!), `SLH-DSA-128s`, `Equi-X`, and `/znn/tls-pq/1.0.0`. |
| **`ZP-Q20` / `ZP-Q28`** | `internal/crypto/zkverify/whir_sha3_v1_test.go` | `0` heap allocs in `256 KiB` arena, `32-bit` grind + `224-bit` query (`2^-128` QROM), rejects `> 8,000` Keccak perms in `< 50 µs`, `<= 3.5 ms` on Pi 5 Cortex-A76 (`R4-04`). |
| **`ZP-Q23`–`Q26`** | `internal/vm/verifier/sunset_test.go`, `sunset_anchor_test.go` | Rejects `H_ack < H_sunset` bypasses on BOTH user blocks AND `Bridge`/`Swap`/`PTLC` `ContractReceive`s at `H_inc >= H_sunset`, verifies `Version = 2` embedded `ContractSend`s (`R4-03`), cleans `ptlcReclaimLock` on `Reclaim`, and enforces `SunsetAnchorCheckpoint`. |

---

## 5. Copy-Paste LLM Coding Agent Execution Prompt

```text
You are upgrading 0x3639/go-zenon-v1 to implement the v4-verified Post-Quantum validator upgrade
defined in ZNN-IMP-PQ-V1:
  https://0x3639.com/zenon-phase-1/raw/post-quantum/go-zenon-v1-pq-implementation-spec.md

Execution rules:
1. Work strictly in PR order: PR-PQ-01 -> PR-PQ-02 -> ... -> PR-PQ-08.
2. Hard invariants:
   - CGO_ENABLED=0 pure Go on Go 1.27+ in production; zero floating-point math in consensus/verify.
   - Preserve strictly acyclic L0-L9 package layering and 100% Phase 0 historical replay parity.
   - Address all 10 codebase landmines in Section 3 (including BoundSigningDigest R4-01, O(1)
     GenesisReceive/producer exposure resolver R4-02, postPromoStore + InclusionHeight/Store +
     Version=2 embedded descendants R4-03, [0x00]/[0x01] smt-v1 & [0x11] witness sidecars R4-07).
3. After each PR slice, run BOTH:
   CGO_ENABLED=1 go test -race ./...
   CGO_ENABLED=0 go test ./...
   and report exact files changed, tests added, and gate verification results before advancing.
```
