0x3639/go-zenon-v1 Post-Quantum Validator Implementation Spec (ZNN-IMP-PQ-V1 · v4)
ZNN-SPEC-PHASE1-v4 Aligned)- Status:
v4 VERIFIED REVIEW DRAFT(source-audited against0x3639/go-zenon-v1@1c6e3d8..ff9496a,zenon-rs, and livego1.27.1, incorporating Round-4 findingsR4-01..R4-09). - Target Codebase:
0x3639/go-zenon-v1(CGO_ENABLED=0,Go 1.27+). - Standalone LLM File:
/raw/post-quantum/go-zenon-v1-pq-implementation-spec.md(feed directly to an AI coding agent alongside thego-zenon-v1repository). - Normative References: 0x02 Addresses & AuthRegistry (#14) · AccountBlock v2 & H_inc Rules · Two-Lane Plasma & SporkMask · Day-1 PoKoS & Complete Sunset · Go 1.27+ Blueprint.
1. Purpose, Scope & Hard Invariants
This specification is a byte-exact, file-anchored engineering blueprint for upgrading the 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)
- Toolchain & PQ Cryptographic Core (
L0): Upgradego.modtogo 1.27.0+, wirecrypto/mldsa(ML-DSA-44, FIPS 204) with mandatory startupAssertMLDSAReady()KAT (GOFIPS140 != v1.0.0), non-separable key/alg-bound signing transcriptboundDigest32(R4-01), full pure-Go (CGO_ENABLED=0)FN-DSA-512keygen + signing +0-FPU integer-NTT verification (fn-dsa v0.332BseedR4-09), pure-KeccakSLH-DSA-SHAKE-128s(FIPS 205), transitionalAlgHybridEdMLDSA44(0x81), PQSLIP-0010KDF, and true2^-128QROM (2^-256classical RBR) pure-SHA3-256WHIR-SHA3-v1zero-alloc verifier (<= 8,000Keccak permsR4-04). - Phase 1A State & Account Layer (
Spork #9: StateRootSpork+Spork #10: PQAccountsSpork):- Domain-separated (
[0x00]leaf /[0x01]internal)smt-v1depth-256SHA3-256Sparse Merkle Tree committingMomentum.StateRootonMomentum v3(R4-07). AccountBlock v2preserving the exact306-byteComputeHash()preimage while addingProofWitness(tag24),EquiXSolution(tag25), witness-separated[0x11]persistence (R4-07), length-framed(Hash, WitnessCommitment)gossip dedup (C03), andInvalidWitnessPenaltypeer scoring.20-byte0x02PQ user addresses (z1q{2,f,g,t}...) + fail-closed{0x00, 0x02}sender class allowlist;0x81forbidden on unregistered0x00Path-C reveals (R4-01).AuthRegistryContract(Embedded #14,z1qxemdeddedxauthxxxxxxxxxxxxxxxxx2a36sk):RotateKey,RescueWithPoKoS,PrecommitKey,UpgradeHybridToPureMLDSA44, exact179-byteGenesisHash-bound PoP,expectedRotationNonce(ErrAuthNonceOverflow),ctx.InclusionHeight() + 1promotion (R4-03), andO(1)GenesisReceive- & producer-awarepubKey_A-boundEd25519-PoKoS(AuthRegistry[0x03]+AccountStore[0x0a]+ByHeight(1..2)R4-02).AccountStore[0x09]public-key caching +32 BpubKeyHashRAM pinning inHotStateCache.uint64 SporkMaskwidening (preserving Phase 00x1fbits0..4verbatim), statelessWitnessPlasma, two-stageEqui-Xverification, and1-slot/MomentumPoKoSanti-starvation inContentSelector.LegacyDposV1PQ Pillar production & seal verification supporting both in-place rotated0x00Pillars and native0x02producer addresses onMomentum v3.
- Domain-separated (
- PQ P2P Transport (
v1.1/Phase 1A):X25519MLKEM768TLS 1.3 +/znn/tls-pq/1.0.0ML-DSA-44host identity ininternal/p2p/libp2p, disabling classicalnoise.IDatSpork #14. - Stake-Coordinated Hard-Fork Governance & Complete Classical Sunset (
Spork #14: LegacyCryptoSunsetSpork):- On-chain
>= 85%active-stakeMaxProtocolVersionreadiness across2consecutive epochs +HardForkEnforcementDelay = 8,640(24h) forSporks #9..#14. - Era-separated
InclusionMomentumHeight(H_inc) enforcement across both user blocks andGenerateEmbeddedReceive(DEEZ-B02, R4-03), plusVersion = 2upgrade on embeddedContractReceive/ContractSendblocks (R4-03). - Complete embedded-contract sunset (
BridgeContractECDSA,SwapContract,Pillar.RegisterLegacy, zero-stranded-fundsPtlcContract{0,1,2}drain withDeletePtlcReclaimLock) +SunsetAnchorCheckpoint(MaxPreCRQCBitcoinHeight,DEEZ-B11, B12, R4-09).
- On-chain
1.2 Explicitly Out of Scope (Deferred to Subsequent Specs)
- Phase 1B
Mahi-Mahi/SteelheadMeta-DAG consensus,M=4,096voting shares,HashRand-PQ(M_coin = 256) coin,Momentum v4(1.0 s),MomentumPQQC, andH_fork10xheight rescaling. - Phase 1C
SettlementContract (#13)Zenodomains (d_wasm,d_zvm,d_accounts) — only the reservedSettlementContractaddress constant is pinned here. - Phase 1D
d_btcSPV bridge andChannelContract (#15)(z1qxemdeddedxchannelxxxxxxxxxxxxxxr7xsx2).
1.3 Non-Negotiable Engineering Invariants for the Implementing LLM
- Zero CGo in Production (
CGO_ENABLED=0): Every cryptographic keygen/signer/verifier,Equi-Xsolver/verifier,WHIR-SHA3-v1verifier, and trie implementation MUST compile and pass tests withCGO_ENABLED=0acrosslinux/amd64,linux/arm64(Raspberry Pi 5), anddarwin/arm64(usingCGO_ENABLED=1solely when runninggo test -raceC05). - 100% Phase 0 Alphanet Replay Parity: For every Momentum
HwhereSpork #9andSpork #10are inactive,AccountBlock.ComputeHash(),AccountBlock.ChangesHash,Momentum.ComputeHash(),Momentum.ChangesHash, Protobuf, RLP, JSON, and all 74 existingvmerrverdicts MUST remain bit-for-bit identical togo-zenon-v1@1c6e3d8. Never write[0x09],[0x0a], or[0x11]witness sidecars whenSporkBitPQAccountsis inactive! - Acyclic
L0–L9Layering: Preservego-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. - 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.
- No Speculative
TODOStubs 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:
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.ChangesHashes 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 ContractReceives! | 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 ongo1.27.1). MaintainCGO_ENABLED=0. - Create
internal/crypto/pq_wire.gowith exact algorithm IDs, wire sizes, and non-separable key-bound digest construction (R4-01):
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
v2AccountBlock, PQv3Momentum, andAuthPopV3signature, computedigest := BoundSigningDigest(domainCtx, pubWire, msg):0x01(ML-DSA-44):mldsa.Verify(pk, digest[:], rawSig, &mldsa.Options{Context: domainCtx}) == nil.0x00(Ed25519insidev2):VerifyEd25519(edPub, digest[:], edSig)(legacyv1AccountBlock/v1..v2Momentumcontinue signing rawHash[:]unchanged!).0x02(FN-DSA-512,internal/crypto/fndsa512_v03.go): full pure-GoCGO_ENABLED=0implementation of pinnedfn-dsa v0.3(32-byteseed NTRU keygen + deterministic/emulated-binary64 signing +0-FPU integer-NTTmod 12289verificationR4-09) overdigest[:]with contextdomainCtx.0x03(SLH-DSA-SHAKE-128s,internal/crypto/slhdsa.go): pure-Go FIPS 205SLH-DSA-SHAKE-128s(crypto/sha3.NewSHAKE256()) overdigest[:]with contextdomainCtx.0x81(AlgHybridEdMLDSA44): returnstrueiff BOTHVerifyEd25519(edPub, digest[:], edSig)ANDVerifyMLDSA44(mldsaPub, digest[:], mldsaSig, domainCtx)succeed (wheredigestcommits to[0x81] || edPub || mldsaPub!).
AssertMLDSAReady()(cmd/znnd/main.go,cmd/libznn): verifies both the low-levelSignMLDSA44DeterministicKAT (621b16f8e3e2c7c064aec7ab540f1f64b1d1665feef964f07c6cded92d99f33b) and theBoundSigningDigestKAT (b7444ca31c5c802bd2cdc7f3fd5c76d1e2bce8655bfd44dd96a099e26c8608cfoverSHA3-256("zenon-v4-bound-ab-kat")), panicking fail-closed ifGOFIPS140=v1.0.0disablescrypto/mldsa.
- For every
- PQ
SLIP-0010Derivation (internal/crypto/slip0010.go,R4-09):- Master HMAC key
"zenon-pq-slip0010:v1", hardened pathm / 44' / 73404' / 1' / <algID>' / <accountIndex>':0x01:mldsa.NewPrivateKey(mldsa.MLDSA44(), leaf.Key[:])(32 B)0x02:SHA3_256("zenon-fndsa512-keygen:v1" || leaf.Key[:])(32 Bseed ->fn-dsa v0.3keygenR4-09)0x03:SHAKE256("zenon-slhdsa128s-keygen:v1" || leaf.Key[:], 48)-> FIPS 205(SK.seed[16], SK.prf[16], PK.seed[16])
- Master HMAC key
- True
2^-128QROMWHIR-SHA3-v1Verifier (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 mson Cortex-A76 withoutFEAT_SHA3),32-bitFiat-Shamir PoW grinding +>= 224-bitclassical query security +256-bitextension field (<= 2^-128QROM soundness),100%FIPS-202 SHA3-256/SHAKE256,0heap allocations insidearena *[262144]byte. R_PoKoS(circuitId = 0x01) public-input digest: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 1popDigest[32] // SHA3-256 of exact 179B zenon-auth-pop:v3 preimage)
- Enforce hard pre-check bounds:
PR-PQ-02 — Layers 0–1: Params, SporkIds, 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, impliesBit 8),LegacyCryptoSunsetSpork = SporkId{31: 0x0e}(Bit 13, impliesBits 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), andSunsetAnchorCheckpoint(Height,MomentumHash,StateRoot,CommitteeHash,BitcoinAnchorHeight,MaxPreCRQCBitcoinHeightR4-09).
4.2.2 internal/types/address.go
- Add
PQUserAddrByte = 0x02,DerivePQAddress,IsPQUserAddress,IsAllowedUserSenderClass({0x00, 0x02}),SettlementContract(z1qxemdeddedxsettlementxxxxxxxxxxxh5rx6j),AuthRegistryContract(z1qxemdeddedxauthxxxxxxxxxxxxxxxxx2a36sk), andEmbeddedContractsForSporkMask(mask uint64).
4.2.3 Domain-Separated smt-v1 Sparse Merkle Tree (internal/trie/smtcore/, R4-07 Fix)
- Implement depth-256 binary
SHA3-256Sparse 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)(prevents32B-value leaves from colliding with64Binternal nodes!).InternalHash(left[32], right[32]) = EmptyHashifleft == 0 && right == 0, elseSHA3-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
MomentumChangesexcluding[0x00, 0x01, 0x02], persisted under Pebble namespace[0x10] || nodeHash[32]outsideMomentumChanges.
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 tag24; RLP elem23) andEquiXSolution []byte(Proto tag25; RLP elem24). Keep306-byteComputeHash()unchanged! - Witness-Separated
[0x02]vs[0x11]Storage (R4-07Fix):- For
Version == 1:buildStoredAccountPatch(account_pool.go:1009) keepsb.SerializeProto()in[0x02] || be_u64(height)unchanged (100%Phase 0Momentum.ChangesHashparity!). - For
Version == 2:[0x02] || be_u64(height)storesb.SerializeStrippedBodyProto()(omittingPublicKey,Signature,ProofWitness,EquiXSolutionand appending tag26WitnessCommitment[32]), while raw witness bytes are persisted in Pebble namespace[0x11] || b.Hash[32](outsideMomentumChanges) so14-day witness compaction never altersMomentum.ChangesHash!
- For
4.3.2 internal/nom/momentum.go
- Add
StateRoot types.Hash(Prototag14,RLPoptional elem14);Version >= 3ComputeHash()hashes208 B(StateRootat176..208); updatesnapshotHashPreimageinverifier/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 MiBP2P,MaxHTTPBodySize = 5 MiBRPC,MaxDescendantDepth = 10,000), enforceValidateAccountBlockWitnessCapsimmediately post-decode (PublicKeyin{0,33,898,1313,1345},Signaturein{0,65,667,2421,2485,7857},ProofWitness <= 131,072only toAuthRegistry/Settlement,EquiXSolutionin{0,16}), chargeInvalidWitnessPenalty = 512inbudget.go, and keyTxMsgbroadcast/seen caches by(block.Hash, WitnessCommitment).
PR-PQ-04 — Layers 3–4: uint64 SporkMask, WitnessPlasma, Equi-X & AccountStore[0x09]/[0x0a]
- Widen
type SporkMask uint64preserving Phase 00x1fbits0..4verbatim; registerAuthRegistryContract(0xeb35f142,0x60c3b470,0x3a1c6df1,0xe2043a81) andPillar(0xc807dc32,0x0cf340ef) atEmbeddedSimplePlasma (52,500); implementWitnessPlasmaand two-stageEqui-X(internal/pow/equix.go). - Add
KeyAccountCachedPublicKey = 0x09andKeyAccountLegacyEd25519PK = 0x0ainaccount_store.go; pin only32BSHA3-256(pubWire)inHotStateCache; widenSporkIndexwith 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]→ ABIauthRecordPrefixPendingIndex = 0x02:[0x02] || be_u64(pendingEffectiveHeight) || targetAddr[20]→be_u64(1)PrefixExternalEd25519Reveal = 0x03(R4-02):[0x03] || addr[20]→pk32[32], populated ONLY for non-AccountBlockEd25519signature reveals (Momentum0x00producer keys &PtlcContractPointTypeEd25519unlocks —< 250entries total =< 15 KiB!). AtH_spork10Step 0, seed[0x03]from the<= 150historical Pillar producer/PTLC reveals (< 1 ms), and afterm.Contentin eachMomentum, record any unrotated0x00m.PublicKeyinto[0x03](never mutatingAccountStore(producer), avoidingAccountBlock.ChangesHashconflicts!).
- Execution Context (
R4-03): All 4AuthRegistrymethods execute againstctx.InclusionMomentumStore()(momStore, seeing live intra-Momentum writes!) and computependingEffectiveHeight = ctx.InclusionHeight() + 1(NEVERtargetMA.Height + 1!). Enforcerec.RotationNonce < math.MaxUint64(ErrAuthNonceOverflow). ResolveLegacyEd25519Exposure(ms, targetAddress)insideRescueWithPoKoS(O(1),R4-02):- Check
AuthRegistry[0x03 || targetAddress]andAccountStore(targetAddress)[0x0a]: if found (assertingPubKeyToAddress(pk32) == targetAddress; mismatch fails closed), return(hasExposedPK = 1, pk32). - Else inspect
hh = acct.Identifier():hh.Height == 0: return(0, [32]byte{0}).hh.Height == 1: loadblk1 := acct.ByHeight(1). Ifblk1 == nil, returnErrAuthUnknownExposure! Ifblk1.BlockType == BlockTypeGenesisReceive, return(0, [32]byte{0}); else return(1, blk1.PublicKey[0:32]).hh.Height >= 2: loadblk1 := acct.ByHeight(1); ifblk1 != nil && blk1.BlockType != BlockTypeGenesisReceive, return(1, blk1.PublicKey[0:32]); else loadblk2 := acct.ByHeight(2)(returningErrAuthUnknownExposureifnil, else(1, blk2.PublicKey[0:32])).
- Check
4.5.3 MomentumVM, GenerateEmbeddedReceive & Verifiers (R4-01, R4-03 Fix)
momentum_vm.go(Landmine #8): Run Step-0AuthRegistrypromotion onmomOverlay, then constructpostPromoStoreovermomOverlayasevalStoreform.Content! Afterm.Contentsucceeds and beforeMomentumChanges(), ifSporkBitPQAccountsis active andlen(m.PublicKey) == 32(0x00unrotated producer), stageAuthRegistry[0x03 || expectedProducer] = m.PublicKeyif absent.vm.go(Landmines #9 & #10): PassinclusionHeight(m.Height) andinclusionStore(momStore) intoGenerateEmbeddedReceive; emitAccountBlock.Version = 2on all generatedContractReceive(AutoReceiver) andContractSenddescendants/refunds wheneverSporkBitPQAccountsis active atH_inc!account_block.go(R4-01): On Path C (First Reveal), forbidalgID == 0x81whenAddress[0] == 0x00(Address[0] == 0x00Path C permits ONLYalgID == 0x00pre-sunset;0x81requires0x02address derivation orAuthRegistryPoP!). Verify allv2signatures overBoundSigningDigest.
PR-PQ-06 — Layers 6–8: >= 85% Spork Gate, Pillar Worker & Phase 1E Sunset (R4-03, R4-09)
- Enforce
>= 85%active-stake 2-epochMaxProtocolVersionreadiness +HardForkEnforcementDelay = 8,640(24h) inSpork.ActivateSpork. - Enforce Phase 1E sunset (
Bridge,Swap,Pillar.RegisterLegacy,PTLC {0..2}) atH_inc >= H_sunsetinside BOTHApplySendandReceiveBlock(ctx.InclusionHeight()R4-03). In post-expiryPtlc.Reclaim(id), call bothDeletePtlcInfoandDeletePtlcReclaimLock(R4-03). - Enforce
SunsetAnchorCheckpoint(Height,MomentumHash,StateRoot,MaxPreCRQCBitcoinHeightR4-09) indownloader.goandreorg.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-44exporter binding), disablenoise.IDatSpork #14, addPQKeyPair(SignAccountBlockV2/SignMomentumV3usingBoundSigningDigest), exposeembedded.auth.*+ledger.getStateProofRPCs, and callcrypto.AssertMLDSAReady()atznndstartup.
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 ContractReceives at H_inc >= H_sunset, verifies Version = 2 embedded ContractSends (R4-03), cleans ptlcReclaimLock on Reclaim, and enforces SunsetAnchorCheckpoint. |
5. Copy-Paste LLM Coding Agent Execution Prompt
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.