# zenon-post-quantum — Complete LLM Specification & Implementation Corpus > Single-file post-quantum cryptography specification and AI coding agent implementation blueprint for the Zenon Network of Momentum (`go-zenon-v1`, `zenon-rs`, `syrius`). ================================================================================ FILE: docs/intro.md | URL: https://0x3639.com/zenon-post-quantum/docs/intro ================================================================================ # Post-Quantum Zenon (`zenon-post-quantum`) > **For Humans & AI Coding Agents:** Every page in this documentation portal opens with a **60-second TL;DR**, followed by **byte-exact wire layouts, state-machine invariants, and source-grounded file maps** against [`0x3639/go-zenon-v1`](https://github.com/0x3639/go-zenon-v1), [`0x3639/zenon-rs`](https://github.com/0x3639/zenon-rs), and [`syrius`](https://syrius.zenon.foo/). > > **Single-File LLM Ingestion:** Point any AI coding agent at [`/llms-full.txt`](pathname:///llms-full.txt) (full concatenated corpus) or [`/llms.txt`](pathname:///llms.txt) (structured index + raw `.md` endpoints). --- ## 60-Second TL;DR Cryptographically Relevant Quantum Computers (CRQCs) running **Shor's algorithm** break every elliptic-curve primitive currently securing the Zenon Network of Momentum (`Ed25519` account & Momentum signatures, `secp256k1` Bridge TSS / Swap / P2P keys, `BIP-340` & `[k]G` PTLC locks, and `X25519` Noise handshakes). By contrast, Zenon's symmetric and hash primitives (`FIPS-202 SHA3-256`, `Argon2id`, `AES-256-GCM`, `HMAC-SHA512`, and 24-word `BIP-39` mnemonics) retain **≥ 128-bit post-quantum security** against Grover's algorithm. Rather than betting the ledger on a single mathematical family, Zenon should deploy an **algorithm-agile, 3-tier NIST post-quantum signature framework** via Spork (`AccountBlockVersion = 2`): | `algID` | Algorithm | NIST Standard | Math Family | PK / Sig Size | Cached Repeat-Tx Witness | Primary Role on Zenon | |---|---|---|---|:---:|:---:|---| | `0x00` | `Ed25519` *(Legacy)* | RFC 8032 | Twisted Edwards | `32 B` / `64 B` | `96 B` *(no cache)* | Legacy `v1` compatibility; sunset in Phase 3 | | **`0x01`** | **`ML-DSA-44`** | **FIPS 204** | Module-LWE Lattice | `1,312 B` / `2,420 B` | **`2,421 B`** | **Primary Default:** User `AccountBlock`s & Pillar `Momentum`s (native Go 1.26 `crypto/mldsa`, 32B seed, zero CGo) | | **`0x02`** | **`FN-DSA-512`** *(Falcon)* | **FIPS 206** | NTRU Lattice | `897 B` / `666 B` | **`667 B`** | **Compact / BFT Tier:** High-frequency accounts & 21-of-30 Narwhal/Tusk BFT quorum certificates (`~14 KB`) | | **`0x03`** | **`SLH-DSA-SHAKE-128s`** | **FIPS 205** | Stateless Hash (Keccak) | `32 B` / `7,856 B` | **`7,857 B`** | **Zero-Lattice Vaults:** `SporkAddress`, `BridgeAdministrator`, Pillar `StakeAddress`es, and cold custody | | `0x81` | `Ed25519 + ML-DSA-44` | Hybrid | Curve + Module-LWE | `1,344 B` / `2,484 B` | **`2,485 B`** | Optional Phase 1–2 defense-in-depth transition mode | --- ## Why Zenon Upgrades Cleaner Than Bitcoin or Solana Inspecting `go-zenon-v1` reveals three structural properties of the **Network of Momentum (`NoM`) dual ledger** that eliminate the hardest post-quantum bottlenecks faced by UTXO and monolithic chains: 1. **SegWit-Style Witness Separation Already Exists in `v1`:** In `internal/nom/account_block.go:124` and `internal/nom/momentum.go:132`, `PublicKey` and `Signature` are **already excluded** from `AccountBlock.ComputeHash()` (fixed `306-byte` preimage), client PoW (`SHA3-256(Address || PreviousHash)`), and `Momentum.Content` (`60-byte` `AccountHeader`s). Upgrading to multi-kilobyte witnesses mutates **zero** block hashes, **zero** `FromBlockHash` links, and **zero** PoW nonces. 2. **Sequential Per-Account Chains Enable Public-Key Caching:** Every user account is an ordered chain (`Height = 1, 2, 3, ...`). Recording an account's post-quantum `PublicKey` once in `AccountStore` (at `Height = 1` or via `AuthRegistry`) lets every subsequent `AccountBlock` omit `PublicKey` (`Protobuf tag 22`), slashing steady-state witness sizes by **35% (`ML-DSA-44`)** to **57% (`FN-DSA-512`)**. 3. **30-Pillar Consensus Avoids the BLS12-381 Aggregation Crisis:** Ethereum (~1M validators) and Solana (~1,500 validators) rely on pairing-based `BLS12-381` signature aggregation, which Shor's algorithm breaks completely. Zenon's `LegacyDposV1` uses **1 Pillar signature per 10-second `Momentum`**, and future `MomentumVersionV3` Narwhal & Tusk (`NodeCount = 30`, quorum `2f+1 = 21` in `internal/consensus/engine/seam.go:202`) requires only **`~14 KB` (`FN-DSA-512`)** or **`~51 KB` (`ML-DSA-44`)** per quorum certificate with **zero aggregation**. ```mermaid flowchart TD BIP39["Existing 24-Word BIP-39 Mnemonic (256-bit Entropy)"] --> KDF["Hardened PQ Derivation Path m/44'/73404'/1'/alg'/idx'"] KDF --> S1["0x01 ML-DSA-44 (Go 1.26 crypto/mldsa)"] KDF --> S2["0x02 FN-DSA-512 (Integer NTT Verify)"] KDF --> S3["0x03 SLH-DSA-SHAKE-128s (Pure Keccak)"] S1 & S2 & S3 --> ADDR["0x02 PQ Native Address OR AuthRegistry Rotation on 0x00 Address"] ADDR --> AB["AccountBlock v2 (Unchanged 306B SHA3-256 Hash Preimage)"] AB --> CACHE["AccountStore PK Cache (Omit Tag 22 PublicKey for Height > 1)"] CACHE --> PLASMA["Dynamic Plasma Witness Surcharge (QSR Fusion / PoW)"] PLASMA --> MOM["10s Momentum (60B AccountHeaders + ML-DSA/FN-DSA Seal)"] ``` --- ## Five Protocol Traps That Must Be Solved Together :::warning Critical Consensus & Economic Findings from `go-zenon-v1` A naive drop-in replacement of `crypto.VerifyEd25519` fails five Zenon-specific invariants. Every compliant implementation MUST address all five: ::: 1. **Address-Locked Stakes & Pillars Require In-Place Key Rotation (`AuthRegistry`):** `PillarInfo.StakeAddress`, `Sentinel` registrations, and 1–12 month `Stake` entries are bound to existing `0x00` addresses (`internal/vm/contracts/pillar/pillar.go:220`). Users cannot transfer locked positions to a new address. Zenon must decouple an account's **20-byte `Address` identity** from its **active authentication key** via an embedded `AuthRegistry` contract while keeping `types.Address` at 20 bytes (`0x00` legacy, `0x01` contract, `0x02` PQ user) so all 12 embedded contract ABIs remain untouched. 2. **Unpriced Witness Bytes in Dynamic Plasma (`GetBasePlasmaForAccountBlock`):** In `internal/pow/plasma.go:269`, `ABByteDataPlasma = 68` is charged **only on `block.Data`**, charging **`0` plasma** for `PublicKey` and `Signature`. Leaving `1.5 KB – 7.9 KB` PQ witnesses free in a feeless PoW/QSR network opens a trivial bandwidth and `pebble/v2` storage bloat attack. 3. **First-Receive Public-Key Exposure on `0x00` Addresses:** Untouched `z1q...` addresses hide `Ed25519` public keys behind `SHA3-256(pub)[0..19]` (`152` bits → `2^76` sequential Grover cost). However, **claiming funds requires publishing a `BlockTypeUserReceive` (`3`) block**, which attaches `block.PublicKey` on-chain! Phase 1 must let receive-only `0x00` holders atomically rotate to a PQ key on their very first transaction—and Phase 3 provides **`Ed25519-PoKoS`** STARK seed proofs for dormant accounts. 4. **Classical Curve Assumptions Inside Embedded Contracts:** `PtlcContract` (`PointTypeSecp256k1Point` `[k]G` adapter locks), `BridgeContract` (`DecompressedTssECDSAPubKey` single-key ECDSA), and `Pillar.RegisterLegacy` (`secp256k1` recovery) require targeted PQ upgrades or Spork sunsets. 5. **P2P Harvest-Now-Decrypt-Later (`Noise_XX_25519` & `RLPx`):** Modern `go-libp2p` (`internal/p2p/libp2p/server.go:65`) uses `X25519` ECDH and `Secp256k1` peer IDs. Upgrading stream security to hybrid **`X25519 + ML-KEM-768`** (via Go 1.26 `crypto/mlkem`) protects Pillar and Sentinel gossip immediately. --- ## Documentation Map | Section | Document | Purpose | |---|---|---| | **Threat & Survey** | [Quantum Threat Model on Zenon](./landscape/quantum-threat-model) | Primitive-by-primitive audit of `go-zenon-v1` under Shor & Grover | | **Threat & Survey** | [Bitcoin, Solana & Peer L1 Survey](./landscape/bitcoin-and-solana) | `BIP-360`/`361`, Solana `Tx v1` / `Quantumglow` / `PoKoS`, Algorand, Sui, Aptos | | **Threat & Survey** | [Post-Quantum Signature Evaluation](./landscape/signature-schemes) | Exact byte sizes, verification µs, floating-point determinism & Momentum math | | **Specification** | [`0x02` Addresses, `AuthRegistry` & KDF](./specification/addresses-and-key-derivation) | 20B address preservation, in-place key rotation ABI, and BIP-39 KDF | | **Specification** | [`AccountBlock v2` & PK Caching](./specification/account-blocks-and-pk-caching) | `algID` wire format, `AccountStore` PK cache, and Stage-2 pre-verification | | **Specification** | [Dynamic Plasma Witness Pricing](./specification/dynamic-plasma-and-dos) | Exact witness Plasma formula & Momentum byte-cap enforcement | | **Specification** | [Consensus, Contracts & P2P](./specification/consensus-bridge-ptlc-p2p) | Pillar rotation, Narwhal BFT certs, `t-of-n` PQ Bridge, PTLC/HTLC & `ML-KEM-768` | | **Migration** | [3-Phase Spork & `Ed25519-PoKoS`](./migration/spork-roadmap-and-pokos) | Activation timeline, legacy sunset rules, and STARK seed-ownership rescue | | **Migration** | [`go-zenon-v1` Go 1.26 Blueprint](./migration/go-zenon-v1-blueprint) | 8-stage LLM coding blueprint mapped to `L0`–`L9` packages + Bend proof laws | ================================================================================ FILE: docs/landscape/quantum-threat-model.md | URL: https://0x3639.com/zenon-post-quantum/docs/landscape/quantum-threat-model ================================================================================ # Quantum Threat Model on Zenon (`NoM`) > **TL;DR:** Quantum algorithms split Zenon's cryptography cleanly in half. **Shor's algorithm** runs in polynomial time `O((log N)^3)` and completely breaks `Ed25519`, `secp256k1`, `BIP-340`, `X25519`, and discrete-log `PTLC` point locks. **Grover's algorithm** achieves at most a quadratic `O(2^(n/2))` speedup (heavily bottlenecked by serial circuit depth), leaving Zenon's `SHA3-256` ledger hashes, PoW, `HTLC` preimages, `Argon2id` keystores, and 24-word `BIP-39` seeds **post-quantum secure today**. --- ## Complete `go-zenon-v1` Cryptographic Surface Audit Every cryptographic package and consensus path in `go-zenon-v1` was audited against both **Shor's algorithm** (abelian hidden subgroup / discrete logarithm) and **Grover / BHT quantum search** (preimage & collision finding): | Subsystem | Source File in `go-zenon-v1` | Current Primitive | Classical Bits | Quantum Bits | Verdict & Action | |---|---|---|:---:|:---:|---| | **Block & State Hashing** | `internal/crypto/keccak.go` | `FIPS-202 SHA3-256` | `256` preimage / `128` coll | `128` Grover / `85–128` BHT | **SAFE** — No change to `ComputeHash()` or `PatchHash()` | | **Client PoW Links** | `internal/pow/pow.go` | `SHA3-256(Addr \|\| PrevHash)` | Difficulty-bound | Quadratic ASIC-like | **SAFE** — Dynamic Plasma `NextWorkPrice` auto-adjusts | | **Wallet Mnemonic** | `internal/crypto/bip39.go` | 24-word `BIP-39` (`PBKDF2-SHA512`) | `256` entropy | `128` Grover | **SAFE** — Existing user seed phrases remain valid | | **HD Key Derivation** | `internal/crypto/slip0010.go` | `HMAC-SHA512` (`SLIP-0010`) | `256` | `128` Grover | **SAFE** — Add domain-separated PQ hardened path | | **Keystore Encryption** | `internal/crypto/argon2id.go` | `Argon2id` + `AES-256-GCM` | `256` | `128` Grover | **SAFE** — Symmetric vault format stays intact | | **HTLC Atomic Swaps** | `internal/vm/contracts/htlc/htlc.go` | `SHA3-256` / `SHA-256` (32B preimage) | `256` | `128` Grover | **SAFE** — Primary PQ cross-chain swap primitive | | **User Address Hash** | `internal/types/address.go:165` | `0x00 \|\| SHA3-256(pub)[0..19]` | `152` preimage | `76` Grover *(serial)* | **SAFE UNEXPOSED** — Vulnerable once `pub` is revealed | | **User `AccountBlock` Sig** | `internal/crypto/ed25519.go:19` | `Ed25519` (RFC 8032) | `~128` | **`0` (Broken — Shor)** | **CRITICAL** — Upgrade to `ML-DSA-44` / `FN-DSA-512` / `SLH-DSA` | | **Pillar `Momentum` Sig** | `internal/vm/verifier/momentum.go:110` | `Ed25519` (RFC 8032) | `~128` | **`0` (Broken — Shor)** | **CRITICAL** — Exposed every 10s; rotate Pillar producers first | | **PTLC Point Locks** | `internal/vm/contracts/ptlc/ptlc.go:29` | `Ed25519` (`0`), `BIP-340` (`1`), `[k]G` (`2`) | `~128` | **`0` (Broken — Shor)** | **HIGH** — Add PQ sig types `3..4`; sunset types `0..2` | | **Bridge TSS Oracles** | `internal/vm/contracts/bridge/methods_bridge.go` | `secp256k1` TSS ECDSA | `~128` | **`0` (Broken — Shor)** | **HIGH** — Add `t-of-n` Guardian `ML-DSA-44` quorum | | **Legacy Swap & Pillars** | `internal/vm/contracts/swap/swap.go:147` | `secp256k1` ECDSA recovery + `Hash160` | `~128` | **`0` (Broken — Shor)** | **MEDIUM** — Swap decayed to `0%` at Epoch 389; sunset `RegisterLegacy` | | **P2P Transport & IDs** | `internal/p2p/libp2p/server.go:65` | `Noise_XX_25519` + `secp256k1` `peer.ID` | `~128` | **`0` (HNDL + Shor)** | **HIGH** — Add `X25519MLKEM768` + PQ `peer.ID`s; retire `RLPx` | --- ## Threat Vector Taxonomy on Zenon ### 1. Long-Exposure Shor Attacks (Highest Immediate Risk) A **long-exposure attack** targets any account whose classical public key is already recorded on the public ledger, giving a quantum adversary unlimited offline wall-clock time (hours, days, or weeks) to compute the discrete logarithm `d = log_G(P)`. On Zenon Alphanet (`chainId = 1`), three classes of keys suffer permanent long-exposure visibility: 1. **Active Pillar `BlockProducingAddress` Keys:** Every `Momentum` (`internal/nom/momentum.go:83`) embeds `m.PublicKey` (`32 B`). The 30 active Pillars publish their raw `Ed25519` public keys **8,640 times per day**. Compromising ≥ 20 Pillar producing keys lets an adversary forge arbitrary chains within `LegacyMaxReorgDepth` (or forge a `2f+1` quorum certificate under future BFT). 2. **Every User Account With `Height >= 1`:** In Zenon's dual-ledger model, sending tokens to `z1q...` creates a `BlockTypeUserSend` (`2`) on the *sender's* chain; the recipient's public key is **not** revealed yet. However, the moment the recipient claims those funds with a **`BlockTypeUserReceive` (`3`)** block—even if they never send a single token out!—`internal/vm/verifier/account_block.go:1055` requires `len(block.PublicKey) == 32`. That `Ed25519` public key is now permanently on-chain. 3. **Bridge `DecompressedTssECDSAPubKey`:** Stored in `BridgeInfo` state (`64 B` uncompressed `secp256k1` point). Recovering this single scalar allows an attacker to mint arbitrary wrapped assets via `UnwrapToken` or drain bridge vaults on connected EVM chains via `UpdateWrapRequest`. ```mermaid sequenceDiagram participant Alice as Sender participant Ledger as Zenon Ledger participant Bob as Recipient (0x00 Address) participant QC as Quantum Adversary Alice->>Ledger: UserSend (BlockType=2) to z1q_bob Note over Ledger,QC: Only 20B Addr = 0x00 || SHA3-256(pk)[0..19] visible (Safe: 2^76 serial Grover) Bob->>Ledger: UserReceive (BlockType=3, Height=1, PublicKey=pk_ed25519) Note over Ledger,QC: DANGER: 32B Ed25519 PublicKey is now permanently exposed on-chain! QC->>QC: Offline Shor's Algorithm recovers sk_ed25519 from pk_ed25519 QC->>Ledger: Forged UserSend / Stake.Cancel / Pillar.Revoke! ``` ### 2. Short-Exposure (Mempool / Slot) Shor Attacks A **short-exposure attack** occurs when a previously unexposed account broadcasts its first transaction (`Height = 1`), revealing `PublicKey` in the mempool (`TxMsg 0x12`), and a fast CRQC derives the private key and front-runs the transaction before confirmation. * On Bitcoin (~600s block interval), the mempool exposure window is 10–60+ minutes. * On Zenon (`BlockTimeSec = 10s`), the mempool window is **≤ 10 seconds**—requiring a quantum computer orders of magnitude faster than one needed for long-exposure theft. * Nevertheless, **post-quantum `0x02` addresses** and **`Ed25519-PoKoS` zero-knowledge seed migrations** eliminate *both* long-exposure and short-exposure windows completely. ### 3. Address Truncation (`152-bit` `SHA3-256`) Under Grover's Algorithm Zenon user addresses (`internal/types/address.go:165`) are 20 bytes: ```text Address[0] = ClassByte (0x00 = Legacy User, 0x01 = Embedded Contract, 0x02 = PQ User) Address[1..20] = SHA3-256(PublicKeyPayload)[0..19] // 19 bytes = 152 bits ``` How secure is a **152-bit truncated `SHA3-256` digest** against a quantum preimage attack finding *some* valid public key `P'` that hashes to an existing target address? * **Quantum Preimage Cost (Grover):** Finding a preimage for a 152-bit output requires `(pi / 4) * 2^(152 / 2) ≈ 2^75.6` **sequential** evaluations of the reversible `Keccak-f[1600]` + key-validation oracle. * **NIST `MAXDEPTH` Reality Check:** Grover's algorithm does **not** parallelize efficiently: splitting across `S` quantum processors reduces depth only by `sqrt(S)`, increasing total gate work to `2^76 * sqrt(S)`. Under NIST's PQC evaluation standard (`MAXDEPTH = 2^64 .. 2^96` logical gate cycles, where a single reversible `SHA3-256` evaluation costs `> 2^15` Toffoli depth), executing `2^76` serial Grover iterations exceeds realistic physical bounds for decades. * **Collision Attacks Do Not Steal Existing Accounts:** Brassard-Høyer-Tapp quantum collision search (`O(2^(n/3)) ≈ 2^50.7` with massive QRAM) only lets an *attacker* generate two colliding addresses of their *own* before funding—which has no economic exploit vector in Zenon because embedded contracts never authorize callers by cross-user hash collisions. * **Why Domain Separation Still Matters:** To prevent cross-algorithm preimage grinding, PQ `0x02` addresses hash the **domain-separated tuple** `"zenon-pq-addr:v1" || [algID] || pqPublicKey` rather than raw key bytes. ### 4. Harvest-Now-Decrypt-Later (HNDL) on P2P Gossip Even before a CRQC exists, state-level adversaries can record encrypted P2P TCP streams between Pillar validators and Sentinel nodes (`internal/p2p/libp2p/server.go:26`, `Noise_XX_25519_ChaChaPoly_SHA256`, and legacy DevP2P `RLPx` `secp256k1` ECIES) to retroactively deanonymize transaction originators or map Pillar validator topologies. Upgrading `go-libp2p` stream negotiation to **hybrid `X25519 + ML-KEM-768`** closes HNDL immediately with ~1.1 KB of handshake overhead per TCP connection. ================================================================================ FILE: docs/landscape/bitcoin-and-solana.md | URL: https://0x3639.com/zenon-post-quantum/docs/landscape/bitcoin-and-solana ================================================================================ # Industry Survey: Bitcoin, Solana & Peer L1s > **TL;DR:** Across 2025–2026, major Layer-1 ecosystems split into two camps based on their blockspace and consensus constraints: > - **Bitcoin (`BIP-360` & `BIP-361`)** prioritizes ultra-conservative assumptions—stripping exposed Schnorr public keys first (`P2MR`) and favoring stateless/stateful hash-based signatures (`SLH-DSA` / Winternitz) despite painful `4 MWU` block-weight pressure. > - **Solana (`Transaction v1`, `FN-DSA-512` / `ML-DSA`, `Quantumglow`, `Ed25519-PoKoS`)** expanded packet limits (`1,232 B → 4,096 B`), adopted compact lattice signatures for 18,500+ TPS user throughput, moved consensus off `BLS12-381` to hash trees, and pioneered zero-knowledge BIP-39 seed migration (`Ed25519-PoKoS`). > - **Zenon** can combine the best of both worlds: Solana-style `Ed25519-PoKoS` seed continuity + Sui/Aptos-style in-place key rotation + `ML-DSA-44`/`FN-DSA-512` throughput + Bitcoin/Ethereum-style `SLH-DSA` hash-only vaults. --- ## 1. Bitcoin: `BIP-360 (P2MR)`, Hash Opcodes & `BIP-361` Sunset Bitcoin faces two acute structural constraints: ~6–7 million BTC sitting in **key-exposed outputs** (early `P2PK` "Satoshi-era" coins, reused `P2PKH` addresses, and every Taproot `P2TR` UTXO!) and a rigid **4,000,000 weight-unit (`4 MWU` / 1–4 MB)** block cap every 10 minutes. ### `BIP-360`: From `P2QRH` → `P2TSH` → `P2MR` (Pay-to-Merkle-Root) Originally drafted by Hunter Beast (and refined with Ethan Heilman and Isabel Foxen Duke through late 2025 and early 2026), **BIP-360** intentionally **decouples hiding public keys from picking a permanent post-quantum signature opcode**: * **Why Taproot (`P2TR`, SegWit v1) Made Quantum Exposure Worse:** Taproot encodes a 32-byte tweaked `secp256k1` x-only Schnorr public key *directly in the `scriptPubKey`* on-chain, exposing funds to long-exposure Shor attacks the instant an output is *created* (even before spending). * **How `P2MR` (SegWit v2) Fixes Long-Exposure:** `P2MR` keeps Tapscript Merkle trees (MAST) while **completely removing the elliptic-curve key-path spend**. Funds are locked solely to a 32-byte SHA-256 Merkle root (`OP_2 <32-byte-hash>`), restoring hash-level preimage protection for resting UTXOs via a clean soft fork. ### Bitcoin's Post-Quantum Signature Debate To protect the spend transaction itself in the mempool (short-exposure), Bitcoin researchers are evaluating three paths: 1. **`SLH-DSA` / `SPHINCS+` Variants (`SPHINCS+C` / tailored parameter sets):** Favored by Bitcoin conservatives because security reduces purely to SHA-256—matching Bitcoin's existing Proof-of-Work trust assumption—with 32-byte public keys. However, ~4–8 KB signatures cut Bitcoin's effective throughput by **60%–85%** without a witness-weight discount Increase. 2. **`OP_CAT` (`BIP-347`) + Lamport / Winternitz One-Time Signatures:** Re-enabling `OP_CAT` allows users to build stateful/one-time hash-based covenants in Tapscript today without waiting for a dedicated PQ opcode, at the cost of strict single-use address hygiene. 3. **`FN-DSA` (Falcon) / `ML-DSA` Tapscript Opcodes:** Advocated by throughput-focused engineers (`666 B` Falcon-512 vs. `7,856 B` SLH-DSA), though debated by Bitcoin minimalists wary of algebraic lattice assumptions. ### `BIP-361`: Post-Quantum Migration & Legacy Signature Sunset Authored by Jameson Lopp and collaborators, **BIP-361** confronts the economic catastrophe of millions of dormant `P2PK` coins becoming lootable by the first CRQC: * **Phase A:** Disallow sending *new* outputs to quantum-vulnerable output types. * **Phase B:** Enforce a flag-day sunset (~5 years post-activation) disabling classical `ECDSA`/`Schnorr` verification on unmigrated UTXOs so lost coins freeze rather than flood the market via quantum theft. * **Phase C:** Evaluate zero-knowledge BIP-39 seed proofs allowing legitimate owners who missed the deadline (and never had a raw P2PK without a hash/seed) to recover frozen UTXOs. --- ## 2. Solana: High-Throughput Lattice PQC, `Quantumglow` & `Ed25519-PoKoS` Unlike Bitcoin, Solana optimizes for sub-second slots (`400 ms`) and tens of thousands of TPS, where every account address *is* a raw 32-byte `Ed25519` public key (meaning **100% of Solana accounts have exposed public keys**!). Core teams at **Anza** (Agave), **Jump Crypto** (Firedancer), and **Blueshift** executed an aggressive 2025–2027 engineering roadmap: ### Expanding the Wire (`Transaction v1`: `1,232 B → 4,096 B`) Solana's legacy transaction format was hard-capped at `1,232 bytes` (single IPv6 UDP MTU). Because even the smallest NIST PQ scheme (`FN-DSA-512`: `897 B` PK + `666 B` sig = `1,563 B`) overflows `1,232 bytes`, Solana introduced **Transaction v1**, raising maximum transaction payload capacity to **`4,096 bytes`** alongside dedicated `Keccak-p[1600]` / lattice verification syscalls. In October 2026, Solana PQ test clusters demonstrated **18,500 TPS** end-to-end. ### Solana's Three Cryptographic Layers 1. **Cold Custody Today (`Winternitz Vaults`):** Blueshift deployed on-chain hash-based Winternitz one-time signature vaults (`~896 B` witness, zero lattice assumptions) so treasuries and whales can lock SOL behind SHA-256/Keccak commitments immediately, rotating to a fresh vault address on spend. 2. **Retail Accounts (`FN-DSA-512` & `ML-DSA-44`):** Both Anza and Firedancer converged on **`FN-DSA-512` (Falcon-512)** for high-frequency user transactions due to its `666-byte` signature footprint, paired with **`ML-DSA-44`** (FIPS 204) in standardized ecosystem wallets. 3. **Validator Consensus (`Quantumglow`):** Solana's Alpenglow consensus relied on `BLS12-381` aggregate signatures across ~1,500 validators. Because post-quantum lattice schemes lack sub-kilobyte non-interactive aggregation at 1,500-signer scale, **Quantumglow** replaces BLS aggregation with tailored **hash-based Merkle signatures (`Ax` / XMSS-style epoch trees)** bounded to validator epochs. ### `Ed25519-PoKoS` (Zero-Knowledge Proof of Knowledge of Seed) To avoid forcing hundreds of millions of wallet users to generate new seed phrases or manually migrate before a hard deadline, Anza introduced **`Ed25519-PoKoS`** (building on Mysten Labs' ZK-seed research): * Standard wallets derive `sk_ed25519 = HMAC-SHA512(seed)` (`SLIP-0010` / `BIP-39`). * Even **after** a quantum computer breaks `Ed25519` (recovering the scalar `s` from the public point `A = [s]B`), the quantum computer **cannot invert `SHA-512`** to find the 32-byte pre-hash seed! * A rightful owner generates a post-quantum **STARK proof** demonstrating knowledge of a 32-byte `seed` that hashes via `SHA-512` to `s` such that `[s]B = A`, binding a new post-quantum public key to the account **without ever revealing `seed` or signing with `Ed25519`**. --- ## 3. Peer L1 Benchmarks: Algorand, Sui, Aptos & Ethereum | Ecosystem | Live / Approved Upgrades | Key Architectural Takeaway for Zenon | |---|---|---| | **Algorand** | `Falcon-1024` State Proofs + native AVM `falcon_verify` & `Falcon-1024` accounts (`v4.3`–`v5.0`) + Trezor Safe 5 PoC | Proves **Falcon integer NTT verification** runs deterministically and safely in production L1 consensus. | | **Sui** | Native **`ML-DSA-65`** (FIPS 204) accounts + **`SLH-DSA-SHA2-128s`** Move vaults + **Address Aliases** | Maps `ML-DSA` keys directly to **32-byte BIP-39 seeds** and uses on-chain **Address Aliases** so users keep their existing address. | | **Aptos** | **`AIP-137`** (`SLH-DSA-SHA2-128s`) + **`AIP-55`** Hybrid `MultiKey` (`Ed25519 + PQ`) | Decouples `AccountAddress` from `AuthenticationKey` in account state—allowing **zero-transfer in-place key rotation**. | | **Ethereum** | `EIP-8051` (`ML-DSA` precompile), `EIP-8052` (`Falcon` precompile), `EIP-7702`/`8141` AA + Lean Consensus (STARK-aggregated XMSS) | Uses smart-account verification abstraction for EOAs; only needs heavy STARK signature aggregation because Ethereum has ~1,000,000 validators (vs. Zenon's 30 Pillars). | --- ## Synthesis: What Zenon Should Adopt vs. Skip | Design Question | Bitcoin / Solana / Peer Pattern | Optimal Choice for Zenon (`NoM`) | |---|---|---| | **Primary User Signature** | Solana: `FN-DSA-512` + `ML-DSA-44`; Sui: `ML-DSA-65` | **`ML-DSA-44` (`0x01`)** immediately (Go 1.26 stdlib `crypto/mldsa`, zero CGo) + **`FN-DSA-512` (`0x02`)** once FIPS 206 finalizes | | **Conservative Vaults** | Bitcoin / Aptos / Sui: `SLH-DSA-128s`; Solana: Winternitz | **`SLH-DSA-SHAKE-128s` (`0x03`)** — stateless (no state-reuse footguns!) and uses pure Keccak/SHAKE256 | | **Address Migration** | Sui Aliases / Aptos AuthKey rotation | **Keep 20B `types.Address`**, add `0x02` PQ class byte + **`AuthRegistry` in-place rotation** for locked `0x00` stakes/Pillars | | **Bandwidth Control** | Solana `Tx v1` (`4 KiB`); Bitcoin SegWit weight | **Sequential Account-Chain PK Caching** (omit `PublicKey` after `Height = 1`) + **Dynamic Plasma witness byte pricing** | | **Consensus Signing** | Solana `Quantumglow`; Ethereum STARK-XMSS | **Direct `ML-DSA-44` / `FN-DSA-512`** (`1` sig per 10s in `LegacyDposV1`; `21` sigs = `14–51 KB` in Narwhal v3 — **skip complex STARK aggregation!**) | | **Dormant Account Rescue** | Solana `Ed25519-PoKoS`; Bitcoin `BIP-361` Phase C | **Adopt `Ed25519-PoKoS`** over Zenon's exact `BIP-39` → `SLIP-0010` (`m/44'/73404'/i'`) derivation circuit in Phase 3 | ================================================================================ FILE: docs/landscape/signature-schemes.md | URL: https://0x3639.com/zenon-post-quantum/docs/landscape/signature-schemes ================================================================================ # Post-Quantum Signature Evaluation for Zenon > **TL;DR:** In distributed ledgers, **witness bandwidth and state bloat** dominate raw CPU verification time. Pairing **`ML-DSA-44` (FIPS 204)** as Zenon's day-one standard with **`FN-DSA-512` (FIPS 206)** for high-density throughput and **`SLH-DSA-SHAKE-128s` (FIPS 205)** for hash-only vaults fits comfortably inside Zenon's existing `8.0 MiB` `MaxMomentumContentBytes` limit (`2.4%–6.5%` utilization at 200 user blocks per 10-second Momentum when combined with Account-Chain Public-Key Caching). --- ## Byte-Exact Candidate Comparison All byte sizes below reflect finalized NIST **FIPS 204** (`ML-DSA`), **FIPS 205** (`SLH-DSA`), and **FIPS 206** (`FN-DSA` padded format) specifications: | Scheme | Standard | NIST Cat. | Private Seed | Public Key (`PK`) | Signature (`Sig`) | 1st-Tx Witness (`PK + Sig`) | PK-Cached Repeat Tx (`1B alg + Sig`) | Typical Verify CPU (1 Core) | |---|---|:---:|:---:|---:|---:|---:|---:|---:| | `Ed25519` *(Current)* | RFC 8032 | `0` *(Broken)* | `32 B` | `32 B` | `64 B` | `96 B` | `64 B` | `~35 µs` | | **`ML-DSA-44`** | **FIPS 204** | **2** (~AES-128+) | **`32 B`** | **`1,312 B`** | **`2,420 B`** | **`3,734 B`** | **`2,421 B`** | **`~45 µs`** | | `ML-DSA-65` | FIPS 204 | 3 (~AES-192) | `32 B` | `1,952 B` | `3,309 B` | `5,263 B` | `3,310 B` | `~75 µs` | | `ML-DSA-87` | FIPS 204 | 5 (~AES-256) | `32 B` | `2,592 B` | `4,627 B` | `7,221 B` | `4,628 B` | `~115 µs` | | **`FN-DSA-512`** *(Falcon)* | **FIPS 206** | **1** (~AES-128) | **`32–64 B`** | **`897 B`** | **`666 B`** | **`1,565 B`** | **`667 B`** | **`~35 µs`** | | `FN-DSA-1024` | FIPS 206 | 5 (~AES-256) | `32–64 B` | `1,793 B` | `1,280 B` | `3,075 B` | `1,281 B` | `~70 µs` | | **`SLH-DSA-SHAKE-128s`** | **FIPS 205** | **1** (SHAKE) | **`48 B`** *(3×16B)* | **`32 B`** | **`7,856 B`** | **`7,890 B`** | **`7,857 B`** | **`~1,800 µs`** | | `SLH-DSA-SHAKE-128f` | FIPS 205 | 1 (SHAKE) | `48 B` | `32 B` | `17,088 B` | `17,122 B` | `17,089 B` | `~4,200 µs` | | `XMSS-SHAKE_10_256` | SP 800-208 | Stateful Hash | `32 B` + index | `64 B` | `2,500 B` | `2,564 B` | `2,500 B` | `~400 µs` | *(Note: "1st-Tx Witness" includes the 1-byte `algID` prefix on both `PublicKey` and `Signature`; "PK-Cached Repeat Tx" omits `PublicKey` and carries only `[algID] || Signature`.)* --- ## Deep Dive by Candidate Family ### 1. Why `ML-DSA-44` (`0x01`) Is the Ideal Day-One Default 1. **Zero-CGo Go 1.26 Standard Library Support:** `go-zenon-v1` targets `go 1.26.0` with a strict policy of minimal external dependencies (`4` direct dependencies in `go.mod`, zero CGo). Go 1.26 ships a constant-time, FIPS 140-3 audited pure-Go implementation in **`crypto/mldsa`** (`mldsa.MLDSA44()`, `mldsa.NewPrivateKey(params, seed32)`, `mldsa.Verify`). 2. **Why `ML-DSA-44` Over `ML-DSA-65` for L1 Transactions:** `ML-DSA-44` targets NIST Security Category 2 (comparable to breaking SHA-256 collision / AES-128), matching the exact 128-bit quantum security ceiling already set by Zenon's `SHA3-256` hashes and 24-word `BIP-39` seeds! Moving from `ML-DSA-44` to `ML-DSA-65` inflates every cached transaction by **`+889 bytes` (+37%)** (`2,420 B → 3,309 B`) and initial public keys by **`+640 bytes` (+49%)** without raising Zenon's end-to-end security floor above `SHA3-256`. 3. **Simple Integer Signing for Hardware Wallets:** Unlike Falcon, `ML-DSA-44` signing uses only uniform rejection sampling and 32-bit modular arithmetic (`q = 8,380,417`), making constant-time Ledger, Trezor, and Dart/Flutter (`syrius`) implementations straightforward. ### 2. Why `FN-DSA-512` (`0x02`) Should Be Added as the Compact Tier 1. **3.6× Smaller Repeat Signatures (`666 B` vs. `2,420 B`):** With Account-Chain Public-Key Caching active, a repeat `FN-DSA-512` `AccountBlock` adds only **`667 bytes`** of signature witness—less than one-third of `ML-DSA-44` and small enough to pack **8,000+ user blocks** into a single `8 MiB` Momentum if Dynamic Plasma limits are raised in the future. 2. **Consensus Determinism Myth vs. Reality:** A common misconception is that Falcon cannot be used in blockchain consensus because it uses IEEE-754 floating-point FFTs. **Floating-point math is used ONLY during key generation and signing—NEVER during verification!** * `FN-DSA` verification computes `h * s2 + s1 == c (mod 12289)` and checks the integer squared Euclidean norm `||(s1, s2)||^2 <= floor(beta^2)` using **100% exact 16-bit/32-bit integer Number-Theoretic Transforms (NTT)**. * Every `go-zenon-v1` and `zenon-rs` validator across `x86_64`, `arm64`, and `riscv64` reaches bit-for-bit identical verification verdicts with zero FPU involvement. ### 3. Why `SLH-DSA-SHAKE-128s` (`0x03`) Beats Stateful `XMSS` / `Winternitz` for User Vaults * **Stateless Safety for Multi-Device Wallets:** Stateful hash-based schemes (`XMSS`, `LMS`, or multi-tx Winternitz trees) catastrophic-fail if a user restores their BIP-39 mnemonic on a second laptop or mobile wallet and accidentally reuses a leaf index `i`—leaking forged-signature preimages immediately. * **`SLH-DSA-SHAKE-128s` Is Completely Stateless:** Derived deterministically from a 48-byte seed (derived via `SHAKE256` from the user's 32-byte SLIP-0010 child key), `SLH-DSA-SHAKE-128s` can sign from multiple devices safely, uses a tiny **`32-byte` public key**, and relies **exclusively on `Keccak-f[1600]` (`SHAKE256`)**—already implemented in `go-zenon-v1/internal/crypto/keccak.go`! * While its `7,856-byte` signature and `~1.8 ms` verification time make it too heavy for high-frequency bots, Dynamic Plasma naturally prices it (~`285,000` total base plasma ≈ `136` fused QSR) as a premium **vault, governance (`SporkAddress`), and `BridgeAdministrator`** tier. --- ## Zenon 10-Second Momentum Bandwidth & CPU Budget Analysis Under Alphanet post-`DynamicPlasmaSpork` defaults (`internal/common/params.go:296-335`): * `BlockTimeSec = 10` seconds * `DefaultMaxBasePlasmaInMomentum = 4,200,000` → up to **`200` user blocks** (`21,000` base plasma each) per Momentum (`20 TPS` baseline) * `MaxMomentumContentBytes = 8,388,608` (`8.0 MiB` serialized Protobuf cap) * Non-witness `AccountBlock` Protobuf overhead ≈ `300 bytes` | Workload Scenario (200 User Blocks / 10s Momentum) | Serialized Momentum Body Size | % of `8.0 MiB` Cap | Stage-2 Parallel Verify Time (8 Cores) | Annual Ledger Growth (at 20% Avg Utilization = 4 TPS) | |---|---:|---:|---:|---:| | `Ed25519` *(Current v1)* | `~79 KB` | `0.9%` | `~0.9 ms` | `~49 GB / yr` | | **`FN-DSA-512` (PK Cached)** | **`~193 KB`** | **`2.3%`** | **`~0.9 ms`** | **`~121 GB / yr`** | | **`ML-DSA-44` (PK Cached)** | **`~544 KB`** | **`6.5%`** | **`~1.2 ms`** | **`~343 GB / yr`** | | `ML-DSA-44` *(Uncached — PK on every tx)* | `~807 KB` | `9.6%` | `~1.4 ms` | `~509 GB / yr` | | `SLH-DSA-SHAKE-128s` *(100% Vault txs)* | `~1,631 KB` | `19.4%` | `~45.0 ms` | `~1.02 TB / yr` | :::tip Takeaway on PK Caching + Witness Pruning Account-Chain Public-Key Caching alone saves **`166 GB/year`** of Pebble v2 disk growth under `ML-DSA-44` at 4 sustained TPS. Furthermore, because `PublicKey` and `Signature` are **excluded** from `AccountBlock.ComputeHash()` and `Momentum.Content`, archival vs. pruned nodes can optionally prune historical witnesses deeper than `FinalityRollbackWindow` (`360` momentums) while retaining 100% verifiable state and hash-chain integrity! ::: ================================================================================ FILE: docs/specification/addresses-and-key-derivation.md | URL: https://0x3639.com/zenon-post-quantum/docs/specification/addresses-and-key-derivation ================================================================================ # `0x02` Addresses, `AuthRegistry` & Wallet KDF > **TL;DR:** Keep `types.Address` at **exact 20 bytes (`z1...` Bech32)** so all 12 embedded contracts, ABI words, `AccountHeader`s (`60 B`), and storage keys remain 100% unchanged. Introduce user class byte **`0x02`** (`z1p...` / `z1r...` under HRP `"z"`) for fresh post-quantum accounts, deploy a `13th` embedded contract **`AuthRegistryContract`** (`0x01...`) so existing `0x00` addresses with locked `Stake`, `Pillar`, or `Sentinel` state can rotate to a PQ key **in place**, and derive all PQ keys deterministically from existing 24-word `BIP-39` seeds. --- ## 1. Preserving the 20-Byte `types.Address` Invariant In `go-zenon-v1/internal/types/address.go:11-28`, `Address` is a `[20]byte` value type permeated throughout consensus: * Every ABI `"address"` parameter across all 12 embedded contracts (`internal/codec/abi/`) unpacks into `[20]byte`. * `types.AccountHeader` (`internal/types/account_header.go`) is a fixed `60-byte` tuple `Address[20] || Hash[32] || Height[8]` sorted lexicographically inside `Momentum.Content`. * `AccountBlock.ComputeHash()` (`internal/nom/account_block.go:152-153`) places `Address` at bytes `104..124` and `ToAddress` at `124..144` of the fixed `306-byte` preimage. Changing `AddressSize` from `20` to `32` bytes would fork every ABI selector, storage key (`ProducingPillarNameKey`, `DelegationInfoKey`, etc.), RPC payload, and `AccountBlock` hash preimage. Instead, Zenon's existing **class byte `addr[0]`** cleanly namespaces post-quantum accounts within the exact 20-byte envelope: | `addr[0]` | Constant Name | Bech32 Prefix (`HRP = "z"`) | Meaning & Payable Status | |:---:|---|---|---| | `0x00` | `UserAddrByte` | `z1q...` | Legacy `Ed25519` user address (may bind a PQ key in `AuthRegistry`) | | `0x01` | `ContractAddrByte` | `z1qxemdedded...` | Canonical Embedded Contract address | | **`0x02`** | **`PQUserAddrByte`** | **`z1z...` / `z1y...`** | **Native Post-Quantum user address** (`algID` ∈ `{0x01, 0x02, 0x03, 0x81}`) | :::info Required Helper Updates in `internal/types/address.go` & `ptlc.go` 1. Update `(a Address) IsUserAddress() bool` (`address.go:197`) from `a[0] == UserAddrByte` to: `a[0] == UserAddrByte || (pqSporkActive && a[0] == PQUserAddrByte)`. 2. Update `ptlc.IsPayableDestination(addr)` (`internal/vm/contracts/ptlc/ptlc.go:289`) to accept both `0x00` (if not sunset) and `0x02` user addresses. ::: --- ## 2. Canonical `0x02` Address Derivation Formula To prevent cross-algorithm preimage collisions, a `0x02` address hashes a domain-separated tag, the 1-byte `algID`, and the exact canonical public key encoding: ```text DomainTag = "zenon-pq-addr:v1" // 16 ASCII bytes Preimage = DomainTag || [algID] || pqPubKey // 17 + len(pqPubKey) bytes Digest = FIPS202_SHA3_256(Preimage) // 32 bytes Address[0] = 0x02 Address[1:] = Digest[0:19] // 19 bytes (152 bits) ``` | `algID` | Scheme | `len(pqPubKey)` | Exact `Preimage` Length | Allowed on `0x02` Address? | |:---:|---|---:|---:|:---:| | `0x01` | `ML-DSA-44` | `1,312 B` | `1,329 B` | Yes | | `0x02` | `FN-DSA-512` | `897 B` | `914 B` | Yes *(post-Phase 2)* | | `0x03` | `SLH-DSA-SHAKE-128s` | `32 B` | `49 B` | Yes | | `0x81` | `Hybrid Ed25519 + ML-DSA-44` | `32 + 1,312 = 1,344 B` | `1,361 B` | Yes | * **Bech32 vs. Bech32m Encoding:** `internal/types/address.go:175` (`ParseAddress`) **already accepts both BIP-173 Bech32 and BIP-350 Bech32m**, while `String()` emits canonical 40-character lowercase Bech32 (`z1...`) for full backwards compatibility with existing explorers and RPC clients. --- ## 3. In-Place Key Rotation via `AuthRegistryContract` ### Why Sending Funds to a New Address Is Insufficient on Zenon On Zenon Alphanet, four embedded contracts lock high-value state to an immutable `types.Address` that **cannot** be transferred via `UserSend`: 1. **`PillarContract` (`internal/vm/contracts/pillar/pillar.go:220`):** `UpdatePillar` rotates `BlockProducingAddress` and `RewardWithdrawAddress`, **but NEVER `StakeAddress`** (`15,000 ZNN` locked; revoking destroys the Pillar slot permanently!). 2. **`StakeContract` (`internal/vm/contracts/stake/stake.go`):** Time-locked ZNN stakes (`1` to `12` months) can only be cancelled after `expirationTime` by the original `Address`. 3. **`SentinelContract` (`5,000 ZNN + 50,000 QSR`):** Bound to the registering `Address`. 4. **`LiquidityContract` & Governance (`SporkAddress`, `BridgeInfo.Administrator`):** Bound to `0x00` addresses. ### `AuthRegistryContract` Specification Deploy **`AuthRegistryContract`** (`0x01` embedded class address `z1qxemdeddedxauthregystryxxxxxxxxxx...`) gated by `PostQuantumAccountsSpork`: ```json [ {"type":"function","name":"RotateKey","inputs":[ {"name":"algId","type":"uint8"}, {"name":"newPublicKey","type":"bytes"}, {"name":"newKeyPopSignature","type":"bytes"}, {"name":"revokeLegacy","type":"bool"} ]}, {"type":"function","name":"RescueWithPoKoS","inputs":[ {"name":"targetAddress","type":"address"}, {"name":"algId","type":"uint8"}, {"name":"newPublicKey","type":"bytes"}, {"name":"starkProof","type":"bytes"} ]}, {"type":"variable","name":"authRecord","inputs":[ {"name":"algId","type":"uint8"}, {"name":"publicKeyHash","type":"hash"}, {"name":"publicKey","type":"bytes"}, {"name":"legacyRevoked","type":"bool"}, {"name":"updatedHeight","type":"uint64"} ]} ] ``` #### Storage Layout Inside `AuthRegistryContract` (`[0x04]` Contract State) * **Key:** `[0x01] || userAddr[20]` (`21 bytes`) → ABI-packed `authRecord`. * **Proof of Possession (`newKeyPopSignature`):** Prevents a user from bricking their account by accidentally registering a corrupted `newPublicKey` for which they do not hold the secret key. `newKeyPopSignature` MUST verify under `(algId, newPublicKey)` over the 61-byte domain-separated digest: `SHA3-256("zenon-auth-rotate:v1" || be_u64(chainId) || sendBlock.Address[20] || be_u64(sendBlock.Height) || [algId])`. * **Immediate Legacy Lockout (`revokeLegacy = true`):** Once `AuthRegistryContract` executes `ReceiveBlock`, `legacyRevoked` becomes `true`. From the next Momentum onward, `accountBlockVerifier.signature` **rejects** `Ed25519` (`algID = 0x00`) on `userAddr`—even before the Phase 3 network-wide sunset! * **Zero-Exposure First Tx for Untouched `0x00` Accounts:** During Phase 1–2, an untouched `0x00` account (`Height = 1`) whose first block is a `UserSend` (or `UserReceive` followed immediately in the same Momentum by `RotateKey`) only exposes its `Ed25519` key for a single 10-second slot before `legacyRevoked = true` permanently locks out Shor attacks. --- ## 4. Deterministic `BIP-39` Key Derivation (Zero New Seed Phrases) Zenon wallets (`syrius`, `znn_cli_dart`, `go-zenon-v1/internal/crypto/slip0010.go`) currently derive `Ed25519` keys from a 24-word `BIP-39` mnemonic (`64-byte` PBKDF2-HMAC-SHA512 seed) along: ```text Classical Path: m / 44' / 73404' / ' (HMAC-SHA512 key = "ed25519 seed") ``` To guarantee **strict cryptographic domain separation** (so compromising a classical `SLIP-0010` child key or chain code leaks zero bits about any post-quantum key, even to an unbounded quantum adversary), post-quantum keys MUST use a dedicated master HMAC domain tag and purpose subtree: ```text Master Node: HMAC-SHA512(Key = "zenon-pq-slip0010:v1", Data = bip39Seed64) Derivation: m / 44' / 73404' / 1' / ' / ' ``` | `algId'` Segment | Target Scheme | Seed Extraction from 32-Byte Leaf `SLIP0010Key.Key` | |:---:|---|---| | `1'` (`0x80000001`) | `ML-DSA-44` | Pass `leaf.Key[0:32]` directly to `mldsa.NewPrivateKey(mldsa.MLDSA44(), leaf.Key[:])` | | `2'` (`0x80000002`) | `FN-DSA-512` | Expand `SHAKE256("zenon-fndsa512-keygen:v1" \|\| leaf.Key[:], 64)` into deterministic fixed-point FIPS 206 keygen | | `3'` (`0x80000003`) | `SLH-DSA-SHAKE-128s` | Expand `SHAKE256("zenon-slhdsa128s-keygen:v1" \|\| leaf.Key[:], 48)` → `(SK.seed[16], SK.prf[16], PK.seed[16])` | :::tip UX Win for Syrius Users Because all three post-quantum tiers derive deterministically from the exact same `bip39Seed64`, **existing Syrius users do not need to write down a new 24-word recovery phrase**. Restoring their existing mnemonic in a PQ-upgraded Syrius wallet automatically recovers both their legacy `0x00` accounts and their `0x02` / `AuthRegistry`-rotated PQ accounts! ::: ================================================================================ FILE: docs/specification/account-blocks-and-pk-caching.md | URL: https://0x3639.com/zenon-post-quantum/docs/specification/account-blocks-and-pk-caching ================================================================================ # `AccountBlock v2`, Witness Envelope & Public-Key Caching > **TL;DR:** Upgrade `AccountBlock.Version` from `1` to `2` on activation of `PostQuantumAccountsSpork`. Keep the `306-byte` `AccountBlock.ComputeHash()` preimage, Protobuf tags `1..23`, and RLP list arity **100% unchanged**. Prefix `Signature` (tag 23) and `PublicKey` (tag 22) with a 1-byte `algID`, cache each account's PQ `PublicKey` in `AccountStore` upon its first v2 block, and allow all subsequent blocks (`Height > 1`) to set `PublicKey = nil`—saving **`1,313 bytes`** per `ML-DSA-44` tx and **`898 bytes`** per `FN-DSA-512` tx. --- ## 1. Why `AccountBlock.ComputeHash()` Requires Zero Changes Inspecting `internal/nom/account_block.go:124-166` confirms that Zenon's `AccountBlock` hash is computed over a fixed `306-byte` stack buffer: ```text Bytes 0..8 : be_u64(Version) // 1 -> 2 post-Spork Bytes 8..16 : be_u64(ChainIdentifier) // 1 on Alphanet Bytes 16..24 : be_u64(BlockType) // 1..5 Bytes 24..56 : PreviousHash[32] Bytes 56..64 : be_u64(Height) Bytes 64..104 : MomentumAcknowledged[40] // Hash[32] || be_u64(Height) Bytes 104..124 : Address[20] Bytes 124..144 : ToAddress[20] Bytes 144..176 : Amount[32] Bytes 176..186 : TokenStandard[10] Bytes 186..218 : FromBlockHash[32] Bytes 218..250 : SHA3_256(DescendantHashes)[32] Bytes 250..282 : SHA3_256(Data)[32] Bytes 282..290 : be_u64(FusedPlasma) Bytes 290..298 : be_u64(Difficulty) Bytes 298..306 : Nonce[8] ``` `BasePlasma`, `TotalPlasma`, `ChangesHash`, **`PublicKey` (tag 22)**, and **`Signature` (tag 23)** are **excluded** from `ComputeHash()`. Both Protobuf (`SerializeProto` in `account_block.go:389-394`) and RLP (`EncodeRLP`) already encode `PublicKey` and `Signature` as arbitrary variable-length `[]byte` slices! --- ## 2. Canonical `algID` Witness Wire Envelope (`Version == 2`) In `AccountBlock` (`Version == 2`) and `Momentum` (`Version >= 3` or post-`PostQuantumConsensusSpork`), witness byte slices carry an explicit 1-byte algorithm tag at index `0`: ```text PublicKeyWire := []byte{} // Omitted when cached in AccountStore / AuthRegistry! OR [algID] || RawPublicKeyBytes SignatureWire := [algID] || RawSignatureBytes ``` ### Exact Byte-Length Validation Table (Consensus-Critical) Any deviation from the exact byte lengths below MUST return `vmerr.ErrABSignatureInvalid` (on `AccountBlock`) or `vmerr.ErrMSignatureInvalid` (on `Momentum`), **never** panicking and **never** returning `ErrVerifierInternal`: | `algID` | Constant | `len(PublicKeyWire)` (When Present) | `len(SignatureWire)` (Always Required on User Blocks) | Signing Domain Message | |:---:|---|---:|---:|---| | `0x00` | `AlgEd25519` | `1 + 32 = 33 B` *(or raw `32 B` in `v1`)* | `1 + 64 = 65 B` *(or raw `64 B` in `v1`)* | `block.Hash[:]` (`32 B`) | | **`0x01`** | **`AlgMLDSA44`** | **`1 + 1,312 = 1,313 B`** | **`1 + 2,420 = 2,421 B`** | `block.Hash[:]` with FIPS 204 `ctx = "zenon-ab:v2"` (`"zenon-mom:v2"` for Momentums) | | **`0x02`** | **`AlgFNDSA512`** | **`1 + 897 = 898 B`** | **`1 + 666 = 667 B`** | `"zenon-ab:v2" \|\| block.Hash[:]` | | **`0x03`** | **`AlgSLHDSA128s`** | **`1 + 32 = 33 B`** | **`1 + 7,856 = 7,857 B`** | `block.Hash[:]` with FIPS 205 `ctx = "zenon-ab:v2"` | | `0x81` | `AlgHybridEdMLDSA44` | `1 + 32 + 1,312 = 1,345 B` | `1 + 64 + 2,420 = 2,485 B` | Both `Ed25519` AND `ML-DSA-44` MUST verify | :::tip Built-in FIPS 204 / FIPS 205 Context String Domain Separation Both **FIPS 204 (`ML-DSA`)** and **FIPS 205 (`SLH-DSA`)** natively accept a domain-separation `context` string (`0..255` bytes) inside the standard `Verify(pk, msg, sig, &Options{Context: ...})` call! Passing `"zenon-ab:v2"` for `AccountBlock`s, `"zenon-mom:v2"` for `Momentum`s, `"zenon-ptlc:v2"` for `PTLC`, and `"zenon-bridge:v2"` for `Bridge` prevents cross-object signature replay across the entire protocol at zero extra hashing cost. ::: --- ## 3. Sequential Account-Chain Public-Key Caching ### State Storage Key in `AccountStore` In `go-zenon-v1/internal/chain/account_store.go`, each user/contract `AccountStore` namespaces keys under the account's 20-byte address inside `VersionedStore` (`nom` DB), automatically participating in `FlatOverlay` staging, `ChangesHash` (`Patch.Dump()`), and 30-block fork rollbacks (`Pop()`). Add a single per-account key: ```text PrefixAccountPubKey = [0x09] // Stores PublicKeyWire ([algID] || RawPublicKeyBytes) ``` ### Deterministic Resolution Order During Verification When verifying a user `AccountBlock` (`!types.IsEmbeddedAddress(block.Address)` and `block.Version == 2`): ```mermaid flowchart TD START["Verify User AccountBlock (Version == 2)"] --> AUTH{"AuthRegistry entry exists for block.Address?"} AUTH -- Yes --> USE_AUTH["ActiveKey = AuthRegistry[block.Address].PublicKey"] USE_AUTH --> PK_EMPTY1{"len(block.PublicKey) == 0?"} PK_EMPTY1 -- No --> ERR_MUST_OMIT["Reject: ErrABPublicKeyMustBeCached"] PK_EMPTY1 -- Yes --> VERIFY["Verify SignatureWire against ActiveKey"] AUTH -- No --> CACHE{"AccountStore[0x09] cached PK exists?"} CACHE -- Yes --> PK_EMPTY2{"len(block.PublicKey) == 0?"} PK_EMPTY2 -- No --> ERR_MUST_OMIT PK_EMPTY2 -- Yes --> VERIFY_CACHED["Verify SignatureWire against AccountStore[0x09]"] CACHE -- No --> HAS_PK{"len(block.PublicKey) > 0?"} HAS_PK -- No --> ERR_MISSING["Reject: ErrABPublicKeyMissing"] HAS_PK -- Yes --> DERIVE["Verify Address == DeriveAddress(block.PublicKey)"] DERIVE --> WRITE_CACHE["Write block.PublicKey to AccountStore[0x09]"] WRITE_CACHE --> VERIFY ``` 1. **Enforce Omission Once Cached (`ErrABPublicKeyMustBeCached`):** Once an account's public key is recorded in `AuthRegistry` or `AccountStore[0x09]`, subsequent blocks **MUST** set `block.PublicKey = nil` (`len == 0`). Forbidding redundant `1,312 B` public keys prevents malicious senders from wasting Momentum byte space or malleating uncommitted witness bytes. 2. **Rollback Safety:** Because `AccountStore[0x09]` is written inside the normal `AccountBlockTransaction` `storage.Patch`, rolling back a side-chain Momentum (`VersionedStore.Pop()`) automatically reverts `AccountStore[0x09]` if the `Height = 1` block is un-committed! --- ## 4. Preserving Lock-Free Stage-2 Parallel Pre-Verification A signature strength of `go-zenon-v1` (`internal/vm/verifier/account_block.go:81-108`) is **`PreverifyAccountBlock`**, which verifies `ComputeHash()`, `VerifyEd25519`, and `CheckPoWNonce` concurrently across `GOMAXPROCS` worker goroutines in **Stage 2** completely outside database locks. With Public-Key Caching (`len(block.PublicKey) == 0` for `Height > 1`), how does Stage 2 pre-verify a signature without holding a DB lock? * **`HotStateCache` Public-Key Lookup:** `go-zenon-v1` already maintains a lock-free 256-shard `128 MiB` `HotStateCache` (`internal/storage/hotcache.go`) alongside lock-free MVCC `*pebble.Snapshot` reads in **Stage 3 (Prefetch)**. * **Two-Path Stage-2 Preverify:** 1. If `len(block.PublicKey) > 0` (`Height == 1` block): Stage 2 verifies `SignatureWire` against `block.PublicKey` immediately with zero lookups. 2. If `len(block.PublicKey) == 0` (`Height > 1` block): Stage 2 probes the lock-free `HotStateCache` (keyed by `(Address, frontierEpoch)` or immutable `AccountStore[0x09]`). On cache hit (>99% of active accounts), Stage 2 verifies `ML-DSA-44` / `FN-DSA-512` across all CPU cores and records `resolvedPubKeyHash [32]byte` on `PreverifiedBlock` so Stage 4 (`accountBlockVerifier.signature`) simply checks `pv.resolvedPubKeyHash == activeKeyHash` in `O(1)`! --- ## 5. Updating `wrapIfBodyTampered` in `verifier/momentum.go` In `internal/vm/verifier/momentum.go:323-341`, `wrapIfBodyTampered` prevents a malicious P2P peer from getting a canonical `Momentum.Hash` blacklisted by mutating uncommitted witness fields inside a `DetailedMomentum` (`BlocksMsg 0x16` / `NewBlockMsg 0x17`): ```go // CURRENT v1 CODE (internal/vm/verifier/momentum.go:331): if blk.ComputeHash() != blk.Hash || len(blk.PublicKey) > 32 || len(blk.Signature) > 64 { return vmerr.UncommittedBodyError(err) } ``` When `AccountBlockVersion == 2` is active, update the upper-bound sanity guard from `32` / `64` to `crypto.MaxValidPubKeyWireLen(blk.Version)` (`1,345 B`) and `crypto.MaxValidSigWireLen(blk.Version)` (`7,857 B`)—and mark **any** `ErrABSignatureInvalid` / `ErrABPublicKeyMustBeCached` failure inside a `DetailedMomentum` body as `UncommittedBodyError` whenever `blk.Header() == m.Content[i]`! That preserves `go-zenon-v1`'s exact P4-04 peer-quarantine immunity under post-quantum witnesses. ================================================================================ FILE: docs/specification/dynamic-plasma-and-dos.md | URL: https://0x3639.com/zenon-post-quantum/docs/specification/dynamic-plasma-and-dos ================================================================================ # Dynamic Plasma Witness Pricing & DoS Hardening > **TL;DR:** In `go-zenon-v1/internal/pow/plasma.go:269`, `GetBasePlasmaForAccountBlock` currently charges `68` plasma/byte (`ABByteDataPlasma`) **only on `block.Data`**, charging **`0` plasma** for `block.PublicKey` and `block.Signature`. With 96-byte `Ed25519` witnesses, that omission was harmless. With `1.5 KB – 7.9 KB` post-quantum witnesses, zero-cost witness bytes allow an attacker to exhaust the `8.0 MiB` `MaxMomentumContentBytes` cap (`~1,060` blocks instead of `~27,000`) and bloat Pebble v2 storage for just `21,000` base plasma. Introducing **`GetWitnessPlasma`** closes this DoS vector cleanly. --- ## 1. Quantifying the Unpriced Witness Attack Vector Examine `GetBasePlasmaForAccountBlock` in `internal/pow/plasma.go:275-285`: ```go if block.IsReceiveBlock() { return AccountBlockBasePlasma, nil // Always 21,000 — ignores witness size! } if !types.IsEmbeddedAddress(block.ToAddress) { if len(block.Data) > MaxDataLength { return 0, ErrABDataTooBig } return AccountBlockBasePlasma + uint64(len(block.Data))*ABByteDataPlasma, nil } ``` And examine `verifyMomentumContent` in `internal/vm/verifier/momentum.go:385-435`: 1. A Momentum admits user blocks until `totalBasePlasma <= vars.MaxBasePlasmaInMomentum` (`4,200,000` default, tunable up to `2,100,000,000`) **AND** `totalProtoBytes <= MaxMomentumContentBytes` (`8,388,608 B`). 2. Dynamic Plasma (`pow.NextResourcePrice` in `internal/pow/dynamic_plasma.go`) adjusts `NextFusionPrice` (`P_F`) and `NextWorkPrice` (`P_W`) **strictly as a function of `usedFused` and `usedWork` base plasma**—it has **no visibility into `totalProtoBytes`** unless witness bytes contribute to `canonicalBase`! 3. If a `7,857-byte` `SLH-DSA-SHAKE-128s` `UserReceive` block costs the exact same `21,000` base plasma (`10` fused QSR) as a `667-byte` cached `FN-DSA-512` block: * It consumes **11.8× more wire bandwidth and disk space** and **40× more verifier CPU** at `0` marginal QSR/PoW cost. * Worse, if `MaxBasePlasmaInMomentum` is raised via `Plasma.SetVariables`, attackers can hit the hard `8 MiB` `MaxMomentumContentBytes` wall while `totalBasePlasma` remains below `FusedPlasmaTarget`—**preventing `NextFusionPrice` and `NextWorkPrice` from rising during congestion!** --- ## 2. Canonical Post-Quantum Witness Plasma Formula When `PostQuantumAccountsSpork` is active and `block.Version >= 2` (for non-embedded senders `!types.IsEmbeddedAddress(block.Address)`): ```text CanonicalBasePlasma(block) = LegacyBasePlasma(block) + WitnessPlasma(block) ``` Where `WitnessPlasma(block)` prices **both** marginal storage/bandwidth bytes above the 96-byte legacy `Ed25519` baseline **and** non-trivial verifier CPU cost: ```text WitnessBytes = len(block.PublicKey) + len(block.Signature) ExcessWitnessBytes = max(0, WitnessBytes - 96) ABWitnessBytePlasma = 17 // 25% of ABByteDataPlasma (68), reflecting SegWit-style 4:1 witness discount! VerifyComputePlasma(algID): 0x00 (Ed25519) -> 0 0x01 (ML-DSA-44) -> 2,100 (+1 QSR fusion unit) 0x02 (FN-DSA-512) -> 1,050 (+0.5 QSR fusion unit) 0x03 (SLH-DSA-SHAKE-128s) -> 42,000 (+20 QSR fusion units; ~1.8 ms Keccak tree verify) 0x81 (Hybrid Ed+MLDSA44) -> 3,150 (+1.5 QSR fusion units) WitnessPlasma(block) = ExcessWitnessBytes * ABWitnessBytePlasma + VerifyComputePlasma(algID) ``` ### Why `ABWitnessBytePlasma = 17` (4:1 SegWit Witness Ratio) Is Economically Ideal * `block.Data` (`68` plasma/byte) is hashed inside `ComputeHash()`, unpacked by the VM ABI decoder, and often persisted in embedded contract key-value state (`Pebble` state trie). * Witness bytes (`PublicKey` + `Signature`) are **never** parsed by embedded contracts, **excluded** from `ComputeHash()`, and prunable after finality—matching Bitcoin SegWit's exact `1:4` witness-to-calldata weight discount (`68 / 4 = 17` plasma/byte)! --- ## 3. Resulting Plasma & QSR Fusion Schedule Across Schemes Recall `PlasmaPerFusionUnit = 2,100` (`1` fused QSR = `2,100` plasma; minimum account fusion `FuseMinAmount = 10 QSR` = `21,000` plasma) and `PoWDifficultyPerPlasma = 1,500`: | Transaction Type & Scheme | `WitnessBytes` | `LegacyBase` | `WitnessPlasma` | **Total `CanonicalBase`** | Equivalent Fused QSR (at `1.0×` Price) | |---|---:|---:|---:|---:|---:| | `Ed25519` Send / Receive *(v1 baseline)* | `96 B` | `21,000` | `0` | **`21,000`** | **`10.0 QSR`** | | **`FN-DSA-512` (PK Cached, `H > 1`)** | **`667 B`** | `21,000` | `10,757` | **`31,757`** | **`~15.2 QSR`** | | `FN-DSA-512` *(1st Tx w/ PK, `H = 1`)* | `1,565 B` | `21,000` | `26,023` | **`47,023`** | **`~22.4 QSR`** | | **`ML-DSA-44` (PK Cached, `H > 1`)** | **`2,421 B`** | `21,000` | `41,625` | **`62,625`** | **`~29.9 QSR`** | | `ML-DSA-44` *(1st Tx w/ PK, `H = 1`)* | `3,734 B` | `21,000` | `63,946` | **`84,946`** | **`~40.5 QSR`** | | `ML-DSA-44` `Pillar.Delegate()` *(Cached)* | `2,421 B` | `52,500` | `41,625` | **`94,125`** | **`~44.9 QSR`** | | **`SLH-DSA-SHAKE-128s` Vault Tx** | **`7,857 B`** | `21,000` | `173,937` | **`194,937`** | **`~92.9 QSR`** | --- ## 4. Consensus Invariants Preserved by This Formula 1. **Client PoW FallbackStill Works Without QSR:** Post-`DynamicPlasmaSpork`, `PostDPMaxPoWPlasmaForAccountBlock = 210,000,000,000` (`internal/pow/plasma.go:39`). Even a zero-QSR user onboarding their very first `ML-DSA-44` (`84,946` plasma) or `SLH-DSA-128s` (`194,937` plasma) transaction can generate client PoW (`difficulty = plasma * 1,500`, ~0.15s–0.35s on modern desktop/mobile cores)! 2. **Strong Economic Incentive to Cache Public Keys:** Omitting `PublicKey` after `Height = 1` saves **`22,321` plasma (`~10.6 QSR`)** on every `ML-DSA-44` block and **`15,266` plasma (`~7.3 QSR`)** on every `FN-DSA-512` block. 3. **Dynamic Plasma Controller Remains Saturation-Proof:** At `DefaultMaxBasePlasmaInMomentum = 4,200,000`: * Max `SLH-DSA-128s` blocks per Momentum = `floor(4,200,000 / 194,937) = 21` blocks (`~170 KB` wire size, `~38 ms` verify time on 1 core / `~5 ms` on 8 cores). * Max cached `ML-DSA-44` blocks per Momentum = `floor(4,200,000 / 62,625) = 67` blocks (or raise `DefaultMaxBasePlasmaInMomentum` via `Plasma.SetVariables` from `4,200,000` → **`12,600,000`** on Spork activation to preserve the exact **200 cached `ML-DSA-44` user blocks/Momentum** throughput target while staying at just `6.5%` of `MaxMomentumContentBytes`!). :::info Determinism Rule for `GetBasePlasmaForAccountBlock` Notice that `GetBasePlasmaForAccountBlock(blk, mask)` (`internal/pow/plasma.go:269`) is a **pure stateless function** of `blk` and `sporkMask`—called both in mempool admission and in `verifyMomentumContent` (`internal/vm/verifier/momentum.go:419`). Because `blk.Signature[0]` always carries `algID` (`len(blk.Signature) >= 1` for user blocks) and `len(blk.PublicKey)` + `len(blk.Signature)` are right on `blk`, `WitnessPlasma(blk)` remains **100% stateless with zero DB reads**! ::: ================================================================================ FILE: docs/specification/consensus-bridge-ptlc-p2p.md | URL: https://0x3639.com/zenon-post-quantum/docs/specification/consensus-bridge-ptlc-p2p ================================================================================ # Consensus, Embedded Contracts & P2P Hardening > **TL;DR:** Upgrading user `AccountBlock`s is necessary but not sufficient. A complete post-quantum Zenon upgrade must also transition **Pillar `Momentum` seals** (and future `MomentumVersionV3` Narwhal/Tusk certificates), replace single-key `secp256k1` TSS ECDSA in **`BridgeContract`** with a `t-of-n` Guardian `ML-DSA-44` quorum, deprecate discrete-log **`PtlcContract`** point locks in favor of `SHA3-256` `HTLC`s and PQ signature locks, sunset **`Pillar.RegisterLegacy`**, and upgrade **`go-libp2p`** stream handshakes to hybrid `X25519 + ML-KEM-768`. --- ## 1. Pillar `Momentum` Signing & Narwhal/Tusk BFT (`MomentumVersionV3`) ### `LegacyDposV1` (10-Second Single-Leader Momentums) In `internal/consensus/engine/legacy_dpos.go:274-306` and `internal/vm/verifier/momentum.go:87-114`: * Every 10 seconds, the elected slot Pillar signs `m.Hash` (`32 B`) using its `BlockProducingAddress` keypair. * Fortunately, **`Pillar.UpdatePillar` (`internal/vm/contracts/pillar/pillar.go:82-88`) ALREADY allows every Pillar operator to hot-swap `producerAddress` on-chain** without revoking their Pillar or touching their cold `StakeAddress`! * **Upgrade Rule (`PostQuantumConsensusSpork`):** 1. Pillar operators generate a fresh `0x02` `ML-DSA-44` (or `FN-DSA-512`) producing keypair on their validator node (`znnd`) and submit `Pillar.UpdatePillar(..., newPQProducerAddr, ...)`. 2. `Momentum.PublicKey` (tag 10) carries `[algID] || RawPublicKeyBytes` (`1,313 B` for `ML-DSA-44` or `898 B` for `FN-DSA-512`), and `Momentum.Signature` (tag 11) carries `[algID] || RawSignatureBytes` (`2,421 B` or `667 B`). 3. After a grace window (e.g., `30` epochs = 30 days), `VerifyMomentumStatic` rejects `algID == 0x00` (`Ed25519`) on `Momentum` headers—securing 100% of block production against Shor's algorithm. ### Future `MomentumVersionV3`: Narwhal & Tusk DAG-BFT (`internal/consensus/engine/seam.go`) `go-zenon-v1` defines the consensus seam for **Narwhal & Tusk** (`seam.go:189-236`), where a `Certificate` attests `2f+1` stake-weighted Pillar signatures over a `VertexHeader`. :::tip Why Zenon Should NOT Use BLS12-381 or Complex STARK Vote Aggregation Classical Narwhal/HotStuff implementations use `BLS12-381` aggregate signatures, which are **completely broken by Shor's algorithm**. Meanwhile, Ethereum's Lean Consensus needs heavy STARK-aggregated XMSS proofs only because Ethereum has ~1,000,000 validators per epoch. Zenon elects **`NodeCount = 30` Pillars per tick (`2f+1 = 21` signers)** (`internal/common/params.go:280`)! ::: With `NodeCount = 30`, a simple **concatenated multi-signature + 32-bit signer bitmask** (storing Pillar producing public keys in `ElectionData` so certificates omit public keys) is tiny and verifies in under `1 ms` across 8 cores: | BFT Certificate Scheme (`21` of `30` Pillars) | Certificate `Signature` Size | Parallel Verify Latency (8 Cores) | Pairing / Lattice Assumptions | |---|---:|---:|---| | **`FN-DSA-512` (`algID = 0x02`)** | **`4 B bitmap + 21 × 666 B = 13,990 B (~13.7 KiB)`** | **`~0.10 ms`** | NTRU Lattice (FIPS 206) | | **`ML-DSA-44` (`algID = 0x01`)** | **`4 B bitmap + 21 × 2,420 B = 50,824 B (~49.6 KiB)`** | **`~0.14 ms`** | Module-LWE (FIPS 204, Go 1.26 stdlib) | | Epoch-Bound `XMSS-SHAKE_14_256` (`2^14` sigs/day) | `4 B bitmap + 21 × 2,692 B = 56,536 B (~55.2 KiB)` | `~1.10 ms` | **Pure SHAKE256 (Zero Lattice!)** | --- ## 2. `BridgeContract`: From `secp256k1` TSS to `t-of-n` PQ Guardian Quorum In `internal/vm/contracts/bridge/methods_bridge.go:215-249, 330-383`: * `UpdateWrapRequest` and `UnwrapToken` currently verify a single 65-byte recoverable `secp256k1` ECDSA signature (`maxECDSASigBase64Len = 88`) against `BridgeInfo.DecompressedTssECDSAPubKey`. * While post-quantum threshold lattice MPC (`TRaccoon` / threshold `ML-DSA`) is an active NIST MPTC standardization area, multi-party lattice signing ceremonies carry complex abort/noise-flooding state and larger communication rounds than classical GG20/FROST. * Look at `internal/common/params.go:412-413`: Zenon's `BridgeContract` **already bounds Guardians to `MinGuardians = 5 .. MaxGuardiansPostDP = 30`**! ### Recommended Bridge Upgrade (`Bridge.UnwrapTokenPQ` / `SetBridgePQGuardians`) 1. Register an ordered list of up to `N <= 30` Orchestrator/Guardian `ML-DSA-44` public keys (`[0x09]` storage prefix in `BridgeContract`) with threshold `T = floor(2*N/3) + 1` (e.g., `11-of-15` or `21-of-30`). 2. **Inbound (`UnwrapTokenPQ` — External Chain → Zenon):** Guardians independently verify the external chain lock event and produce deterministic `ML-DSA-44` signatures over `UnwrapMessageHash` (`ctx = "zenon-bridge:v2"`). A `15-of-22` quorum witness (`4 B bitmap + 15 × 2,420 B = 36,304 B`, or `15 × 666 B = 9,994 B` with `FN-DSA-512`) fits inside a single `AccountBlock` (raising `MaxDataLength` from `16 KiB` to `64 KiB` for `BridgeContract`, or preferring `FN-DSA-512` which fits inside the existing **`16,384-byte` `MaxDataLength`** with 6 KiB to spare!). 3. **Outbound (`WrapToken` — Zenon → External Chain):** Outbound signature format is dictated by the *destination* chain's smart contract (e.g., ECDSA until Ethereum/BNB deploy `EIP-8051`/`EIP-8052` precompiles, at which point `UpdateWrapRequestPQ` stores the PQ quorum signature). --- ## 3. `PtlcContract`, `HtlcContract` & Legacy `SwapContract` ### `PtlcContract` (`internal/vm/contracts/ptlc/ptlc.go:29-33`) Currently supports three `pointType`s: * `0`: `PointTypeEd25519` (`32 B` lock, `64 B` sig) * `1`: `PointTypeBIP340` (`32 B` x-only lock, `64 B` Schnorr sig) * `2`: `PointTypeSecp256k1Point` (`33 B` compressed point `[k]G`, unlocked by revealing scalar `k`) **Post-Quantum Action:** 1. **Cross-Chain Atomic Swaps → Use `HtlcContract`:** `PointTypeSecp256k1Point` (`[k]G` scalar adapter lock) relies directly on discrete-log hardness and has no drop-in compact stateless equivalent without lattice adaptor proofs (~40+ KB). By contrast, **`HtlcContract` (`internal/vm/contracts/htlc/htlc.go`)** uses 32-byte `SHA3-256` / `SHA-256` preimages, which already provide **128-bit post-quantum security** against Grover's algorithm! 2. **Signature-Locked Escrows → Add `PointType` `3` & `4`:** Add `PointTypeMLDSA44 = 3` (`32 B` `SHA3-256(pk)` lock commitment, witness = `pk[1312] || sig[2420]`) and `PointTypeFNDSA512 = 4` (`32 B` `SHA3-256(pk)` lock commitment, witness = `pk[897] || sig[666]`) to `PtlcContract`, keeping storage records `ptlcInfo` compact (`32 B` lock!) regardless of PQ public-key size. 3. **Phase 3 Sunset:** Reject `Create` / `CreateWithReclaimLock` for `pointType` ∈ `{0, 1, 2}` once `LegacyCryptoSunsetSpork` activates. ### `SwapContract` & `Pillar.RegisterLegacy` * **`SwapContract` (`internal/vm/contracts/swap/swap.go:205-228`):** `DecayPercentage(epoch)` **already reached `0%` at `epoch >= 389`** (~1 year after Alphanet Genesis). Even if a CRQC forges a legacy Bitcoin-style `secp256k1` signature in `Swap.RetrieveAssets`, `znnOut` and `qsrOut` evaluate to **`0`**! * **`Pillar.RegisterLegacy` (`internal/vm/contracts/pillar/pillar.go:38, 73`):** Still checks `PrefixLegacyPillarEntry` (`[0x03] || keyIdHash`) via `secp256k1` signature recovery. Sunset `SelectorRegisterLegacy` (`0xe4588207`) in Phase 3 so unclaimed legacy `.znn` swap entries cannot be hijacked to mint discounted Pillar slots. --- ## 4. P2P Transport (`go-libp2p` & `RLPx` Retirement) In `internal/p2p/libp2p/server.go:26, 65-95` and `internal/p2p/legacy/rlpx.go`: 1. **Retire Legacy DevP2P `RLPx` (`secp256k1` ECIES):** Now that `Libp2pSpork` is active on Alphanet, deprecate legacy `enode://` `RLPx` and `discv4` completely. 2. **Upgrade Stream Security to Hybrid `X25519 + ML-KEM-768`:** Go 1.26's standard library includes **`crypto/mlkem`** (`mlkem.GenerateKey768()`, `X25519MLKEM768` in `crypto/tls`). Configure `go-libp2p` TLS 1.3 (`libp2p-tls` with Go 1.26 default `X25519MLKEM768` curve preferences) or PQ-Noise (`Noise_XX_25519_MLKEM768`) so all `/znn/eth/1` and `/znn/kad/1.0.0` traffic is immediately immune to **Harvest-Now-Decrypt-Later** recording. 3. **Post-Quantum Peer Identity (`peer.ID`):** `NodeIDFromPeerID` (`server.go:75`) currently enforces `pub.Type() == lp2pcrypto.Secp256k1` to map onto legacy 64-byte `p2p.NodeID`. Decouple internal peer tracking (`peer.ID` multihash string) from 64-byte uncompressed `secp256k1` coordinates, and register a multicodec `ML-DSA-44` host identity key (`network-pq-private-key`, `32-byte` seed) so Sentinels and Pillar sentry nodes cannot be MITM-impersonated by a CRQC. ================================================================================ FILE: docs/migration/spork-roadmap-and-pokos.md | URL: https://0x3639.com/zenon-post-quantum/docs/migration/spork-roadmap-and-pokos ================================================================================ # 3-Phase Spork Rollout & `Ed25519-PoKoS` Seed Rescue > **TL;DR:** Zenon's on-chain `SporkContract` (`z1qxemdeddedxsp0rkxxxxxxxxxxxxxxxx956u48`) allows a zero-hard-fork-drama, three-phase migration: > 1. **Phase 1 (`PostQuantumAccountsSpork`)** enables `0x02` PQ addresses, `ML-DSA-44` (`0x01`) + `SLH-DSA-SHAKE-128s` (`0x03`), `AuthRegistry` in-place key rotation on `0x00` accounts, Account-Chain PK caching, and Witness Plasma pricing. > 2. **Phase 2 (`PostQuantumConsensusSpork`)** adds `FN-DSA-512` (`0x02`), transitions Pillar `Momentum` producers off `Ed25519`, upgrades `BridgeContract` to `t-of-n` PQ Guardians, and enables `X25519MLKEM768` on `go-libp2p`. > 3. **Phase 3 (`LegacyCryptoSunsetSpork`)** disables raw `Ed25519`/`secp256k1` verification across the entire ledger while keeping **`AuthRegistry.RescueWithPoKoS`** open permanently—allowing any dormant user who still holds their 24-word `BIP-39` mnemonic to recover unmigrated `0x00` funds safely even *after* quantum computers break `Ed25519`. --- ## 1. Three-Phase Spork Activation Schedule ```mermaid flowchart LR P0["Alphanet Today (8 Sporks)"] --> P1["Phase 1: PostQuantumAccountsSpork"] P1 --> P2["Phase 2: PostQuantumConsensusSpork"] P2 --> P3["Phase 3: LegacyCryptoSunsetSpork"] P1 --- D1["AccountBlock v2, 0x02 Addr, ML-DSA-44, SLH-DSA-128s, AuthRegistry, Witness Plasma"] P2 --- D2["FN-DSA-512, Pillar Momentum Rotation, t-of-n PQ Bridge, libp2p ML-KEM-768"] P3 --- D3["Disable Raw Ed25519 & secp256k1; Enable STARK Ed25519-PoKoS Seed Rescue"] ``` | Spork Bit | Spork Name | Consensus & State Rules Activated (`EnforcementDelay = 6` Momentums) | |:---:|---|---| | **Bit 5** (`9th`) | `PostQuantumAccountsSpork` | • Accept `AccountBlock.Version` ∈ `{1, 2}`
• Enable `0x02` PQ user addresses (`ML-DSA-44`, `SLH-DSA-SHAKE-128s`, Hybrid `0x81`)
• Deploy `AuthRegistryContract` (`RotateKey` with `revokeLegacy` lockout)
• Activate `AccountStore[0x09]` Public-Key Caching & `ABWitnessBytePlasma = 17` surcharge
• Rotate `SporkAddress` and `BridgeInfo.Administrator` to `SLH-DSA-SHAKE-128s` (`0x03`) | | **Bit 6** (`10th`) | `PostQuantumConsensusSpork` | • Enable `FN-DSA-512` (`algID = 0x02`)
• Require Pillar `BlockProducingAddress`es to sign `Momentum`s with `algID` ∈ `{0x01, 0x02}` after 30-epoch migration window
• Enable `Bridge.UnwrapTokenPQ` (`t-of-n` Guardian `ML-DSA-44` / `FN-DSA-512` quorum) & `PTLC` types `3..4`
• Enforce `X25519MLKEM768` on `go-libp2p` and retire legacy DevP2P `RLPx` | | **Bit 7** (`11th`) | `LegacyCryptoSunsetSpork` | • Reject `AccountBlock.Version == 1` and `algID == 0x00` (`Ed25519`) across **all** `0x00` accounts
• Reject `PTLC` `pointType` ∈ `{0, 1, 2}` and `Pillar.RegisterLegacy`
• Enable **`AuthRegistry.RescueWithPoKoS`** (STARK seed-ownership proof) for unmigrated `0x00` accounts | --- ## 2. Solving the "Dormant Account Dilemma" with `Ed25519-PoKoS` Every blockchain transitioning off elliptic curves faces the **Bitcoin `BIP-361` dilemma**: * If you **never** disable `Ed25519` on unmigrated `0x00` accounts (`Height >= 1`), a CRQC eventually steals every dormant user's ZNN/QSR and crashes the market. * If you **permanently freeze** unmigrated `0x00` accounts at Phase 3, legitimate long-term holders (stakers, cold-storage users, estates) who missed the migration announcement lose their life savings. ### Why `BIP-39` + `SLIP-0010` + `RFC 8032` Creates a Quantum Trapdoor Asymmetry Look at how every standard Zenon wallet (`syrius`, `znn_cli_dart`, `go-zenon-v1/internal/crypto/slip0010.go` + `ed25519.go`) derives an `Ed25519` public key from a 24-word mnemonic: ```text Step 1 (BIP-39): seed64 = PBKDF2_HMAC_SHA512(mnemonic, "mnemonic" || passphrase, 2048) Step 2 (SLIP-0010): master = HMAC_SHA512("ed25519 seed", seed64) child_0 = HMAC_SHA512(master.ChainCode, 0x00 || master.Key || 0x8000002c) // 44' child_1 = HMAC_SHA512(child_0.ChainCode, 0x00 || child_0.Key || 0x80011ebc) // 73404' leaf = HMAC_SHA512(child_1.ChainCode, 0x00 || child_1.Key || (0x80000000 + idx)) Step 3 (RFC 8032): h512 = SHA512(leaf.Key[0:32]) scalar_s = Clamp25519(h512[0:32]) pubKey_A = CompressEdwards([scalar_s] * B) Step 4 (Zenon): addr20 = 0x00 || FIPS202_SHA3_256(pubKey_A)[0:19] ``` **Observe where Shor's algorithm stops:** * Given `pubKey_A` on-chain, a quantum computer running Shor's algorithm **easily recovers `scalar_s`** (inverting Step 3's scalar multiplication `[scalar_s] * B`). * **HOWEVER, a quantum computer CANNOT invert `SHA512(leaf.Key[0:32])` to find `leaf.Key`!** `SHA-512` preimage search requires `2^128+` Grover work over a 512-bit state (completely infeasible). * Therefore: * **Quantum Attacker:** Knows `scalar_s` and `pubKey_A`, **does NOT know `leaf.Key`**. * **Rightful Wallet Owner:** Holds the 24-word mnemonic, therefore **knows `leaf.Key`** (and `child_1` if stricter path provenance is desired)! --- ## 3. Exact `Ed25519-PoKoS` Relation on Zenon `AuthRegistry.RescueWithPoKoS(targetAddress, algId, newPublicKey, starkProof)` verifies a **post-quantum hash-based STARK proof** (`FRI` over Goldilocks/Mersenne31/KoalaBear field using `SHA3-256` / `Poseidon2` Merkle commitments—**zero elliptic curves or pairings!**) proving the NP relation `R_PoKoS`: ### Public Inputs (`x`) * `chainId`: `uint64` (`1` on Alphanet) * `targetAddress`: `20-byte` `0x00` Zenon address (`authRecord` MUST NOT already exist) * `newKeyDigest`: `SHA3-256([algId] || newPublicKey)` (`32 bytes` — binds the proof non-malleably to the exact destination PQ key so mempool front-runners cannot steal the proof!) ### Private Witness (`w` — Never Revealed On-Chain) * `leafSeed32`: `32-byte` `SLIP-0010` leaf key (`leaf.Key[0:32]`) ### Circuit Constraints Verified Inside the STARK 1. Compute `h = SHA-512(leafSeed32)`. 2. Clamp `s = h[0:32]` per RFC 8032 (`s[0] &= 248`, `s[31] &= 127`, `s[31] |= 64`). 3. Compute fixed-base Edwards25519 scalar multiplication `A = [s]B` over `GF(2^255 - 19)` and encode compressed 32-byte `pubKey_A`. 4. Compute `derivedAddr = 0x00 || SHA3-256(pubKey_A)[0:19]` and assert `derivedAddr == targetAddress`. 5. Bind `newKeyDigest` into the Fiat-Shamir transcript challenge so the proof is valid **only** for `(chainId, targetAddress, newKeyDigest)`. :::warning Hardware Wallet & Raw-Seed Caveat 1. **Standard BIP-39 / Syrius / Ledger / CLI Wallets:** 100% compatible with `RescueWithPoKoS`, because RFC 8032 always hashes a 32-byte seed `leafSeed32` through `SHA-512` before clamping `scalar_s`. Only the single `SHA-512` + `[s]B` + `SHA3-256` step needs to be proven (~`45,000` Plonky3/Starky trace rows; proof size `~65–110 KB`, client prove time `~0.8s`, validator verify time `~2.5 ms`). 2. **Non-Standard "Raw Clamped Scalar" Keys:** Any custom tool that bypassed RFC 8032 seed hashing and generated a bare scalar `s` directly without a pre-`SHA-512` 32-byte seed MUST migrate via `AuthRegistry.RotateKey` during Phase 1 or Phase 2 (before `LegacyCryptoSunsetSpork`). ::: ================================================================================ FILE: docs/migration/go-zenon-v1-blueprint.md | URL: https://0x3639.com/zenon-post-quantum/docs/migration/go-zenon-v1-blueprint ================================================================================ # `go-zenon-v1` LLM Implementation Blueprint (`Go 1.26`) > **Audience:** Starts with the **acyclic package map (`L0`–`L9`)** for human maintainers, followed by an **8-stage, file-by-file AI coding agent refactoring blueprint** with ready-to-compile Go 1.26 `crypto/mldsa` and `crypto/mlkem` implementations, error-precedence rules, cross-client notes (`zenon-rs` & `syrius`), and **Bend 2.0.40 + Lean 4.34.0** proof laws. --- ## Ground-Truth Impact Map Across `go-zenon-v1` (`L0`–`L9`) `go-zenon-v1` enforces a strictly acyclic `L0` → `L9` package DAG (`OWNERSHIP.tsv`). Every post-quantum addition fits cleanly inside existing layers **without introducing a single new external `go.mod` dependency** for Phase 1 (`ML-DSA-44`, `SLH-DSA-SHAKE-128s`, and `ML-KEM-768` all build on Go 1.26 stdlib + `internal/crypto/keccak.go`): | Layer | Package Path | Files Added / Modified | Responsibility | |:---:|---|---|---| | **L0** | `internal/common` | `params.go` | Add `PostQuantumAccountsSporkID`, `PostQuantumConsensusSporkID`, `LegacyCryptoSunsetSporkID`, `AccountBlockVersionV2 = 2`, `ABWitnessBytePlasma = 17` | | **L1** | `internal/crypto` | `pq.go` *(new)*, `mldsa.go` *(new)*, `slhdsa.go` *(new)*, `slip0010_pq.go` *(new)* | `AlgID` dispatch, Go 1.26 `crypto/mldsa` wrapper, pure-Keccak `SLH-DSA-SHAKE-128s`, domain-separated PQ `SLIP-0010` KDF | | **L2** | `internal/types` | `address.go` | Add `PQUserAddrByte = 0x02`, `PQPubKeyToAddress(algID, rawPub)`, era-gated `IsUserAddress` | | **L3** | `internal/nom` | `account_block.go`, `momentum.go` | Zero wire changes needed; add helper methods `SigAlgID() (uint8, bool)` | | **L4** | `internal/pow` | `plasma.go` | Add stateless `WitnessPlasma(block)` inside `GetBasePlasmaForAccountBlock` when `hasPQAccounts && block.Version >= 2` | | **L5** | `internal/chain` | `account_store.go`, `spork_index.go` | Add `PrefixAccountPubKey = 0x09` (`GetCachedPubKey` / `SetCachedPubKey`) + `HotStateCache` pubkey slot | | **L6** | `internal/vm` | `contracts/auth/` *(new)*, `contracts/ptlc/ptlc.go`, `contracts/bridge/`, `verifier/account_block.go`, `verifier/momentum.go` | `AuthRegistryContract`, Stage-2 `PreverifyAccountBlock` PQ dispatch, `AccountStore[0x09]` enforcement, `wrapIfBodyTampered` bounds, `PTLC` types `3..4`, `Bridge` PQ Guardian quorum | | **L7** | `internal/p2p` | `libp2p/server.go`, `switcher/switcher.go` | Enable hybrid `X25519MLKEM768` stream security via Go 1.26 `crypto/tls` / `crypto/mlkem`; sunset `RLPx` | | **L8** | `internal/wallet`, `internal/rpc` | `keystore.go`, `manager.go`, `api_embedded_ext.go` | Derive `m/44'/73404'/1'/alg'/idx'`, sign `Version = 2` blocks, expose `embedded.auth.*` JSON-RPC methods | --- ## Detailed AI / LLM Coding Blueprint (`go-zenon-v1`) :::info Instructions for an AI Coding Agent Modifying `go-zenon-v1` Execute **Stages 1 through 8 strictly in order**, one commit/PR per stage. After **every** stage, run: 1. `CGO_ENABLED=0 go test -race ./...` 2. Historical Alphanet replay & golden wire tests (`go test ./internal/nom/... ./internal/vm/... ./test/fuzz/...`) 3. `test/bend/run.sh` (verifying zero regressions on all 300 existing Alphanet laws). **Hard Consensus Invariants (NEVER violate):** 1. Pre-Spork blocks (`Version == 1`, `momentumHeight` prior to `PostQuantumAccountsSpork` enforcement) MUST execute **bit-for-bit identically** to Alphanet (`ChangesHash`, error strings, and error precedence). 2. `VerifyPQ` and `ParsePQPublicKey` MUST **never panic** on arbitrary malformed or truncated P2P/RPC byte slices; invalid lengths or encodings ALWAYS map to `vmerr.ErrABSignatureInvalid` / `vmerr.ErrMSignatureInvalid` (never `ErrVerifierInternal`). 3. `GetBasePlasmaForAccountBlock` MUST remain 100% stateless (zero DB reads). 4. Preserve `CGO_ENABLED=0` across all targets except `cmd/libznn`. ::: --- ### Stage 1: Add `internal/crypto/mldsa.go` & `pq.go` Using Go 1.26 `crypto/mldsa` Create `internal/crypto/pq.go` and `internal/crypto/mldsa.go` wrapping Go 1.26's standard library `crypto/mldsa` with strict length guards and FIPS 204 domain-separation contexts: ```go title="internal/crypto/pq.go" package crypto import ( "crypto/ed25519" "crypto/mldsa" "errors" ) const ( AlgEd25519 uint8 = 0x00 AlgMLDSA44 uint8 = 0x01 AlgFNDSA512 uint8 = 0x02 AlgSLHDSA128s uint8 = 0x03 AlgHybridEdMLDSA44 uint8 = 0x81 MLDSA44PubKeySize = 1312 MLDSA44SigSize = 2420 MLDSA44SeedSize = mldsa.PrivateKeySize // 32 bytes FNDSA512PubKeySize = 897 FNDSA512SigSize = 666 SLHDSA128sPubKeySize = 32 SLHDSA128sSigSize = 7856 DomainAccountBlockV2 = "zenon-ab:v2" DomainMomentumV2 = "zenon-mom:v2" DomainAuthRotateV1 = "zenon-auth-rotate:v1" DomainPtlcV2 = "zenon-ptlc:v2" DomainBridgeV2 = "zenon-bridge:v2" ) var ( ErrUnsupportedSigAlg = errors.New("crypto: unsupported signature algorithm") ErrInvalidPQKeyLen = errors.New("crypto: invalid post-quantum public key length") ErrInvalidPQSigLen = errors.New("crypto: invalid post-quantum signature length") ) // ExpectedWireLengths returns exact (len(PublicKeyWire), len(SignatureWire)) including the 1-byte algID prefix. func ExpectedWireLengths(algID uint8) (pkWireLen, sigWireLen int, ok bool) { switch algID { case AlgEd25519: return 1 + ed25519.PublicKeySize, 1 + ed25519.SignatureSize, true case AlgMLDSA44: return 1 + MLDSA44PubKeySize, 1 + MLDSA44SigSize, true case AlgFNDSA512: return 1 + FNDSA512PubKeySize, 1 + FNDSA512SigSize, true case AlgSLHDSA128s: return 1 + SLHDSA128sPubKeySize, 1 + SLHDSA128sSigSize, true case AlgHybridEdMLDSA44: return 1 + ed25519.PublicKeySize + MLDSA44PubKeySize, 1 + ed25519.SignatureSize + MLDSA44SigSize, true default: return 0, 0, false } } // VerifyWire verifies sigWire ([algID] || rawSig) against pubWire ([algID] || rawPub) over msg with domainCtx. // Never panics on malformed inputs. func VerifyWire(pubWire, msg, sigWire []byte, domainCtx string) bool { if len(pubWire) == 0 || len(sigWire) == 0 || pubWire[0] != sigWire[0] { return false } algID := sigWire[0] wantPK, wantSig, ok := ExpectedWireLengths(algID) if !ok || len(pubWire) != wantPK || len(sigWire) != wantSig { return false } rawPub := pubWire[1:] rawSig := sigWire[1:] switch algID { case AlgEd25519: return VerifyEd25519(rawPub, msg, rawSig) case AlgMLDSA44: return VerifyMLDSA44(rawPub, msg, rawSig, domainCtx) case AlgHybridEdMLDSA44: return VerifyEd25519(rawPub[:32], msg, rawSig[:64]) && VerifyMLDSA44(rawPub[32:], msg, rawSig[64:], domainCtx) case AlgSLHDSA128s: return VerifySLHDSA128s(rawPub, msg, rawSig, domainCtx) case AlgFNDSA512: return VerifyFNDSA512(rawPub, msg, rawSig, domainCtx) default: return false } } ``` ```go title="internal/crypto/mldsa.go" package crypto import "crypto/mldsa" // MLDSA44KeyPairFromSeed derives a deterministic FIPS 204 ML-DSA-44 keypair from a 32-byte seed. func MLDSA44KeyPairFromSeed(seed32 []byte) (rawPub []byte, priv *mldsa.PrivateKey, err error) { if len(seed32) != MLDSA44SeedSize { return nil, nil, ErrInvalidPQKeyLen } sk, err := mldsa.NewPrivateKey(mldsa.MLDSA44(), seed32) if err != nil { return nil, nil, err } return sk.PublicKey().Bytes(), sk, nil } // SignMLDSA44Deterministic computes a deterministic 2,420-byte FIPS 204 ML-DSA-44 signature. func SignMLDSA44Deterministic(sk *mldsa.PrivateKey, msg []byte, domainCtx string) ([]byte, error) { return sk.Sign(nil, msg, &mldsa.Options{ Context: domainCtx, Deterministic: true, }) } // VerifyMLDSA44 verifies a 2,420-byte ML-DSA-44 signature against a 1,312-byte public key. func VerifyMLDSA44(rawPub, msg, rawSig []byte, domainCtx string) bool { if len(rawPub) != MLDSA44PubKeySize || len(rawSig) != MLDSA44SigSize { return false } pk, err := mldsa.NewPublicKey(mldsa.MLDSA44(), rawPub) if err != nil { return false } return mldsa.Verify(pk, msg, rawSig, &mldsa.Options{Context: domainCtx}) == nil } ``` --- ### Stage 2: Add Domain-Separated PQ `SLIP-0010` Derivation (`internal/crypto/slip0010_pq.go`) 1. Define `var slip0010PQSeedKey = []byte("zenon-pq-slip0010:v1")` (never reusing `"ed25519 seed"`). 2. Implement `DeriveZenonPQKey(bip39Seed []byte, algID uint8, accountIndex uint32) (SLIP0010Key, error)` deriving hardened path `m / 44' / 73404' / 1' / uint32(algID)' / accountIndex'`. 3. Scrub all intermediate `SLIP0010Key` and `HMAC-SHA512` stack buffers with `clear(...)` matching `internal/crypto/slip0010.go:46`. --- ### Stage 3: Add `0x02` `PQUserAddrByte` to `internal/types/address.go` 1. Add `PQUserAddrByte byte = 0x02`. 2. Add `PQPubKeyToAddress(pubWire []byte) (Address, error)`: * Reject `len(pubWire) == 0` or `pubWire[0] == AlgEd25519` (`0x00` keys belong exclusively to `0x00` addresses). * Validate `len(pubWire)` against `crypto.ExpectedWireLengths(pubWire[0])`. * Hash `"zenon-pq-addr:v1" || pubWire` with `crypto.SHA3256` and return `[0x02] || sum[0:19]`. --- ### Stage 4: Add Stateless `WitnessPlasma` to `internal/pow/plasma.go` 1. Extend `SporkMask` (`internal/pow/plasma.go:45`) from 5 bits to 8 bits: * `SporkBitPQAccounts SporkMask = 1 << 5` * `SporkBitPQConsensus SporkMask = 1 << 6` * `SporkBitLegacySunset SporkMask = 1 << 7` (with implication closure `LegacySunset => PQConsensus => PQAccounts => DynamicPlasma`). 2. In `GetBasePlasmaForAccountBlock(block, sporkMask)`: * Compute `base` exactly as today when `block.Version == 1` or `!hasPQAccounts`. * When `hasPQAccounts && block.Version == 2 && !types.IsEmbeddedAddress(block.Address)`, add `WitnessPlasma(block)` (`max(0, len(PublicKey)+len(Signature)-96)*17 + VerifyComputePlasma(algID)`). --- ### Stage 5: Add `AccountStore[0x09]` Caching & `AuthRegistryContract` 1. In `internal/chain/account_store.go`, add `GetCachedPubKey() ([]byte, error)` and `SetCachedPubKey(pubWire []byte) error` at sub-key `[0x09]`, mirrored in `HotStateCache`. 2. Implement `internal/vm/contracts/auth/auth.go` (`AuthRegistryContract`): * `RotateKey(uint8 algId, bytes newPublicKey, bytes newKeyPopSignature, bool revokeLegacy)` (`EmbeddedSimplePlasma = 52,500` + calldata/witness plasma). * Register `AuthRegistryContract` in `internal/vm/supervisor/registry_all.go` gated on `SporkBitPQAccounts`. --- ### Stage 6: Update `PreverifyAccountBlock`, `accountBlockVerifier` & `VerifyMomentum` 1. **`internal/vm/verifier/account_block.go`:** * Step 1 (`version`): Accept `Version == 2` iff `PostQuantumAccountsSpork` is active at `MomentumAcknowledged`; reject `Version == 1` once `LegacyCryptoSunsetSpork` is active. * `PreverifyAccountBlock`: If `block.Version == 2`, resolve `pubWire` from `block.PublicKey` (if non-empty) or lock-free `HotStateCache`, then invoke `crypto.VerifyWire(pubWire, block.Hash[:], block.Signature, crypto.DomainAccountBlockV2)`. * `signature` & `producer`: Enforce the exact resolution order (`AuthRegistry` → `AccountStore[0x09]` → first-reveal `block.PublicKey`), returning `ErrABPublicKeyMustBeCached` if `block.PublicKey` is non-empty when already cached. 2. **`internal/vm/verifier/momentum.go`:** * Update `wrapIfBodyTampered` (`line 331`) to use version-aware witness bounds and mark uncommitted `Version == 2` witness tampering as `vmerr.UncommittedBodyError`. * Update `VerifyMomentumStaticWithPreverified` and `LegacyDposV1.VerifyMomentumProducer` to accept `algID` ∈ `{0x01, 0x02}` once `PostQuantumConsensusSpork` is active. --- ### Stage 7: Upgrade `PtlcContract`, `BridgeContract` & `go-libp2p` (`X25519MLKEM768`) 1. **`internal/vm/contracts/ptlc/ptlc.go`:** Add `PointTypeMLDSA44 = 3` and `PointTypeFNDSA512 = 4` (`pointLock = SHA3-256(rawPub)[32]`, `witness = rawPub || rawSig`). 2. **`internal/vm/contracts/bridge/`:** Add Guardian PQ public-key registry and `t-of-n` bitmap multi-signature verification over `UnwrapMessageHash` (`DomainBridgeV2`). 3. **`internal/p2p/libp2p/server.go`:** Enable Go 1.26 `crypto/tls` (`CurvePreferences: []tls.CurveID{tls.X25519MLKEM768}`) alongside Noise / PQ-peer-ID support. --- ### Stage 8: Cross-Client Parity (`zenon-rs` & `syrius`) and Bend 2.0.40 Formal Laws * **`zenon-rs` (Rust):** Use the RustCrypto audited crates `ml-dsa` (FIPS 204), `slh-dsa` (FIPS 205), and `fn-dsa` (`c-fn-dsa` / pure-Rust integer verifier by Thomas Pornin) behind the exact same `algID` wire tags. Run the 6-node 3-way `mixed-testnet-fuzzer` (`go-zenon-v1 + zenon-rs`) across live `PostQuantumAccountsSpork` activation, 3v3 reorgs (`Pop()` reverting `AccountStore[0x09]` and `AuthRegistry`), and malformed witness fuzzing. * **`syrius` (Dart/Flutter):** Expose `libznn` C-ABI exports (`ZnnSignAccountBlockPQ`, `ZnnDerivePQAddress`) directly from `go-zenon-v1/cmd/libznn/exports.go` so `syrius` desktop/mobile inherits Go 1.26's constant-time `crypto/mldsa` with zero duplicate Dart lattice math! * **New Bend 2.0.40 Formal Verification Suite (`test/bend/pq_witness/`):** 1. `Law_PKCache_Idempotence`: Once `AccountStore[0x09]` or `AuthRegistry` is populated at height `H`, every valid block at `H' > H` satisfies `len(PublicKey) == 0`, and `Pop(H)` restores exact pre-`H` auth state. 2. `Law_LegacyLockout_Monotonic`: Once `authRecord.legacyRevoked == true`, no sequence of `Ed25519` (`0x00`) blocks is ever accepted on that address. 3. `Law_WitnessPlasma_Monotonic`: For all blocks `b1, b2`, larger excess witness bytes strictly increase `CanonicalBasePlasma`, bounding worst-case `Momentum` verification CPU and wire bytes under `MaxMomentumContentBytes` (`8 MiB`).