# zBTC: Bitcoin–Zenon Interoperability Protocol Specification — `v2` (`v3.1.0-rfc`) > Public RFC `v2` (`v3.1.0-rfc`, **Zero-Federation Phased Architecture — R8 Hardened**): explicitly rejects custodial federated multisigs and defines a phased non-custodial Bitcoin–Zenon interoperability roadmap: > - **Stage 0 (`0–6 mo`, `0 BTC` bridge custody):** Direct-on-L1 Bitcoin SPV Event Oracle (`len(strippedTx) >= 65`, 1-/2-block coinbase midstate) + Erlang-hardened non-custodial PTLC (`T_znn >= 48h`, automated block-72 RBF watchtower) & Lightning HTLC (`Δ_safety >= 24h`) atomic swaps. > - **Stage 1A (`12–18+ mo` incl. audit, `12.80–18.80 BTC` locked / `14.75–21.25 BTC` operational baseline, Bitcoin Core `>= 29.0`):** Right-sized `BitVMX-CPU` (`n = 8`, 100% BIP-431 TRUC v3 + `0`-sat `P2A`, `RV32IM` wrapped-SNARK verifier only, `M = 3–5` operators, `N = 7` pre-committed verifiers, deleted-key `{0.50, 0.25, 0.25}` BTC vaults with acyclic pre-funding `vault_id`, L1 `AdmissionTicketUTXO` cap exclusion, $2^M$ Hall's Marriage invariant, native-L1 `Stake_r` verifier payouts `+0.0645/+0.0232 BTC` EV @ `500/750 sat/vB`) + **Bitcoin-Anchored Sovereign ZK Validity Rollup** (`0-of-N` Zenon trust — survives **49%–100%** Zenon compromise, `V_unassigned + V_assigned = C + L + E + R + A + B`, L1-subsidized feeless `AccountBlock.Data` sequencer rails, fail-closed BIP-141 `wtxid` witness completeness, uncensorable Bitcoin L1 forced inbox `0x00..0x07`, immutable `vk_STF`, `0%` ZNN slashing/custody). > - **Stage 1B Alternative Gate (`3–6 mo`, `2–5 BTC` liquidity):** `clArk` discrete expiring VTXO coordination (relinquishing pooled fungible `zBTC` in favor of `0-of-N` post-round unilateral exit with `log2(N)` L1 exit branches + automated watchtowers). > - **Stage 2:** Zero-TTP scaling via `N`-of-`N` voluntary cohort handover or clean non-commingled `zBTC_v2`, plus optional covenant-enabled sovereign ZK-rollup track. > > Remediates Consolidated Hostile Review `R8` of archived `v1` (`v3.0.0-rfc`, frozen byte-for-byte under `versions/v1/`), redlines directly against `v1`, and supersedes archived `v0` (`v2.5.0-rfc`, frozen byte-for-byte under `versions/v0/`). - **Current Version:** `v2` (`v3.1.0-rfc`) — pre-implementation zero-federation RFC open for independent security review. NOT mainnet-active. - **Current `v2` Integrity Manifest:** https://btc-moonshot.github.io/spec/raw/SHA256SUMS.txt - **Archived Previous Version (`v1` / `v3.0.0-rfc`, commit `6ab3999` — redline base for `v2`):** https://btc-moonshot.github.io/spec/v1/ - **Archived Initial Version (`v0` / `v2.5.0-rfc`, commit `7b47b8c`, superseded):** https://btc-moonshot.github.io/spec/v0/ - **Changelog & Redline Diffs (`v1 → v2` + `R8`):** https://btc-moonshot.github.io/spec/changelog/ - **Canonical Web Site:** https://btc-moonshot.github.io/spec/ - **How to Review & LLM Guardrails:** https://btc-moonshot.github.io/spec/review-guide/ - **Copy-Paste LLM Review Prompt (plain text):** https://btc-moonshot.github.io/spec/llm-review-prompt.txt - **GitHub Repository:** https://github.com/btc-moonshot/spec - **Zenon Developer Commons (TminusZ — required context):** https://github.com/TminusZ/zenon-developer-commons - **Zenon Reference Node (`go-zenon` — required context):** https://github.com/zenon-network/go-zenon - **Single-Fetch Full Bundle (`v2`):** https://btc-moonshot.github.io/spec/llms-full.txt - **Consistency & Bounds Checker:** `python3 -I scripts/verify_spec_bounds.py` ## How to Review & Hard Guardrails for LLMs Every LLM or human reviewer auditing this spec MUST obey these five guardrails (full prompt: https://btc-moonshot.github.io/spec/llm-review-prompt.txt): 1. **No federated signature schemes:** Custodial `k`-of-`n` multisig / HSM federations and custodial backup committees are explicitly rejected. Never propose a federation as a fix. 2. **Trustless recovery if signers do not act:** Test whether users can still recover BTC on Bitcoin L1 when signers refuse to sign or when Zenon is compromised up to 49% (or worse). 3. **Fungibility on Bitcoin + feeless Zenon rails:** Test Bob (`1 BTC -> 1 zBTC -> spend 0.5 -> recover 0.5 BTC` under `<=49%` Zenon compromise) and Mike (`Alice 1 BTC + Bob 1 BTC -> Mike 2 zBTC -> recover 0.25 BTC` when Zenon signers refuse to sign). 4. **Do not require waiting for Bitcoin covenants:** Target Bitcoin Mainnet today (`BIP-340/341/342`, `OP_CSV`, `BIP-431` TRUC v3 on Bitcoin Core `>= 29.0`) with zero Bitcoin soft forks. If a property is provably impossible without covenants, state the exact mathematical boundary and compare against the strongest covenant-free design. 5. **Young project & low market cap realism (`~25–33 BTC` ZNN mcap):** Do not rely on ZNN slashing/PoS consensus for BTC custody or require hundreds of BTC of bootstrap bonds. Cross-check claims against https://github.com/TminusZ/zenon-developer-commons (especially `essays/Verify Bitcoin, Don't Bridge It.md`, `docs/specs/spv-event-oracle-spec.md`, `docs/specs/Minimum Verifier Spec.md`, `docs/specs/commitments-and-proofs.md`, `docs/specs/threat-model.md`, and `docs/specs/Zenon Portal/Portal V2/zenon_portal_final.md`) and https://github.com/zenon-network/go-zenon. ## Normative Specification Files (`v2` / `v3.1.0-rfc`) Read in authority-precedence order (`SPEC.md §2.1`): - [Part 1 — Zero-Federation Bitcoin Taproot Vault Enforcement (`BTC-BITVMX-V1`), Stage 1B `clArk` Gate & Track B Annex](https://btc-moonshot.github.io/spec/raw/spec/01-bitcoin-taproot-vault-enforcement.md): Highest precedence. Explicit rejection of federated multisigs; Propositions 1–2; acyclic pre-funding `vault_id` & L1 `AdmissionTicketUTXO` cap exclusion; deleted-key `{0.50, 0.25, 0.25}` BTC vaults; `n = 8` `BitVMX-CPU` (`RV32IM` wrapped-SNARK verifier only, `301` W-OTS digits ≈ `7.44 kvB <= 10,000 vB` 100% TRUC v3 on Core `>= 29.0`, `20` steps, `76.53/16.53 kvB` incl. `10 × 153 vB` CPFP, `F_chal = 0.40 BTC`); widened timelocks `[0, 144]` → `1,584 < T_take = 1,728 < T_cooldown = 1,872 < Retire = 2,016`; acyclic 256-bit Lamport `TakeTx` (`~3.17 kvB`); native-L1 `Stake_r` `ChalPayoutEscrow` verifier payouts (`0.15 BTC` native BTC each, `+0.0645/+0.0232 BTC` EV @ `500/750 sat/vB`, `0%` `zBTC` crisis discount); active-op `(2M_active+1)`-leaf `ExitSlotUTXO` w/ cyclic `(H(exitId)+r) mod M_active`; $2^M$ Hall's Marriage invariant; full operational capital (`14.75–21.25 BTC` baseline + multi-dispute headroom) & `~94–104d` bank-run math; graduated TVL ramps & voluntary unwind circuit breaker; Stage 1B `clArk` gate; Stage 2 & Track B annex. HTML: https://btc-moonshot.github.io/spec/part-01/ - [Master Overview (`SPEC.md`)](https://btc-moonshot.github.io/spec/raw/SPEC.md): Zero-federation phased architecture, Propositions 1–2, end-to-end flows (Bob `0.5 BTC` under 49% Zenon attack & Mike `0.25 BTC` zero-signer exit), honest threat model (`0-of-M` & probabilistic PoW disclosures), Stage 0/1A/1B/2 gates, `bigidea` claims alignment table, and written Q&A answering all 12 `R8` questions + `R7` summary. HTML: https://btc-moonshot.github.io/spec/ - [Part 2 — Stage 0 Bitcoin SPV Event Oracle & Stage 1A L1 DA / Forced-Inclusion Inbox](https://btc-moonshot.github.io/spec/raw/spec/02-btc-authorization-domain-and-spv.md): Pure-Go panic-recovered (`B1`) Stage 0 SPV Event Oracle (`65 <= len(strippedTx) <= 6,144`, 1-/2-block coinbase midstate proof, `B2` pinned `2.1M` Plasma floor); Stage 1A off-chain stripped-block ZK scanner (`vk_STF` wrapped SNARK verifier), fail-closed BIP-141 witness authentication on last `6a24aa21a9ed` coinbase output, full stripped-`vin` tracked-UTXO scan, complete `0x02` DA schema + slotted batcher priority, `K >= 18` unpublished-fork heuristic (Budish sensitivity), interactive heaviest-chainwork check, and `>= K` `DEEP_REORG_HALT` circuit breaker. HTML: https://btc-moonshot.github.io/spec/part-02/ - [Part 3 — Erlang-Hardened PTLC/LN Rails, Sovereign Rollup STF & Feeless Zenon Sequencer](https://btc-moonshot.github.io/spec/raw/spec/03-settlement-minted-zbtc-and-feeless-rails.md): Stage 0 Erlang-hardened PTLC (`>= 72`-blk CSV, automated block-72 RBF watchtower, `T_znn >= 48h`, `P(T_72 > 48h | 2.3×) < 10^{-6}`) and LN HTLC (`hashType = 1`, outbound `Δ_safety >= 24h`); Stage 1A immutable Rollup SMT with explicit `AssignedObligations (A)` conservation (`V_unassigned + V_assigned = C + L + E + R + A + B`), hard-partitioned `B_custody`/`B_grief`, oldest-`PendingExit` priority, `TransferCredit`, `MIN_EXIT_SATS = 100,000` sats, `500`-sat new-leaf deposit + `<= 1,000`/epoch cap, two-column Zenon TPS vs Bitcoin L1 `0x02` physical DA ceiling (`166.7` blended leaves/s @ 100%), and Stage 1B `clArk` VTXO rails. HTML: https://btc-moonshot.github.io/spec/part-03/ - [Part 4 — Zenon 49% Consensus Boundary, Inverted Trust Hierarchy & Light Clients](https://btc-moonshot.github.io/spec/raw/spec/04-bitcoin-anchoring-and-light-client.md): Code-grounded proof of why `go-zenon` DPoS fails at 49% and classical BFT fails at `> 33.3%`, proving why Stage 1A inverts trust to Bitcoin L1 (`0-of-N` Zenon trust, probabilistic PoW finality at `K >= 18`); optional non-custodial light-client infrastructure. HTML: https://btc-moonshot.github.io/spec/part-04/ - [Part 5 — Detailed `go-zenon` Upgrade Plan & Pre-Mainnet Conformance Gates (`G1–G7`)](https://btc-moonshot.github.io/spec/raw/spec/05-go-zenon-upgrade-plan.md): Stage 0 `go-zenon` prerequisites (`0aa299e`, closure of `#239`/`#299`/`#312`, mainnet `PTLC PR #138` & `DynamicPlasmaSpork` 5-param pinning, SPV Event Oracle), Bitcoin Core `>= 29.0` floor, Stage 1A/1B zero-hard-fork custody isolation, and mandatory Pre-Mainnet Conformance Gates `G1–G7`. HTML: https://btc-moonshot.github.io/spec/part-05/ - [Changelog (`v1 → v2` `R8` Remediation & Historical `v0 → v1`)](https://btc-moonshot.github.io/spec/raw/CHANGELOG.md): Complete 27-finding `R8` disposition (Amendments A1–A11 + verified pushbacks) plus historical 31-finding `R7` disposition and rejection rationale for custodial federated multisigs. HTML: https://btc-moonshot.github.io/spec/changelog/ ## Consistency Checker & Review Trail - [Consistency & Bounds Checker (`scripts/verify_spec_bounds.py`)](https://btc-moonshot.github.io/spec/raw/scripts/verify_spec_bounds.py): Run `python3 -I scripts/verify_spec_bounds.py` (pure stdlib Python 3) to verify Stage 0 coinbase midstate + `>= 65 B` filter, exact stdlib Erlang tails (`>= 48h` / `>= 24h`), Zenon TPS vs Bitcoin `0x02` DA ceilings, Stage 1A `n = 8` BitVMX TRUC v3 + `10 × 153 vB` CPFP, acyclic `vault_id` Lamport `TakeTx`, native-L1 verifier EV (`500–750 sat/vB`, `0%` `zBTC` discount), $2^M$ Hall checks, cyclic priority, `13.0d` bank-run bounds, `K >= 18` + Budish sensitivity, a non-no-op 2,000-step `V = C+L+E+R+A+B` simulation with `AdmissionTicketUTXO`, `k = 20` grief burst, `TransferCredit` & real reorgs, and Stage 1B `clArk` bounds. HTML: https://btc-moonshot.github.io/spec/oracle/ - [Consolidated Hostile Review (`R8` — Audit of archived `v1 / v3.0.0-rfc`, Remediated in `v2 / v3.1.0-rfc`)](https://btc-moonshot.github.io/spec/raw/reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md) - [Consolidated Hostile Review (`R7` — Historical Audit of archived `v0 / v2.5.0-rfc`)](https://btc-moonshot.github.io/spec/raw/reviews/HOSTILE_REVIEW_R7_CONSOLIDATED.md) - [Adversarial Review Audit Trail (R1–R8)](https://btc-moonshot.github.io/spec/reviews/) - [Current `v2` SHA-256 Manifest](https://btc-moonshot.github.io/spec/raw/SHA256SUMS.txt) · [Archived `v1` SHA-256 Manifest](https://btc-moonshot.github.io/spec/raw/v1/SHA256SUMS.txt) · [Archived `v0` SHA-256 Manifest](https://btc-moonshot.github.io/spec/raw/v0/SHA256SUMS.txt) ================================================================================ # FULL NORMATIVE SPECIFICATION CORPUS — v2 (v3.1.0-rfc) ================================================================================ # zBTC: Bitcoin–Zenon Interoperability Protocol Specification **Version:** `v2` (`v3.1.0-rfc` — **Zero-Federation Phased Architecture, R8 Hardened**: Stage 0 Verify Bitcoin SPV + Non-Custodial PTLC/LN → Stage 1A Right-Sized `BitVMX` `n=8` Sovereign ZK Validity Rollup | Stage 1B `clArk` Alternative Gate → Stage 2 Zero-TTP Scale & Upgrade; remediates Consolidated Hostile Review [`R8`](./reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md) of archived [`v1` / `v3.0.0-rfc`](./versions/v1/SPEC.md) and supersedes archived [`v0` / `v2.5.0-rfc`](./versions/v0/SPEC.md), see [CHANGELOG.md](./CHANGELOG.md)) **Status:** Public Request for Comment (`v2` / `v3.1.0-rfc`) — NOT mainnet-active; Stage 0 gated on upstream `go-zenon` release (`0aa299e` + `#239`/`#299`/`#312` closure + mainnet `PTLC PR #138` & `DynamicPlasmaSpork` activation with full `SetPlasmaVariables` pinning — Gate G6); Stage 1A gated on Bitcoin Core `>= 29.0` (`v31.0` preferred) Signet execution (Gate G1), compiled `RV32IM` wrapped-SNARK verifier ELF proof (Gate G2), extended checker (Gate G3), formal verification & Bitcoin Core differential fuzzing (Gate G4), vault-bundle disaster-recovery drill (Gate G5), independent third-party cryptography/Bitcoin-Script audit (**M-15**), graduated TVL ramps (`2 → 5 → 15 BTC`), and hard-BTC operator/verifier capital commitment. **Target Networks:** Bitcoin Mainnet TODAY (`bip-0141`/`bip-0340`/`bip-0341`/`bip-0342`/`bip-0431` Taproot + TRUC v3 + `0`-sat `P2A` ephemeral dust on **Bitcoin Core `>= 29.0`**, `v31.0` preferred — **zero Bitcoin soft forks**, **zero federated signers**) ↔ Zenon Network (`go-zenon` first tagged mainnet release containing `0aa299e`, `#239`/`#299`/`#312` closed, `DynamicPlasmaSpork` & `PtlcSpork` `PR #138` enforced; local reference clone `master` `e8986a6` / `origin/dev` `770e893`) **Consistency & Bounds Checker:** All modeled `n = 8` `BitVMX` W-OTS/TRUC v3 weights, acyclic `vault_id` 256-bit Lamport `TakeTx` stack/size bounds, widened timelock ordering (`[0, 144] → 1,584 < 1,728 < 1,872 < 2,016`), native-L1 `Stake_r` verifier positive-EV matrices (including `16.53 kvB` P2A CPFP, `0.00285 BTC` lockup, `30%` `zBTC` crisis discount, `500–750 sat/vB`, `k_collude = 0..6`), $2^M$ Hall's Marriage recoverability checks, cyclic `(H(exitId)+r) mod M` priority permutations, `{0.50, 0.25, 0.25}` BTC bank-run exit bounds, `K >= 18` unpublished-fork heuristic & Budish flow-cost sensitivity, 1-/2-block coinbase midstate SHA-256 padding, honest `8 MiB` `go-zenon` Plasma bounds vs Bitcoin L1 `0x02` physical DA ceilings, Erlang-verified PTLC (`>= 48h`) and LN HTLC (`>= 24h`) `2.3×` slow-block tail bounds, `clArk` exit weights, and a **non-no-op randomized state-machine simulation with explicit `AssignedObligations (A)` conservation (`V_unassigned + V_assigned = C + L + E + R + A + B`), `AdmissionTicketUTXO` cap exclusion, concurrent `k = 20` `ExitSlotUTXO` grief bursts, `TransferCredit`, real Bitcoin reorgs, and Lamport equivocation slashes** are asserted by [`scripts/verify_spec_bounds.py`](./scripts/verify_spec_bounds.py) (`python3 -I scripts/verify_spec_bounds.py`). *This script checks internal mathematical consistency against explicitly labeled `SOURCED_`, `POLICY_`, and `PRE_MAINNET_TARGET_` inputs; it is not an empirical Signet benchmark or audit.* **Upstream Provenance, Pinning & Review Trail:** - Vision Proposal: [`https://btc-moonshot.github.io/bigidea/`](https://btc-moonshot.github.io/bigidea/) *(see §9 for mandatory claims alignment)* - Zenon Non-Bridging Thesis: `zenon-developer-commons/essays/Verify Bitcoin, Don't Bridge It.md` & `docs/specs/spv-event-oracle-spec.md` - Reference Node Codebase: [`go-zenon`](https://github.com/zenon-network/go-zenon) (`master` `e8986a6`, `origin/dev` `770e893`, target mainnet release tag containing `0aa299e`, `PR #138`, `#239`/`#299`/`#312`) - Current `v2` (`v3.1.0-rfc`) Integrity Manifest: generated deterministically at build time in `public/raw/SHA256SUMS.txt` (`R8-L02`) - Archived Previous Version (`v1` / `v3.0.0-rfc`): Frozen byte-for-byte from commit `6ab3999` in [`versions/v1/`](./versions/v1/) (SHA-256 verified in CI; current `v2` redlines directly against `v1`). - Archived Initial Baseline (`v0` / `v2.5.0-rfc`): Frozen byte-for-byte from commit `7b47b8c` in [`versions/v0/`](./versions/v0/) (SHA-256 verified in CI). - Consolidated Hostile Reviews: - [`R8` (`reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md`)](./reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md) — independent multi-agent audit of archived `v1 (v3.0.0-rfc)` (6 Critical, 10 High, 9 Medium, 2 Low; Stage 0 & 1B Conditional Pass, Stage 1A Fail as written); **every confirmed R8 defect is remediated in `v2 (v3.1.0-rfc)`**, with exact line-level dispositions and verified pushbacks documented in §10 and [`CHANGELOG.md`](./CHANGELOG.md). - [`R7` (`reviews/HOSTILE_REVIEW_R7_CONSOLIDATED.md`)](./reviews/HOSTILE_REVIEW_R7_CONSOLIDATED.md) — historical audit of archived `v0` (`v2.5.0-rfc`) that triggered the zero-federation `v1` redesign. --- ## 1. Executive Summary & Architectural Evolution (`v0` → `v1` → `v2`) ### 1.1 Why `v0` Failed — and Why Custodial Federated Multisigs Are Explicitly Rejected The consolidated hostile review of `v0` (`v2.5.0-rfc`, [`R7`](./reviews/HOSTILE_REVIEW_R7_CONSOLIDATED.md)) and subsequent consensus/cryptographic audits established that **`v0` cannot be patched**: 1. **ZNN cannot secure BTC (`C-1`):** Real market liquidity (`400k–727k ZNN/BTC`, total ZNN market cap `~25–33 BTC`) makes `v0`'s `10,500 ZNN/BTC` slashing deterrents worth only `1.4–2.6%` of stated value (`~0.43–0.79 BTC` for 21 Pillars against a `15 BTC` cap). 2. **Zenon consensus fails at `≤ 49%` compromise (`C-2, H-1, H-2, H-3`):** Current `go-zenon` is longest-chain DPoS with zero slashing, deterministic height-only grindable `findSeed`, unweighted top-30 `groupA` sybil amplification, and a 30-Momentum hard rollback cliff (`protocol/chain_bridge.go`) allowing permanent chain splits at `49%`; adding classical BFT (`CommitteeRootSpork`) breaks BOTH safety and liveness at `> 33.3%`. Single-key `SporkAddress` / `CommunitySporkAddress` can mutate consensus code, and refundable QSR fusion allows whale Dynamic Plasma DoS. 3. **BitVM2 script costs break low-cap economics (`C-3, H-4, M-6`):** Real chunked Groth16 BitVM2 asserts (`~1.0–1.3M vB` / `4.0–4.8 MB` W-OTS) are `4.4–10×` larger than `v0`'s `220 kvB`, forcing `~13.30–18.175 BTC`/lane (`~40–91 BTC` in bonds even at bare-minimum `M = 3–5, L = 1`, exceeding ZNN's entire market cap!). 4. **Never-deleted `N`-of-`N` `Q_graph` & `CommitteeIdentityKey` (`C-4, N-2`) + fixed `1.0 BTC` buckets:** Rotating 30-day PoS committee roots forced never-deleted standing keys (sweep-all OR 1-key bricking at day 56), while fixed `1.0 BTC` buckets rejected `0.50` and `0.25 BTC` exits. **Why `v2` explicitly REJECTS custodial `k`-of-`n` federated multisigs:** Falling back to a custodial `k`-of-`n` federated multisig is **normatively forbidden in `v2`**. Federated custody: - Violates Bitcoin's non-custodial ethos and Zenon's own thesis (*"Bridges Are Custody Wearing a Mask"* — `Verify Bitcoin, Don't Bridge It.md`); - Fails **Bob's partial-recovery test** under `49%` Zenon compromise (a 49% `go-zenon` DPoS split breaks cross-signer Zenon state agreement and freezes payouts, while safety depends entirely on trusting external custodians); - Fails **Mike's zero-signer-cooperation test** completely (if federated signers refuse to sign Mike's `0.25 BTC` payout, `0` satoshis leave custody; a backup recovery timelock belongs to another custodial multisig and never unlocks while active signers refresh UTXOs). ### 1.2 Governing Cryptographic & Engineering Boundaries (Proposition 1 & Proposition 2) Every design decision in `v2` is constrained by two formal boundary propositions (detailed in [`spec/01 §1`](./spec/01-bitcoin-taproot-vault-enforcement.md#1-cryptographic-boundaries-proposition-1--proposition-2) and [`spec/04 §1`](./spec/04-bitcoin-anchoring-and-light-client.md)): > **Proposition 1 (Bitcoin Mainnet No-Covenant 4-Way Impossibility — BIP-340/341/342, Zero Soft Forks):** On Bitcoin Mainnet today (no covenant opcodes), no protocol can simultaneously achieve: **(1)** pooled cross-depositor custody (`U_A`, `U_B` created at `t_0`), **(2)** zero new signatures at `t_1` (`0-of-N` liveness) for an unknown future recipient Mike (`P_Mike`, `0.25 BTC` unknown at `t_0`) while binding the `0.75 BTC` remainder back into custody, **(3)** zero per-hop key-deletion / statechain trust across prior owners, and **(4)** non-expiring fungible liquidity. Tapscript lacks output introspection (`nValue`/`scriptPubKey`), so any unsigned spend is trivially miner-front-run, while pre-signed transactions at `t_0` cannot bind future unknown `(P_Mike, 0.25 BTC)`. **Corollary 1B:** On Bitcoin Mainnet today, optimistic reimbursement bridges (`BitVM2`/`BitVMX`/`BitVM3`) are strictly bounded by **`1-of-N` ephemeral setup deletion + challenger/verifier safety + `1-of-M` pre-committed operator exit liveness**. > **Proposition 2 (Young Low-Cap Engineering / Capital / Trust Trilemma — 0 Federation, 0 Soft Forks, `~25–33 BTC` ZNN MCap):** Under current Bitcoin Script & ZK-proving engineering with zero federated signers, zero Bitcoin soft forks, and `0%` ZNN slashing usable (`~25–33 BTC` ZNN mcap), no current design fits inside `2–20 BTC` total hard capital while simultaneously achieving all three of: > - **(A)** Instant, non-expiring, fungible cross-depositor `zBTC` (`Alice + Bob → Mike` with zero sender-collusion risk), > - **(B)** `1-of-∞` permissionless challenging surviving `200–500 sat/vB` fee spikes (blocked by current Groth16 BitVM2's `~40–91 BTC` bond floor even at `M = 3–5, L = 1`; future reusable BitVM3-GC reduces on-chain dispute weights substantially but currently carries `1-of-N` garbler trust plus `2.2–11.2+ TB` one-time off-chain garbled-circuit DA across `M × L × R × N` rounds — see `spec/01 Appendix A.2`), AND > - **(C)** `0-of-N` unilateral arbitrary-amount Bitcoin L1 exit (blocked by Proposition 1; `clArk` achieves post-round `0-of-N` only by sacrificing **(A)** via discrete expiring VTXOs and pre-round `arkoor` sender+ASP collusion). ### 1.3 What `v2` (`v3.1.0-rfc`) Is, Stated Plainly `v2` (`v3.1.0-rfc`) specifies a **zero-federation, zero-soft-fork, zero-ZNN-custody-coupling** phased architecture starting from zero custody risk: 1. **Stage 0 (`0–6 months`, `0 BTC` bridge custody risk, `0–5 BTC` voluntary LP — Mandatory Start):** - Ship the **Direct-on-L1 Bitcoin SPV Event Oracle** (`spec/02 §2`, strictly Event Validity, zero custody authority, `len(strippedTx) >= 65`, 1-/2-block coinbase midstate padding) and **Erlang-hardened non-custodial PTLC (`T_znn >= 48h`, automated block-72 RBF watchtowers) / Lightning HTLC (`Δ_safety >= 24h`) atomic swaps** (`spec/03 §1`, `P(tail failure | 2.3× slowdown) < 0.0002`, explicitly disclosing conditional atomicity) while building and auditing the Stage 1A Rollup Core + `BitVMX-CPU` wrapped-SNARK verifier on Signet. 2. **Stage 1 Decision Gate (Explicitly Governed by Hard-BTC Commitment, Engineering Scope & Timeline):** - **Stage 1A — Primary Path for Pooled Fungible `zBTC` (`12–18+ months` incl. audit for 4–6 engineers; requires `12.80–18.80 BTC` locked protocol capital → `14.75–21.25 BTC` full single-dispute operational baseline ≈ `45–85%` of ZNN's `~25–33 BTC` market cap, plus explicit `M`-simultaneous-dispute verifier headroom disclosure):** - **Shared Core (0% Zenon Trust — Survives 49%–100% Zenon Compromise):** A **Bitcoin-Anchored Sovereign ZK Validity Rollup** where Zenon is demoted to an untrusted **L1-subsidized soft-preconfirmation sequencer** (`AccountBlock.Data`, `28,480` Plasma, `0` sat direct user BTC fee, NOT native ZTS; bounded against `0x02` DA spam via refundable `500`-sat new-leaf deposit + `<= 1,000` new leaves/6-block epoch cap). Canonical ordering, complete mutated-leaf DA (`0x02 BATCH_DA` covering `Accounts`, `RollupLocks`, and cooperative `PendingExits` + embedded `π_batch`, slotted batcher priority), and uncensorable forced inclusion (`0x01 FORCED_EXIT`, `0x03 FORCED_TRANSFER`) live strictly on Bitcoin L1 via full stripped-block (`≤ 1,000,000 B`) scanning, fail-closed BIP-141 `wtxid` witness authentication (last `0x6a24aa21a9ed` coinbase output), and full stripped-`vin` tracked-UTXO scanning. - **Custody Engine (Right-Sized `BitVMX`, `n = 8`, `M = 3–5`, `L = 1`, `N = 7`, Bitcoin Core `>= 29.0`):** Open-source `BitVMX-CPU` (`RV32IM`) interactive bisection executing **strictly a constant-size wrapped SNARK verifier (`vk_STF`, Gate G2)** (`~7.44 kvB`/prover tx, **100% BIP-431 TRUC v3** with `0`-sat `P2A` ephemeral anchors on Core `>= 29.0` + direct-to-miner rails; `76.53 kvB` Prover / `16.53 kvB` Verifier incl. `10 × 153 vB` CPFP; `F_chal = 0.40 BTC` covering `500 sat/vB` sustained, `522 sat/vB` break-even; widened `T_step = 72` blks → `T_take = 1,728`, `T_cooldown = 1,872`, `Retire = 2,016`). Deleted-key `{0.50, 0.25, 0.25}` BTC vaults with **acyclic pre-funding `vault_id`** (`R8-C01`), L1 consensus **`AdmissionTicketUTXO`** `Cap_TVL` mutual exclusion (`R8-C03`), exact **$2^M$ Hall's Marriage** recoverability (`R8-C04`), explicit **`AssignedObligations (A)`** conservation (`R8-C02`), **native Bitcoin L1 `Stake_r` verifier payouts (`0.15 BTC` native BTC to every active honest challenger via `ChalPayoutEscrow` — `0%` `zBTC` crisis discount, `+0.0645 BTC` net EV @ `500 sat/vB` & `+0.0232 BTC` @ `750 sat/vB`, `890 sat/vB` break-even, `R8-H02`/`R8-N05`)**, hard-partitioned `B_grief` (`0.05 BTC`) with active-operator-only `ExitSlotUTXO` (`R8-H01`), cyclic `(H(exitId)+r) mod M` priority (`R8-M03`), and `zbtc-vault-bundle-v1` public DA archival (`R8-H06`). **Pre-mainnet maturity explicitly disclosed; Gate G2 evaluates BitVMX-CPU vs BitVM3-GC prior to final freeze.** - **Stage 1B — Explicit Alternative Gate (If Hard-BTC Budget `< 10–15 BTC`, `3–6 mo` Launch Target, or `0-of-N` Post-Round Exit Outweighs Pooled Fungibility):** - Do **NOT** under-bond `BitVMX`/`BitVM2`. Deploy **`clArk` (`Second bark` / `Ark Labs arkd`) + Zenon SPV/PTLC** (`2–5 BTC` active ASP liquidity, `0` bonds), explicitly relinquishing global pooled `zBTC` in favor of discrete expiring VTXOs (disclosing `arkoor` sender+ASP collusion, automated watchtower refreshes, and `log2(N)` L1 exit fees). 3. **Stage 2 (`12+ months`, Zero-TTP Scale & Upgrade — Zero Dead-End User Trap):** - Deleted-key Stage 1A vaults carry **no expiry / no CLTV bricking** and drain organically 1:1 to native BTC via `0x01` exits (subject to `1-of-M` eligible operator liveness; no deleted-key L1 rollover). Identical-STF `BitVMX` expansion (`M = 5 → 20`, `L = 1 → 4`, `K = 42 → 144`) uses strictly `N`-of-`N` Cohort 1 voluntary handover; changing custody backends (`BitVM3-GC` / `BitVM2` / **Appendix A Track B Pure Tier-0 `OP_CCV + OP_TXHASH + OP_VERIFY_STARK` or `OP_CAT` Covenant**) ALWAYS launches a clean, non-commingled `zBTC_v2` instance with zero governance backdoor. --- ## 2. Normative Module Map & Authority Precedence | Module | File | Normative Scope in `v2` (`v3.1.0-rfc`) | |---|---|---| | **Master** | [`SPEC.md`](./SPEC.md) | Zero-federation phased architecture, Propositions 1–2, end-to-end Bob & Mike traces (§3), honest Threat Model & Privileged Powers Table (§4), `go-zenon` baseline (§5), Upstream Amendments (§6), Stage 0/1A/1B/2 Decision Gates & graduated TVL ramps (§7), Non-Bridging Alignment & Public Claims (§8–§9), and Written Q&A answering all 12 R8 Questions + R7 summary (§10). | | **Part 1** | [`spec/01-bitcoin-taproot-vault-enforcement.md`](./spec/01-bitcoin-taproot-vault-enforcement.md) | **Highest Custody Precedence (`BTC-BITVMX-V1`):** Propositions 1–2; acyclic `OP_DROP` `DepositTx` + L1 `AdmissionTicketUTXO` cap exclusion (`{0.50, 0.25, 0.25}` deleted-key vaults, `certBlob = 104 B`, `opBitmask`, $2^M$ Hall's Marriage invariant, `zbtc-vault-bundle-v1` public DA); `BitVMX-CPU` `n = 8` wrapped-SNARK verifier bisection (`301` W-OTS digits ≈ `7.44 kvB`, `20` steps, `76.53/16.53 kvB` incl. P2A CPFP, Core `>= 29.0`, `F_chal = 0.40 BTC`); widened timelocks (`[0, 144]` → `1,584 < T_take=1,728 < T_cool=1,872 < Retire=2,016`); acyclic `vault_id` 256-bit Lamport `TakeTx` (`5,922 B` script, `~3.14–3.17 kvB`); native-L1 `Stake_r` `ChalPayoutEscrow` verifier payouts (`0.15 BTC` native BTC each, `>= 0.95 BTC` burn, `+0.0645/+0.0232 BTC` EV @ `500/750 sat/vB`); active-op `(2M_active+1)`-leaf `ExitSlotUTXO` w/ cyclic `(H(exitId)+r) mod M`; full operational capital (`14.75–21.25 BTC` + `M`-dispute headroom) & `94–104d` bank-run math; voluntary unwind circuit breaker (`R8-H08`); Stage 1B `clArk` spec; **Appendix A (Track B Soft-Fork Covenant + BitVM2/BitVM3 Reference)**. | | **Part 2** | [`spec/02-btc-authorization-domain-and-spv.md`](./spec/02-btc-authorization-domain-and-spv.md) | **Stage 0 Direct-on-L1 Bitcoin SPV Event Oracle** (Event Validity only, `len(strippedTx) >= 65`, 1-/2-block coinbase midstate SHA-256 final padding, exact ABI/storage-op/`dp.MaxContractBlocks = 40` budget) + **Stage 1A Bitcoin-L1-Canonical Authorization Domain** (`0x00`..`0x07` `OP_RETURN "ZBTX"` tags, off-chain stripped-block scanner proved by wrapped SNARK `vk_STF`, fail-closed BIP-141 witness authentication on last `6a24aa21a9ed` coinbase output, full stripped-`vin` scan of tracked UTXOs, complete `0x02` DA schema + slotted batcher priority, `K >= 18` unpublished-fork heuristic, interactive heaviest-chainwork comparison, and `>= K` `DEEP_REORG_HALT` circuit breaker). | | **Part 3** | [`spec/03-settlement-minted-zbtc-and-feeless-rails.md`](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | **Stage 0 Erlang-Hardened Non-Custodial PTLC (`T_znn >= 48h`, block-72 RBF watchtower) & LN HTLC (`Δ_safety >= 24h`) Swaps** + **Stage 1A Sovereign Rollup STF `F` & L1-Subsidized Feeless Zenon Sequencer Rails** (explicit `AssignedObligations (A)` conservation `V_unassigned + V_assigned = C + L + E + R + A + B`, hard-partitioned `B_custody`/`B_grief`, oldest-`PendingExit` credit priority, `TransferCredit` & `R -> C` residual consolidation, `MIN_EXIT_SATS = 100,000` sats dust floor, `500`-sat new-leaf deposit + `1,000`/epoch cap, two-column Zenon TPS vs Bitcoin L1 `0x02` DA ceiling) + **Stage 1B `clArk` VTXO Coordination**. | | **Part 4** | [`spec/04-bitcoin-anchoring-and-light-client.md`](./spec/04-bitcoin-anchoring-and-light-client.md) | **Zenon `49%` Consensus Reality (`go-zenon` Code Proof) & Inverted Trust Hierarchy:** Proof of DPoS failure at `49%` (height-only `findSeed`, unweighted top-30 `groupA`, zero slashing, 30-Momentum cliff) and BFT failure at `> 33.3%`, why Bitcoin L1 ordering + DA + forced inbox achieves `0-of-N` Zenon trust (with probabilistic PoW finality at depth `K >= 18`), and non-custodial light-client UX notes. | | **Part 5** | [`spec/05-go-zenon-upgrade-plan.md`](./spec/05-go-zenon-upgrade-plan.md) | **Minimal `go-zenon` Upgrade Plan & R8 Pre-Mainnet Gates G1–G7:** Stage 0 prerequisites (`0aa299e` tag, `#239`/`#299`/`#312` closure, mainnet `PTLC PR #138` & `DynamicPlasmaSpork` activation with 5-parameter `SetPlasmaVariables` pinning, Stage 0 SPV Event Oracle) + **zero-hard-fork custody boundary for Stage 1A/1B** (`SporkAddress` cannot steal BTC or censor L1 exits) + **Bitcoin Core `>= 29.0` (`v31.0` preferred)** + **Gates G1–G7**. | | **Checker** | [`scripts/verify_spec_bounds.py`](./scripts/verify_spec_bounds.py) | Stdlib-only Python 3 Consistency & Bounds Checker asserting all Stage 0 (exact Erlang tails), Stage 1A (`BitVMX n=8`, acyclic `vault_id`, native-L1 verifier EV, $2^M$ Hall, `K >= 18` + Budish sensitivity, `0x02` DA ceilings), Stage 1B (`clArk`), and Proposition 2 bounds + non-no-op randomized state-machine simulation with explicit `A` conservation, `AdmissionTicketUTXO`, concurrent `k = 20` grief burst, `TransferCredit`, real Bitcoin reorgs, and slashes. | | **Changelog** | [`CHANGELOG.md`](./CHANGELOG.md) | Complete **`v1` (`v3.0.0-rfc`) → `v2` (`v3.1.0-rfc`) (`R8` Consolidated Hostile Review Disposition — all 27 findings + verified pushbacks)** plus historical `v0` (`v2.5.0-rfc`) → `v1` (`v3.0.0-rfc`) `R7` disposition and rejection rationale for custodial federated multisigs. | ### 2.1 Authority & Conflict Precedence (`M-13` Fixed) 1. **Bitcoin L1 Consensus & Part 1 Vault Scripts ([`spec/01`](./spec/01-bitcoin-taproot-vault-enforcement.md), `BTC-BITVMX-V1`)** — non-overridable custody layer. Hard-pinned `vk_STF`, deleted-key Taproot graphs, `AdmissionTicketUTXO`s, `StakeChain`, and `ExitSlotUTXO` rules cannot be overridden by any Zenon contract, Pillar, or spork. 2. **Bitcoin-L1-Canonical Authorization & Rollup STF ([`spec/02`](./spec/02-btc-authorization-domain-and-spv.md) & [`spec/03`](./spec/03-settlement-minted-zbtc-and-feeless-rails.md))** — deterministic state transition over Bitcoin L1 blocks (`0x00`..`0x07`). 3. **Stage 0 `go-zenon` Runtime & SPV Event Oracle ([`spec/05`](./spec/05-go-zenon-upgrade-plan.md))** — governs feeless Zenon sequencing UX and Stage 0 non-custodial SPV/PTLC rails; holds ZERO authority over Stage 1A BTC custody. 4. **Non-Custodial Anchoring & Light-Client Infrastructure ([`spec/04`](./spec/04-bitcoin-anchoring-and-light-client.md))** — informational/UX layer only. --- ## 3. End-to-End Protocol Flows & Hostile Scenario Traces ### 3.1 Stage 0: Verify Bitcoin (SPV Event Oracle + Erlang-Hardened Non-Custodial PTLC/LN) Zero pooled BTC custody (`0 BTC` bridge exposure): 1. Relayers submit Bitcoin headers and Merkle inclusion proofs (`len(strippedTx) >= 65`, 1- or 2-block SHA-256 coinbase midstate padding) to the Stage 0 SPV Event Oracle (`spec/02 §2`), proving Event Validity on the best PoW chain. 2. Users swap native BTC / Lightning against Zenon assets atomically via BIP-327 Taproot MuSig2 PTLCs (`<72> OP_CSV` refund leaf, mandatory automated high-fee RBF refund watchtower firing at `h_conf + 72`, `T_znn >= now + 172,800s` = **`48.0h`** achieving `P(T_72 > 48h | 2.3× slowdown) < 10^{-6}` and `>= 9.25h` tail margin past `p99.9 = 38.75h`) or SHA-256 HTLCs (`hashType = 1`, `Δ_safety_blocks = 36`, outbound `Δ_safety_sec >= 86,400s` = **`24.0h`** with `P(T_36 > 24h | 2.3×) < 0.0002`, Hold Invoice rate limits, `spec/03 §1`). Stage 0 atomicity is explicitly conditional on bounded chain progress and timely refund broadcast. ### 3.2 Stage 1A: Sovereign ZK Validity Rollup + Right-Sized `BitVMX` (`n = 8`, `M = 3–5`, `N = 7`) #### Flow A — Acyclic Deposit With L1 `AdmissionTicketUTXO` Cap Exclusion (`Alice 1 BTC`, `Bob 1 BTC`, Closes `R8-C01`, `R8-C03`, `R8-H06`) 1. Alice confirms `1.0 BTC + fee` in her own self-custodial staging UTXO `U_Alice_wallet` (`funding_txid:funding_vout`, Tapscript `OP_DROP OP_CHECKSIG`). Because `funding_txid:funding_vout` is already confirmed on Bitcoin L1, each vault's domain-separated identifier **`vault_id = SHA256("zbtc:vault-id:v1" || funding_txid || funding_vout || vault_vout || amount_sats || opBitmask)`** is 100% deterministic **before** Taproot tree construction (completely acyclic — zero `SHA256(outpoint_d)` cycle!). 2. Alice prepares `DepositTx` spending `vin[0] = U_Alice_wallet` AND **denomination-matched `AdmissionTicketUTXO`s (`vin[1] = Ticket_050`, `vin[2..3] = 2 × Ticket_025`)** → `vout[0..2]` = deleted-key vaults **`{0.50, 0.25, 0.25}` BTC** (`3` vaults/BTC, avg `0.333 BTC`, `maxVaultDenom = 0.50 BTC`) + `vout[3]` = `69 B` `OP_RETURN "ZBTX" || 0x00 || recipientAcctHash(32B) || vaultParamsHash(32B)`. Because `DepositTx` consumes live L1 tickets, two competing deposits racing across `Cap_TVL` cannot both confirm on Bitcoin L1 — the loser's `DepositTx` is rejected by Bitcoin consensus and Alice's BTC never leaves her wallet (`R8-C03`). 3. Alice + `N = 7` presigners + all online operators (`≥ M_min`, recorded in `opBitmask`, checked against the exact **$2^M$ Hall's Marriage Invariant** `R8-C04`) presign the `TakeTx_{d,j,l,r}` graphs (`M × L × R = 5 × 1 × 64 = 320` pre-signed `TakeTx`s per vault ≈ `40 KB`, `< 100ms` MuSig2 ONCE at deposit, each recycling its exact matching `AdmissionTicketUTXO` at `vout[1]`) using fresh per-deposit ephemeral keys `Q_setup_d = MuSig2(P_{1..N,d}, P_{A,d})`. 4. Each presigner **permanently deletes `x_{i,d}`** and signs non-spending identity attestation `σ_cert` over `(txid_dep, Q_setup_d, opBitmask, vaultParamsHash)`, forming `certBlob = σ_cert(64B) || Q_setup_d(32B) || opBitmask(8B)` (`104 B ≤ 520 B` BIP-342 stack limit). The complete **`zbtc-vault-bundle-v1`** (scripts, control blocks, W-OTS/Lamport pubkeys, all presigned `TakeTx`s) is replicated and cryptographically verified across `>= 3` independent public archival mirrors (`R8-H06`). 5. Only after verifying all pre-signed `TakeTx`s, `σ_cert`, and public bundle replication does Alice delete `x_{A,d}`, push `[sig_Alice, certBlob, script, controlBlock]` into `DepositTx.vin[0].witness`, and broadcast. At `K = 18` confirmations, the off-chain ZK prover (verified by `vk_STF`) scans `DepositTx` via stripped block + BIP-141 `wtxid_dep` and credits `1.0 zBTC` to Alice (identical for Bob). #### Flow B — L1-Subsidized Feeless `zBTC` Transfers on Zenon (`AccountBlock.Data`) - Signed rollup transfers (`~110 B`) are submitted in Zenon `AccountBlock.Data`, paying **`0` satoshis direct user BTC fee**, **`0` burned ZNN/QSR**, and **`21,000 + 68 × 110 = 28,480` Plasma** (`14` refundable fused QSR or `~42.7M` SHA3-256 PoW hashes at floor price `1,000`; `~11.4s` soft confirmations). Honest Zenon transport throughput (`4.4/8.8` 2-blk tx/s, `6.5/12.9` 1-blk rollup sends/s, `1,050–1,200` `8 MiB` ceiling) is paired explicitly in `spec/03 §2.2` with **Bitcoin L1's hard physical `0x02` mutated-leaf DA ceiling (`~166.7` blended `10 vB` leaves/s at 100% of all Bitcoin blockspace; `~1.67` leaves/s at 1%)** (`R8-M08`). - To prevent zero-cost `0x02` L1 DA griefing (`R8-M01`), creating a brand-new SMT account leaf locks a **refundable `500`-sat `zBTC` leaf deposit** (reclaimed on full account closure) and batches enforce a **`<= 1,000` new leaves per 6-block epoch** cap. Deterministic **slotted batcher priority** (`primary = H(btc_block_hash) mod K_batchers`, open fallback after 2 blocks) eliminates stale-root `0x02` fee burn (`R8-M02`). - Batch proposers post `0x02 BATCH_DA` every `~6` Bitcoin blocks carrying **complete mutated SMT leaves (`Accounts`, `RollupLocks`, cooperative `PendingExits`)** + succinct embedded proof `π_batch`. First valid `0x02` matching `R_{h-1}` in Bitcoin L1 block/tx order wins; `wtxid`-authenticated malformed batches are deterministically skipped while missing witnesses fail closed (`R8-C05`). #### Flow C — Hostile Trace 1: Bob (`1 BTC → 1 zBTC → spends 0.5 → recovers 0.5 BTC` Under `49%`–`100%` Zenon Compromise) 1. Bob deposits `1.0 BTC` (`{0.50, 0.25, 0.25}` vaults) → `1.0 zBTC` canonical on Bitcoin L1 at `K = 18` confirmations. 2. Bob spends `0.5 zBTC` feelessly on Zenon (retaining `0.5 zBTC`). Even if **`49%`–`100%` of Zenon Pillars are Byzantine**, `go-zenon` permanently splits across its 30-Momentum cliff, Dynamic Plasma spikes `100,000×`, or `SporkAddress` upgrades `go-zenon` maliciously: **no attacker can forge Bob's signature on his remaining `0.5 zBTC` or mutate `vk_STF`**. 3. Bob bypasses Zenon completely by broadcasting a `~150 vB` Bitcoin L1 **`0x01 FORCED_EXIT`** (`0.50 BTC → P_Bob`, `grossSats >= MIN_EXIT_SATS = 100,000` sats) creating a `546`-sat `(2M_active + 1)`-leaf **`ExitSlotUTXO`** with cyclic operator priority `k_r = (H(exitId) + r) mod M_active`. 4. Any `1-of-M` (`M = 3–5`) active operator spends `ExitSlotUTXO` as `vin[0]` and pays **`0.50 BTC - f_op`** directly to `P_Bob` in `vout[0]` (**confirmed in ~1 Bitcoin block / ~10 minutes**). 5. At `K = 18`, the STF credits `ReimbursementCredit[O_j] += 0.50 BTC`, FIFO-assigns one `0.50 BTC` vault `U_d` to `O_j` (moving `0.50 BTC` from `ReimbursementCredit` → **`AssignedObligations (A)`** so `V_unassigned + V_assigned == C + L + E + R + A + B` holds across the `1,728`-block gap!), and `O_j` claims `U_d` via `RoundTx_r → TakeTx` (`T_take = 1,728` blks, verified by `N = 7` pre-committed verifiers under `n = 8` `BitVMX` bisection, recycling `Ticket_050`). #### Flow D — Hostile Trace 2: Mike (`Alice 1 + Bob 1 → Mike 2 → recovers 0.25 BTC` When Zenon Signers Refuse to Sign) 1. Alice (`1.0 BTC`) and Bob (`1.0 BTC`) deposit into `{0.50, 0.25, 0.25}` vaults and send `2.0 zBTC` feelessly to Mike on Zenon. - Once anchored in `0x02 BATCH_DA` at depth `K = 18`, Mike's `2.0 zBTC` has **probabilistic Bitcoin PoW finality under `<50%` honest hashrate** (immune to 100% Zenon + 100% Alice/Bob collusion; `R8-L01`). - If Zenon Pillars stall or refuse to batch BEFORE `0x02` posts, Mike self-includes Alice's and Bob's raw signed transfers directly on Bitcoin L1 via **`0x03 FORCED_TRANSFER`**! *(Pre-L1-batch `~11.4s` Zenon confirmation is honestly disclosed as an L1-subsidized soft confirmation; large receipts like `2 BTC` wait for L1 batch confirmation.)* 2. **Zenon signers refuse to sign everything.** Mike ignores Zenon completely and broadcasts L1 **`0x01 FORCED_EXIT`** (`0.25 BTC → P_Mike`, creating `ExitSlotUTXO`; Mike retains `1.75 zBTC`). 3. Any `1-of-M` (`M = 3–5`) active operator spends `ExitSlotUTXO` and pays **`0.25 BTC - f_op`** directly to `P_Mike` in `vout[0]` (~10 minutes). **Alice and Bob cannot front-run or steal it; Bitcoin L1 UTXO exclusion prevents double-fronting.** 4. At `K = 18`, the STF FIFO-assigns one `0.25 BTC` vault to `O_j` (moving `0.25 BTC` into `AssignedObligations (A)`; the remaining `0.75 BTC` of Alice's split — `0.50 + 0.25` — stays untouched in deleted-key BitVMX vaults!). For arbitrary non-bucket exits (`>= 0.001 BTC` = `MIN_EXIT_SATS`), `O_j` still pays the exact amount in `FrontingTx`, accumulates `ReimbursementCredit[O_j]`, and may consolidate `< 0.25 BTC` residuals via `TransferCredit(from_op, to_op, amt)` (`R8-M04`). Oldest-`PendingExit` credit priority blocks operators from jumping ahead of waiting retail exits via fresh self-fronting (`R8-N01`). 5. **Fee-spike & grief recovery:** If Bitcoin fees spike above `f_op`, Mike bumps `f_op` via `0x06 EXIT_FEE_BUMP` (or Dutch-auction fee schedule) or cancels after `<288> OP_CSV` via Leaf `2M_active` (`EXIT_CANCEL`, restoring `0.25 zBTC`, NOT native BTC). If a rogue operator sweeps `ExitSlotUTXO` without paying `vout[0]` (even in a concurrent `k = 20` burst!), the STF atomically refunds `100%` of `grossSats` `zBTC` to every victim, distributes up to `0.01 BTC`/victim (pro-rata capped strictly at `O_j`'s hard-partitioned `0.05 BTC` `B_grief` buffer — **zero `B_custody` overflow!**), suspends `O_j`, and excludes `O_j` from all new `ExitSlotUTXO` scripts (`R8-H01`, `R8-N05`). --- ## 4. Honest Threat Model, Residual Boundaries & Privileged Powers Table (`H-3`, `R8-C06`, `R8-H03`, `R8-H08`) **`v2` Stage 1A (`BitVMX` Rollup) is trust-minimized (`Tier 1`), NOT pure `Tier 0` (which Proposition 1 proves requires a Bitcoin soft fork — see `spec/01 Appendix A`).** Delivered security is bounded by the following explicit, un-sugarcoated assumptions: 1. **Zero Zenon Consensus or ZNN Market-Cap Trust (`0-of-N` Zenon — Survives 49%–100% Zenon Compromise):** Neither Zenon Pillars, `go-zenon` DPoS/BFT, ZNN's `~25–33 BTC` market cap, nor Zenon `SporkAddress` sit in the Bitcoin custody safety or L1 forced-exit path. Zenon Plasma DoS temporarily degrades *feeless* UX to L1 BTC fees (`0x03`/`0x01`), never custody. 2. **`1-of-N` Ephemeral Setup Deletion & Open-Cohort Attestation (`N = 7` Pilot):** At least 1 of `N` presigners honestly deletes its per-deposit ephemeral share `x_{i,d}` (depositor also participates and deletes `x_{A,d}`!) AND at least 1 of `N` long-term attestation keys `id_i` remains uncompromised while a cohort is open to new deposits. Compromising all `N` `id_i` keys cannot sweep existing deleted-key vaults; losing 1 of `N` `id_i` never bricks existing vaults (only halts *new* deposits on `v1`, requiring a clean non-commingled `zBTC_v2`). 3. **`1-of-N` Pre-Committed Online Verifier Safety (`N = 7` Pilot, NOT `1-of-∞`):** At least 1 of `N = 7` independent pre-committed verifiers monitors Bitcoin within `[0, 144]` blks (~24h) and runs `n = 8` `BitVMX` bisection (`20` steps, `T_step = 72` blks, `16.53 kvB` total verifier weight incl. `10 × 153 vB` P2A CPFP on Bitcoin Core `>= 29.0` + direct-to-miner backup). Anyone on Earth can detect fraud and alert all 7 verifiers off-chain, and every active honest verifier receives **`0.15 BTC` in native Bitcoin L1 BTC directly from `Stake_r` (`0%` `zBTC` crisis discount!)**, yielding **`+0.0645 BTC` net EV @ `500 sat/vB`** (`+0.0232 BTC` even @ `750 sat/vB`, break-even `890 sat/vB`, after CPFP and `0.00285 BTC` lockup) even if `6 of 7` verifiers collude with the operator. If ALL `7` verifiers go offline or collude simultaneously during `[0, 144]`, a cheating operator can steal `≤ 0.50 BTC`/round. Simultaneous `M`-operator attacks require `0.483 BTC/lane` (`1.45 / 2.41 BTC`) of liquid standby in at least 1 honest verifier (`R8-H02`). 4. **`1-of-M` Pre-Committed Operator Exit Liveness (`M = 3–5` Pilot — Irreducible Corollary 1B Bound, `R8-C06`):** Stage 1A vaults carry **no CLTV expiration**, but native Bitcoin L1 recovery strictly requires at least `1-of-M` active eligible operators (`opBitmask` satisfying Hall's Marriage Invariant) with liquid BTC to front exits. **If `0-of-M` operators remain permanently offline (`100%` permanent disappearance), native BTC remains permanently unrecoverable on Bitcoin Mainnet today** (`0` theft; `EXIT_CANCEL` after `288` blocks restores `zBTC` inside the rollup, **NOT** native BTC on L1). This is an irreducible no-covenant boundary (Proposition 1). 5. **Sustained Dispute Fee-Rate Envelope (`≤ 500 sat/vB` for `10.0` Consecutive Days on Core `>= 29.0`):** `F_chal = 0.40 BTC` covers `76.53 kvB` Prover bisection (incl. `10 × 153 vB` P2A CPFP) up to `522 sat/vB` sustained across all `20` steps (`10.0` days); Verifier `16.53 kvB` is covered in native L1 BTC (`0.15 BTC`) up to **`890 sat/vB`** after lockup cost. Historical peaks (`1,805 sat/vB` April 2024 lasted `~33h` ≈ 2–3 steps) fit comfortably; a hypothetical 10-day `> 522 sat/vB` spike erodes honest prover coverage. 6. **Probabilistic PoW Finality & Conditional Private-Fork Heuristic (`K >= 18`, `R8-H03`, `R8-M07`, `R8-L01`):** Depth `K >= 18` provides **probabilistic PoW finality under `<50%` honest hashrate** (NOT absolute finality). The inequality `0.50 × K × Subsidy(era) > Cap_TVL_total` (`Cap_user + M × B_zbtc`) is explicitly an **unpublished-fork opportunity-cost heuristic** (under Budish's winning-fork subsidy offset, a majority-hashrate attacker publishing the winning chain recaptures subsidies and pays net flow/hardware cost `κ × K × Subsidy` plus external BTC-devaluation cost). Each lane pins `(h_lane_init, H, D)` with `D(h) ≥ 0.50 × D(h_lane_init)`, supports **interactive heaviest-chainwork competing-header comparison** inside `vk_STF`, and enforces a fail-closed **`DEEP_REORG_HALT`** circuit breaker with `>= 144`-block rollback snapshots if a `>= K` reorg ever occurs. 7. **Immutable `vk_STF` Bug Risk (`R8-H08`):** Because `vk_STF` is immutable on existing vaults (zero governance override), a soundness or completeness bug in `vk_STF` could freeze or threaten active vaults. Mitigated strictly BEFORE mainnet via formal verification & Bitcoin Core differential fuzzing (Gate G4), graduated TVL ramps (`2 → 5 → 15 BTC`), and a non-custodial voluntary unwind circuit breaker (`spec/01 §6.3`). 8. **Bank-Run Recycling Queue (`~94–104` Days for 100% Run at `M = 3–5, L = 1`, `T_cooldown = 13.0d`):** While individual exits front in ~10m up to available operator float (`2.20–3.00 BTC`), a 100% bank run recycles at `0.077 BTC/day` (`M = 3`, `~101–104d` for `10 BTC` user cap) or `0.128 BTC/day` (`M = 5`, `~94–104d` for `15 BTC` user cap) under `{0.50, 0.25, 0.25}` vaults (or `~62–68d` under `{0.50, 0.50}` vaults). Oldest-`PendingExit` credit priority blocks self-fronting queue jumping (`R8-N01`), while secondary-market `zBTC` discounting during prolonged queues remains an explicit economic risk. 9. **Stage 1B (`clArk`) Alternative Assumptions (If Chosen Instead):** Zero operator bonds and pure `0-of-N` post-round unilateral exit until VTXO expiry, BUT sacrifices pooled fungible `zBTC`, carries hard VTXO expiry (`log2(N)` L1 branch exit fees, requiring watchtower refresh), requires `100%` ASP liquidity per cycle, and exposes pre-round `arkoor` transfers to `sender + ASP` collusion. ### 4.1 Complete Privileged Powers Table (`H-3` Closed — ZERO Custodial Authority) | Power / Action | Holder | Threshold | Timelock | Maximum Effect / Blast Radius on Stage 1A BTC Custody | |---|---|---|---|---| | **Spend Existing Stage 1A BTC Vaults (`U_d`)** | **NOBODY (ephemeral `Q_setup_d` deleted)** | N/A | N/A | **0 sats custodial sweep power.** Spendable ONLY via pre-signed `TakeTx` after `T_take = 1,728` blks subject to `N = 7` `BitVMX` verifiers + Lamport equivocation slash. | | **Mutate Rollup STF Rules (`vk_STF`) on Existing Vaults** | **NOBODY (`vk_STF` hard-pinned at `t = 0`)** | N/A | N/A | **0 effect.** No Zenon spork, governance vote, or operator can alter STF rules on existing vaults (see `spec/01 §6.3` for non-custodial voluntary unwind circuit breaker). | | **Voluntary Cohort Handover (Same `vk_STF` Only)** | Cohort 1 Presigners (`id_1..id_N`) | **`N`-of-`N` (`7-of-7`)** | None (new deposits only) | Strictly `1-of-N` safe; cannot touch existing vaults. Involuntary `1-of-N` loss halts new `v1` deposits cleanly (`zBTC_v2` required). | | **Zenon Protocol Sporks (`CreateSpork`, `ActivateSpork`, `SetPlasmaVariables`)** | `SporkAddress` (`z1qpxsw...`) / `CommunitySporkAddress` (`z1qqvwz...`, window heights `14,567,887–19,791,986`, `origin/dev:vm/embedded/definition/spork.go`) → future `GovernanceContract` | `1-of-1` today | `SporkMinHeightDelay = 6` Momentums (node layer) | **0 BTC custody blast radius in Stage 1A.** Can disrupt feeless Zenon sequencing or Stage 0 embedded SPV contract, but **cannot steal 1 satoshi from BitVMX vaults or censor L1 `0x01`/`0x03` exits**. *(Stage 0 pins full `SetPlasmaVariables` floor in `spec/05`.)* | | **Operator Fronting & Reimbursement Claim (`O_1..O_M`)** | Independent Bonded Operators (`M = 3–5` pilot) | `1-of-M` for exit liveness | `T_take = 1,728` blks; `T_cooldown = 1,872` blks | **Zero theft power** under `1-of-N` verifier honesty (`-2.00` to `-1.10 BTC` L1 loss alone; `-2.55` to `-1.65 BTC` incl. `B_custody` across `k_collude = 0..6`); permanent `0-of-M` disappearance permanently stalls native BTC exits (`0` theft; `EXIT_CANCEL` restores `zBTC` only). | | **BitVMX Fraud Challenge (`V_1..V_7`)** | Independent Pre-Committed Verifiers (`N = 7`) | **`1-of-7`** | `[0, 144]` blks open; `T_step = 72` blks | Any 1 honest verifier stops fraud, collects **`0.15 BTC` native L1 BTC** directly from `Stake_r` (`+0.0645 BTC` net EV @ `500 sat/vB`, `+0.0232 BTC` @ `750 sat/vB` after CPFP & lockup), and forces `0.95–1.85 BTC` L1 burn. | --- ## 5. Reference `go-zenon` Ground-Truth Baseline (`M-3`, `B1`, `B2`, `L-3`, `R8-M08`) - **Verified Local Clone:** `master` (`e8986a6`, `v0.0.10-alphanet`, live mainnet `v1` Momentums capped at `100` blocks/Momentum) and `origin/dev` (`770e893`, carrying `DynamicPlasmaSpork`, `PtlcSpork`, `Libp2pSpork`). *(Note: upstream commit `0aa299e`, `PTLC PR #138` mainnet merge/spork activation, and open issues `#239`, `#299`, and `#312` are NOT yet active on `go-zenon` mainnet and remain explicit Stage 0 upstream release gates — Gate G6.)* - **Stage 0 Hard Preconditions (`spec/05`):** (1) First tagged mainnet `go-zenon` release containing `0aa299e`; (2) closure of upstream issues **`#239`** (FIFO panic-stall deterministic failed receive, **B1**), **`#299`**, and **`#312`**; (3) mainnet merge & activation of **`PTLC PR #138`** (`PtlcSpork`) and **`DynamicPlasmaSpork`** with **complete 5-parameter `SetPlasmaVariables` pinning** (`MaxBasePlasmaInMomentum >= 2,100,000`, `MaxPriceChangePercent <= 25%`, `FusedPlasmaTarget >= 525,000`, `PowPlasmaTarget >= 525,000`, `PriceChangeDenominator >= 8`). - **Stage 1A / 1B Zero-Hard-Fork Property:** Stage 1A Rollup nodes read standard Zenon `AccountBlock.Data` and Bitcoin L1 — requiring **zero `go-zenon` consensus hard fork** beyond Stage 0. --- ## 6. Upstream Amendment Register (`v2` Zero-Federation Scope) | ID | Upstream Target | Status in `v2` | Normative Requirement | |---|---|---|---| | **A-SPEC-1, A-SPEC-2, A-SPEC-6** | `Project Zeno` optimistic bridge framework | **Not required in `v2`** | Stage 0 uses direct Event-Validity SPV; Stage 1A uses Bitcoin-L1-canonical ZK validity (`0x00`..`0x07`). | | **A-SPEC-4** | Deterministic Exit ID | **Required (`Stage 1A`)** | `exitId = SHA256("ZBTX_EXIT_V1" \|\| bitcoinTxid \|\| voutOrIdx \|\| nonce)` derived deterministically on Bitcoin L1; priority sequence uses cyclic permutation `k_r = (H(exitId) + r) mod M_active`. | | **A-BTC-1** | Bitcoin Refund / Exclusion Rules | **Required (`Stage 1A`)** | Refunds enforced strictly by Bitcoin L1 UTXO exclusion (`ExitSlotUTXO` spend-or-refund rule) — zero timeout-vs-fronting double-pay races (`M-8`), hard-partitioned `B_grief` (`0.05 BTC`), and active-operator-only Taproot trees (`R8-H01`). | | **A-MINT-1** | `TokenContract.IssueMinted` | **Retired in `v2`** | Stage 1A `zBTC` balances live in the Bitcoin-canonical Rollup SMT (NOT pre-minted inside a Zenon embedded contract, eliminating `H-8` entirely!). | | **A-PILLAR-1** | `go-zenon` `pillars.go` BLS12-381 & 72d lock | **Not required in `v2`** | Zenon consensus & Pillar committees are removed from BTC custody completely (`spec/04`). | --- ## 7. Phased Delivery, Capital Decision Gates & Zero-Dead-End Growth (`M-15`, `R8-H08`, `R8-M09`) | Stage | Timeline & Full Hard-BTC Capital | Normative Scope & Blocking Exit Criteria | Zero-Dead-End Migration Guarantee | |---|---|---|---| | **Stage 0 (Mandatory Foundation — Verify Bitcoin)** | **`0–6 months`**, **`0 BTC` bridge custody risk** (`0–5 BTC` voluntary LP) | Ship `go-zenon` Gate G6 (`0aa299e`, `#239`/`#299`/`#312`, mainnet `PR #138` & `DynamicPlasmaSpork` 5-param pin), **Direct-on-L1 Bitcoin SPV Event Oracle** (`len(strippedTx) >= 65`, 1-/2-block coinbase midstate, `≤ 24` storage ops, `dp.MaxContractBlocks = 40`), and **Erlang-hardened non-custodial PTLC (`T_znn >= 48h`, block-72 RBF watchtower) / LN HTLC (`Δ_safety >= 24h`) swaps**. Build & benchmark Rollup STF + wrapped SNARK verifier on `BitVMX-CPU` (`RV32IM`) and evaluate BitVM3-GC on Signet. | Zero custodial BTC at risk while proving every Rollup + `BitVMX` primitive on Signet. | | **Stage 1A (Primary Path — Right-Sized `BitVMX` Rollup)** | **`12–18+ months` (incl. audit, 4–6 engineers)**; **Locked:** `12.80` (`M=3`) / `18.80 BTC` (`M=5`); **Operational Baseline (1 dispute):** **`14.75`** (`45–59%` ZNN mcap) / **`21.25 BTC`** (`64–85%` ZNN mcap); **Multi-dispute headroom:** `~17–26+ BTC` (`spec/01 §6`) | **Hard Entry Gates G1–G5 + M-15:** (G1) Bitcoin Core `>= 29.0` (`v31.0` preferred) `regtest`/`signet` full graph execution incl. `AdmissionTicketUTXO` & `153 vB` P2A 1P1C CPFP; (G2) compiled `RV32IM` wrapped-SNARK verifier ELF proving `init_steps + exec_steps <= 0.5 × 8^9` (else `l = 10` or BitVM3 evaluation); (G3) extended `verify_spec_bounds.py` clean; (G4) formal verification of `V=C+L+E+R+A+B`, $2^M$ Hall, & BIP-141 completeness + Bitcoin Core differential fuzzing; (G5) `zbtc-vault-bundle-v1` disaster-recovery drill; (M-15) independent third-party audit; **Graduated TVL ramps:** **`2 BTC` (90d) → `5 BTC` (90d) → `10/15 BTC`**. | Non-expiring deleted-key vaults stay redeemable 1:1 via `0x01 FORCED_EXIT` subject to `1-of-M` operator liveness (plus voluntary unwind circuit breaker in `spec/01 §6.3`). | | **Stage 1B (Explicit Alternative Gate — `clArk`)** | **`3–6 months`**, **`2–5 BTC`** active ASP liquidity (`0` bonds) | **Trigger:** Choose Stage 1B ONLY if the ecosystem cannot commit `~14.75–21.25+ BTC` of non-yielding hard BTC OR prioritizes `3–6 mo` launch / `0-of-N` post-round exit over pooled fungibility. Deploy `Second bark` / `Ark Labs arkd` + automated watchtowers + Zenon SPV/PTLC (`spec/01 §7`, `spec/03 §3`). Do **NOT** under-bond `BitVMX`/`BitVM2`. | Users hold self-custodial expiring VTXOs with unilateral L1 exit; explicitly non-commingled with any future Rollup `zBTC`. | | **Stage 2 (Zero-TTP Scale & Upgrade)** | **`12+ months` post-Stage 1** (`15–200+ BTC` TVL, or unlimited w/ soft fork) | **(a) Same-STF `BitVMX` scaling (`M=5→20, L=1→4, K=42→144`):** strictly via pre-planned **`N`-of-`N` Cohort 1 voluntary handover** (zero governance key). **(b) Custody backend upgrades (`BitVM3-GC` / `BitVM2` / Appendix A Track B Pure Tier-0 `OP_CCV` or `OP_CAT` Covenant):** ALWAYS launch a clean, non-commingled `zBTC_v2` reusing the open-source Rollup STF codebase. | Zero deleted-key L1 rollover needed; Stage 1A vaults drain organically 1:1 to native BTC via `0x01` exits. | --- ## 8. Alignment with Zenon's Non-Bridging Philosophy (`Verify Bitcoin, Don't Bridge It.md`) - **Stage 0** implements `Verify Bitcoin, Don't Bridge It.md` verbatim: Bitcoin stays strictly in user custody while Zenon imports verified PoW Event Validity and coordinates atomic PTLC/LN swaps. - **Stage 1A** respects the essay's core warning (*"Zenon can't prevent spending. That's Bitcoin's job"*) by refusing custodial federations and refusing to place Zenon consensus in Bitcoin's enforcement path — pushing 100% of custody enforcement, canonical ordering, DA, and forced exits onto Bitcoin L1 (`BitVMX` + ZK validity). --- ## 9. Public Claims Alignment (`bigidea` Synchronization) All public materials (including [`btc-moonshot.github.io/bigidea`](https://btc-moonshot.github.io/bigidea/)) MUST match `v2` (`v3.1.0-rfc`) verbatim: | Outdated Public Claim (`v0` / `v1` / `bigidea` errata) | Accurate `v2` (`v3.1.0-rfc`) Statement | |---|---| | "The network never holds a pooled key" / "100% live forever" | **True in `v2` for existing vault spend keys:** per-deposit ephemeral keys `Q_setup_d` are permanently deleted at deposit (with zero custodial federation). **Honest disclosure (`R8-C06`):** Stage 1A vaults carry *no CLTV expiration*, but native BTC recovery requires `1-of-M` (`M = 3–5`) active eligible operators (`0-of-M` permanent disappearance permanently locks native BTC; `EXIT_CANCEL` restores `zBTC` only), plus `1-of-N` (`N = 7`) open-cohort attestation and `1-of-7` pre-committed online `BitVMX` verifiers. Pure `0-of-N` unilateral exit requires a Bitcoin soft fork (`spec/01 Appendix A`). | | "One honest watcher can stop a bad payout" | **Clarified for Stage 1A:** Any **`1-of-7` pre-committed online `BitVMX` verifier** can stop a bad payout with positive native-L1 EV (**`+0.0645 BTC` @ `500 sat/vB`**, **`+0.0232 BTC` @ `750 sat/vB`** after CPFP & lockup), and anyone on Earth can detect fraud and relay it to all 7 verifiers. (`1-of-∞` permissionless BitVM2 requires `~40–91+ BTC` in bonds even at `M=3–5`.) | | Proofs "end at Bitcoin's proof-of-work" / "100% Bitcoin PoW finality" | **Clarified (`R8-L01`):** Canonical `zBTC` state ordering, DA (`0x02`), and forced exits (`0x01`/`0x03`) are anchored directly on Bitcoin PoW with `0%` Zenon consensus trust, delivering **probabilistic PoW finality at depth `K >= 18` under `<50%` honest hashrate** (subject to conditional unpublished-fork heuristic and interactive heaviest-chainwork dispute verification). | | "Security is funded by the network's own staking token" | **False — explicitly rejected.** ZNN (`~25–33 BTC` total market cap) is **0% in the BTC custody safety path**; all operator/verifier collateral and operational reserves (`14.75–21.25+ BTC`) are hard BTC. | | "Millions of transactions per second"; per-second streams | Zenon Dynamic Plasma (`~11.4s`/Momentum) provides `~4.4`/`8.8` 2-blk tx/s, `~6.5`/`12.9` 1-blk rollup sends/s (`2.1M`/`4.2M`), and a **`~1,050–1,200` tx/s `8 MiB` Zenon transport ceiling** — strictly bounded for L1-anchored settlement by **Bitcoin L1's `0x02` physical DA ceiling (`~166.7` blended `10 vB` leaves/s at 100% of Bitcoin blockspace; `~1.67` leaves/s at 1%)** (`R8-M08`). | | "0 satoshi fees" / unbounded free transfers | **L1-subsidized soft preconfirmations (`0` sat direct user BTC fee on Zenon `AccountBlock.Data`, costing `28,480` refundable QSR/PoW Plasma; NOT native ZTS).** Creating a brand-new SMT account locks a refundable `500`-sat `zBTC` leaf deposit (`<= 1,000` new leaves/6-block epoch) to bound `0x02` L1 DA spam (`R8-M01`). Deposits, L1 forced exits (`0x01`), and fronting spreads pay Bitcoin L1 fees. | | "Oracle verified" | **Consistency-checked** via `scripts/verify_spec_bounds.py` against `SOURCED_`, `POLICY_`, and `PRE_MAINNET_TARGET_` inputs; not empirically audited until Gates G1–G6 & M-15 pass. | | Omission of Zenon / ZNN / QSR / Pillars / Core `>= 29.0` | Public pages MUST explicitly name **Zenon Network, ZNN, QSR, and Pillars**, pin **Bitcoin Core `>= 29.0` (`v31.0` preferred)**, and disclose `BitVMX-CPU`'s pre-mainnet status (`12–18+ mo` timeline), `14.75–21.25+ BTC` full operational capital, and `~94–104d` 100% bank-run exit queue (`T_cooldown = 13.0d`). | --- ## 10. Written Answers to Consolidated Hostile Review (`R8`) & Historical `R7` Summary Every one of the 12 mandatory questions raised in [`R8 §24`](./reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md) against archived `v1 (v3.0.0-rfc)` is answered normatively in `v2 (v3.1.0-rfc)` (with zero federated multisigs; full 27-finding `R8` + 31-finding `R7` disposition tables live in [`CHANGELOG.md`](./CHANGELOG.md)): 1. **`R8-C01` (Circular `SHA256(outpoint_d)` Lamport cycle):** *Confirmed & fixed (Amendment A1).* Replaced `SHA256(outpoint_d)` with acyclic pre-funding `vault_id = SHA256("zbtc:vault-id:v1" || funding_txid || funding_vout || vault_vout || amount_sats || opBitmask)` bound to the already-confirmed `U_dep_wallet` outpoint (`spec/01 §2.2, §3.3`). `TakeTx` is `~3,142–3,166 vB <= 3,200 vB` TRUC v3 parent with `258` peak stack and zero unconfirmed TRUC child chaining. 2. **`R8-C02` (Missing `AssignedObligations (A)` in conservation law):** *Confirmed & fixed (Amendment A2).* Added explicit `AssignedObligations (A)` SMT namespace and amended conservation to `V_unassigned + V_assigned = C + L + E + R + A + B` with atomic transitions for `fifo_assign`, `take_confirmed`, `0x07 release_assignment`, `disprove_dual_slash`, `lamport_equivocation_slash` (including cross-operator equivocation recovery), `retire`, and `reorg` (`spec/03 §2.1`, verified explicitly in `verify_spec_bounds.py` across the `T_take` gap!). 3. **`R8-C03` (Deposit race past `Cap_TVL` burning BTC):** *Confirmed & fixed (Amendment A3).* Enforced `Cap_TVL_total` mutual exclusion directly at Bitcoin L1 consensus via denomination-matched **`AdmissionTicketUTXO`s** (`1 × Ticket_050 + 2 × Ticket_025` consumed as `DepositTx.vin[1..3]` and recycled at `TakeTx.vout[1]`, `spec/01 §2.2`), plus optional two-stage `PreDepositUTXO`. Competing deposit losers never spend `U_dep_wallet`. 4. **`R8-C04` (Global round cap violates Hall's Marriage Theorem):** *Confirmed & fixed (Amendment A4).* Mandated the exact $2^M$ **Hall's Marriage Invariant** across all `deposit_admit`, `operator_retire`, `round_consume`, and `operator_slash` transitions (`<= 31` subset checks at `M = 5`), tightest-slack FIFO prioritization, and retirement unlock gating (`spec/01 §6.2`, tested in `verify_spec_bounds.py`). 5. **`R8-C05` (BIP-141 witness completeness, untagged spends, `0x02` DA schema):** *Partially confirmed & fixed (Amendment A5).* While `v3.0.0-rfc` `spec/02:L115` already mandated BIP-141 `wtxid` verification, `v3.1.0-rfc` closes all 3 real gaps: (a) extract witness commitment from the **LAST** coinbase output starting with `0x6a24aa21a9ed` (`len >= 38 B`, coinbase `wtxid = 0x00^32`) and formally separate **fail-closed (`REFUSED_DATA_UNAVAILABLE`)** on missing/unauthenticated witness from **deterministic skip** on `wtxid`-authenticated malformed payload; (b) scan **every `vin` of every stripped transaction** for untagged spends of tracked protocol UTXOs; (c) expand `0x02 BATCH_DA` binary schema to serialize `Accounts`, `RollupLocks`, and cooperative `PendingExits` (`spec/02 §3.1–3.2`). 6. **`R8-H01` & `R8-N05` (Concurrent/post-suspension `ExitSlotUTXO` griefing draining `0.55 BTC` verifier pool):** *Confirmed & fixed (Amendment A7).* Hard-partitioned `B_grief` (`0.05 BTC`) from `B_custody` (`0.55 BTC`) with pro-rata burst capping (`0` sats ever debited from `B_custody`), excluded suspended operators from all new `ExitSlotUTXO` Taproot trees (`2M_active + 1` leaves), AND moved all verifier bounties onto **Bitcoin L1 `Stake_r`** (`0%` coupling to `B_zbtc` — `R8-N05` eliminated completely!). 7. **`R8-H02` (Crisis-discounted `zBTC` verifier payouts, CPFP/lockup EV, `M`-simultaneous dispute liquidity):** *Confirmed & fixed (Amendment A7).* Restructured `DisproveTx_{r,i}`/`TimeoutSlashTx_{r,i}` on `Stake_r (2.00 BTC)` to pay **`0.15 BTC` in native Bitcoin L1 BTC** to EVERY active honest challenger via `6` `ChalPayoutEscrow_{r,j}` outputs paired with `ChalProofConnector_{r,j}` (`0.95 BTC` minimum immediate burn, zero `2^7` explosion!). Net honest verifier EV including `16.53 kvB` P2A CPFP + `0.00285 BTC` lockup is **`+0.0645 BTC` @ `500 sat/vB`** and **`+0.0232 BTC` @ `750 sat/vB`** (`890 sat/vB` break-even, `0%` `zBTC` discount!), while combined attacker P&L stays `-2.00` to `-1.10 BTC` on L1 alone (`-2.55` to `-1.65 BTC` incl. `B_custody`). Multi-dispute verifier liquidity (`1.45 / 2.41 BTC` per honest verifier across `M = 3 / 5` simultaneous disputes) is explicitly budgeted in `spec/01 §6`. 8. **`R8-H05` (`RV32IM` $8^9$ instruction budget contradiction):** *Confirmed & fixed (Amendment A9).* Clarified normatively across `spec/01 §3.2`, `spec/02 §3.2`, and `spec/05 §3` that `BitVMX-CPU` (`RV32IM`) executes **strictly a constant-size wrapped SNARK verifier (`vk_STF`)**, NEVER bare 1 MB SHA-256 block scanning; gated Stage 1A on **Gate G2** (compiled ELF proving `init_steps + exec_steps <= 0.5 × 8^9`, else `l = 10` or BitVM3). 9. **`R8-H03` & `R8-M07` (Private-fork bound vs Budish subsidy offset, canonical fork check, `>= K` reorg):** *Confirmed & fixed (Amendment A8).* Relabeled `0.50 × K × Subsidy > Cap_TVL_total` honestly as an unpublished-fork opportunity-cost heuristic (printing Budish net flow-cost sensitivity in `verify_spec_bounds.py`), raised the minimum floor to **`K >= 18`** covering `Cap_user + M × B_zbtc`, specified **interactive heaviest-chainwork competing-header comparison** inside `vk_STF`, and mandated a fail-closed **`DEEP_REORG_HALT`** circuit breaker with `>= 144`-block rollback snapshots (`spec/02 §4`). 10. **`R8-H07` (Stage 0 PTLC & LN HTLC Erlang tail failure):** *Confirmed & fixed (Amendment A10).* Raised Stage 0 `T_znn` from `30h` to **`>= 48h` (`172,800s`, `P(T_72 > 48h | 2.3×) < 10^{-6}`)** and outbound LN HTLC `Δ_safety_sec` from `6h` to **`>= 24h` (`86,400s`, `P(T_36 > 24h | 2.3×) < 0.0002`)**, mandated automated block-72 RBF refund watchtowers, and disclosed conditional atomicity (`spec/03 §1`). 11. **`R8-N01` & `R8-M01` (Bank-run self-fronting arbitrage & feeless `0x02` DA spam):** *Confirmed & fixed (Amendment A11).* Enforced oldest-`PendingExit` timestamp priority for reimbursement credit eligibility + optional Dutch-auction fee discovery (`R8-N01`), reframed Zenon transfers as L1-subsidized soft preconfirmations, and bounded `0x02` new-leaf DA spam via a refundable `500`-sat `zBTC` new-account leaf deposit + `<= 1,000` new leaves/6-block epoch cap + deterministic slotted batcher priority (`spec/03 §2.2–2.4`). 12. **`BitVMX-CPU` vs `BitVM3-GC` engineering trade-off:** *Answered transparently (`spec/01 Appendix A.2`, Gate G2).* While BitVM3 shrinks on-chain disprove size to `~93 vB` / 2 rounds, current non-reusable BitVM3 garbled circuits introduce a **`1-of-N` garbler trust assumption** AND require **`~2.2–11.2+ TB`** of one-time off-chain garbled-circuit DA across `M × L × R × N = 5 × 1 × 64 × 7 = 2,240` rounds (`1–5 GB` per round!). Stage 0 runs an explicit **Gate G2** evaluation comparing compiled `RV32IM` BitVMX-CPU traces against emerging reusable DV-SNARK BitVM3-GC before locking Stage 1A's final custody engine — and Stage 2 cleanly supports a non-commingled `zBTC_v2` upgrade if reusable BitVM3 matures later. *(Historical `R7` closures — `C-1..C-4`, `H-1..H-8`, `M-1..M-15`, `L-1..L-4`, `N-1..N-6`, `B1..B5` — remain intact in [`CHANGELOG.md`](./CHANGELOG.md). Note also verified pushbacks on `R8`: `R8-M06` anti-64-byte filtering was already present at `spec/02:L67-72` and tightened to `>= 65 B`; `R8-M08` `4.4/8.8` and `6.5/12.9` Plasma rates were exact at observed `11.4s`/Momentum; `R8-C05` BIP-141 `wtxid` checking was already present at `spec/02:L115`; and `R8-H03` used `K = 14`, now raised to `K >= 18`.)* # Part 1: Zero-Federation Bitcoin Taproot Vault Enforcement (`BTC-BITVMX-V1`), Stage 1B `clArk` Gate & Track B Soft-Fork Annex **Document Class:** Normative Bitcoin Custody Specification (`v2` / `v3.1.0-rfc`; supersedes archived `v1` `v3.0.0-rfc` and `v0` `BTC-ENFORCEMENT-V1`) **Spec Identifier:** `BTC-BITVMX-V1` **Precedence:** **Highest normative layer** ([`SPEC.md §2.1`](../SPEC.md#21-authority--conflict-precedence-m-13-fixed)) — Bitcoin L1 scripts, deleted-key Taproot graphs, `AdmissionTicketUTXO`s, `StakeChain` timelocks, and `ExitSlotUTXO` consensus rules cannot be overridden by any Zenon contract, Pillar, or spork. **Target Chain:** Bitcoin Mainnet TODAY (`bip-0141` SegWit, `bip-0340` Schnorr, `bip-0341` Taproot, `bip-0342` Tapscript, `bip-0068`/`bip-0112` relative CSV timelocks, `bip-0431` TRUC v3 + `0`-sat `P2A` ephemeral dust + 1P1C package relay requiring **Bitcoin Core `>= 29.0`**, `v31.0` preferred — **zero Bitcoin soft forks**, **zero custodial federated multisigs**) **Consistency Checker:** [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py) --- ## 1. Cryptographic Boundaries (Proposition 1 & Proposition 2) & Prohibition of Federated Custody ### 1.1 Explicit Prohibition of Custodial Federated Multisigs Pooled custodial `k`-of-`n` multisig federations (whether `OP_CHECKSIGADD`, FROST, or HSM-backed, with or without custodial backup recovery leaves) are **STRICTLY FORBIDDEN** in `v2`. Federated custody introduces up to `100%` collusion loss, breaks liveness whenever `n - k + 1` signers refuse to sign Mike's `0.25 BTC` exit, and stalls under `49%` Zenon DPoS consensus splits. ### 1.2 Formal Boundary Propositions **Proposition 1 (4-Way Impossibility of Pure `0-of-N` Arbitrary Unilateral Exit on Bitcoin Mainnet Today):** On Bitcoin Mainnet today (BIP-340/341/342, zero covenant soft forks), no protocol can simultaneously achieve: **(1)** pooled cross-depositor deposit UTXOs `U_A` (`1 BTC`), `U_B` (`1 BTC`) created at `t_0`, **(2)** `0-of-N` unilateral liveness at `t_1` allowing an unknown future recipient Mike (`P_Mike`, `0.25 BTC` unknown at `t_0`) to spend `U_A` or `U_B` paying `0.25 BTC → P_Mike` while locking `0.75 BTC` back into custody with zero new signatures at `t_1`, **(3)** zero per-hop key-deletion / statechain trust across prior owners, and **(4)** non-expiring fungible liquidity: 1. BIP-342 Tapscript lacks output introspection (`nValue`/`scriptPubKey`); any spend succeeding without a signature committing to outputs is trivially RBF-replaced by miners substituting `(1.0 BTC → P_miner)`. 2. Pre-signed transactions at `t_0` using `SIGHASH_ALL`/`SINGLE` fix outputs before `(P_Mike, 0.25 BTC)` exist; `SIGHASH_NONE` permits total theft. 3. **Corollary 1A (Bob's `0.5 BTC`):** Depositor CSV refund leaves on active admitted vault `U_B` are forbidden after fungible minting (Bob would spend `0.5 zBTC` then reclaim `1.0 BTC` via CSV). 4. **Corollary 1B (Optimistic Reimbursement Bound):** On Bitcoin Mainnet today, every BitVM-family bridge (`BitVM2`/`BitVMX`/`BitVM3`) requires **`1-of-N` ephemeral setup deletion + challenger/verifier safety + `1-of-M` pre-committed operator exit liveness**. **Proposition 2 (Young Low-Cap Engineering / Capital / Trust Trilemma — 0 Federation, 0 Soft Forks, `~25–33 BTC` ZNN MCap):** With `0` federated signers, `0` soft forks, and `0%` ZNN slashing usable (`~25–33 BTC` ZNN mcap), no current Bitcoin Script / ZK-proving design fits inside `2–20 BTC` total hard capital while simultaneously achieving **(A)** instant non-expiring fungible cross-depositor `zBTC`, **(B)** `1-of-∞` permissionless challenging surviving `200–500 sat/vB`, and **(C)** `0-of-N` unilateral arbitrary L1 exit: - **Minimal `BitVM2` (`M = 3–5, L = 1`) fails `C ≤ 20 BTC`:** Current Groth16 `AssertTx` (`~1.0–1.3M vB` / `4.0–4.8 MB` W-OTS) imposes `13.30–18.175 BTC`/lane (`39.9–90.9 BTC` in bonds alone before fronting liquidity; under-bonding breaks above `50 sat/vB`). - **Stage 1A Right-Sized `BitVMX` (`n = 8`, `M = 3–5`, `L = 1`, `N = 7`)** achieves **(A)** with **`12.80–18.80 BTC`** locked protocol capital (**`14.75–21.25 BTC`** single-dispute operational baseline; `~17–26+ BTC` multi-dispute headroom) by accepting `1-of-N` (`N = 7`) pre-committed online verifiers and `1-of-M` (`M = 3–5`) operator liveness. - **Stage 1B `clArk`** achieves post-round **(C)** inside **`2–5 BTC`** by sacrificing **(A)** (discrete expiring VTXOs, pre-round `arkoor` sender+ASP collusion, no global pooled `zBTC`). | Custody Track | Soft Fork? | Bootstrap Hard BTC | Zenon Trust (`49%–100%`) | Custody Safety | Mike `0.25 BTC` Liveness (0 Zenon Signers) | Status in `v2` | |---|---|---|---|---|---|---| | **Stage 0 (SPV + PTLC/LN)** | No | `0 BTC` bonds (`0–5` LP) | `0-of-N` | Pure self-custody (conditional on bounded chain progress) | N/A (no pooled `zBTC`) | **Mandatory Stage 0** | | **Stage 1A (`BitVMX n=8` Rollup)** | **No (Core `>= 29.0`)** | **`14.75–21.25 BTC` op baseline** (`12.8–18.8` locked; `17–26+` multi-dispute) | **`0-of-N`** | `1-of-N` setup/cohort + **`1-of-7`** online verifier (native L1 payouts) | **`1-of-M` (`M=3–5`)** op (`~10m` front; `94–104d` 100% run; `0-of-M` locks BTC) | **Primary Stage 1A** *(pre-mainnet R&D)* | | **Stage 1B (`clArk` VTXOs)** | **No (Today)** | **`2–5 BTC` liq** | **`0-of-N`** | Post-round `0-of-N` (pre-round `arkoor` trusts ASP) | Post-round `0-of-N` until expiry (whole VTXO) | **Explicit Stage 1B Alt** | | **Appendix A: Track B Covenant+ZK** | **Yes (`OP_CCV`+ZK or `OP_CAT`)** | **`0 BTC` bonds** | **`0-of-N`** | **Pure `0-of-N`** | **Pure `0-of-N`** (1 L1 tx direct from pooled UTXO) | **Non-Normative Annex** | --- ## 2. Stage 1A Deleted-Key Vaults, Acyclic Deposit Ceremony, L1 `AdmissionTicketUTXO` & Zero-TTP Cohort Rule ### 2.1 Multi-Tier Vault Split (`{0.50, 0.25, 0.25}` BTC) Every `1.0 BTC` deposit splits at deposit time into three standardized deleted-key vault UTXOs: - **Canonical Stage 1A Split:** **`{0.50, 0.25, 0.25}` BTC** (`3` vaults/BTC, average vault **`0.333 BTC`**, **`maxVaultDenom = 0.50 BTC`**). - Bob's `0.50 BTC` recovery maps 1:1 to a `0.50 BTC` vault immediately; Mike's `0.25 BTC` recovery maps 1:1 to a `0.25 BTC` vault immediately; arbitrary non-bucket amounts (`>= MIN_EXIT_SATS = 100,000` sats = `0.001 BTC`) are paid in exact satoshis by `FrontingTx` and batched via `ReimbursementCredit[O_j]` (plus `TransferCredit` for `< 0.25 BTC` residual consolidation, `spec/03 §2.4`) until hitting an available `0.25`/`0.50 BTC` vault (**zero new presigning needed**). - *Throughput Option:* Deployments prioritizing faster bank-run recycling over direct `0.25 BTC` vault mapping may configure `{0.50, 0.50}` BTC (`2` vaults/BTC, avg `0.50 BTC`, reducing 100% bank-run duration by `~33%` with identical `maxVaultDenom = 0.50 BTC` and zero bond increase). ### 2.2 Acyclic `DepositTx` Ceremony With L1 `AdmissionTicketUTXO` Cap Exclusion (Closes `R8-C01`, `R8-C03`, `R8-H06`) Because `vk_STF` is immutably hard-pinned and never rotates with PoS epochs, **Stage 1A vault graphs carry no CLTV expiration and never require re-graphing**. There is NO `ProvisionalDepositScript`, NO `RolloverTx`, and NO standing `CommitteeIdentityKey`: 1. **Confirmed Self-Custodial Staging UTXO (`U_dep_wallet`) & Acyclic `vault_id` (`R8-C01`):** - Depositor first confirms `1.0 BTC + fee` on Bitcoin L1 in staging UTXO `U_dep_wallet` (`funding_txid:funding_vout`, Tapscript **`OP_DROP OP_CHECKSIG`**). - Because `funding_txid:funding_vout` is already confirmed on-chain and Bitcoin consensus prevents spending `U_dep_wallet` twice, each output vault `vout ∈ {0, 1, 2}` has a **globally unique, pre-Taproot-construction deterministic identifier**: ```text vault_id = SHA256("zbtc:vault-id:v1" || funding_txid(32B) || u32BE(funding_vout) || u32BE(vault_vout) || u64BE(amount_sats) || u64BE(opBitmask)) ``` *Zero SHA-256d fixed-point cycle:* Every vault's Lamport `TakeTx` Tapscript leaf commits to `vault_id` (NOT `SHA256(outpoint_d)`!), so Taproot script construction, `Q_setup_d` Taproot tweaking, and `txid_dep` computation form a strict DAG. 2. **L1 Consensus `Cap_TVL` Mutual Exclusion via Denomination-Matched `AdmissionTicketUTXO`s (`R8-C03`):** - At cohort genesis, setup mints exact denomination-matched `546`-sat `AdmissionTicketUTXO` connectors matching the total vault cap `Cap_TVL_total = Cap_user + M × B_zbtc` (e.g., for `M = 5`, `Cap_user = 15.0 BTC` + `3.0 BTC` operator `B_zbtc` = `18.0 BTC` total vaults ⇒ `18 × Ticket_050` + `36 × Ticket_025` = `54` tickets totaling `29,484` sats; operator initial `B_zbtc` deposits consume their dedicated `M × 0.60 BTC` allocation, leaving exact `15 × Ticket_050 + 30 × Ticket_025` for `15.0 BTC` of external user deposits!). - Every `1.0 BTC` `DepositTx` MUST spend `vin[0] = U_dep_wallet` AND `vin[1] = Ticket_050`, `vin[2] = Ticket_025`, `vin[3] = Ticket_025` (signed via cohort ticket key with zero BTC value risk — tickets carry `546` sats dust only) → `vout[0..2]` = vault UTXOs `U_0 (0.50 BTC)`, `U_1 (0.25 BTC)`, `U_2 (0.25 BTC)` + `vout[3]` = **`69 B` standard `OP_RETURN`**: ```text OP_RETURN <"ZBTX"(4B) || 0x00(1B) || recipientAcctHash(32B) || vaultParamsHash(32B)> ``` - Every pre-signed `TakeTx_{d,j,l,r}` spending vault `U_d` recreates the exact matching-denomination **`AdmissionTicketUTXO` at `vout[1]`** (`Ticket_050` or `Ticket_025`), so **Bitcoin L1 consensus itself enforces `sum(live_vaults) <= Cap_TVL_total` by strict UTXO conservation!** If two depositors race across the last remaining slot, Bitcoin consensus confirms at most ONE `DepositTx`; the loser's `DepositTx` fails with `missing-inputs` and the loser's `1.0 BTC` **never leaves `U_dep_wallet` (`0` BTC burn!)**. - *(Optional Alternative — Two-Stage `PreDepositUTXO`:)* Deployments opting out of ticket connectors MAY instead lock `1.0 BTC` first into `PreDepositUTXO` (`MuSig2(Q_setup_d) OR (<144> OP_CSV )`), deferring ephemeral key deletion and sweep into the active vault until `K`-deep slot admission confirms. **Normative Prohibition:** An active admitted vault `U_d` MUST NEVER retain an unconditional depositor CSV leaf (Corollary 1A). `AdmissionTicketUTXO` is the normative Stage 1A default. 3. **Ephemeral Deleted-Key Presigning & Hall's Marriage Admission Check (`R8-C04`):** - Before presigning, presigners verify that admitting `{U_0, U_1, U_2}` with `opBitmask` satisfies the **$2^M$ Hall's Marriage Invariant** (§6.2). - Depositor + `N = 7` presigners + all online operators (`≥ M_min`, encoded in `opBitmask` `u64`) generate fresh per-deposit ephemeral keys `(x_{i,d}, P_{i,d})` (including the depositor's own ephemeral key `P_{dep,d}`!) forming `Q_setup_d = MuSig2_KeyAgg(P_{1,d}, ..., P_{N,d}, P_{dep,d})`. They presign ONE `TakeTx_{d,j,l,r}` per eligible operator lane `(j, l)` and unused round `r ∈ {r_cur..R}` (Stage 1A `M = 5, L = 1, R = 64` ⇒ **`320` pre-signed `TakeTx`s per vault**, `~40 KB` off-chain, `< 100ms` batch MuSig2 ONCE at deposit). 4. **Immediate Ephemeral Key Deletion, Non-Spending Attestation & Public `zbtc-vault-bundle-v1` DA (`R8-H06`):** - Each presigner `i` **permanently deletes `x_{i,d}`** and signs a non-spending identity attestation `σ_cert` (`64 B` MuSig2 over `id_1..id_N`, co-verified by eligible operators) covering `(txid_dep, Q_setup_d, opBitmask, vaultParamsHash)`: ```text certBlob = σ_cert(64B) || Q_setup_d(32B) || opBitmask(8B) [exact 104 B <= 520 B BIP-342 limit] ``` - The ceremony MUST publish the canonical **`zbtc-vault-bundle-v1`** artifact (`vault_id`, `funding_txid:vout`, `DepositTx`, full Taproot Merkle tree scripts & control blocks, all `L_{j,l,r}` Lamport & W-OTS pubkeys, `certBlob`, and all `320` pre-signed `TakeTx`s, content-addressed by `SHA256(bundle)`) to **`>= 3` independent public archival mirrors** (IPFS/Arweave/Git/HTTP mirrors operated independently of operators). 5. **Zero-Stranding Broadcast:** Only after verifying every pre-signed `TakeTx`, `σ_cert`, and cryptographic retrieval of `zbtc-vault-bundle-v1` from `>= 3` public mirrors does the depositor delete `x_{dep,d}`, push witness stack **`[sig_depositor, certBlob, script, controlBlock]`** into `DepositTx.vin[0].witness`, and broadcast. Because witness stacks are excluded from `txid_dep` and authenticated by `wtxid_dep` in the coinbase BIP-141 witness commitment, there is **zero hash cycle**. At `K = 18` confirmations, the Rollup STF (`spec/02 §3`) verifies real satoshi outputs, `AdmissionTicketUTXO` consumption, Taproot script derivation from `vault_id`, `σ_cert`, and Hall's invariant, and credits `1.0 zBTC`. ### 2.3 Zero-TTP Cohort Lifecycle Rule (`R8-C06` Clarified) Inside a single fungible `zBTC` pool, **NO governance key, Pillar vote, or threshold committee can EVER add a new presigner cohort**: 1. **Voluntary Handover (Same `vk_STF` Only):** Only **`N`-of-`N`** (`7-of-7`) of Cohort 1 (preserving strict `1-of-N` safety!) may sign a handover certificate registering Cohort 2. 2. **Involuntary `1-of-N` `id_i` Key Loss:** All existing Cohort 1 vaults carry **no CLTV expiration** and remain safe and redeemable 1:1 to native BTC **strictly subject to `1-of-M` active eligible operator liveness** (zero `id_i` bricking), while *new* deposits on `v1` halt cleanly. Future deposits launch a **clean, non-commingled sovereign deployment (`zBTC_v2`)** with fresh Cohort 2. *(Long-term `id_i` uses redundant HSM backup; ephemeral `x_{i,d}` is NEVER backed up.)* 3. **Explicit Residual Open-Cohort Bound:** While a cohort accepts new deposits, at least `1-of-N` `{id_1..id_N}` must remain uncompromised (otherwise all `N` compromised `id_i` keys could attest a fake new deposit into the shared pool; existing deleted-key vaults still cannot be swept directly). --- ## 3. Right-Sized `BitVMX` (`n = 8`, `RV32IM`) `StakeChain`, Acyclic 256-Bit Lamport `TakeTx` & Core `>= 29.0` TRUC v3 Wiring ### 3.1 Launch-Time `StakeChain` & PoW Anchor (`t = 0`, `M = 3–5`, `L = 1`, `N = 7`, `R = 64`) Before accepting deposits, each operator `O_j` (`j ∈ {1..M}`) launches `L = 1` serial `StakeChain` lane `(j, l)` (`R = 64` finite rounds): - **Launch-Time Bitcoin PoW Anchor (Zero Pre-Broadcast Cycle):** Each lane pins an **already-confirmed** Bitcoin block `(h_lane_init, H(h_lane_init), D(h_lane_init))` inside its wrapped SNARK verifier `vk_STF` at `t = 0` (before `Q_lane_{j,l}` deletion). Header verification inside the off-chain ZK prover enforces full Bitcoin PoW + 2,016-block retargeting from `h_lane_init` with minimum difficulty floor **`D(h) ≥ 0.50 × D(h_lane_init)`** across the lane's finite `R = 64`-round horizon, PLUS **interactive heaviest-chainwork competing-header comparison** (`spec/02 §4`). - **Halving-Indexed Confirmation Depth (`K >= 18` Hard Minimum Floor, `R8-H03`):** Sized via the conditional unpublished-fork opportunity-cost heuristic `0.50 × K × Subsidy(era) > Cap_TVL_total` (`Cap_user + M × B_zbtc`), subject to a hard minimum floor **`K >= 18`** (`~3.0h` nominal): - **`Cap_user ≤ 10 BTC` (`11.80 BTC` total incl. `M=3` `B_zbtc`):** **`K = 18`** (`28.125 BTC` floor / `56.25 BTC` nominal in 2024–2028). - **`Cap_user ≤ 15 BTC` (`18.00 BTC` total incl. `M=5` `B_zbtc`):** **`K = 18`** (`28.125 BTC` floor / `56.25 BTC` nominal in 2024–2028). - **`Cap_user ≤ 50 BTC` (`62.00 BTC` total, Stage 2):** **`K = 42`** (`65.625 BTC` floor / `131.25 BTC` nominal). - **`Cap_user ≤ 200 BTC` (`224.00 BTC` total, Stage 2):** **`K = 144`** (`225.00 BTC` floor / `450.00 BTC` nominal). *(See `spec/02 §4` for full Budish winning-fork subsidy-offset disclosure and 2028–2036 halving table.)* - **Pre-Signed Linear `StakeChain` (`Stake_0 → RoundTx_1 → Stake_1 → ... → RoundTx_R`):** - `O_j` locks **`Bond_BTC = 2.00 BTC`** in `Stake_0` under ephemeral `Q_lane_{j,l}` (all `N = 7` presigner ephemeral shares **permanently deleted** after presigning the `R = 64` rounds!). - Each round `r ∈ {1..R}` binds a one-time **256-bit Lamport keypair `L_{j,l,r}`** (`256` `OP_HASH160` pairs `(H_{k,0}, H_{k,1})`) signing the acyclic pre-funding **`vault_id`** (§2.2). - **`RoundTx_r`** (spends `Stake_{r-1}` after `<1,872> OP_CSV`, revealing `256` Lamport preimages = `5,376 B` witness ≈ `1,344 vB`, total `RoundTx_r ≈ 1.8 kvB ≤ 10,000 vB` **TRUC v3**) creates: - **`Out 0 = Stake_r` (`Bond_BTC = 2.00 BTC`):** - **Leaf 1 (Next Round):** `<1,872> OP_CSV` (`13.0d` — enforces `W_max = 1` active kickoff per lane on L1!) → `RoundTx_{r+1}`. - **Leaf 2 (Clean Retirement):** `<2,016> OP_CSV` (`14.0d`) → **`RetireStakeTx_r`** (returns `2.00 BTC` to `O_j`; spending `Stake_r` **permanently double-spends and kills `RoundTx_{r+1..R}` forever**! The STF forbids unlocking `O_j`'s `B_zbtc` until `RetireStakeTx_r` confirms `K`-deep, `AssignedObligations[O_j] == 0`, AND removing `O_j`'s remaining rounds satisfies Hall's Marriage Invariant §6.2!). - **Leaf 3 (Native-L1 Multi-Challenger Bisection Slash — Closes `R8-H02` & `R8-N05`):** Immediate → `DisproveTx_{r,i}` / `TimeoutSlashTx_{r,i}` (**MUST spend BOTH `vin[0] = Stake_r` AND `vin[1] = VaultConnector_r`!**) paying: - `vout[0] = 0.15 BTC` immediately in native Bitcoin L1 BTC to winning verifier `P_{V_i}`, - `vout[1..6] = 6 × 0.15 BTC` **`ChalPayoutEscrow_{r,j}`** (`j ≠ i`) — each a 2-leaf Taproot output: **Leaf 1** co-spends `ChalProofConnector_{r,j}` (created ONLY when `V_j` actually broadcast `ChallengeTx_{r,j}` during `[0, 144]`) + ` OP_CHECKSIG` → pays **`0.15 BTC` native L1 BTC** directly to `P_{V_j}`; **Leaf 2** `<144> OP_CSV` → pre-signed `OP_RETURN` burn if `V_j` did NOT challenge! - `vout[7] = 0.95 BTC` immediate `OP_RETURN` burn (`0.95` min burn if all `7` challenge; up to `1.85 BTC` burn if `1` challenges!), - `vout[8] = 0`-sat `P2A` ephemeral anchor! *(Zero `2^7 = 128` subset explosion: only `7` pre-signed `DisproveTx`/`TimeoutSlashTx` pairs per round + `6` tiny 2-input claim/burn txs per verifier!)* - **Leaf 4 (256-Leaf Lamport Equivocation Slash, Depth 8, Pre-Signed at `t = 0`):** Leaf `k ∈ [0..255]` verifies `OP_HASH160 OP_EQUALVERIFY OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG` → `BurnBondTx_{r,k}` (`~200 vB` TRUC v3, spends `Stake_r` alone) burning **`100%` of `2.00 BTC` `Bond_BTC` to `OP_RETURN`**. - **`Out 1 = VaultConnector_r` (`546` sats):** `<1,728> OP_CSV` (`12.0d` > `max_dispute_end = 1,584` blks!) → **ONE single `TakeTx_{d,j,l,r}`** (OR spent immediately as `vin[1]` of `DisproveTx_{r,i}`/`TimeoutSlashTx_{r,i}`, guaranteeing **`0` satoshis stolen from `U_d`** on any bisection slash!). - **`Out 2..8 = VerifierSlot_1..7` (`546` sats each):** **Simultaneous non-staggered `[0, 144]` block challenge window** — ALL `N = 7` slots open at block `0` (` OP_CHECKSIG`) and expire at `<144> OP_CSV` (`24h`). Each `ChallengeTx_{r,i}` creates BOTH `ChalEscrow_{r,i}` (`F_chal = 0.40 BTC`) AND a `546`-sat **`ChalProofConnector_{r,i}`** unlocking `V_i`'s `0.15 BTC` native L1 payout in `ChalPayoutEscrow_{r,i}` if `O_j` is slashed! - **`Out 9 = 0`-sat `P2A` Ephemeral Anchor** (`0x51024e73`). ### 3.2 `n = 8` `BitVMX-CPU` (`RV32IM`) Wrapped-SNARK Verifier Bisection & Core `>= 29.0` TRUC v3 Compliance (`R8-H04`, `R8-H05`) - **Normative `RV32IM` Guest Computation Boundary (`R8-H05` Closed):** - The disputed `RV32IM` guest program running inside `BitVMX-CPU` (`≤ 8^9 = 2^27 = 134,217,728` RISC-V instructions) is **STRICTLY a constant-size wrapped SNARK verifier (`vk_STF`)** (verifying a succinct BN254 Groth16 or compact recursive STARK proof over constant-size authenticated public inputs `(h_prev, R_prev, h_tip, R_tip, claimHash, competingChainWork)`). - **Bare `1 MB` Bitcoin stripped-block SHA-256 scanning and SMT reconstruction MUST NOT execute directly inside `RV32IM`** — they run inside the off-chain ZK prover proved by `vk_STF` (`spec/02 §3.2`). - **Mandatory Gate G2 (`spec/05 §5`):** Before Stage 1A code freeze, the team MUST publish reproducible Rust → `RV32IM` source and compiled ELF binary demonstrating `init_steps + exec_steps <= 0.5 × 8^9 = 67,108,864` on worst-case adversarial inputs (if exceeded, either bump search depth `l = 9 → 10`, `8^{10} = 1.074B` steps adding `+2` steps / `+144` blks, or adopt reusable BitVM3-GC). - **`n = 8` Search Branching (`3` bits/round, `7 × 20 B` `OP_HASH160` Intermediate Trace Hashes):** - W-OTS cost per prover search tx: `7` hashes × `43` digits (`40` data nibbles + `3` checksum nibbles per 20-byte hash) = **`301` W-OTS digits** × `95.5 WU/digit` = **`28,746 WU`** (`7,186.5 vB`) + `~250 vB` tx overhead **`≈ 7,437 vB (7.44 kvB) ≤ 10,000 vB` (100% BIP-431 TRUC v3!)**. - Search depth: `ceil(27 / 3) = 9` search rounds (`9` prover txs + `9` verifier 3-bit interval choice txs) + `1` Start/Read (`~3.0 kvB` prover) + `1` Final Trace (`~5.0 kvB` prover) / Execute-1-RISC-V-Opcode (`~8.0 kvB` verifier) = **`20` sequential steps**. - **Total Worst-Case Dispute Weights (INCLUDING `10 × 153 vB = 1,530 vB` P2A CPFP Children, `R8-H02`/`R8-H04`):** - **Prover (`O_j`):** `9 × 7.44 + 3.0 + 5.0 = 74.96 kvB` (cap `75.00 kvB`) + `10 × 153 vB` P2A CPFP (`1.53 kvB`) = **`76.53 kvB`**. - **Verifier (`V_i`):** `Challenge (0.35) + 9 × 0.35 (3.15) + Execute/Disprove (8.0) = 11.50 kvB` (conservative cap `15.00 kvB`) + `10 × 153 vB` P2A CPFP (`1.53 kvB`) = **`16.53 kvB`**. - **Widened Exact Timelock Ordering (`T_step = 72` blocks = `12h`/step, `R8-H04`):** ```text Challenge Window [0, 144] (24h) → Max Dispute End: 144 + (20 * 72) = 1,584 blocks (11.00 days) → VaultConnector_r (T_take): 1,728 blocks (12.00 days) [+144 blk / 24h margin] → Stake_r -> RoundTx_{r+1} (T_cool): 1,872 blocks (13.00 days) [+144 blk post-TakeTx equivocation margin] → RetireStakeTx_r: 2,016 blocks (14.00 days) [+144 blk clean retirement margin] ``` - **Bitcoin Core `>= 29.0` (`v31.0` Preferred), TRUC v3 (`nVersion = 3`), `P2A` & Out-of-Band Relay Audit (`R8-H04`, `R8-M09`):** - **Normative Node Floor:** Zero-value (`0`-sat) `P2A` ephemeral dust + 1P1C package relay requires **Bitcoin Core `>= 29.0`** (`v31.0` preferred; Core `28.0` rejects `0`-sat `P2A` outputs as non-standard!). - Every pre-signed tx is `≤ 10,000 vB` (`RoundTx_r` ~`1.8 kvB`, `TakeTx` ~`3.17 kvB`, Prover search tx `7.44 kvB`, Execute-1-Opcode `≤ 8.0 kvB`, Verifier choice/Slash/Burn `~0.2–0.5 kvB`). - **Zero Unconfirmed TRUC Child Chaining:** Because `TakeTx` (`~3.17 kvB`) and prover search txs (`7.44 kvB`) exceed BIP-431's `1,000 vB` child limit, EVERY protocol step spends ONLY **confirmed** parent outputs (`ancestor_count = 1`), attaching at most ONE `~153 vB ≤ 1,000 vB` CPFP child via `0`-sat `P2A` (`descendant_count = 2`). - **Sibling-Eviction Mitigation:** All operators and verifiers MUST maintain direct-to-miner out-of-band submission rails (e.g., Slipstream / mining-pool RPC) alongside public P2P 1P1C relay; `T_step = 72` blocks (`12h`) absorbs prolonged sibling-eviction pinning and transient fee spikes. - **Honest Fee-Rate Design Envelope (`500 sat/vB` Sustained Across ALL `20` Steps):** - Prover worst-case fee @ `500 sat/vB` (incl. `10 × 153 vB` CPFP): `76,530 × 500 = 38,265,000` sats (`0.38265 BTC`) ≤ **`F_chal = 0.40 BTC`** (exact break-even **`522 sat/vB`** sustained across all `10` prover txs!). - Verifier worst-case fee (incl. `10 × 153 vB` CPFP): `16,530 × 500 = 8,265,000` sats (`0.08265 BTC` @ `500 sat/vB`; `12,397,500` sats = `0.12398 BTC` @ `750 sat/vB`). ### 3.3 Acyclic 256-Bit Lamport `TakeTx` Leaf (Zero `ReimburseEscrow`, Zero `RecoveryVault`, `R8-C01`) At deposit `d`, `U_d`'s Tapscript leaf for `(j, l, r)` verifies `L_{j,l,r}(vault_id)` directly inside `TakeTx_{d,j,l,r}` (`vin[0] = U_d`, `vin[1] = VaultConnector_r`, `vout[0] = D_d → P_{O_j}`, `vout[1] = AdmissionTicketUTXO` recycled at `546` sats, `vout[2] = 0`-sat `P2A`): ```text # 256 iterations (k = 0..255, b_k = bit k of pre-funding acyclic vault_id): OP_HASH160 OP_EQUALVERIFY ... OP_CHECKSIG ``` - **Exact BIP-342 & TRUC v3 Weights:** - Tapscript size: `256 × 23 + 34 = 5,922 B`. - Preimages in witness: `256 × 21 = 5,376 B`. - Control block: **`321 B`** (depth 9 for `320` leaves at Stage 1A `M = 5, R = 64`) or **`417 B`** (depth 12 for `2,560` leaves at Stage 2 `40` lanes × `64`). - Peak stack elements: **`258 << 1,000`** BIP-342 limit. - Total `TakeTx` weight (incl. `VaultConnector_r` input + recycled `AdmissionTicketUTXO` output + `P2A`): **`~3,142 vB`** (depth 9) / **`~3,166 vB`** (depth 12) **`≤ 3,200 vB ≤ 10,000 vB` TRUC v3 parent** (must spend confirmed `VaultConnector_r` only). - **Equivocation Solvency:** If `O_j` committed `vault_id_1` in `RoundTx_r`, passed `T_take = 1,728`, and broadcast `TakeTx` on `vault_id_2 ≠ vault_id_1`, `O_j` MUST reveal both preimages for `~128` differing bits `k`, letting any `1-of-∞` challenger execute `BurnBondTx_{r,k}` on `Stake_r` Leaf 4 during `[1,728, 1,872]` (`144`-blk window). `100%` of `2.00 BTC` `Bond_BTC` burns to `OP_RETURN`, and the STF burns `D_d` (`≤ 0.50 BTC`) from `O_j`'s hard-partitioned `B_custody` (`0.55 BTC`) + pays `0.05 BTC` equivocation bounty (and restores `R[O_k] += D_d` if `vault_id_2` was assigned to another honest operator `O_k`) — keeping remaining `zBTC` **100% 1:1 solvent (`0` user loss)**. --- ## 4. Native-L1, Collusion-Proof, Crisis-Discount-Immune Verifier Economics (`R8-H02`, `R8-N05` Closed) Every `ChallengeTx_{r,i}` opened by Verifier `V_i` during `[0, 144]` locks **`F_chal = 0.40 BTC`** in **`ChalEscrow_{r,i}`**, creates `546`-sat **`ChalProofConnector_{r,i}`**, and appends `41 B` `OP_RETURN "ZBTX" || 0x04 || kickoffTxid || verifierAcctId_i`: - `ChalEscrow_{r,i}` pays `0.40 BTC` to `O_j` **ONLY IF** `O_j` wins `Dispute_i` (covering full `76.53 kvB` honest prover fees + CPFP up to `522 sat/vB`); otherwise `V_i` reclaims `100%` of `0.40 BTC` cleanly. - Each operator lane locks **`B_zbtc = 0.60 BTC`** inside canonical Rollup state, **HARD-PARTITIONED** into two non-overlapping sub-buckets (`R8-H01`, `R8-N05`): - **`B_custody = 0.55 BTC`** (`0.50 BTC` max-vault Lamport equivocation restitution + `0.05 BTC` equivocation bounty; NEVER debited by `ExitSlotUTXO` griefing!), AND - **`B_grief = 0.05 BTC`** (strictly dedicated `ExitSlotUTXO` grief buffer). - **100% Native Bitcoin L1 Verifier Payouts (`0%` `zBTC` Crisis Discount, `0%` `R8-N05` Coupling!):** Because `DisproveTx_{r,i}` / `TimeoutSlashTx_{r,i}` spends **BOTH `Stake_r (2.00 BTC)` AND `VaultConnector_r`** (`0` BTC stolen from `U_d`), EVERY active honest challenger receives **`0.15 BTC` in native Bitcoin L1 BTC** (`vout[0]` immediately for winner `V_i`, and `vout[1..6]` `ChalPayoutEscrow_{r,j}` claimed via `ChalProofConnector_{r,j}` for every other challenger `V_j`; unclaimed slots burn after `144` blks, plus `0.95 BTC` minimum immediate `OP_RETURN` burn!). On L2, `O_j`'s `0.55 BTC` `B_custody` is additionally slashed to the protocol insurance/honest-verifier pool (not needed for positive verifier EV!). **Native-L1 Bisection Slash Matrix (`k_collude ∈ {0..6}` of `N = 7` Colluding Verifiers; `16.53 kvB` incl. CPFP + `0.00285 BTC` lockup + `30%` `zBTC` crisis discount):** | Colluding Verifiers (`k_collude`) | Vault Stolen | Every Active Honest Verifier L1 Payout (`Stake_r`) | Min `Stake_r` L1 Burned | Honest Verifier Net EV @ `500 sat/vB` (`0.08265` fee + `0.00285` lockup) | Honest Verifier Net EV @ `750 sat/vB` (`0.12398` fee + `0.00285` lockup) | Combined `(O_j + k_collude)` Net P&L (L1 Only / Incl. `B_custody`) | |---|---|---|---|---|---|---| | `0` (all honest) | `0.00 BTC` | **`0.1500 BTC` native L1** | `0.95–1.85 BTC` | **`+0.0645 BTC`** | **`+0.0232 BTC`** | **`-2.00 BTC`** L1 / **`-2.55 BTC`** total | | `1` (`V_1` throws & claims L1) | `0.00 BTC` | **`0.1500 BTC` native L1** | `0.95–1.70 BTC` | **`+0.0645 BTC`** | **`+0.0232 BTC`** | **`-1.85 BTC`** L1 / **`-2.40 BTC`** total | | `6` (worst case: ONLY `V_7` honest; `V_1..V_6` claim L1) | `0.00 BTC` | **`0.1500 BTC` native L1** | **`0.95 BTC`** | **`+0.0645 BTC`** (`V_7` strictly profitable!) | **`+0.0232 BTC`** (`V_7` STILL profitable!) | **`-1.10 BTC`** L1 / **`-1.65 BTC`** total | *Result: Even under `6-of-7` verifier collusion, `750 sat/vB` sustained fees with `10 × 153 vB` P2A CPFP, `0.00285 BTC` lockup cost, `100%` `B_grief` exhaustion (`R8-N05`), AND a `30%` (or even `100%`!) `zBTC` crisis discount, the lone honest verifier `V_7` earns **`+0.0645 BTC` @ `500 sat/vB`** (`+0.0232 BTC` @ `750 sat/vB`, break-even **`890 sat/vB`**), while the cheating cartel loses **`-1.10` to `-2.00 BTC` on Bitcoin L1 alone** (`-1.65` to `-2.55 BTC` incl. `B_custody`) with `0` sats stolen from users!* --- ## 5. Atomic Active-Operator `(2M_active + 1)`-Leaf `ExitSlotUTXO` (Cyclic Priority, Zero `B_custody` Overflow — `R8-H01`, `R8-M03`, `R8-N01`) Every Stage 1A exit (`grossSats >= max(dust(destScriptPubKey), MIN_EXIT_SATS = 100,000)` sats — `R8-M05`) — both hostile L1 `0x01 FORCED_EXIT` and cooperative `0x02 BATCH_DA` exits — outputs a **`546`-sat `ExitSlotUTXO`** (P2TR, unspendable `H_NUMS` internal key) containing ONLY **currently active, non-suspended operators** `M_active <= M` from canonical state `R_{h-1}` (`2M_active + 1` Tapscript leaves, zero anonymous `OP_TRUE` leaves!): - **Leaves `0 .. M_active - 1` (Collision-Free Cyclic Priority Windows — Closes `R8-M03`):** `<6*r> OP_CSV OP_DROP OP_CHECKSIG` where **`k_r = (H(exitId) + r) mod M_active`** (`0%` repeat across `r = 0..M_active - 1`!). - **Leaves `M_active .. 2M_active - 1` (Registered Open Race After `6*M_active` Blocks):** `<6*M_active> OP_CSV OP_DROP OP_CHECKSIG` for each active operator `O_j`. - **Leaf `2M_active` (`EXIT_CANCEL`):** `<288> OP_CSV OP_DROP OP_CHECKSIG` (`288 > 6*M_active` blks). **Universal STARK Spend-or-Refund Rule (`K`-deep spend of `ExitSlotUTXO`, `R8-H01` Hardened):** 1. **Valid Fronting (Leaf `0..2M_active-1` AND `vout[0] == (destScriptPubKey, ≥ grossSats - f_op)`):** Exit marked `COMPLETED`; `ReimbursementCredit[O_j] += grossSats` (tagged with the exit's creation height for oldest-`PendingExit` reimbursement priority — `R8-N01`!). Bitcoin L1 UTXO exclusion makes double-fronting and refund-vs-front races (`M-8`) cryptographically impossible. 2. **Non-Paying Operator Grief Spend (Leaf `0..2M_active-1` AND `vout[0]` fails payout check — Even in a `k = 20` Single-Block Burst!):** STF **atomically cancels EVERY grieved exit, refunds `100%` of `grossSats` `zBTC` to every victim (`E -> C`), deducts `min(0.01 BTC, floor(B_grief[O_j] / k_burst))` strictly from `O_j`'s hard-partitioned `B_grief` (`0.05 BTC`) to each victim in that block, auto-suspends `O_j`, and excludes `O_j` from all NEW `ExitSlotUTXO` Taproot trees!** Even a `k = 20` single-block grief burst pays every victim `250,000` sats (`0.0025 BTC`, covering a `150 vB` retry fee up to `1,666 sat/vB`), **NEVER debits 1 satoshi from `B_custody` (`0.55 BTC`), and has `0` impact on L1 `Stake_r` verifier payouts (`R8-N05`)**. 3. **User Cancel (Leaf `2M_active`) or Fee Bump (`0x06 EXIT_FEE_BUMP`):** `0x06` raises `f_op` in-place during fee spikes (and wallets may optionally attach a deterministic Dutch-auction `f_op` schedule); Leaf `2M_active` cleanly refunds `grossSats` `zBTC` (NOT native BTC) after `288` blks unfronted. --- ## 6. Stage 1A Complete Hard-BTC Capital, $2^M$ Hall's Marriage Invariant, Voluntary Unwind & Bank-Run Bounds ### 6.1 Complete Hard-BTC Capital & Bank-Run Table (`R8-M09`, `R8-H02`, `T_cooldown = 13.0d`) Every parameter below is verified in [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py). **`Cap_user`** is net external user `zBTC` capacity; **`Cap_TVL_total = Cap_user + M × B_zbtc`** is total confirmed vault BTC covered by `K >= 18` (`spec/02 §4`): | Configuration (`L = 1`, `N = 7`, `R = 64`, `K >= 18`, `T_cooldown = 13.0d`) | Locked Protocol Capital (`Bonds + Float + 7×F_chal`) | Mandatory Operational Reserves (`0.70` CPFP + `0.50` DA + `0.25M` Top-up) | **Total Operational Baseline (1 Dispute)** (`%` of `25–33 BTC` ZNN MCap) | Multi-Dispute Headroom (`M` Concurrent Attacks: `0.483 BTC/lane` per honest verifier) | Recycling Rate (`{0.50, 0.25, 0.25}` avg `0.333 BTC`) | **100% Bank-Run Exit Duration** (`{0.50, 0.25, 0.25}` / `{0.50, 0.50}`) | |---|---|---|---|---|---|---| | **Bare-Minimum Pilot (`M = 3`, `Cap_user ≤ 10 BTC` / `11.80` total)** | **`12.80 BTC`** (`7.80 + 2.20 + 2.80`) | `+1.95 BTC` (`0.70 + 0.50 + 0.75`) | **`14.75 BTC`** (`44.7%–59.0%`) | `1.45 BTC`/honest verifier (`~16.7–21.5 BTC` net-wide if all 7 hold `3×`) | `0.231` vaults/d (**`0.077 BTC/d`**) | `2.20 BTC` in ~10m + `7.80 BTC` in **`~101–104 days`** (`~68d` w/ `{0.50, 0.50}`) | | **Recommended Stage 1A Pilot (`M = 5`, `Cap_user ≤ 15 BTC` / `18.00` total)** | **`18.80 BTC`** (`13.00 + 3.00 + 2.80`) | `+2.45 BTC` (`0.70 + 0.50 + 1.25`) | **`21.25 BTC`** (`64.4%–85.0%`) | `2.41 BTC`/honest verifier (`~23.2–34.8 BTC` net-wide if all 7 hold `5×`) | `0.385` vaults/d (**`0.128 BTC/d`**) | `3.00 BTC` in ~10m + `12.00 BTC` in **`~94–104 days`** (`~62d` w/ `{0.50, 0.50}`) | | **Stage 2 Scaled (`M = 20, L = 2`, `Cap_user ≤ 50 BTC` / `62.0` total, `K = 42`)** | `122.8 BTC` (`104.0 + 16.0 + 2.80`) | `+11.20 BTC` | `134.0 BTC` | Scales w/ concurrent dispute cap | `3.077` vaults/d (**`1.026 BTC/d`**) | `16 BTC` in ~10m + `34 BTC` in **`~33 days`** | ### 6.2 Exact $2^M$ Hall's Marriage Recoverability Invariant (`R8-C04` Closed) Because vaults carry per-vault operator bitmasks `opBitmask` (`E(v) ⊆ {1..M}`) and operators consume rounds or retire asynchronously, a global scalar cap `N_live_vaults <= 0.50 * sum(r_i)` is **insufficient** and can strand historical cohorts. On EVERY `deposit_admit`, `operator_retire`, `round_consume`, and `operator_slash`, the STF MUST enforce the exact **Hall's Marriage Invariant** across all `2^M - 1` non-empty operator subsets (`<= 31` checks for `M = 5`; Edmonds-Karp max-flow if `M > 10`): $$\forall T \subseteq \{1..M\} \setminus \{\emptyset\}: \quad \left|\{v \in V_{\text{live}} : E(v) \subseteq T\}\right| \;\le\; \sum_{i \in T} r_i^{\text{usable}}$$ - **Deposit Admission Headroom:** New deposits MUST additionally satisfy `|{v ∈ V_live ∪ V_new : E(v) ⊆ T}| <= floor(0.50 * sum_{i ∈ T} r_i^usable)` for every `T` containing `E(v_new)` (`<= 160` live vaults at `M = 5, R = 64`), guaranteeing `2×` round slack even if half of an eligible subset retires or gets slashed. - **Tightest-Slack FIFO Assignment:** Deterministic FIFO vault assignment prioritizes the oldest eligible vault inside the **minimum-slack Hall subset** `argmin_T (sum_{i ∈ T} r_i^usable - |{v : E(v) ⊆ T}|)` so constrained legacy cohorts always drain first. - **Retirement Gating:** `RetireStakeTx_r` cannot unlock `O_i`'s `B_zbtc` if removing `O_i`'s remaining rounds violates Hall's Marriage Invariant above. - **Zero Passive-Timeout Slash:** Once `U_d` is assigned to `O_j` (moving `D_d` from `R[O_j] → AssignedObligations (A)`), assigned vaults NEVER passively expire into a slashable state (eliminating withholding-miner slash attacks); only explicit `O_j`-signed `0x07 RELEASE_ASSIGNMENT` releases an assignment. ### 6.3 Graduated TVL Ramps & Non-Custodial Voluntary Unwind Circuit Breaker (`R8-H08`) Because `vk_STF` is immutable on existing vaults (zero governance override), Stage 1A mitigates latent `vk_STF` bug risk via three non-custodial controls: 1. **Graduated Mainnet TVL Ramps:** Stage 1A launches with `AdmissionTicketUTXO` genesis capped strictly at **`2.0 BTC`** (90 days live bug-bounty soaking) → **`5.0 BTC`** (90 days) → **`10.0 / 15.0 BTC`** pilot cap. 2. **Gate G4 Formal Verification & Differential Consensus Fuzzing (`spec/05 §5`):** Mandatory formal proof of `V = C + L + E + R + A + B`, Hall's invariant, and BIP-141 witness completeness plus differential fuzzing against Bitcoin Core before mainnet launch. 3. **Voluntary Unwind Circuit Breaker:** If a critical non-exploited bug is discovered in `vk_STF`, Cohort 1 (`1-of-N` presigner halts new `σ_cert` attestations immediately — zero new deposits!), operators front all outstanding user `0x01` exits via `ExitSlotUTXO` to drain `zBTC` organically to `0` on Bitcoin L1, and remaining `v1` lanes retire cleanly via `RetireStakeTx_r` before launching a patched, non-commingled `zBTC_v2`. *(No governance key ever touches existing vault funds.)* - **Maturity & Engineering Reality:** `BitVMX-CPU` / `BitVMX-protocol` is **pre-mainnet** today. Production delivery (off-chain stripped-block ZK prover + compiled `RV32IM` wrapped-SNARK verifier ELF + `StakeChain` ceremony + `AdmissionTicketUTXO` + `ExitSlotUTXO` + Gate G1–G5 audits) is realistically **`12–18+ months`** for 4–6 strong engineers. --- ## 7. Stage 1B Explicit Alternative Gate: `clArk` (Covenant-Free Ark VTXOs) If a young project **cannot commit `~14.75–21.25+ BTC` of non-yielding hard BTC** OR requires mainnet launch in **`3–6 months`** OR prioritizes `0-of-N` post-round unilateral exit over pooled fungibility, **do NOT under-bond `BitVMX`/`BitVM2`** — adopt Stage 1B **`clArk`** (`Second bark` / `Ark Labs arkd` + automated watchtower refreshes + Zenon SPV/PTLC coordination): - **Bootstrap Capital:** **`2–5 BTC`** active ASP liquidity (`0` slashing bonds; round turnover capped by ASP liquidity per 30–60 day VTXO expiry cycle). - **Bob & Mike Security Model:** - **Post-L1-round (after `P_Bob`/`P_Mike` confirms in an Ark VTXO tree):** **Pure `0-of-N` unilateral exit** (zero ASP, zero Zenon signers!) by broadcasting `log2(N)` pre-signed tree-branch transactions (`N = 64 → 6` txs; `N = 1,024 → 10` txs) prior to VTXO expiry. - **Explicit Compromises Relinquished:** (1) **No pooled fungible `zBTC` token** (discrete VTXOs; exiting `0.25 BTC` unilaterally from a `2.0 BTC` VTXO requires exiting the entire `2.0 BTC` VTXO on-chain unless pre-split in-round); (2) **Pre-round `arkoor` transfers trust the ASP not to collude with sender `Alice`/`Bob`** (wallets MUST separate trustless in-round VTXOs from `arkoor` balances explicitly in UX); (3) **Hard VTXO expiry** requires automated watchtowers/online refreshes or `log2(N)` L1 branch fees. --- ## Appendix A: Non-Normative Future Tracks — Track B Pure Tier-0 Bitcoin Soft-Fork Covenant & Track A1/A2 Reference > **Status: NON-NORMATIVE.** Nothing in `v2` depends on Bitcoin soft forks or BitVM2/BitVM3. ### A.1 Track B: Pure Tier-0 (`0-of-N` Safety AND `0-of-N` Liveness) With Minimal Bitcoin Soft Fork If Bitcoin activates a stateful covenant soft fork, a **clean non-commingled `zBTC_v2`** eliminates ALL presigning committees, ALL operators, ALL verifiers, ALL bonds, and ALL bank-run delays: - **Direct L1 Pooled Covenant Custody (`U_vault(R_t, V_t)` — Zero Header Scanning!):** - Internal key = provably unspendable `H_NUMS`. **Every custody transition spends `vin[0] = U_vault(R_t, V_t)` directly on Bitcoin L1**, so Bitcoin consensus natively enforces exact BTC inputs/outputs and canonical UTXO ordering (zero private-fork/orphaned-block drain; no `OP_BLOCKHASH` needed for custody!): 1. **Deposits:** Depositor's `DepositInboxUTXO(acctHash, <144> OP_CSV refund)` is spent directly as `vin[1..d]` of `T`; covenant verifies `V_out0 = V_in0 + sum(V_in_dep) - sum(V_out_exit)` (miner fee paid strictly by external fee input!). 2. **Feeless Zenon Batches:** Complete mutated-leaf state diffs + transparent STARK `π_STF` live directly in `T`'s witness (zero CRS). 3. **Mike's Direct Unilateral `0.25 BTC` Exit (`0` Signers, `0` Operators, `0` LPs):** Mike spends `vin[0] = U_vault(R_t, 2.0 BTC)` + `vin[1] = Mike_fee_UTXO` → `vout[0] = U_vault(R_{t+1}, 1.75 BTC)` + `vout[1] = 0.25 BTC → P_Mike` + fee change in **1 Bitcoin block (~10m)**. - **Two Concrete Minimal Soft-Fork Primitives:** - **Path B1 (`OP_CCV` BIP-443 + `OP_TXHASH` + `OP_VERIFY_STARK`):** Single `~1–3 kvB` L1 tx, instant 1-block finality, zero challengers. - **Path B2 (`OP_CAT` BIP-347 Alone):** Poelstra Schnorr-trick sighash introspection enforcing recursive state-carry + value conservation, paired with either chained in-Script Circle-STARK (`~40–100 kvB` witness, 0 challengers) OR `OP_CAT`-MATT optimistic bisection (`~500 vB` happy path, `~5–20 kvB` on dispute, `0` committees/operators, `1-of-∞` safety). - **UTXO Contention Handling:** Track B-Base enforces `<1> OP_CSV` (`nSequence ≥ 1`, max 1 spend/block) + native Bitcoin RBF fee-market priority (zero `OP_BLOCKHASH`). Optional **Track B+** additionally adds `OP_BLOCKHASH` if an external `OP_RETURN` mandatory forced-exit queue (`D_force = 6` blks) without RBF bidding against batchers is desired. ### A.2 High-Capital / Research Reference (`BitVM2` & `BitVM3-GC` + Clementine) - **Scaled `BitVM2` (`1-of-∞` Permissionless Challenger, Zero Soft Fork):** Viable only once `≥ 40–91+ BTC` (minimal `M = 3–5`) or `532–1,454 BTC` (`40–80` lanes) of operator capital is available (`13.30–18.175 BTC`/lane at `~1.0–1.3M vB` Groth16 asserts, `nVersion = 2` non-TRUC large txs, `≤ 500 sat/vB` fee ceiling). - **Emerging `BitVM3-GC` (Garbled-Circuit SNARK + Clementine Reusable Rounds — Evaluated at Gate G2):** - **Advantages:** Shrinks on-chain disprove to `~93 vB`–`1.0 kvB` and `2` rounds (versus `20`-step `BitVMX-CPU`), with variable-difficulty light-client comparison and dramatically lower dispute fee exposure. - **Current Trade-Offs Requiring Gate G2 Resolution:** Current non-reusable BitVM3 garbled circuits introduce a **`1-of-N` garbler trust model** AND require **`1–5 GB` per one-time garbled circuit instance** — totaling **`~2.2–11.2+ TB`** of off-chain archival DA across `M × L × R × N = 5 × 1 × 64 × 7 = 2,240` rounds (until **reusable DV-SNARK garbled circuits** mature). Gate G2 explicitly benchmarks compiled `RV32IM` `BitVMX-CPU` against mature reusable `BitVM3-GC` before Stage 1A code freeze; Stage 2 always supports clean non-commingled `zBTC_v2` adoption. # Part 2: Stage 0 Direct-on-L1 Bitcoin SPV Event Oracle & Stage 1A Bitcoin-L1-Canonical Authorization Domain **Document Class:** Normative Bitcoin SPV Verification & L1 Authorization Domain Specification (`v2` / `v3.1.0-rfc` — Zero-Federation Phased Architecture; supersedes archived `v1` `v3.0.0-rfc` and `v0` `v2.5.0-rfc`) **Philosophical Anchor:** Stage 0 implements Zenon's non-custodial verification thesis (`zenon-developer-commons`: `essays/Verify Bitcoin, Don't Bridge It.md` & `docs/specs/spv-event-oracle-spec.md`): **Event Validity only, zero custody authority**. Stage 1A moves canonical `zBTC` authorization, data availability, and forced exit directly onto **Bitcoin L1** so that `49%–100%` Zenon compromise cannot forge state or censor exits. **Consistency Checker:** [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py) --- ## 1. Two-Layer Separation: Stage 0 Event Oracle vs Stage 1A Canonical L1 Domain This specification strictly separates two orthogonal verification surfaces with **zero federated signers** anywhere: 1. **Stage 0 — Direct-on-L1 Bitcoin SPV Event Oracle (`vm/embedded/btcspv`):** - Runs deterministically inside an embedded Zenon contract (`BtcSpvOracleContract`), wrapped in mandatory panic recovery (`recover()`, zero `common.DealWithErr` calls — closing upstream issue `#239` / **B1**). - Proves **Event Validity ONLY**: cryptographic evidence that a Bitcoin transaction `txid` is included at depth `>= K_oracle` on the heaviest cumulative-PoW Bitcoin header chain. - **Hard Non-Custody Invariant:** Stage 0 SPV has **ZERO minting, burning, sweeping, or vault-spending authority**. It powers Bitcoin-verified receipts, proof-of-payment triggers, and non-custodial PTLC/HTLC atomic swaps (`spec/03 §1`). 2. **Stage 1A — Bitcoin-L1-Canonical Authorization Domain (`vk_STF` Rollup Circuit):** - For pooled, fungible `zBTC` (`Stage 1A`), **Zenon L1 does NOT authorize mints, burns, or exits**. - Instead, an off-chain ZK prover executes the deterministic Rollup State Transition Function ($\mathcal{F}$) over **complete stripped Bitcoin blocks** directly on Bitcoin L1, deriving the entire canonical `zBTC` state root $R_h$ strictly from Bitcoin's heaviest PoW chain (`0-of-N` Zenon trust; `0%` ZNN market-cap coupling). Inside `BitVMX-CPU` (`RV32IM`), only the **constant-size wrapped SNARK verifier `vk_STF`** runs (`R8-H05`), NEVER bare 1 MB block SHA-256 scanning! --- ## 2. Stage 0: Direct-on-L1 Bitcoin SPV Event Oracle (`vm/embedded/btcspv`) ### 2.1 `OracleChainConfig` & Finality Parameters ```text OracleChainConfig { foreignChainId : bytes32 // u16(0x0001) || SHA3-256("BTC_MAINNET_SPV_V1" || btcGenesisHashBE)[0:30] genesisAnchor : Bytes // BitcoinAnchor { blockHashBE(32B), height(u64), header(80B), cumWork(u256), // retargetStartHash(32B), retargetStartTime(u32), retargetHeight(u64), mtpWindow[11](u32) } admissionDepthN : u32 // 6 blocks (provisional event admission; reversible on reorg) finalizationDepthK : u32 // 12 blocks (oracle event finalization depth; probabilistic PoW finality) minimumPostAnchorWork : u256 // finalizationDepthK * blockWork(genesisAnchor.nBits) retainedReorgDepth : u32 // 144 blocks (stale HeaderNode pruning ONLY; ActiveChainByHeight NEVER pruned) maximumHeaderBatch : u32 // 2 headers per SubmitHeaderBatch call maximumMerkleDepth : u32 // 16 levels (65,536 txs/block) minimumStrippedTxBytes : u32 // 65 B (rejects 64-byte CVE-2017-12842 interior nodes & impossibly short txs) maximumStrippedTxBytes : u32 // 6,144 B (per-call Stage 0 proof cap; fits 3x inside pinned 2.1M Plasma floor) futureTimeGuardSecs : u32 // 7,200 s (Bitcoin consensus MAX_FUTURE_BLOCK_TIME) equalWorkTieBreak : u8 // 0 = LOWEST_BLOCK_HASH_BE (deterministic across all Zenon full nodes) } ``` > **Testnet / Signet Scope Caveat:** On Bitcoin Signet (where validity rests in the Signet challenge signature) and Testnet4 (minimum-difficulty block exception), header-only PoW SPV does not resist an adversary. Stage 0 Signet SPV tests are **conformance-only**; full PoW security applies strictly on Bitcoin Mainnet. ### 2.2 Stage 0 Embedded ABI Methods, Exact Sizes & Pinned Plasma Floor (`B1`, `B2`) All 4 Stage 0 oracle methods are **panic-recovered (`B1`)**, require **zero federation signatures**, and stay strictly within the pinned **`MaxBasePlasmaInMomentum >= 2,100,000`** floor (`spec/05 §2.2`) and `dp.MaxContractBlocks = 40` per-Momentum contract-block cap (`origin/dev:dp/dp.go:259-264`). Base Plasma under `DynamicPlasmaSpork` equals `tier + 68 * (abiBytes - 4)` (`origin/dev:vm/plasma.go:185-200`): | ABI Method | Send Plasma Tier | Exact Max Payload | Exact Max ABI (`32 B`-padded) | Exact Base Plasma (`QSR` @ floor `1,000`) | Max Storage Ops | Purpose | |---|---:|---:|---:|---:|---:|---| | `SubmitHeaderBatch(headers)` | `52,500` (Simple) | `160 B` (`2 × 80 B`) | `228 B` | `67,732` (`33 QSR`) | `<= 8` | Validate `1..2` mainnet headers, 2016-block `[302400, 4838400]`s retarget, MTP, update `ActiveChainByHeight`. | | `StepReorg()` | `52,500` (Simple) | `0 B` | `4 B` | `52,500` (`25 QSR`) | `<= 6` | Walk 1 incremental reorg step; emits deterministic reorg state transition if an admitted `< 12`-deep event is orphaned; flags `DeepReorgAlert = 1` if `ReorgSteps > 144`. | | `PruneStaleHeaders(hashes)` | `52,500` (Simple) | `64 B` (`2 × 32 B`) | `132 B` | `61,204` (`30 QSR`) | `<= 4` | Delete `1..2` stale `HeaderNode`s (`height < BestTip - 144 && height % 2016 != 0 && ReorgActive == 0`). | | `ProveTxInclusion(...)` | `73,500` (Heavy SPV) | `7,279 B` | `7,620 B` | `591,388` (`282 QSR`) | `<= 8` | Verify `>= N`-deep `strippedTx` (`65..6,144 B`) + 1-/2-block coinbase midstate + Merkle inclusion → record `VerifiedEvent[txid]`. | *Exact `ProveTxInclusion` ABI Derivation (Full `32 B`-Padded Accounting):* - Static head: `4 B` selector + `8 × 32 B` (`blockHeight`, `txIndex`, `totalCoinbaseBytes`, `sha256Midstate`, + 4 dynamic offsets) `= 260 B`. - Dynamic bodies (`32 B` length prefix + `32 B`-padded bytes): `strippedTx` (`32 + 6,144 = 6,176 B`) + `txBranch` (`32 + 16 × 32 = 544 B`) + `coinbaseTail` (`32 + 64 = 96 B` for `<= 63 B` tail) + `coinbaseBranch` (`32 + 16 × 32 = 544 B`) `= 7,360 B`. - Total ABI `= 260 + 7,360 = 7,620 B <= 16,384 B` (`MaxDataLength`). Base Plasma `= 73,500 + 68 × (7,620 - 4) = 591,388`. Up to **`3`** max-size `ProveTxInclusion` calls (`1,774,164 <= 2,100,000`) fit inside a single Momentum even at the pinned floor (`6` at default `4,200,000`). ### 2.3 Exact 1- and 2-Block Coinbase Midstate Proof (`CVE-2017-12842`, `R8-M06` Hardened) Every `ProveTxInclusion` call MUST verify: 1. `ChainMeta.ReorgActive == 0` and `ChainMeta.PostAnchorWork >= minimumPostAnchorWork`. 2. `ActiveChainByHeight[blockHeight]` exists and `BestTipHeight >= blockHeight + admissionDepthN - 1`. 3. **`65 <= len(strippedTx) <= 6,144`** (rejects `len == 64` **CVE-2017-12842** interior-node forgery AND any impossibly short `< 65 B` non-tx byte sequence, tightened per `R8-M06`), `txIndex != 0`, valid Bitcoin non-witness transaction syntax (`vin_count >= 1`, `vout_count >= 1`, exact byte consumption), and no SegWit marker (`0x00 0x01`) in stripped bytes. 4. `doubleSHA256(strippedTx)` verifies against `merkleRootLE` via `txBranch` at `txIndex` with `len(txBranch) == len(coinbaseBranch) <= 16` and zero duplicate-sibling **CVE-2012-2459** padding. 5. **1- and 2-Block SHA-256 Coinbase Midstate Verification:** - Caller supplies `(sha256Midstate: bytes32, finalChunkTail: bytes, totalCoinbaseBytes: u32, coinbaseBranch: bytes32[])`. - **Normative Constraints:** - `totalCoinbaseBytes >= 65` (rejects `totalCoinbaseBytes == 64` leaf forgery and impossibly short transactions). - **`len(finalChunkTail) == totalCoinbaseBytes % 64`** (strictly `< 64`; rejects any mismatched or unaligned tail!). - **Exact Final SHA-256 Padding (`100%` of valid Bitcoin coinbase lengths, avoiding the `12.5%` single-compression rejection bug when `rem ∈ [56, 63]`):** Let `rem = totalCoinbaseBytes % 64` and `bitLen = u64BE(uint64(totalCoinbaseBytes) * 8)`: - **Case 1 (`rem < 56` — 1-block final padding):** Build single `64 B` block `B_1 = finalChunkTail[0:rem] || 0x80 || 0x00^(55 - rem) || bitLen(8B)`. Compute `innerHash = SHA256_Compress(sha256Midstate, B_1)`. - **Case 2 (`56 <= rem <= 63` — 2-block final padding):** Build `B_1 = finalChunkTail[0:rem] || 0x80 || 0x00^(63 - rem)` and `B_2 = 0x00^56 || bitLen(8B)`. Compute `state_1 = SHA256_Compress(sha256Midstate, B_1)`, then `innerHash = SHA256_Compress(state_1, B_2)`. - Compute `coinbaseTxid = SHA256(innerHash)` and verify `coinbaseBranch` at index `0` against `merkleRootLE` with `len(coinbaseBranch) == len(txBranch)`. - *Explicit Auditability Disclosure:* A midstate proof proves that Merkle index `0` is a valid non-64-byte leaf at the same tree depth as `txIndex` (completely closing CVE-2017-12842 interior-node forgery); it does **not** parse the prefix of the coinbase transaction itself. In Stage 1A below, full coinbase bytes are directly verified inside the off-chain ZK stripped-block scanner to extract the BIP-141 witness commitment. ### 2.4 Stage 0 Oracle Storage Layout (`BtcSpvOracleContract`) | Prefix | Key | Value | Pruning Policy | |---|---|---|---| | `0x20` | singleton | `ChainMeta` (`BestTipHash`, `BestTipHeight`, `BestTipWork`, `PostAnchorWork`, `ReorgActive`, `DeepReorgAlert`) | Never pruned | | `0x21` | `blockHashBE(32B)` | `HeaderNode` (`160 B`, incl. `mtpWindow[11]`) | Pruned via `PruneStaleHeaders` when `< BestTip - 144 && height % 2016 != 0 && ReorgActive == 0` | | `0x22` | `u64BE(height)` | `ActiveChainByHeight` (`68 B`: `blockHashBE \|\| merkleRootLE \|\| blockTime`) | **NEVER PRUNED** | | `0x23` | `txid(32B)` | `VerifiedEvent` (`blockHeight`, `blockHashBE`, `txIndex`, `finalized: bool`) | Never pruned | --- ## 3. Stage 1A: Bitcoin-L1-Canonical Authorization Domain (`0%` Zenon Trust) For pooled, fungible `zBTC`, **Bitcoin L1 is the sole canonical ordering, data-availability, and forced-inclusion layer**. Zenon Pillars act strictly as **untrusted L1-subsidized soft-preconfirmation sequencers** (`spec/03 §2`, `spec/04 §2`). Even if **49%–100% of Zenon Pillars are Byzantine**, they cannot fork `zBTC`, mint 1 unbacked satoshi, or censor Bob's or Mike's exit. ### 3.1 Canonical Bitcoin L1 Tag Schema (`OP_RETURN "ZBTX"` `<= 80 B` + Authenticated Taproot Witness) All Stage 1A protocol events are tagged on Bitcoin L1 with a `4 B` magic prefix `"ZBTX"` (`0x5a 0x42 0x54 0x58`) and `1 B` `tag` inside an `OP_RETURN` output (`<= 80 B` standardness limit). Bulk payloads (`certBlob`, complete mutated SMT leaves, `π_batch`, signed forced transfers) sit inside the spending transaction's Taproot script-path witness, bound by SHA-256 commitment in the `OP_RETURN` and verified against the block's BIP-141 coinbase witness commitment. | Tag | Name | `OP_RETURN` Layout & Exact Size | Taproot Witness / Additional Outputs | Purpose | |---|---|---|---|---| | `0x00` | `DEPOSIT` | `"ZBTX"(4) \|\| 0x00(1) \|\| recipientAcctHash(32) \|\| vaultParamsHash(32)` = **`69 B`** | `vin[0]` = confirmed `U_dep_wallet` (`OP_DROP` `certBlob` `104 B <= 520 B`); `vin[1..3]` = denomination-matched `AdmissionTicketUTXO`s (`R8-C03`); `vout[0..2]` = `{0.50, 0.25, 0.25}` BTC deleted-key vaults keyed by acyclic `vault_id` (`R8-C01`). | Register `K`-deep multi-tier deposit vaults (enforcing `Cap_TVL_total` via L1 ticket conservation & $2^M$ Hall invariant) and credit `recipientAcctHash`. | | `0x01` | `FORCED_EXIT` | `"ZBTX"(4) \|\| 0x01(1) \|\| exitCommitHash(32)` = **`37 B`** | Witness carries `(acctId, nonce, grossSats >= max(dust, MIN_EXIT_SATS=100_000), maxOpFeeSats, destScriptPubKey, cancelPubKey, sig_user)` (`R8-M05`); additional output creates active-operator **`(2M_active+1)`-leaf `ExitSlotUTXO`** (`546` sat dust anchor, `spec/01 §5`). | Uncensorable L1 exit for Bob (`0.50 BTC`) or Mike (`0.25 BTC`), bypassing 49%–100% Zenon censorship & Plasma spikes. | | `0x02` | `BATCH_DA` | `"ZBTX"(4) \|\| 0x02(1) \|\| batchCommitHash(32)` = **`37 B`** | Witness carries `prevRoot(32B) \|\| newRoot(32B) \|\| batcherSlotId(2B) \|\| mutatedAccounts[]` (`16 B` existing / `48 B` new, `<= 1,000` new/6-blk epoch w/ `500`-sat refundable leaf deposit) `\|\| mutatedRollupLocks[]` `\|\| cooperativeExits[]` `\|\| creditTransfers[]` `\|\| π_batch` (`R8-C05`, `R8-M01`, `R8-M02`, `R8-M04`). | Anchor feeless Zenon-sequenced transfers, `RollupLocks`, cooperative `PendingExits`, and `TransferCredit` ops onto Bitcoin L1 with **100% self-contained state-diff DA** across all non-L1-derivable SMT namespaces! | | `0x03` | `FORCED_TRANSFER` | `"ZBTX"(4) \|\| 0x03(1) \|\| txCommitHash(32)` = **`37 B`** | Witness carries signed `110 B` rollup transfer (or `RollupHTLC`/`RollupPTLC` / `TransferCredit` op). | Uncensorable L1 transfer fallback if Zenon censors or Dynamic Plasma spikes. | | `0x04` | `CHALLENGE_CLAIM` | `"ZBTX"(4) \|\| 0x04(1) \|\| kickoffTxid(32) \|\| verifierAcctId(4)` = **`41 B`** | Emitted on every `ChallengeTx_{r,i}` opened in simultaneous window `[0, 144]` (which also creates `ChalProofConnector_{r,i}` for native-L1 `0.15 BTC` payout from `Stake_r`, `spec/01 §4`). | Indexes active challengers on-chain for auditability and optional protocol insurance attribution (native L1 verifier EV comes strictly from `Stake_r`!). | | `0x05` | `FRONT_CLAIM` | `"ZBTX"(4) \|\| 0x05(1) \|\| exitId(32) \|\| operatorId(4)` = **`41 B`** | Emitted when active operator $O_j$ spends `ExitSlotUTXO` paying `destScriptPubKey` `>= grossSats - maxOpFeeSats` in `vout[0]`. *(Note: even untagged `ExitSlotUTXO` spends are caught by full stripped-`vin` scanning, §3.2!)* | Credits `ReimbursementCredit[O_j] += grossSats` (tagged with exit creation height for `R8-N01` oldest-exit priority; or triggers hard-partitioned `B_grief` slash + refund on non-paying spend!). | | `0x06` | `EXIT_FEE_BUMP` | `"ZBTX"(4) \|\| 0x06(1) \|\| exitId(32) \|\| newMaxOpFeeSats(8)` = **`45 B`** | Witness carries user signature over `(exitId, newMaxOpFeeSats)` where `newMaxOpFeeSats > oldMaxOpFeeSats`. | Lets Bob/Mike raise fronting incentive during L1 fee spikes without re-queuing. | | `0x07` | `RELEASE_ASSIGNMENT` | `"ZBTX"(4) \|\| 0x07(1) \|\| vaultId(32) \|\| operatorId(4)` = **`41 B`** | Witness carries explicit `O_j` signature voluntarily releasing an assigned vault (`AssignedObligations[vaultId] -> ReimbursementCredit[O_j]`, `Vaults[vaultId] -> UNASSIGNED`). | Optional `O_j`-signed voluntary release preserving exact `V_unassigned + V_assigned = C + L + E + R + A + B` (`R8-C02`). | ### 3.2 Off-Chain Stripped-Block ZK Scanner, Fail-Closed BIP-141 Witness Completeness & Full `vin` Tracking (`R8-C05`, `R8-H05`) **Architecture Split (`R8-H05`):** The full stripped-block scanner and SMT updater $\mathcal{F}$ execute inside the **off-chain ZK validity prover**, producing a succinct proof verified by the immutable **`vk_STF` wrapped SNARK verifier** inside `BitVMX-CPU` (`RV32IM`, `<= 8^9` instructions, Gate G2). Inside the off-chain ZK circuit proved by `vk_STF`: 1. **Complete Stripped Block Verification (`<= 1,000,000 B` Bitcoin consensus stripped-block cap):** For every confirmed block $h$ in `[h_prev + 1, h_tip - K + 1]`, the prover feeds the **complete stripped block** (`tx_0 .. tx_{m-1}`) into $\mathcal{F}$. $\mathcal{F}$ computes every `txid_i = doubleSHA256(stripped_tx_i)`, reconstructs the full transaction Merkle root, and asserts equality with `header[h].merkleRoot`. **No transaction in block $h$ can ever be omitted or censored by a malicious prover.** 2. **Mandatory Full Stripped-`vin` Scan for Untagged Protocol UTXO Spends (`R8-C05`):** $\mathcal{F}$ MUST inspect **every `vin` of EVERY stripped transaction `tx_1 .. tx_{m-1}` in block `h`** (regardless of whether the spending transaction carries an `OP_RETURN "ZBTX"` tag!) against the canonical tracked outpoint set (`VaultUTXO`, `ExitSlotUTXO`, `Stake_r`, `VaultConnector_r`, `AdmissionTicketUTXO`). Thus an attacker CANNOT bypass `ExitSlotUTXO` grief slashing, `TakeTx` Lamport equivocation accounting, `Stake_r` dual-input slashing, or `RetireStakeTx_r` detection by omitting a `"ZBTX"` tag! 3. **Exact BIP-141 Witness Commitment Extraction & Fail-Closed vs Deterministic-Skip Rule (`R8-C05`):** - $\mathcal{F}$ parses the full stripped coinbase transaction `tx_0` (verifying `vin[0].prevout == 0x00^32 : 0xffffffff`), locates the **LAST output** whose `scriptPubKey` starts with the 6-byte BIP-141 header **`0x6a24aa21a9ed`** and satisfies `len(scriptPubKey) >= 38`, and extracts `witnessCommitment = scriptPubKey[6:38]`. - Using coinbase **`wtxid_0 = 0x00^32`** and the coinbase witness nonce (`32 B` `witnessReservedValue`), $\mathcal{F}$ verifies `SHA256d(witnessRoot || witnessNonce) == witnessCommitment` and authenticates the exact BIP-141 **`wtxid_i` Merkle branch** for every protocol transaction `tx_i` carrying witness data (`0x00`, `0x01`, `0x02`, `0x03`, `0x06`, `0x07`, or any SegWit spend of a tracked UTXO). - **Strict Fail-Closed vs Skip Classification (Eliminating Witness-Withholding Censorship):** - **FAIL CLOSED (`REFUSED_DATA_UNAVAILABLE` — Proof Invalid!):** If a prover omits the witness bytes for a SegWit protocol transaction, submits witness bytes whose computed `wtxid_i` fails the coinbase BIP-141 `witnessRoot` Merkle proof, or fails to locate the valid last `0x6a24aa21a9ed` commitment when SegWit transactions exist, the ZK circuit **MUST REJECT** (`satisfiability = FALSE`). A prover can NEVER claim a valid `0x02`/`0x01`/`0x03` tx was "malformed" by withholding its witness! - **DETERMINISTIC SKIP (Only AFTER `wtxid_i` Authentication):** ONLY AFTER the exact witness bytes of `tx_i` have been cryptographically authenticated against `witnessRoot` inside the coinbase commitment may $\mathcal{F}$ deterministically skip `tx_i` if its authenticated payload fails schema decoding, `prevRoot != R_cur`, slot priority, or `Verify(π_batch) == false`. ### 3.3 Canonical Intra-Block Ordering & Slotted `0x02` Batcher Priority (`R8-M02`) Within each `K`-deep Bitcoin block $h$, $\mathcal{F}$ transitions $R_{h-1} \to R_h$ in strict deterministic order: 1. **Pass 1 — Deposits (`0x00 DEPOSIT`):** Process in Bitcoin block transaction-index order `i = 1..m-1`. Verify `AdmissionTicketUTXO` consumption (`vin[1..3]`), acyclic `vault_id` Taproot script derivation, `wtxid`-authenticated `certBlob` (`104 B`), valid `N`-of-`N` setup cohort binding, `{0.50, 0.25, 0.25}` BTC outputs, and the **$2^M$ Hall's Marriage Invariant** (`spec/01 §6.2`). Credit `Accounts[recipientAcctHash].balanceSats += D_d`. 2. **Pass 2 — First Valid Sequenced Batch (`0x02 BATCH_DA`):** Scan block $h$ in tx-index order and apply **AT MOST ONE** `wtxid`-authenticated valid `0x02` batch whose `prevRoot == R_after_pass_1`, `π_batch` verifies against the complete mutated SMT state diff (`Accounts`, `RollupLocks`, cooperative `PendingExits`, `TransferCredit`, `<= 1,000` new leaves/epoch with `500`-sat refundable deposit), and whose `batcherSlotId` matches the **deterministic slotted batcher priority** (`primary_batcher = H(header[h-1].hash) mod K_batchers` for the first 2 blocks after `prevBatchHeight + 6`, open permissionless fallback to any batcher thereafter — eliminating stale-root L1 fee burn races, `R8-M02`!). Any competing `0x02` batch (e.g. from a 49% Zenon fork) fails `prevRoot` matching and is deterministically skipped. 3. **Pass 3 — Mandatory L1 Forced Inclusion (`0x03`, `0x01`, `0x06`):** Apply EVERY `wtxid`-authenticated valid `0x03 FORCED_TRANSFER`, `0x01 FORCED_EXIT` (`grossSats >= max(dust, 100_000)` sats, active-operator `ExitSlotUTXO`), and `0x06 EXIT_FEE_BUMP` in tx-index order. **100% hostile Zenon Pillars cannot delay or censor a single forced transfer or exit by even 1 Bitcoin block.** 4. **Pass 4 — Tracked-UTXO Spends, Deterministic FIFO Assignment & Slashing Events (Full `vin` Scan + `0x04`, `0x05`, `0x07`):** Process ALL spends of tracked `ExitSlotUTXO`s (universal spend-or-refund rule with hard-partitioned `B_grief` pro-rata burst cap, `spec/01 §5`), `TakeTx` confirmations (`V_assigned -= D_v`, `AssignedObligations.pop(v)`), `0x07 RELEASE_ASSIGNMENT` (`V_assigned -> V_unassigned`, `A[v] -> R[O_j]`), deterministic tightest-slack FIFO vault assignment (`V_unassigned -> V_assigned`, `R[O_j] -> A[v]` respecting oldest-`PendingExit` credit priority, `R8-N01`), `DisproveTx`/`TimeoutSlashTx` dual-input slashes (`0` vault stolen, `B_custody` slashed), `BurnBondTx_{r,k}` Lamport equivocation slashes (`D_v` burned from `B_custody`, innocent `O_k` restored if `v` was assigned to `O_k`, `0.05 BTC` bounty), and `RetireStakeTx_r` (gating `B_zbtc` unlock on `A[O_j] == 0` and Hall's invariant). Assert exact **`V_unassigned + V_assigned == C + L + E + R + A + B`** (`R8-C02`)! --- ## 4. Launch-Time PoW Anchor, `K >= 18` Unpublished-Fork Heuristic, Heaviest-Chainwork Verification & `>= K` Deep-Reorg Circuit Breaker (`R8-H03`, `R8-M07`) Because Bitcoin L1 scripts without covenants cannot inspect arbitrary future chain tips directly, each finite `BitVMX` `StakeChain` lane `(j, l)` (`R = 64` rounds, active horizon `<= ~2.3` years at `T_cooldown = 13.0d`) anchors Bitcoin PoW at lane launch (`t = 0`, **before** `Q_lane_{j,l}` deletion): 1. **Launch-Time Lane Anchor `(h_lane_init, H_init, D_init)`:** Pins an **already-confirmed** Bitcoin mainnet block at lane creation, together with its 2,016-block retarget-period start header and `mtpWindow[11]`. 2. **Full 2,016-Block Retargeting & Difficulty Floor:** The ZK prover validates every 80-byte Bitcoin header from `h_lane_init` to `h_tip` with exact mainnet `SetCompact`, `[302400, 4838400]`s 2,016-block retarget clamping, MTP monotonicity, and minimum difficulty floor **`D(h) >= 0.50 * D(h_lane_init)`**. *(If mainnet difficulty grows `> 2×` during a lane's active lifetime, operators retire old lanes at `2,016` blks and launch fresh lanes re-anchored to current `D`.)* 3. **Interactive Heaviest-Chainwork Competing-Header Challenge (`R8-H03` — Clementine / BitVM3 Light-Client Pattern):** - To prevent a malicious operator from submitting a valid but lower-work private fork anchored at `h_lane_init`, any verifier `V_i` challenging `RoundTx_r` in `[0, 144]` may supply a **competing valid Bitcoin header-chain proof** anchored to the same `(h_lane_init, H_init, D_init)` whose cumulative chainwork strictly exceeds the operator's claimed chain (`cumWork(H_chal) > cumWork(H_op)`) and which diverges at or before the claimed `K`-deep confirmation block. - Inside `vk_STF`, comparing the two header-chain SNARK commitments deterministically proves the operator asserted a non-canonical/lower-work fork and slashes `Stake_r` + `VaultConnector_r`! 4. **Honest Private-Fork Heuristic (`K >= 18` Hard Floor) & Budish Subsidy-Offset Disclosure (`R8-H03`):** - The protocol enforces a hard minimum **`K >= 18` blocks (`~3.0h` nominal)** and sizes `K` across halvings against **`Cap_TVL_total = Cap_user + M × B_zbtc`** using the **conditional unpublished-fork opportunity-cost heuristic**: $$0.50 \times K \times \text{Subsidy}(\text{era}) > \text{Cap}_{\text{TVL,total}}$$ - **Mandatory Economic Honesty Disclosure (Budish Winning-Fork Offset):** This inequality measures the *unpublished/orphaned fork* opportunity cost. Under a **majority (`>50%`) hashrate attack** where the attacker publishes the winning fork and recaptures all `K` block subsidies, the attacker's direct mining cost is only the **net electricity/hardware flow cost `κ × K × Subsidy`** (`κ ∈ [0.05, 0.50]`) PLUS external reputational/BTC-price-crash losses (`verify_spec_bounds.py` prints the exact Budish sensitivity table). Consequently, `K >= 18` delivers **probabilistic PoW finality under `<50%` honest hashrate** — NOT an unconditional economic guarantee against a `>50%` cartel! | Deployment Stage | `Cap_user` / **`Cap_TVL_total`** (incl. `M × B_zbtc`) | `K` (2024–2028, `3.125 BTC`) | `0.50 × K × Sub` (`K × Sub` nom) | `K` (2028–2032, `1.5625 BTC`) | `K` (2032–2036, `0.78125 BTC`) | |---|---:|---:|---:|---:|---:| | **Stage 1A Pilot (`M = 3`)** | `<= 10 BTC` / **`11.80 BTC`** | **`18`** (`~3.0h`) | `28.125` (`56.25`) `> 11.80` | `18` (`14.06 > 11.80`) | `32` (`12.50 > 11.80`) | | **Stage 1A Expanded (`M = 5`)** | `<= 15 BTC` / **`18.00 BTC`** | **`18`** (`~3.0h`) | `28.125` (`56.25`) `> 18.00` | `24` (`18.75 > 18.00`) | `48` (`18.75 > 18.00`) | | **Stage 2 Scaled (`M = 20`)** | `<= 50 BTC` / **`62.00 BTC`** | **`42`** (`~7.0h`) | `65.625` (`131.25`) `> 62.00` | `80` (`62.50 > 62.00`) | `160` (`62.50 > 62.00`) | | **Stage 2 High-Cap (`M = 40`)** | `<= 200 BTC` / **`224.00 BTC`** | **`144`** (`~24.0h`) | `225.00` (`450.00`) `> 224.00` | `288` (`225.00 > 224.00`) | `576` (`225.00 > 224.00`) | 5. **Fail-Closed Deep-Reorg (`>= K`) Circuit Breaker (`R8-M07`):** - All Rollup full nodes, batchers, operators, and verifiers MUST retain **`>= 144`-block rollback snapshots** of `(R_h, SMT_h)`. - If Bitcoin ever experiences a reorg of depth `>= K` (`>= 18` blocks), nodes MUST immediately assert **`DEEP_REORG_HALT`**: (a) freeze new `0x02` batch submissions and new operator fronting, (b) rewind canonical state to the highest common ancestor `h_fork` and deterministically replay the heavier canonical Bitcoin chain from `h_fork + 1`, (c) treat any orphaned `FrontingTx` as valid ONLY if confirmed on the canonical chain (operators explicitly accept `< K`-deep fronting risk and wait `K` blocks before claiming vault reimbursement), and (d) resume normal operation automatically once the canonical tip stabilizes `>= K` blocks past `h_fork`. --- ## 5. Mandatory SPV & Authorization Domain Conformance Test Vectors 1. **Stage 0 Header & Merkle Suite:** All 24 Bitcoin header, 2,016-block retarget (`[302400, 4838400]`s), MTP, `futureTimeGuardSecs = 7,200`, `LOWEST_BLOCK_HASH_BE` tie-break, `CVE-2012-2459`, and `CVE-2017-12842` (`len < 65` rejection, `R8-M06`) vectors. 2. **1- and 2-Block Coinbase Midstate Suite:** Valid coinbase proofs for BOTH `totalCoinbaseBytes % 64 ∈ [0, 55]` (1-block) AND `totalCoinbaseBytes % 64 ∈ [56, 63]` (2-block — e.g. `120 B`, `127 B`, `250 B`), plus rejection of `len(finalChunkTail) != totalCoinbaseBytes % 64` and `totalCoinbaseBytes <= 64`. 3. **Panic-Free & Plasma-Floor Fuzz Gate (`B1`, `B2`):** Malformed ABI inputs across all 4 Stage 0 oracle methods MUST return deterministic errors (zero panics, zero FIFO sequencer stalls), and exact ABI sizing of `ProveTxInclusion` (`7,620 B`, `591,388` Plasma) fits `>= 3×` inside the `2,100,000` floor and `<= 40` contract blocks/Momentum. 4. **Stage 1A Stripped-Block, BIP-141 Completeness & Reorg Suite (`R8-C05`, `R8-M07`):** Rejection (`REFUSED_DATA_UNAVAILABLE`) of omitted or `wtxid`-mismatched witnesses, extraction of the LAST `0x6a24aa21a9ed` coinbase output when multiple matching outputs exist, full stripped-`vin` detection of untagged `ExitSlotUTXO`/`VaultUTXO`/`Stake_r` spends, deterministic skip of `wtxid`-authenticated malformed `0x02 BATCH_DA`, slotted batcher priority, interactive heaviest-chainwork fork rejection, and `>= K` `DEEP_REORG_HALT` rewind/replay. # Part 3: Stage 0 Erlang-Hardened PTLC/HTLC Swaps, Stage 1A Sovereign Rollup STF & Feeless Zenon Rails, and Stage 1B `clArk` Coordination **Document Class:** Normative Settlement, Rollup State Transition & Feeless Payment Specification (`v2` / `v3.1.0-rfc` — Zero-Federation Phased Architecture; supersedes archived `v1` `v3.0.0-rfc` and `v0` `v2.5.0-rfc`) **Custody Posture:** **ZERO federated signers, ZERO ZNN governance/slashing custody coupling, ZERO federated multisig or embedded-contract pre-minting.** **Consistency Checker:** [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py) --- ## 1. Stage 0: Erlang-Hardened Non-Custodial PTLC & HTLC Atomic Swaps (`PtlcSpork`, `M-4`, `R8-H07`) Stage 0 launches with **`0 BTC` protocol custody** (`0–5 BTC` voluntary LP capital), strictly honoring `zenon-developer-commons` (`essays/Verify Bitcoin, Don't Bridge It.md`). Native BTC stays in user self-custody on Bitcoin L1 or Lightning; Zenon swaps native ZNN/QSR/ZTS assets atomically via `PtlcContract` and `HtlcContract`. > **Stage 0 Scope & Conditional Atomicity Honesty (`R8-H07`):** Stage 0 atomic swaps do **not** create pooled, fungible `zBTC` on Zenon. A counterparty LP is required for every swap, and under a severe Zenon attack rational LPs pull liquidity. Furthermore, cross-chain swap atomicity is explicitly **conditional on bounded Bitcoin/Zenon block progress and timely automated refund broadcast** — never unconditional against arbitrary unbounded chain stalls. ### 1.1 Erlang-Hardened BIP-327 Tweaked Taproot PTLC Swap (`M-4`, `R8-H07` Closed) **Protocol (Alice sells BTC on Bitcoin L1; Bob sells Zenon asset on Zenon; Bob holds secret scalar $t \in \mathbb{Z}_n^*$):** 1. **Setup:** Bob sends compressed 33-byte point $T = \text{compress}(t \cdot G)$ to Alice. 2. **Bitcoin Taproot Funding (`>= 72`-Block CSV):** Compute $P_{\text{swap}} = \text{MuSig2\_KeyAgg}(pk_A, pk_B)$, Tapscript refund leaf $L_{\text{ref}} = \text{<72> OP\_CSV OP\_DROP OP\_CHECKSIG}$, tweak $t_{\text{tap}} = H_{\text{"TapTweak"}}(x(P_{\text{swap}}) \parallel \text{TapLeaf}(L_{\text{ref}}))$, and $Q_{\text{swap}} = P_{\text{swap}} + t_{\text{tap}} \cdot G$ with BIP-327 accumulated tweak `t_acc` and parity `g_key`. Alice funds `0x51 0x20 || x(Q_swap)`. Let $h_{\text{conf}}$ be Bitcoin confirmation height and `now_unix` be current UTC Unix seconds. 3. **Absolute Unix Timestamp Lock & Erlang-Safe `>= 48h` Slow-Block Margin (`R8-H07`):** - `go-zenon`'s `PtlcContract.Create` compares `momentum.Timestamp.Unix() >= param.ExpirationTime` (`origin/dev:vm/embedded/implementation/ptlc.go:326`), requiring an **absolute Unix timestamp** (NEVER a relative duration!). - Under Poisson block arrivals at June 2021's worst daily slowdown (`2.3×` nominal = `1,380s`/blk), an old `30h` lock suffered `P(T_72 > 30h | 2.3×) = 22.47%` (`~22.34%` in R8's continuous approx) refund-race exposure (`R8-H07`). Therefore `v3.1.0-rfc` mandates **`T_znn_sec >= 172,800` seconds (`48.0h`, `~15,158` Momentums at observed `11.4s`/Momentum)** and **`expirationTime = now_unix + T_znn_sec`**. - **Exact Erlang Tail Proof (`scripts/verify_spec_bounds.py`):** At `2.3×` slowdown (`λ = 1/1,380` blks/s), the 99.9th percentile of `72` blocks is `p99.9(T_72) = 38.75h`, leaving **`>= 9.25h` wall-clock tail margin** before `48.0h` and reducing tail exceedance to **`P(T_72 > 48h | 2.3×) < 10^{-6}`** (`~9.5 × 10^{-8}`)! - Bob calls `PtlcContract.Create(expirationTime = now_unix + 172800, pointType = 2, pointLock = compress(T), destination = Alice_Addr)` (`origin/dev:vm/embedded/definition/ptlc.go:118-129`). 4. **Mandatory Automated High-Fee RBF Refund Watchtower & Grief Disclosure:** - Alice sends BIP-327 adaptor partial signature $\tilde{s}_A$ within `<= 6` Bitcoin blocks of Zenon PTLC confirmation ($R' = R_A + R_B + T$ with parity $g_R$, $\tilde{s} = \tilde{s}_A + \tilde{s}_B + e \cdot g_{\text{key}} \cdot t_{\text{acc}} \pmod n$). - **Mandatory Watchtower Rule (`R8-H07`):** Alice MUST NOT rely on Bob voluntarily honoring a `h_conf + 66` cutoff. Alice's wallet/watchtower MUST automatically broadcast her `<72> OP_CSV` refund transaction **immediately at height `h_conf + 72`** with aggressive RBF fee-bumping (and direct-to-miner backup if mempools exceed `200 sat/vB`) so Bob cannot confirm a late claim near `48h`! - **Explicit Grief Disclosure:** Because `PtlcContract` has **no early reclaim** prior to `ExpirationTime`, if Alice withholds $\tilde{s}_A$, Bob's Zenon funds remain grief-locked for the full `48h` duration (zero theft, pure time-lock grief). Production LPs bound this via small per-peer swap limits or reputation/Lightning Hold Invoices. 5. **Atomic Claim & Secret Extraction:** Bob completes $s = \tilde{s} + g_R \cdot t \pmod n$ with a `` CPFP anchor prior to Alice's block-72 watchtower refund. Alice extracts $t_{\text{ext}} = g_R \cdot (s - \tilde{s}) \bmod n$, checks `compress(t_ext * G) == PointLock`, and calls `PtlcContract.Unlock(ptlcId, t_ext)` (`origin/dev:vm/embedded/implementation/ptlc.go:82-97`). ### 1.2 Erlang-Hardened HTLC & Lightning Submarine-Swap Gateway (`R8-H07`) - **Hash Type:** ALL Bitcoin/Lightning HTLCs MUST use **`hashType = 1` (`HashTypeSHA256`, `origin/dev:vm/embedded/definition/htlc.go:92`)**. - **Slowdown-Adjusted Erlang-Safe Unix-Second Delta (`R8-H07`):** At `100%` hashrate, `36` nominal blocks (`6h` mean) exceed `6h` with probability `P(T_36 > 6h | 1.0×) = 47.78%`! Therefore, while Bitcoin/Lightning block delta remains `Δ_safety_blocks = 36`, **Zenon wall-clock safety delta MUST be `Δ_safety_sec >= 86,400s` (`24.0h`)** — exceeding `p99.9(T_36 | 2.3×) = 22.01h` with **`P(T_36 > 24h | 2.3×) < 0.0002`** (and `< 10^{-20}` at `1.0×` nominal!): - **Inbound (`LN → Zenon`):** User pays Gateway's LN Hold Invoice FIRST; ONLY AFTER Hold Invoice reaches `ACCEPTED` with `remaining_cltv_blocks >= 72` (`2 × Δ_safety_blocks`) does Gateway lock Zenon funds in `HtlcContract` with **`expirationTime_unix <= now_unix + (remaining_cltv_blocks - 36) * 600`** (ensuring `>= 36` Bitcoin blocks remain after Zenon expiry for Gateway's LN claim/cancel). Gateways MUST enforce `<= 5` concurrent pending hold invoices, `<= 0.10 BTC` exposure per peer, and a **5-minute cancel TTL**. - **Outbound (`Zenon → LN`):** User locks Zenon funds (`hashType = 1`, `expirationTime_unix >= now_unix + 2 * 86,400 = now_unix + 172,800` = `48h`); Gateway pays a BOLT-11 invoice whose CLTV expiry satisfies **`now_unix + (cltv_blocks * 600 * 2.3) <= expirationTime_unix - 86,400`** (leaving `>= 24h` Erlang-safe wall-clock margin even under `2.3×` slowdown!), learns preimage $r$, and unlocks Zenon `HtlcContract`. --- ## 2. Stage 1A: Sovereign Rollup STF $\mathcal{F}$ & L1-Subsidized Feeless Zenon Sequencer Rails In Stage 1A, `zBTC` is a **Bitcoin-Anchored Sovereign ZK Validity Rollup** backed by **right-sized `BitVMX` (`n = 8`, `M = 3–5`, `N = 7`) deleted-key vaults** (`spec/01`). **Zero federated signers and zero ZNN governance keys touch BTC custody or `zBTC` supply.** ### 2.1 Immutable Rollup SMT State Schema & Exact Conservation Law With `AssignedObligations (A)` (`R8-C02`, `R8-H01`) The canonical `zBTC` ledger state $R_h$ is a 256-bit Sparse Merkle Tree (`SHA-256` / Poseidon2) maintained deterministically by $\mathcal{F}$ over Bitcoin L1 blocks (`spec/02 §3`): | SMT Namespace | Key | Value Fields | Invariants | |---|---|---|---| | `Accounts` (`C`) | `acctId (u32)` | `{ pubkey: bytes32 (BIP-340), balanceSats: u64, nonce: u32, leafDepositSats: u64 }` | `balanceSats >= 0`; `nonce` strictly monotonic (`+1`/tx); brand-new leaf locks refundable `500`-sat `leafDepositSats` (`R8-M01`, counted in `C`). | | `Vaults` (`V`) | `vaultId (bytes32)` | `{ outpoint(36B), denomSats: u64 ∈ {50_000_000, 25_000_000}, opBitmask: u64, status: UNASSIGNED \| ASSIGNED(opId, lane, round) \| REIMBURSED \| SLASHED_EQUIV }` | Partitioned into $V_{\text{unassigned}}$ and $V_{\text{assigned}}$; satisfies exact $2^M$ Hall's Marriage Invariant (`spec/01 §6.2`). | | `PendingExits` (`E`) | `exitId (bytes32)` | `{ acctId, grossSats >= max(dust, 100_000), maxOpFeeSats, createdBtcHeight, destScriptPubKey, cancelPubKey, exitSlotOutpoint(36B), status: OPEN \| COMPLETED \| CANCELLED }` | Created ONLY by burning `grossSats` from `Accounts[acctId]` via `0x02` or L1 `0x01`; `MIN_EXIT_SATS = 100,000` sats (`0.001 BTC`, `R8-M05`). | | `RollupLocks` (`L`) | `lockId (bytes32)` | `{ senderAcctId, destAcctId, amountSats, expiryBtcHeight, lockType: HTLC \| PTLC, lockDigest(33B) }` | First-class rollup opcodes (`RollupHTLC`, `RollupPTLC`) serialized in `0x02 BATCH_DA` (`R8-C05`). | | `OperatorState` | `opId (u32)` | `{ active: bool, lanes: [L], remainingRounds: u32, suspended: bool }` | Auto-suspended & excluded from all new `ExitSlotUTXO`s if `B_grief < 0.05 BTC` or `B_custody < 0.55 BTC`. | | `ReimbursementCredit` (`R`) | `opId (u32)` | `{ creditSats: u64, oldestBackedExitHeight: u32 }` | Incremented ONLY on `K`-deep verified `ExitSlotUTXO` payout (`vout[0]`); supports signed `TransferCredit(from_op, to_op, amt)` (`R8-M04`) and oldest-`PendingExit` priority (`R8-N01`). | | `AssignedObligations` (`A`) | `vaultId (bytes32)` | `{ opId: u32, lane: u8, round: u16, denomSats: u64, assignedHeight: u32 }` | **Explicitly tracks pending `TakeTx` claims across the `T_take = 1,728`-block gap (`R8-C02`)!** Created atomically on FIFO assignment (`R -> A`), destroyed on `TakeTx` confirmation (`V_assigned, A -> 0`) or `0x07` release (`A -> R`). | | `LockedOperatorCollateral` (`B`) | `(opId, lane)` | `{ bCustodySats: u64 (floor 55_000_000), bGriefSats: u64 (floor 5_000_000) }` | **Hard-partitioned (`R8-H01`, `R8-N05`):** `bCustodySats` (`0.55 BTC`) NEVER debited by `ExitSlotUTXO` griefing; `bGriefSats` (`0.05 BTC`) exclusively absorbs grief penalties. Total `B_zbtc = 0.60 BTC`/lane. | **Amended Global Solvency Conservation Invariant (`R8-C02` Closed — Checked on EVERY State Transition $R_{h-1} \to R_h$):** $$\underbrace{\sum_{v \in \text{Unassigned}} D_v}_{V_{\text{unassigned}}} \;+\; \underbrace{\sum_{v \in \text{Assigned}} D_v}_{V_{\text{assigned}}} \;=\; \underbrace{\sum_{a \in \text{Accounts}} (\text{bal}_a + \text{dep}_a)}_{C} \;+\; \underbrace{\sum_{\ell \in \text{Locks}} \text{amt}_\ell}_{L} \;+\; \underbrace{\sum_{e \in \text{Exits}_{\text{OPEN}}} \text{gross}_e}_{E} \;+\; \underbrace{\sum_{o} \text{Credit}_o}_{R} \;+\; \underbrace{\sum_{v \in \text{Assigned}} \text{Obl}_v}_{A} \;+\; \underbrace{\sum_{o,l} (B_{\text{custody}} + B_{\text{grief}})}_{B}$$ **Exact Atomic Conservation Matrix Across Every Lifecycle Transition:** | Transition | $\Delta V_{\text{unassigned}}$ | $\Delta V_{\text{assigned}}$ | $\Delta C$ | $\Delta E$ | $\Delta R$ | $\Delta A$ | $\Delta B$ | Net $\Delta(\text{LHS} - \text{RHS})$ | |---|---:|---:|---:|---:|---:|---:|---:|---:| | `deposit` (`0x00`) | $+D$ | $0$ | $+D$ | $0$ | $0$ | $0$ | $0$ | **`0`** | | `forced_exit` (`0x01`) / `0x02` exit | $0$ | $0$ | $-g$ | $+g$ | $0$ | $0$ | $0$ | **`0`** | | `front_paid` (`ExitSlotUTXO` valid) | $0$ | $0$ | $0$ | $-g$ | $+g$ | $0$ | $0$ | **`0`** | | `front_grief` (`k`-burst pro-rata `p <= B_grief`) | $0$ | $0$ | $+g + p$ | $-g$ | $0$ | $0$ | $-p$ (`B_grief` only!) | **`0`** | | `exit_cancel` (Leaf `2M_active`) | $0$ | $0$ | $+g$ | $-g$ | $0$ | $0$ | $0$ | **`0`** | | `fifo_assign` (oldest tightest-slack vault $v$) | $-D_v$ | $+D_v$ | $0$ | $0$ | $-D_v$ | $+D_v$ | $0$ | **`0`** | | `take_confirmed` (after `T_take = 1,728` blks) | $0$ | $-D_v$ | $0$ | $0$ | $0$ | $-D_v$ | $0$ | **`0`** | | `release_assignment` (`0x07`, signed by $O_j$) | $+D_v$ | $-D_v$ | $0$ | $0$ | $+D_v$ | $-D_v$ | $0$ | **`0`** | | `disprove_dual_slash` (`Stake_r + VaultConnector_r`) | $+D_v$ (if assigned) | $-D_v$ (if assigned) | $+0.55$ (insurance) | $0$ | $+D_v$ (if assigned) | $-D_v$ (if assigned) | $-0.55$ (`B_custody`) | **`0`** | | `lamport_equivocation_slash` (unassigned $v$ stolen) | $-D_v$ | $0$ | $+0.05$ (bounty) | $0$ | $0$ | $0$ | $-(D_v + 0.05)$ (`B_custody`) | **`0`** | | `lamport_equivocation_slash` (assigned to innocent $O_k$!) | $0$ | $-D_v$ | $+0.05$ (bounty) | $0$ | $+D_v$ ($O_k$ whole!) | $-D_v$ | $-(D_v + 0.05)$ (`B_custody`) | **`0`** | | `transfer_credit` (`O_a -> O_b`, `R8-M04`) | $0$ | $0$ | $0$ | $0$ | $0$ ($-x/+x$) | $0$ | $0$ | **`0`** | | `retire` (`RetireStakeTx_r` + Hall OK + $A[O_j]=0$) | $0$ | $0$ | $+B_j + R_j$ | $0$ | $-R_j$ | $0$ | $-B_j$ | **`0`** | ### 2.2 Honest L1-Subsidized Feeless Zenon Sequencer Rails & Two-Column Throughput Table (`M-9`, `M-10`, `R8-M01`, `R8-M08`) - **Exact Zenon Transport Format (NOT Native `TokenContract` ZTS):** - Stage 1A `zBTC` balances live strictly in the Bitcoin-canonical Rollup SMT, **NOT** in `go-zenon`'s `TokenContract`. - Users transmit signed `110 B` rollup transactions (`op(1) || domain(1) || fromAcctId(4) || toAcctId(4) || amountSats(8) || nonce(4) || batchTipSats(4) || expiryBtcHeight(4) || memoTag(16) || bip340Sig(64)` = **`110 B`**; `+32 B = 142 B` for new recipient pubkey) inside standard Zenon `AccountBlock.Data` (`UserSend` to canonical sequencer sink with `Amount = 0`). - **Exact Zenon Plasma Cost (At Floor Price `1,000`):** $$\text{BasePlasma}(\text{110 B rollup tx}) = 21{,}000 + 68 \times 110 = \mathbf{28{,}480\text{ Plasma}}$$ - Funded by **`14 QSR` refundable fused Plasma** (`ceil(28,480 / 2,100) = 14 QSR`, zero burn, replenished upon confirmation) OR **`42.72M` SHA3-256 PoW hashes**. - **Honest Fee Framing (`R8-M01`):** Stage 1A transfers on Zenon are **L1-subsidized soft preconfirmations (`0` sat direct user BTC fee for existing accounts)** — NOT unbounded zero-cost Bitcoin L1 DA. To defeat zero-cost `0x02` DA flooding via refundable QSR (`8.8 tx/s` spraying 1-sat dust to fresh addresses = `~3.80 BTC/day` @ `50 sat/vB`), **creating a brand-new SMT account leaf locks a refundable `500`-sat `zBTC` `leafDepositSats`** (reclaimed when the account sweeps to `0` and closes) AND `0x02` batches enforce a hard **`<= 1,000` new SMT leaves per 6-block batch epoch** cap (`<= 48 KB` witness ≈ `12 kvB`/hour max new-leaf DA!). - **Two-Column Throughput Reality Table (`R8-M08` Reconciled — Zenon Transport vs Bitcoin L1 `0x02` Physical DA Cap):** Observed Zenon Momentum cadence is **`~11.4s`** (`origin/dev:vm/embedded/definition/spork.go:43-46`), explaining the exact rates below (note: `2.1M / 28,480 / 10s = 7.37 tx/s` assumes idealized `10s` blocks rather than observed `11.4s`): | Regime / Bottleneck | Zenon Soft-Preconfirmation Transport (`~11.4s`/Mom) | **Bitcoin L1 `0x02` Physical Mutated-Leaf DA Ceiling** (`600s`/blk, `4 MWU` = `1M vB`/blk) | |---|---|---| | **Pinned Floor (`2,100,000` Plasma/Mom)** | `4.4` 2-blk tx/s (`42,000` Plasma) / **`6.5` 1-blk rollup sends/s** (`28,480` Plasma; `7.37` at nominal `10s`) | **Blended `40 B` (`10 vB`) leaf:** `166.7 leaves/s` @ **100%** of all Bitcoin blockspace (**`1.67 leaves/s` @ 1%**) | | **Default Dynamic Plasma (`4,200,000`/Mom)** | `8.8` 2-blk tx/s / **`12.9` 1-blk rollup sends/s** (`14.75` at nominal `10s`) | **Existing `16 B` (`4 vB`) leaf:** `416.7 leaves/s` @ 100% of Bitcoin (**`4.17 leaves/s` @ 1%**) | | **Hard `go-zenon` `8 MiB` Wire Ceiling** (`MaxMomentumContentBytes = 8 MiB`, `MaxDetailedMomentumWireSize = 8.38 MB`) | **`1,050–1,200` 2-blk tx/s** (`~2,100–2,400` 1-blk sends/s; *NOT `4,386` tx/s!*) | **New `48 B` (`12 vB`) leaf:** `138.9 leaves/s` @ 100% of Bitcoin (**`1.39 leaves/s` @ 1%**, further capped to `<= 1,000` new leaves/6-blk epoch = `~0.28 new leaves/s`!) | *Key takeaway (`R8-M08`):* High Zenon transport TPS (`> 10 tx/s`) translates to L1-anchored settlement ONLY to the extent transfers **net across repeated accounts** within each 6-block batch (`0x02` publishes net post-batch leaf states, not individual transactions); distinct mutated accounts per second are strictly physically bounded by Bitcoin L1 blockspace! - **Graceful Degradation Under Dynamic Plasma DoS:** Under a QSR whale Dynamic Plasma spike (`spec/05 §2.2`), feeless Zenon soft preconfirmations degrade cleanly to **Bitcoin L1 `0x03 FORCED_TRANSFER` and `0x01 FORCED_EXIT`**, completely bypassing Zenon! ### 2.3 Slotted Permissionless DA Batcher Economics (`R8-M01`, `R8-M02`) - **Deterministic Slotted Batcher Priority (`R8-M02` Closed):** To prevent competing permissionless batchers from burning L1 fees on stale-root `0x02` collisions in the same block, registered batchers (zero custody power; permissionless registration via `0x03`) follow deterministic slot priority **`primary_batcher = H(header[h-1].hash) mod K_batchers`** for blocks `[prevBatchHeight + 6, prevBatchHeight + 7]`; from `prevBatchHeight + 8` onward, **any** batcher may post `0x02` permissionlessly. - **Sustainable Incentives:** Batchers earn optional `batchTipSats`, operator fronting fee spreads, and merchant/wallet sponsorship. A batch updating `600` existing accounts requires `9.6 KB` witness (`2.4 kvB`) + `~0.1–10 kvB` proof = `~2.5–12.4 kvB` (`~0.0005–0.0025 BTC` at `20 sat/vB`). ### 2.4 Hard-Partitioned `B_zbtc`, Cyclic `ExitSlotUTXO`, Oldest-Exit Priority & `TransferCredit` (`R8-H01`, `R8-H02`, `R8-N01`, `R8-N05`, `R8-M03`, `R8-M04`, `R8-M05`) 1. **Hard-Partitioned Per-Lane `B_zbtc` (`0.60 BTC` = `60,000,000` sats):** - **`B_custody = 0.55 BTC` (`55,000,000` sats):** Reserved strictly for `0.50 BTC` max-vault Lamport equivocation restitution + `0.05 BTC` equivocation bounty (or protocol insurance slash on dual-input `DisproveTx`). **NEVER debited by `ExitSlotUTXO` griefing!** - **`B_grief = 0.05 BTC` (`5,000,000` sats):** Exclusively absorbs `ExitSlotUTXO` non-paying grief penalties (`min(0.01 BTC, floor(B_grief / k_burst))` pro-rata per grieved exit in a block), guaranteeing zero `B_custody` overflow even under `k = 20` concurrent single-block griefs! 2. **Active-Operator `(2M_active + 1)`-Leaf `ExitSlotUTXO` With Collision-Free Cyclic Priority (`R8-M03`, `R8-H01`):** - Created by `0x01 FORCED_EXIT` (`grossSats >= max(dust(destScriptPubKey), MIN_EXIT_SATS = 100,000)` sats, `R8-M05`) using ONLY active non-suspended operators `M_active` from `R_{h-1}`: - **Leaves `0..M_active-1`:** `<6*r> OP_CSV OP_DROP OP_CHECKSIG` where **`k_r = (H(exitId) + r) mod M_active`** (`0%` repeat across `r = 0..M_active - 1`, matching `spec/01 §5` identically!). - **Leaves `M_active..2M_active-1`:** Open-race leaves `<6*M_active> OP_CSV OP_DROP OP_CHECKSIG`. - **Leaf `2M_active` (`EXIT_CANCEL`):** `<288> OP_CSV OP_DROP OP_CHECKSIG`. - On **ANY `K`-deep spend** of `ExitSlotUTXO` (detected via full stripped-`vin` scan even without `0x05` tag, `R8-C05`!): - **Valid Fronting (`vout[0]` pays `destScriptPubKey` `>= grossSats - maxOpFeeSats`):** `PendingExits[exitId] -> COMPLETED`, `ReimbursementCredit[O_j] += grossSats`. - **Non-Paying Grief Spend (`vout[0]` fails payment check):** Atomically `PendingExits[exitId] -> CANCELLED`, refund `100%` of `grossSats` `zBTC` to victim (`E -> C`), distribute `min(0.01 BTC, floor(B_grief[O_j] / k_burst))` strictly from `B_grief` to each victim in that block, auto-suspend `O_j`, and exclude `O_j` from all future `ExitSlotUTXO` trees! - **User Cancel (Leaf `2M_active` after `288` blocks):** `PendingExits[exitId] -> CANCELLED`, refund `grossSats` `zBTC` to `Accounts[acctId]` (restores `zBTC`, NOT native BTC). 3. **Oldest-`PendingExit` Credit Priority & `TransferCredit` (`R8-N01`, `R8-M04`):** - **Anti-Self-Fronting Priority (`R8-N01`):** Whenever open retail `PendingExits` older than `6` blocks exist in the queue, deterministic FIFO vault assignment strictly prioritizes `ReimbursementCredit` earned from fronting the **oldest `createdBtcHeight`** exits ahead of fresh self-fronted exits — stopping operators from pausing par retail fronting to jump the bank-run queue via discounted self-exits! Wallets may additionally specify an optional Dutch-auction `f_op` curve via `0x06` for transparent fee discovery. - **Residual Credit Consolidation (`R8-M04`):** Operators holding `< 0.25 BTC` fractional `ReimbursementCredit` residuals may execute a signed **`TransferCredit(from_op, to_op, amt)`** (via `0x02` or `0x03`, conserving `sum(R)` identically) to merge residuals into a `>= 0.25 BTC` vault claim, or convert remaining `R[op]` into `Accounts[op]` (`R -> C`) upon clean retirement (`RetireStakeTx_r`). 4. **Native-L1 Dual-Input `Stake_r` Slash (`R8-H02`, `R8-N05`):** - On `DisproveTx_{r,i}` / `TimeoutSlashTx_{r,i}` spending `Stake_r` + `VaultConnector_r` before `T_take = 1,728`, **`0` sats** leave `U_d` (if `U_d` was `ASSIGNED`, `V_assigned -> V_unassigned` and `A[U_d] -> R[O_j]`). Every active honest verifier collects **`0.15 BTC` in native Bitcoin L1 BTC** directly from `Stake_r` (`vout[0]` immediate winner, `vout[1..6]` `ChalPayoutEscrow` via `ChalProofConnector`, `>= 0.95 BTC` immediate `OP_RETURN` burn), delivering **`+0.0645 BTC` net EV @ `500 sat/vB`** (`+0.0232 BTC` @ `750 sat/vB`) completely immune to `zBTC` crisis discounts and `B_grief` depletion! On L2, `O_j`'s `0.55 BTC` `B_custody` is slashed to the protocol insurance account (`B -= 0.55, C += 0.55`, exact conservation). ### 2.5 End-to-End State Traces: Bob (`0.50 BTC`) & Mike (`0.25 BTC`) - **Bob's Partial Recovery (`1 BTC → spend 0.50 zBTC → recover 0.50 BTC` under `49%–100%` Zenon Compromise):** 1. Bob confirms `U_Bob_wallet`, consumes `1 × Ticket_050 + 2 × Ticket_025`, and deposits `1.00 BTC` via `0x00 DEPOSIT` → creates deleted-key vaults `{0.50, 0.25, 0.25}` BTC keyed by acyclic `vault_id`; at `K = 18` blocks, `Accounts[Bob] = 1.00 zBTC`. 2. Bob sends `0.50 zBTC` to Carol via `110 B` `AccountBlock.Data` on Zenon (`28,480` Plasma, `0` sat direct BTC fee) → slotted batcher anchors `0x02 BATCH_DA` → `Accounts[Bob] = 0.50 zBTC`, `Accounts[Carol] = 0.50 zBTC`. 3. **Attack:** `49%` (or `100%`) of Zenon Pillars turn hostile, split Zenon across its 30-Momentum cliff, censor Bob on Zenon, and spike Dynamic Plasma. 4. **Bob Exits Directly on Bitcoin L1:** Bob broadcasts `0x01 FORCED_EXIT(0.50 BTC, P_Bob, maxOpFee)` + active-operator `ExitSlotUTXO` on Bitcoin L1 (completely bypassing Zenon!). At `K = 18` blocks, $\mathcal{F}$ moves `0.50 zBTC` from `C → E`. 5. Any `1-of-M` active honest operator $O_j$ (`M = 3–5`) spends `ExitSlotUTXO` paying `0.50 BTC - fee` directly to `P_Bob` in `vout[0]` (~10 min on L1!), moves `0.50` from `E → R[O_j]`, gets FIFO-assigned one `0.50 BTC` vault (`V_unassigned -> V_assigned`, `R[O_j] -> A[v]`), and after `T_take = 1,728` blks claims the vault via `TakeTx` (`V_assigned, A -> 0`, recycling `Ticket_050`). **Zero Zenon signers, zero federated signers, zero ZNN trust.** - **Mike's Cross-Depositor Exit (`Alice 1 + Bob 1 → Mike 2 → Mike recovers 0.25 BTC` with `0` Zenon Signer Cooperation):** 1. Alice (`1.00 BTC`) and Bob (`1.00 BTC`) deposit into `{0.50, 0.25, 0.25}` vaults and send `1.00 zBTC` each feelessly to Mike on Zenon → `0x02 BATCH_DA` (or Mike's `0x03 FORCED_TRANSFER` fallback) sets `Accounts[Mike] = 2.00 zBTC`. 2. **Attack:** Zero Zenon signers cooperate; Alice and Bob are offline or hostile. 3. **Mike Exits `0.25 BTC` Directly on Bitcoin L1:** Mike posts `0x01 FORCED_EXIT(0.25 BTC, P_Mike, maxOpFee)` + `ExitSlotUTXO`. Any `1-of-M` active honest operator $O_j$ fronts `0.25 BTC - fee` directly to `P_Mike` in `vout[0]` (leaving Mike `1.75 zBTC` intact), earns `R[O_j] += 0.25 BTC`, and claims one `0.25 BTC` vault via `R -> A -> TakeTx` (recycling `Ticket_025`). 4. *Irreducible Residual Boundary (`spec/01 §1.2` Corollary 1B, `R8-C06`):* If **`0-of-M` operators remain permanently unavailable**, Mike's native BTC exit stalls permanently (`0` theft; Leaf `2M_active` `EXIT_CANCEL` after `288` blocks restores `0.25 zBTC` inside the rollup, **NOT** native BTC on L1). Under a `100%` bank run of `15 BTC` (`3.0` float + `12.0` vaults, `T_cooldown = 13.0d`), full queue drain takes **`~94–104 days`** (`M = 5`, `0.385` vaults/d ≈ `0.128 BTC/d`) or **`~101–104 days`** (`M = 3` on `10 BTC`; `~62–68d` with `{0.50, 0.50}` vaults). --- ## 3. Stage 1B (Alternative Gate): `clArk` VTXO Coordination Rails If the project cannot commit `~14.75–21.25+ BTC` of hard operator/verifier capital or requires a `3–6` month mainnet ship window using existing audited open-source stacks (`Second bark/barkd` or `Ark Labs arkd`), Stage 1B offers an explicit **non-federated, zero-soft-fork alternative** with **`2–5 BTC` active ASP liquidity** (`0` dead slashing bonds): - **Zenon's Role:** Feeless off-chain coordination, round scheduling, VTXO intent indexing, and Stage 0 SPV verification — **0% Zenon consensus custody dependency**. - **Exact Trade-Offs (Mandatory Disclosure):** 1. **Post-Round `0-of-N` Unilateral Exit (Until Expiry):** Once Mike's `0.25 BTC` VTXO is confirmed in an L1 `clArk` round tree, Mike exits unilaterally on Bitcoin L1 with **zero ASP/signer cooperation** by broadcasting his pre-signed `log2(N)` branch (`6..10` txs for `N = 64..1,024` VTXOs, using TRUC v3 + ephemeral anchors on Core `>= 29.0`). 2. **Pre-Round (`arkoor`) Sender+ASP Collusion Risk:** Instant feeless out-of-round transfers (`Alice -> Mike`) are vulnerable to `Alice + ASP` double-spend collusion until the next L1 round refreshes Mike into a new VTXO tree (wallets MUST visually separate trustless in-round VTXOs from `arkoor` balances!). 3. **Hard VTXO Expiry & Watchtower Requirement:** VTXOs expire (e.g., `30–60` days) back to the ASP sweep key, requiring automated watchtowers/online refreshes or `log2(N)` L1 exit fees; ASP liquidity (`2–5 BTC`) is locked `100%` for each full expiry cycle, capping round turnover to `2–5 BTC`/cycle. 4. **No Global Pooled `zBTC` Token:** `clArk` VTXOs are discrete UTXO trees, not a single global fungible `zBTC` balance sheet composable with Zenon DeFi — and `clArk` VTXOs do **not** migrate automatically into Stage 1A Rollup `zBTC` without on-chain L1 settlement. # Part 4: Zenon Consensus Reality (`go-zenon`), Inverted Trust Hierarchy & Optional Light-Client Anchoring **Document Class:** Normative Consensus Security Proof & Non-Custodial Anchoring Specification (`v2` / `v3.1.0-rfc` — Zero-Federation Phased Architecture; supersedes archived `v1` `v3.0.0-rfc` and `v0` `v2.5.0-rfc`) **Codebase Verified:** `go-zenon` `master` (`e8986a6`, `v0.0.10-alphanet`) and `origin/dev` (`770e893`) **Consistency Checker:** [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py) --- ## 1. Why Zenon Consensus Cannot Sit in the Bitcoin Custody Path (Grounded in `go-zenon`) A bridge or L2 inherits the weakest safety and liveness threshold of the consensus engine it trusts. Direct inspection of `go-zenon` (`master` `e8986a6` and `origin/dev` `770e893`) proves that **neither current `go-zenon` DPoS nor a future classical BFT upgrade (`CommitteeRootSpork`) can survive a `49%` Zenon compromise**: ### 1.1 Current `go-zenon` Is Longest-Chain DPoS With Zero Slashing, Grindable Seeds & a 30-Momentum Split Cliff Across `consensus/`, `protocol/`, `verifier/`, and `vm/embedded/implementation/pillars.go` on **both** `master` and `origin/dev`, there is **zero** BFT voting, **zero** quorum certificates, **zero** finality gadget, **zero** equivocation detection, and **zero** slashing: 1. **Unweighted Top-30 Cutoff (`groupA`) Amplifies Stake Into >50% Slots:** - `vm/constants/consensus.go:15-20` sets `BlockTime = 10s`, `NodeCount = 30`, `RandCount = 15`, `CountingZTS = ZNN` (`300s` election tick, `consensus/context.go:23`). - `consensus/election_algorithm.go:65-75` (`master`; `89-99` on `origin/dev`) puts the top 30 active Pillars by live delegated ZNN (`chain/momentum/embedded.go:59-104`) into `groupA`, selects `15` uniformly from `groupA`, moves the unselected `15` into `groupB`, and selects `15` from `groupB` (`election_algorithm.go:78-118`). Because `groupA` is unweighted inside the top 30, an attacker with `49%` of delegated ZNN can Sybil-split stake just above the #30 Pillar cutoff to capture **>50% of `groupA` slots**. 2. **Deterministic Height-Only PRNG Seed Is Trivially Grindable:** - `consensus/election_algorithm.go:38-40` (`master`; `58-60` on `origin/dev`): `findSeed` returns **`int64(context.hashH.Height)`** — **purely the Momentum height, with ZERO block-hash entropy**. - Because `proofBlock = GetMomentumBeforeTime(EndTime(tick - 2))` (`consensus/election.go:90-145`), a `49%` adversary controlling `~14–15` slots in tick `T - 2` can precompute `SelectProducers` offline for `H_base + {0..15}` and skip just enough of their own slots in tick `T - 2` to land `proofBlock.Height` on the exact integer $H^*$ maximizing their slots in tick `T` (expected max over 15 draws shifts mean `14.7 → ~19.4` slots = **`~65%` of slots in tick `T`**!). 3. **Zero Equivocation Checks + Hardcoded 30-Momentum Rollback Cliff = Permanent Chain Split:** - `verifier/momentum.go:217-275` checks only signature + slot producer — a Pillar can sign arbitrarily many conflicting Momentums for the same slot at zero cost. - `protocol/chain_bridge.go:241, 246` (`master`; `293, 304` on `origin/dev`) enforces pure **longest-chain-by-height** (`tail.Height <= ourFrontier.Height` → reject) AND hard-refuses any rollback deeper than `30` Momentums (`ourFrontier.Height - target.Height > 30` → reject). - **49% Permanent Split Attack:** By equivocating on both sides of a network delay/partition splitting the `51%` honest Pillars into `26%` and `25%`, the `49%` adversary powers Branch A (`26% + 49% = 75%`) and Branch B (`25% + 49% = 74%`) simultaneously past depth `30` (`~6.5` minutes), **permanently locking the two halves on incompatible histories**. - **Censorship & Sync Gating:** Empty Momentums (`len(Content) == 0`) are valid (`verifier/momentum.go:158-210`, `pillar/worker_momentum.go:13`), allowing `49%` Pillars to omit user exits, orphan honest inclusion blocks via seed-ground `>50%` ticks, and exploit `ReadyToProduce` (`protocol/readiness.go:16, 94-122`, `producerStallWindow = 60s`). 4. **No Succinct External State Proof & Low Market Cap:** - `Momentum.ChangesHash` is `SHA3-256(leveldb.Batch.Dump())` (`common/db/patch.go:124-126`) — an opaque diff dump, NOT a state root (`Minimum Verifier Spec.md:735-756`). `Content.Hash()` is a flat hash over headers (`Minimum Verifier Spec.md:168`). - With total ZNN market cap at **`~25–33 BTC`**, ZNN-denominated slashing can never economically secure multi-BTC vaults. ### 1.2 Why Classical BFT (`CommitteeRootSpork`) Also Fails at `49%` Even if Zenon upgraded to a classical partially synchronous BFT finality committee (`n >= 3f + 1`), **`49% > 33.3%` breaks BOTH liveness and safety**: - **Liveness Halt (`>= 33.4%`):** `49%` withholding votes blocks `67%` quorum indefinitely. - **Safety Equivocation (`>= 33.4%`):** `49%` splits `51%` honest validators into `25.5% + 25.5%` and signs **two conflicting `74.5% > 66.7%` finality certificates**, allowing a malicious prover to drain any bridge whose verifier trusts Zenon BFT certificates. *(Synchronous BFT cannot be verified by Bitcoin L1/SNARK circuits because Bitcoin cannot observe Zenon's network delay $\Delta$.)* --- ## 2. The Inverted Trust Hierarchy (`0-of-N` Zenon Trust — Surviving `49%–100%` Zenon Compromise) Because Zenon consensus breaks at `49%` (DPoS) and `>33.3%` (BFT) and ZNN market cap is `~25–33 BTC`, **`v2` completely removes Zenon consensus and ZNN slashing from Bitcoin custody**: ```text Bitcoin Mainnet L1 (PoW Canonical Ordering + Complete 0x02 DA + 0x01/0x03 Forced Inclusion + BitVMX Custody) ▲ │ Canonical zBTC state root R_h derived 100% from Bitcoin L1 blocks (0% Zenon trust!) │ Unilateral L1 forced exit (0x01) & transfer (0x03) bypass Zenon completely │ Zenon Network L1 (Untrusted Feeless Soft-Preconfirmation Sequencer via AccountBlock.Data + Stage 0 SPV Event Oracle) ``` | Property | Traditional Bridge / Archived `v0` | `v2` Inverted Trust Hierarchy (Stage 1A) | |---|---|---| | **Canonical `zBTC` Fork Choice** | Zenon DPoS or BLS BFT Committee (breaks at `33.4%–49%`) | **Bitcoin Mainnet PoW** (first valid `0x02` matching `R_{h-1}` wins; probabilistic PoW finality at depth `K >= 18` under `<50%` honest hashrate + interactive heaviest-chainwork dispute check; `0%` Zenon trust) | | **Data Availability (DA)** | Zenon full nodes / committee | **Bitcoin L1 `0x02` Taproot witness** (fail-closed BIP-141 `wtxid`-authenticated mutated SMT leaves across `Accounts`, `RollupLocks`, `PendingExits` + `π_batch`) | | **Exit Censorship Resistance** | Censored by Zenon Pillars / Plasma spikes / signers | **Bitcoin L1 `0x01 FORCED_EXIT`** (uncensorable even under **100%** Zenon compromise!) | | **Custody Security Coupling to ZNN** | ZNN staking/slashing (`~25–33 BTC` mcap ceiling) | **`0%` ZNN coupling** (100% BTC-denominated `BitVMX` bonds `2.60 BTC`/lane + `1-of-N` verification) | | **Zenon's Actual Value-Add** | Custody bottleneck | **Feeless `~11.4s` soft preconfirmations (`0` sat BTC fee) + Stage 0 Bitcoin Event Oracle** | --- ## 3. Optional Non-Blocking Zenon Anchoring & Light-Client Track (Consumer UX Only) > **Hard Custody Boundary:** Nothing in §3 is required for Stage 0, Stage 1A (`BitVMX`), Stage 1B (`clArk`), or Stage 2 `zBTC` custody. All items below are optional, non-blocking Zenon network infrastructure for consumer mobile/browser light clients verifying *non-BTC Zenon-native state* (ZNN, QSR, Accelerator-Z). ### 3.1 Genesis Bitcoin Anchor (Live on Mainnet) Zenon Genesis Momentum (`Height = 1`, hash `9e204601d1b7b1427fe12bc82622e610d8a6ad43c40abf020eb66e538bb8eeb0`, `ts = 1637755200`) embeds Bitcoin mainnet block `710,968` (`000000000000000000004dd040595540d43ce8ff5946eeaa403fb13d0e582d8f`) in `Momentum.Data` (`chain/genesis/embedded_genesis_string.go:6`), grounding Genesis-Anchored Lineage Verification (`zenon-developer-commons`: `docs/specs/GALV_spec_draft.md`). ### 3.2 Optional Periodic Zenon Checkpoint Anchoring & `StateRoot` (`common/trie`) If Zenon independently ships optional `StateRoot` (`common/trie` 256-bit `SHA3-256` SMT) and periodic Bitcoin checkpoint anchoring (`OP_RETURN "ZNNA" || u64BE(height) || SHA256("ZNN_BTC_ANCHOR_V2" || digest)` every `360` Momentums ≈ `68m` at `11.4s`/Momentum) for native Zenon light clients: - **Honest Light-Client Trust Statement:** Bitcoin checkpoint anchoring provides **immutable timestamp ordering and long-range tie-breaking ONLY — NOT execution validity** of Zenon L1 state. Native Zenon light clients still trust Zenon's Pillar set for non-rollup state transitions. - **Optional U2 Committee Quorum & Selection Hardening (`H-1`, `L-1`):** If Zenon ever deploys an optional non-custodial BLS12-381 finality committee (`K_fin = 30`), any degraded-membership rule for `21 <= eligible < 30` MUST define quorum strictly as **`popcount >= ceil(2 * eligible / 3)`** (e.g., `14-of-21` at `eligible = 21`, up to `20-of-30` / `21-of-30` at `eligible = 30`) — **NEVER** requiring both `ceil(2 * eligible / 3)` AND `popcount >= 21`, which forces `21-of-21` (`100%`) unanimity at `eligible = 21`! Furthermore, any future committee selection MUST NOT rely on non-existent `prevEpochRandao`; it requires either time-weighted variable slashable self-bond or a dedicated VRF/commit-reveal randomness beacon. - **Zero Impact on `zBTC`:** Because Stage 1A `zBTC` derives 100% of its state root $R_h$ from Bitcoin L1, consumer `zBTC` wallets verify their balances directly against Bitcoin headers (via BIP-157/158 Neutrino) + `0x02` SMT Merkle proofs — requiring **zero** Zenon BLS committee or Zenon `StateRoot`! # Part 5: `go-zenon` Upgrade Plan, Zero-Hard-Fork Custody Boundary & Pre-Mainnet Conformance Gates (`G1–G7`) **Document Class:** Engineering Upgrade & Delivery Blueprint (`v2` / `v3.1.0-rfc` — Zero-Federation Phased Architecture; supersedes archived `v1` `v3.0.0-rfc` and `v0` `v2.5.0-rfc`) **Reference Codebase Verified:** Local `go-zenon` clone is at `master` (`e8986a6`, `v0.0.10-alphanet`) and `origin/dev` (`770e893`); Bitcoin node floor pinned to **Bitcoin Core `>= 29.0` (`v31.0` preferred)**. **Consistency Checker:** [`scripts/verify_spec_bounds.py`](../scripts/verify_spec_bounds.py) --- ## 1. Architectural Upgrade Principle: Zero `go-zenon` Custody Authority & Zero Hard Fork for Stage 1A/1B Unlike archived `v0` (which demanded deep `go-zenon` consensus hard forks — `StateRootSpork`, `CommitteeRootSpork`, `OptimisticRefereeSpork`, ZNN slashing, and single-key governance custody controls), **`v2` decouples Bitcoin custody completely from `go-zenon` upgrades and Zenon governance**: | Stage | `go-zenon` Changes Required | Zenon Spork / Governance Authority Over BTC Custody | |---|---|---| | **Stage 0 (`Verify Bitcoin`: SPV Event Oracle + Erlang-Hardened PTLC/LN)** | Upstream `go-zenon` mainnet release (Gate G6: `0aa299e`, `#239`/`#299`/`#312` closed, mainnet `PTLC PR #138` & `DynamicPlasmaSpork` w/ 5-param `SetPlasmaVariables` pinning, lightweight `BtcSpvOracleSpork` `vm/embedded/btcspv`). | **NONE (`0 BTC` custody in Stage 0).** Oracle provides read-only Event Validity only. | | **Stage 1A (Right-Sized `BitVMX` `n = 8` + Sovereign ZK Rollup)** | **ZERO `go-zenon` consensus hard fork required!** Rollup sequencer/indexer reads standard `AccountBlock.Data` (`UserSend`) + Bitcoin L1 (`0x00`–`0x07`). Requires **Bitcoin Core `>= 29.0`** (`v31.0` preferred) for `0`-sat `P2A` ephemeral dust + 1P1C package relay. | **ZERO!** `vk_STF` is immutably pinned on Bitcoin L1 at launch. Even total compromise of `SporkAddress` / `CommunitySporkAddress` or `100%` of Pillars cannot steal 1 satoshi or censor Bitcoin L1 `0x01` exits! | | **Stage 1B (`clArk` Alternative Gate)** | **ZERO `go-zenon` consensus hard fork required!** Uses open-source `Second bark/barkd` or `Ark Labs arkd` + automated watchtowers coordinated alongside Zenon indexing / Stage 0 SPV. | **ZERO!** Custody lives strictly in Bitcoin L1 `clArk` VTXO trees. | | **Stage 2 (Scale / BitVM3-GC / Track B Covenants)** | **ZERO `go-zenon` consensus hard fork required** for BTC custody. Optional `GovernanceContract` / `StateRoot` remain purely Zenon network UX infrastructure. | **ZERO!** Stage 1 vaults drain 1:1 via `0x01` (subject to `1-of-M` operator liveness); identical-STF scaling uses `N`-of-`N` voluntary Cohort 1 handover; backend swaps launch clean non-commingled `zBTC_v2`. | --- ## 2. Stage 0 `go-zenon` Prerequisites (Gate G6, `B1`, `B2`, Full Dynamic Plasma Pinning, `R8-M08`) ### 2.1 Upstream `go-zenon` Mainnet Readiness Gate (`0aa299e`, `PR #138`, `#239`, `#299`, `#312`) - **Mainnet vs `dev` Honesty Disclosure (`R8-M08`):** Live `go-zenon` mainnet currently runs `v0.0.10` (`master` `e8986a6`, `v1` Momentums capped at `100` blocks/Momentum ≈ `8.8–10.0` blocks/s network-wide). `DynamicPlasmaSpork` (`v2`) and `PtlcSpork` (`PR #138`) are implemented on `dev`/devnet (`origin/dev` `770e893`) and await mainnet merge and spork activation. Upstream commit **`0aa299e`** (*post-VM hash re-verification fix for externally supplied blocks mutated by `ValidateSendBlock`*) is not yet present in the local reference clone. - **Explicit Open Upstream Issues Blocking Stage 0 Mainnet (Gate G6):** 1. **Issue `#239` (`B1` — Deterministic Failed Receive / FIFO Panic Stall):** Embedded receives execute strictly FIFO per contract (`verifier/account_block.go:397-417`, `chain/account/sequencer.go:19-33`). On `master`, a VM panic returns `ErrVmRunPanic` (`vm/supervisor.go:228`) and aborts `pillar/worker_contract_generator.go:38-40` without advancing the sequencer, permanently stalling the contract. Every embedded method in `BtcSpvOracleContract` and `vm/embedded/btcspv/` MUST wrap execution in `defer func() { if r := recover(); r != nil { err = constants.ErrInvalidMethodParam } }()`, contain **zero** calls to `common.DealWithErr`, and rely on `#239`'s canonical failed-receive closure. *(Provenance note: verify `#239`'s final merged commit hash against the tagged mainnet release prior to spork activation.)* 2. **Open `go-zenon` Issues `#299` and `#312` (`R8-M08`):** Both open upstream issues MUST be resolved and verified in the tagged mainnet release before activating Stage 0 `BtcSpvOracleSpork` or `PtlcSpork` (`PR #138`). 3. **`PTLC PR #138` Mainnet Merge & Spork Activation:** `PtlcSpork` (`PR #138`) MUST be merged, tagged, and activated on mainnet alongside `DynamicPlasmaSpork`. ### 2.2 `DynamicPlasmaSpork` & Full 5-Parameter `SetPlasmaVariables` Pinning (`B2`) `DynamicPlasmaSpork` (`origin/dev:dp/dp.go`, `origin/dev:vm/plasma.go:172-200`) is a hard precondition for Stage 0 `BtcSpvOracleSpork` because it enables `EmbeddedSendBasePlasma` (`tier + 68/byte` past the 4-byte selector) and stale-acknowledgement rejection (`origin/dev:chain/acknowledgement_recency.go`). **Complete `SetPlasmaVariables` Lower/Upper Parameter Pinning:** In unmodified `origin/dev:vm/embedded/definition/plasma.go:66-84`, `SetPlasmaVariables` (controlled by single-key `SporkAddress` / `CommunitySporkAddress` at `origin/dev:vm/embedded/implementation/plasma.go:199`) permits `MaxBasePlasmaInMomentumLowerLimit = 210,000` (`L66`) and `FusedPlasmaTargetLowerLimit = 1`, `PowPlasmaTargetLowerLimit = 1`, `PriceChangeDenominatorLowerLimit = 1` (allowing a `>100,000×` 10-minute price spike from a single tx!). Therefore `BtcSpvOracleSpork` MUST enforce **ALL FIVE** guardrails simultaneously: | Parameter (`vm/embedded/definition/plasma.go`) | Unmodified `origin/dev` Bound | Normative Stage 0 Spork Floor / Ceiling | Why Required | |---|---|---|---| | `MaxBasePlasmaInMomentum` | `>= 210,000` (`L66`) | **`>= 2,100,000`** | Guarantees `>= 3` max `ProveTxInclusion` calls (`591,388` Plasma) and `dp.MaxContractBlocks >= 40` (`dp/dp.go:259-264`). | | `MaxPriceChangePercent` | `<= 100` (`L75`) | **`<= 25`** (default `10`) | Caps per-Momentum adaptive step size. | | `FusedPlasmaTarget` | `>= 1` (`L69`) | **`>= 525,000`** (`>= 25%` of `2.1M` floor) | Closes `target = 1` exponential fused-Plasma price-spike DoS. | | `PowPlasmaTarget` | `>= 1` (`L72`) | **`>= 525,000`** (`>= 25%` of `2.1M` floor) | Closes `target = 1` exponential PoW-Plasma price-spike DoS. | | `PriceChangeDenominator` | `>= 1` (`L84`) | **`>= 8`** | Damps step amplification even under sustained `100%` utilization. | > **Honest Residual Dynamic Plasma Disclosure:** `origin/dev:dp/dp.go:102-151` intentionally has **no absolute upper clamp** on `NextFusionPrice`/`NextWorkPrice`, and fused QSR is refundable (zero burn). Even with all five bounds pinned, a well-funded QSR whale + `49%` malicious Pillars can still drive Zenon Plasma prices up exponentially over tens of minutes (`1.10^72 ≈ 955×` at default `+10%`/Momentum). This is **explicitly safe for Stage 1A custody** because Bob and Mike can always submit `0x01 FORCED_EXIT` / `0x03 FORCED_TRANSFER` directly on Bitcoin L1, completely bypassing Zenon Plasma! ### 2.3 Stage 0 SPV Event Oracle & Non-Custodial Swaps (`BtcSpvOracleSpork` + `PtlcSpork`) 1. Activate **`PtlcSpork` (`PR #138`)**, **`EmbeddedRefundSpork`**, **`Libp2pSpork`**, and **`EpochRewardTermsSpork`** (implemented on `origin/dev:common/types/spork.go`). 2. Deploy lightweight **`BtcSpvOracleContract`** (`vm/embedded/btcspv/`: `header.go`, `tx.go` with `len(strippedTx) >= 65` and 1-/2-block coinbase midstate verification, `oracle.go` — **zero** custody, minting, or federation code!). 3. Add local RPC/indexer helpers (`DeleteMomentum` WebSocket `momentumsReverted` push + HTLC/PTLC `getByDestination`/`getByPointLock`/`getByHashLock`) plus automated **block-72 high-fee RBF PTLC refund watchtower** software (`R8-H07`). 4. *(Recommended Non-Custodial Zenon Hygiene, Non-Blocking for BTC Custody):* Replace single-key `SporkAddress` / `CommunitySporkAddress` (`vm/embedded/implementation/spork.go:46-49, 117-119`, which can currently terminate all nodes via `os.Exit(2)` after `SporkMinHeightDelay = 6` Momentums at `chain/momentum_pool.go:53-68`) with a timelocked `GovernanceContract`. Even if un-upgraded, **`SporkAddress` compromise has `0` custody power over Stage 1A/1B BTC!** --- ## 3. Stage 1A / 1B Off-Chain Software Stack (Piggybacking on Open-Source Ecosystems, `R8-H05`) A small young engineering team (4–6 engineers) MUST NOT write custom Bitcoin Script Groth16 compilers or custom BitVM3 garbled-circuit frameworks from scratch. Both Stage 1 paths piggyback directly on audited/open-source Bitcoin stacks: - **Stage 1A (`BitVMX` `n = 8` Sovereign Rollup Stack — Primary Path for Pooled Fungible `zBTC`):** 1. **Off-Chain ZK Prover (`zbtc-prover`):** Executes the full deterministic Rollup STF $\mathcal{F}$ (stripped-block scanning `<= 1 MB`, fail-closed BIP-141 witness authentication on last `0x6a24aa21a9ed` coinbase output, full stripped-`vin` tracked-UTXO scanning, SMT conservation `V_unassigned + V_assigned = C + L + E + R + A + B`, $2^M$ Hall's Marriage check, interactive heaviest-chainwork comparison) off-chain and produces a constant-size wrapped SNARK proof (`vk_STF`). 2. **Reuse `BitVMX FORCE` / Fairgate Open-Source Core (`RV32IM` Wrapped-SNARK Verifier Only — `R8-H05`):** `BitVMX-CPU` (`RV32IM`) executes **strictly the constant-size `vk_STF` wrapped SNARK verifier** (`<= 0.5 × 8^9` steps, Gate G2 — NEVER bare 1 MB SHA-256 block scanning!) + `BitVMX-protocol` (pre-signed `n = 8` TRUC v3 bisection graph & W-OTS commitment engine targeting **Bitcoin Core `>= 29.0`**, `v31.0` preferred). 3. **Operational Daemons:** - `zbtc-sequencer` / `zbtc-batcher` (reads Zenon `AccountBlock.Data`, enforces `500`-sat new-leaf deposit + `<= 1,000`/epoch cap + slotted batcher priority, posts `0x02 BATCH_DA`). - Operator fronting & `StakeChain` daemon (`M = 3–5`, manages `AdmissionTicketUTXO`s, `ExitSlotUTXO` fronting, `TransferCredit`, direct-to-miner submission rails, and `>= 144`-blk rollback snapshots for `DEEP_REORG_HALT`). - `N = 7` Verifier watchtower daemon (monitors `RoundTx_r`, opens simultaneous `ChallengeTx_{r,i}` + `ChalProofConnector_{r,i}` in `[0, 144]`, replicates & audits `zbtc-vault-bundle-v1` across `>= 3` public mirrors, maintains direct-to-miner P2A CPFP rails). - **Stage 1B (`clArk` Alternative Gate Stack):** - Fork/integrate mainnet-live **`Second bark/barkd`** or **`Ark Labs arkd`** (`2–5 BTC` active ASP liquidity) + automated VTXO refresh watchtowers + lightweight Zenon coordination/SPV client (`~3–6` months). --- ## 4. Concrete 3-Stage Delivery Roadmap & Capital Gates (`R8-M09`, `R8-H08`) | Stage | Timeline (4–6 Engineers) | Full Hard BTC Capital Required | Deliverables & Security Milestone | Exit / Migration Guarantee | |---|---|---:|---|---| | **Stage 0: `Verify Bitcoin` Foundation** *(Mandatory Start)* | **`0–6 months`** | **`0 BTC` bonds** (`0–5 BTC` voluntary LP) | Gate G6 (`0aa299e`, `#239`/`#299`/`#312`, mainnet `PR #138` & `DynamicPlasmaSpork` 5-param pin) + Stage 0 `BtcSpvOracleContract` (`len >= 65`, 1-/2-block midstate) + Erlang-hardened PTLC (`>= 48h`, block-72 RBF watchtower) / LN HTLC (`>= 24h`) swaps. Parallel Signet prototype of `vk_STF` on `BitVMX-CPU` & BitVM3-GC evaluation (Gate G2). | Zero custody risk; users hold native BTC on L1/LN at all times. | | **Stage 1 Decision Gate** | **Month 6 Gate** | *Gate Check* | **Choose Stage 1A ONLY if** pooled fungible non-expiring `zBTC` is non-negotiable **AND** **`>= 14.75–21.25 BTC`** single-dispute operational hard BTC (`12.80–18.80` locked + reserves, plus multi-dispute headroom) is committed for `12–18+` months (incl. audit). **Otherwise choose Stage 1B (`clArk`)** (`2–5 BTC` active liquidity, `3–6 mo` launch) — NEVER under-bond BitVMX/BitVM2! | Explicit upfront commitment; zero hidden federation fallback. | | **Stage 1A: Right-Sized `BitVMX` (`n = 8`, `M = 3–5`, `N = 7`) Sovereign Rollup** | **`12–18+ months`** *(incl. Gates G1–G5 & M-15 external audit)* | **Locked:** `12.80` (`M=3`) / `18.80 BTC` (`M=5`); **Op Baseline:** **`14.75 / 21.25 BTC`** (`~17–26+` multi-dispute) | Mainnet Core `>= 29.0` TRUC v3 vaults (`{0.50, 0.25, 0.25}`, acyclic `vault_id`, `AdmissionTicketUTXO`, $2^M$ Hall, `V=C+L+E+R+A+B`, native-L1 `Stake_r` verifier payouts `+0.0645/+0.0232 BTC` EV @ `500/750 sat/vB`), **graduated TVL ramps (`2 → 5 → 10/15 BTC`)**. | Non-expiring deleted-key vaults redeemable 1:1 via `0x01` subject to `1-of-M` operator liveness (plus voluntary unwind circuit breaker, `spec/01 §6.3`). | | **Stage 1B *(Alt)*: `clArk` + Zenon SPV/PTLC** | **`3–6 months`** | **`2–5 BTC`** active ASP liquidity (`0` bonds) | Mainnet `bark`/`arkd` VTXO rounds + automated watchtowers + Zenon coordination. Pure `0-of-N` post-round unilateral exit; explicit UX separation of trustless in-round VTXOs vs `arkoor` balances. | Users hold self-custodial pre-signed L1 exit branches at all times. | | **Stage 2: Zero-TTP Scale & Upgrade** | **`12+ months` post-Stage 1** | Scales with TVL (`K = 42` → `50 BTC`; `K = 144` → `200 BTC`) | (a) Identical-STF scaling (`M = 5 → 20`, `L = 1 → 4`) via voluntary `N`-of-`N` Cohort 1 handover; (b) Backend upgrade to mature reusable BitVM3-GC, BitVM2, or **Track B Pure Tier-0 Covenants (`OP_CCV + OP_TXHASH + OP_VERIFY_STARK` / `OP_CAT`)** via clean non-commingled `zBTC_v2`. | Zero dead-end migration: Stage 1 vaults drain organically 1:1 via `0x01` exits (zero deleted-key L1 rollover magic!). | --- ## 5. Mandatory Pre-Mainnet Conformance Gates (`G1–G7`, Closing R8 §22 & M-15) Mainnet deployment of Stage 0 or Stage 1A MUST remain blocked until every applicable gate below publishes publicly reproducible verification artifacts: 1. **Gate G1 — Bitcoin Core `v29.0+` (`v31.0` Preferred) `regtest` & `signet` End-to-End Graph Execution:** Execute consensus-valid serialized `DepositTx` (acyclic `vault_id` + `AdmissionTicketUTXO` consumption), active-operator `ExitSlotUTXO` (fronting, cyclic priority, `k = 20` grief burst, `EXIT_CANCEL`), `RoundTx_r`, full 20-step `n = 8` bisection with `153 vB` `0`-sat `P2A` 1P1C package relay, sibling-eviction stress + direct-to-miner rails, `TakeTx` (`<= 3,200 vB` recycling `AdmissionTicketUTXO`), `DisproveTx_{r,i}` + `ChalPayoutEscrow` native-L1 payouts, and `BurnBondTx_{r,k}` on live Bitcoin Core `>= 29.0` `regtest` and `signet` with zero policy or consensus rejections. 2. **Gate G2 — Compiled `RV32IM` Wrapped-SNARK Verifier Trace Proof (or Reusable `BitVM3-GC` Evaluation):** Publish reproducible Rust → `RV32IM` source and compiled ELF binary of the exact disputed `vk_STF` wrapped SNARK verifier guest, executing worst-case adversarial inputs and proving `init_steps + exec_steps <= 0.5 × 8^9 = 67,108,864` (if exceeded, bump `l = 10` or benchmark mature reusable `BitVM3-GC` + Clementine before code freeze). 3. **Gate G3 — Independent Execution of Extended Consistency & Bounds Checker:** Run `python3 -I scripts/verify_spec_bounds.py` (recording exact Git commit, `public/raw/SHA256SUMS.txt`, Python version, stdout, and exit code 0) verifying all Stage 0 Erlang tails, Stage 1A acyclic Lamport/TRUC v3/native-L1 EV/$2^M$ Hall/Budish/DA bounds, and `>= 2,000` (and CI `>= 100,000`-step nightly) randomized transitions exercising `V_unassigned + V_assigned == C + L + E + R + A + B`. 4. **Gate G4 — `vk_STF` Formal Verification & Bitcoin Core Differential Consensus Fuzzing (`R8-H08`):** Formally verify `V_unassigned + V_assigned == C + L + E + R + A + B`, the $2^M$ Hall's Marriage Invariant, fail-closed BIP-141 witness completeness (last `0x6a24aa21a9ed` coinbase output), and full stripped-`vin` tracking inside the ZK constraint system, AND differentially fuzz the Bitcoin parser against Bitcoin Core's `tx_valid`/`tx_invalid`, `CVE-2012-2459`, and `CVE-2017-12842` suites alongside an independent third-party audit (**M-15**). 5. **Gate G5 — Public `zbtc-vault-bundle-v1` Archival Disaster-Recovery Drill (`R8-H06`):** Destroy all private operator and presigner databases on Signet and prove `100%` recovery of both honest `TakeTx` reimbursements and `DisproveTx`/`BurnBondTx` fraud-proof slashing strictly from `>= 3` public `zbtc-vault-bundle-v1` mirrors plus Bitcoin headers. 6. **Gate G6 — `go-zenon` Mainnet Readiness, Panic/FIFO Fuzz & Stage 0 PTLC Suite (`R8-M08`, `B1`, `B2`, `R8-H07`):** Confirm mainnet merge, tag, and spork activation of `0aa299e`, `PTLC PR #138` (`PtlcSpork`), `DynamicPlasmaSpork` (with MUST-fail tests verifying all 5 `SetPlasmaVariables` bounds), Stage 0 `BtcSpvOracleContract` (zero-panic FIFO fuzz gate, `len(strippedTx) >= 65`, 1-/2-block coinbase midstate vectors), closure of open `go-zenon` issues `#239`, `#299`, and `#312`, and Signet↔Zenon PTLC/LN adversarial tests (`T_znn >= 48h`, `Δ_safety_sec >= 24h`, automated block-72 RBF watchtower, `hashType = 1`, LN Hold Invoice 5-min cancel TTL). 7. **Gate G7 — Local Repository Audit Trail & Release Integrity Pinning (`R8-L02`):** Verify every `v2` normative file against generated `public/raw/SHA256SUMS.txt` and frozen `versions/v1/SHA256SUMS.txt` & `versions/v0/SHA256SUMS.txt` in CI, keeping `CHANGELOG.md` synchronized with every `R1–R8` disposition. # Changelog — `v1` (`v3.0.0-rfc`) → `v2` (`v3.1.0-rfc`) & Historical `v0` → `v1` **Date:** 2026-11-28 **Current Version (`v2`):** [`v3.1.0-rfc`](./SPEC.md) (Zero-Federation Phased Architecture, hardened by Consolidated Hostile Review [`R8`](./reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md); redlines directly against archived `v1`) **Archived Previous Version (`v1`):** [`v3.0.0-rfc`](./versions/v1/SPEC.md) (frozen byte-for-byte from commit `6ab3999`, SHA-256 verified in [`versions/v1/SHA256SUMS.txt`](./versions/v1/SHA256SUMS.txt)) **Archived Initial Baseline (`v0`):** [`v2.5.0-rfc`](./versions/v0/SPEC.md) (frozen byte-for-byte from commit `7b47b8c`, SHA-256 verified in [`versions/v0/SHA256SUMS.txt`](./versions/v0/SHA256SUMS.txt)) --- ## `v1` (`v3.0.0-rfc`) → `v2` (`v3.1.0-rfc`): Consolidated Hostile Review (`R8`) Remediation (Amendments A1–A11) **Trigger:** Independent multi-agent Consolidated Hostile Review [`R8`](./reviews/HOSTILE_REVIEW_R8_CONSOLIDATED.md) of archived `v1 (v3.0.0-rfc)` (6 Critical, 10 High, 9 Medium, 2 Low; Stage 0 & Stage 1B `CONDITIONAL PASS`, Stage 1A `FAIL` as written). Every confirmed `R8` defect is remediated in **`v2` (`v3.1.0-rfc`)** below with **zero federated multisigs** and **zero Bitcoin soft forks**; line-level local-repo pushbacks are recorded transparently under **Verified Pushbacks**. ### `R8` Critical Findings (`R8-C01` – `R8-C06`) | ID | Finding Summary (`v1` / `v3.0.0-rfc`) | Disposition in `v2` (`v3.1.0-rfc`) | Amendment / Ref | |---|---|---|---| | **R8-C01** | Circular `SHA256(outpoint_d)` inside `U_d`'s Lamport `TakeTx` Tapscript created an impossible SHA-256d fixed-point cycle | **Closed (A1).** Replaced `SHA256(outpoint_d)` with acyclic pre-funding `vault_id = SHA256("zbtc:vault-id:v1" \|\| funding_txid \|\| funding_vout \|\| vault_vout \|\| amount_sats \|\| opBitmask)` bound to confirmed `U_dep_wallet`. `TakeTx` verified `~3,142–3,166 vB <= 3,200 vB` TRUC v3 parent, peak stack `258 < 1,000`, zero unconfirmed TRUC child chaining. | [Part 1 §2.2, §3.3](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-C02** | Conservation law `V = C + L + E + R + B` omitted `AssignedObligations (A)`, breaking `vk_STF` during the `T_take` gap after FIFO assignment | **Closed (A2).** Added explicit `AssignedObligations (A)` SMT namespace and amended conservation to `V_unassigned + V_assigned = C + L + E + R + A + B` with exact atomic transition table across `fifo_assign`, `take_confirmed`, `0x07`, `disprove_dual_slash`, `lamport_equivocation_slash` (including cross-operator recovery), `retire`, and `reorg`. Separated `fifo_assign` and `take_confirmed` across `T_take` in `verify_spec_bounds.py`. | [Part 3 §2.1](./spec/03-settlement-minted-zbtc-and-feeless-rails.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-C03** | Racing deleted-key deposits crossing `Cap_TVL` could both confirm on L1, burning the rejected loser's BTC permanently | **Closed (A3).** Enforced `Cap_TVL_total` mutual exclusion directly at Bitcoin L1 consensus via denomination-matched **`AdmissionTicketUTXO`s** (`1 × Ticket_050 + 2 × Ticket_025` consumed as `DepositTx.vin[1..3]` and recycled at `TakeTx.vout[1]`; loser's `DepositTx` is consensus-invalid so BTC never leaves `U_dep_wallet`), plus optional two-stage `PreDepositUTXO` alternative. | [Part 1 §2.2](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-C04** | Scalar round cap `N_live <= 0.50 * RemainingTotalRounds` violates Hall's Marriage Theorem under heterogeneous `opBitmask` subsets & retirements | **Closed (A4).** Mandated the exact $2^M$ **Hall's Marriage Invariant** across every `deposit_admit`, `operator_retire`, `round_consume`, and `operator_slash` (`<= 31` checks at `M = 5`), tightest-slack FIFO prioritization, and retirement unlock gating. | [Part 1 §6.2](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-C05** | Witness completeness vs deterministic skip ambiguity, untagged tracked-UTXO spends, and incomplete `0x02` DA schema | **Closed (A5) + Pushback Noted.** *(Note: `v3.0.0-rfc` `spec/02:L115` already mandated BIP-141 `wtxid` verification.)* Closed all 3 real gaps: (a) extract witness commitment strictly from the **LAST** coinbase output starting with `0x6a24aa21a9ed` (`len >= 38 B`, coinbase `wtxid = 0x00^32`) and fail closed (`REFUSED_DATA_UNAVAILABLE`) on missing/unauthenticated witness vs skip ONLY after `wtxid` authentication; (b) scan **every `vin` of every stripped tx** for untagged spends of tracked UTXOs; (c) expand `0x02` DA schema to serialize `Accounts`, `RollupLocks`, cooperative `PendingExits`, and `TransferCredit`. | [Part 2 §3.1–3.2](./spec/02-btc-authorization-domain-and-spv.md) | | **R8-C06** | Contradictory `"100% live forever"` prose despite `0-of-M` permanent operator unavailability permanently locking native BTC | **Closed (A6).** Excised `"100% live forever"` across all files. Stated explicitly: Stage 1A vaults have *no CLTV expiration*, but native BTC recovery strictly requires `1-of-M` active eligible operators (`0-of-M` permanent disappearance locks native BTC; `EXIT_CANCEL` restores `zBTC` only). | [SPEC §4, §9](./SPEC.md), [Part 1 §2.3](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 5 §4](./spec/05-go-zenon-upgrade-plan.md) | ### `R8` High Findings (`R8-H01` – `R8-H08`, `R8-N01`, `R8-N05`) | ID | Finding Summary (`v1` / `v3.0.0-rfc`) | Disposition in `v2` (`v3.1.0-rfc`) | Amendment / Ref | |---|---|---|---| | **R8-H01** & **R8-N05** | Concurrent (`k >= 6..20`) or post-suspension `ExitSlotUTXO` griefing overflowed `0.05 BTC` buffer into `0.55 BTC` verifier bounties, turning verifier EV negative pre-theft | **Closed (A7).** Hard-partitioned `B_grief` (`0.05 BTC`) from `B_custody` (`0.55 BTC`) with pro-rata burst capping (`0` sats ever debited from `B_custody`), excluded suspended operators from all new `ExitSlotUTXO` Taproot trees (`2M_active + 1` leaves), AND moved all verifier bounties to **Bitcoin L1 `Stake_r`** (`0%` coupling to `B_zbtc`!). Verified under a `k = 20` single-block grief burst in `verify_spec_bounds.py`. | [Part 1 §4–5](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 3 §2.4](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **R8-H02** | Non-winning honest challengers paid in crisis-discounted `zBTC` failed EV once `10 × 153 vB` P2A CPFP (`16.53 kvB`) + `0.00285 BTC` lockup + `6.7%–30%` discount were counted; `M`-dispute liquidity unbudgeted | **Closed (A7).** Restructured `DisproveTx_{r,i}`/`TimeoutSlashTx_{r,i}` on `Stake_r (2.00 BTC)` so EVERY active challenger claims **`0.15 BTC` in native Bitcoin L1 BTC** via `ChalPayoutEscrow_{r,j}` + `ChalProofConnector_{r,j}` (`0.95 BTC` minimum immediate burn, zero `2^7` explosion!). Net honest verifier EV (incl. `16.53 kvB` CPFP + `0.00285 BTC` lockup, `0%` `zBTC` discount) = **`+0.0645 BTC` @ `500 sat/vB`** and **`+0.0232 BTC` @ `750 sat/vB`** (`890 sat/vB` break-even); attacker P&L = `-2.00` to `-1.10 BTC` L1 alone (`-2.55` to `-1.65 BTC` incl. `B_custody`). Multi-dispute verifier liquidity (`1.45/2.41 BTC` per honest verifier) explicitly budgeted. | [Part 1 §3.1, §4, §6.1](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-H03** | `0.50 × K × Subsidy > TVL` unproven under Budish's winning-fork subsidy offset; missing canonical chainwork check; `B_zbtc` omitted from cap sizing | **Closed (A8) + Pushback Noted.** *(Note: `v3.0.0-rfc` used `K = 14`, not `K = 10`.)* Relabeled inequality honestly as a conditional unpublished-fork heuristic (printing Budish net flow-cost sensitivity across `κ = 5..50%` in checker), raised hard floor to **`K >= 18`** covering **`Cap_TVL_total = Cap_user + M × B_zbtc`**, and added **interactive heaviest-chainwork competing-header comparison** inside `vk_STF`. | [Part 2 §4](./spec/02-btc-authorization-domain-and-spv.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-H04** | TRUC v3 compliance does not guarantee dispute completion under sibling-eviction pinning, `T_step = 48` tightness, and unconfirmed child limits | **Closed (A9).** Pinned **Bitcoin Core `>= 29.0`** (`v31.0` preferred), mandated direct-to-miner submission rails, explicitly prohibited unconfirmed TRUC child chaining (`TakeTx`/`ProverStep > 1,000 vB`), included `10 × 153 vB` P2A CPFP in prover (`76.53 kvB`, `522 sat/vB` break-even) and verifier (`16.53 kvB`) budgets, and widened **`T_step = 72` blks (`12h`)** → `max_dispute = 1,584 < T_take = 1,728 < T_cool = 1,872 < Retire = 2,016` (`13.0d` cycle, `94–104d` bank run). | [Part 1 §3.2, §6.1](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-H05** | `RV32IM` $8^9 = 134.2\text{M}$ step budget contradicted bare `1 MB` SHA-256 block scanning prose | **Closed (A9).** Explicitly partitioned computation: off-chain ZK prover performs stripped-block scanning & SMT updates; `BitVMX-CPU` (`RV32IM`) executes **strictly the constant-size wrapped SNARK verifier `vk_STF`**. Added **Gate G2** requiring compiled ELF `init_steps + exec_steps <= 0.5 × 8^9` (else `l = 10` or mature reusable BitVM3-GC). | [Part 1 §3.2](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 2 §3.2](./spec/02-btc-authorization-domain-and-spv.md), [Part 5 §3, §5](./spec/05-go-zenon-upgrade-plan.md) | | **R8-H06** | `104 B` on-chain `certBlob` did not specify public DA archival for presigned `TakeTx`s, scripts, and Lamport keys | **Closed (A9).** Specified canonical **`zbtc-vault-bundle-v1`** artifact replicated & cryptographically verified across `>= 3` independent public archival mirrors before depositor deletes `x_{dep,d}`, plus **Gate G5** disaster-recovery drill. | [Part 1 §2.2](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 5 §5](./spec/05-go-zenon-upgrade-plan.md) | | **R8-H07** | Stage 0 PTLC (`30h`: `P(T_72 > 30h \| 2.3×) = 22.34%`) & outbound LN HTLC (`6h`: `P(T_36 > 6h \| 1.0×) = 47.78%`) failed Erlang tails | **Closed (A10).** Raised `T_znn` to **`>= 48h` (`172,800s`, `P(T_72 > 48h \| 2.3×) < 10^{-6}`)** and outbound LN `Δ_safety_sec` to **`>= 24h` (`86,400s`, `P(T_36 > 24h \| 2.3×) < 0.0002`)**, mandated automated block-72 RBF refund watchtowers, disclosed conditional atomicity, and added exact stdlib Erlang assertions in `verify_spec_bounds.py`. | [Part 3 §1](./spec/03-settlement-minted-zbtc-and-feeless-rails.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-H08** | Immutable `vk_STF` bug risk on unrecoverable legacy vaults | **Closed (A6).** Added **Gate G4** formal verification + Bitcoin Core differential fuzzing, **graduated mainnet TVL ramps (`2 → 5 → 10/15 BTC`)**, and a non-custodial **voluntary unwind circuit breaker** (halt new `σ_cert`, drain organically via `0x01`, launch clean `zBTC_v2`). | [Part 1 §6.3](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 5 §5](./spec/05-go-zenon-upgrade-plan.md) | | **R8-N01** | Rational operators could pause retail par fronting during a bank run to jump the queue via discounted self-fronting | **Closed (A11).** Enforced **oldest-`PendingExit` timestamp priority** for reimbursement credit eligibility whenever open retail exits `> 6` blks exist + optional Dutch-auction `f_op` discovery (`spec/03 §2.4`), while keeping bank-run discount risk explicitly disclosed in `SPEC §4`. | [Part 3 §2.4](./spec/03-settlement-minted-zbtc-and-feeless-rails.md), [SPEC §4](./SPEC.md) | ### `R8` Medium & Low Findings (`R8-M01` – `R8-M09`, `R8-L01` – `R8-L02`) | ID | Finding Summary (`v1` / `v3.0.0-rfc`) | Disposition in `v2` (`v3.1.0-rfc`) | Spec Reference | |---|---|---|---| | **R8-M01** | Unbounded zero-cost `0x02` L1 DA spam via refundable QSR spraying 1-sat transfers to fresh addresses (`~3.80 BTC/d`) | **Closed (A11).** Reframed Zenon transfers honestly as *L1-subsidized soft preconfirmations*; added refundable **`500`-sat `zBTC` new-account SMT leaf deposit** + **`<= 1,000` new leaves per 6-block epoch** cap. | [Part 3 §2.2](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **R8-M02** | Competing permissionless `0x02` batchers burn L1 fees on stale-root collisions | **Closed (A11).** Added deterministic **slotted batcher priority** (`primary = H(header[h-1].hash) mod K_batchers` for first 2 blocks after `+6`, open permissionless fallback thereafter). | [Part 2 §3.3](./spec/02-btc-authorization-domain-and-spv.md), [Part 3 §2.3](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **R8-M03** | `k_r = H(exitId \|\| r) mod M` had `20%` dead-operator collision rate & mismatched `spec/03` `<6*j>` | **Closed (A11).** Standardized collision-free cyclic permutation **`k_r = (H(exitId) + r) mod M_active`** across BOTH `spec/01 §5` and `spec/03 §2.4` (`0%` repeat across `r = 0..M_active-1`). | [Part 1 §5](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 3 §2.4](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **R8-M04** | `< 0.25 BTC` operator `ReimbursementCredit` residuals stranded permanently | **Closed (A11).** Added signed **`TransferCredit(from_op, to_op, amt)`** (via `0x02`/`0x03`) + retirement `R -> C` conversion (`RetireStakeTx_r`). | [Part 3 §2.1, §2.4](./spec/03-settlement-minted-zbtc-and-feeless-rails.md), [Checker](./scripts/verify_spec_bounds.py) | | **R8-M05** | `MIN_EXIT_SATS` dust floor absent from normative prose | **Closed (A11).** Normatively mandated `grossSats >= max(dust(destScriptPubKey), MIN_EXIT_SATS = 100,000)` sats (`0.001 BTC`) in `spec/01`, `spec/02`, and `spec/03`. | [Part 2 §3.1](./spec/02-btc-authorization-domain-and-spv.md), [Part 3 §2.1, §2.4](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **R8-M06** | Stage 0 SPV 64-byte leaf filter verification | **Verified Pushback + Tightened.** `v3.0.0-rfc` `spec/02:L67, L72` *already* rejected `len == 64` and enforced `totalCoinbaseBytes >= 65`. Tightened `len(strippedTx) != 64` to **`65 <= len(strippedTx) <= 6,144`** with explicit syntax validation. | [Part 2 §2.1, §2.3](./spec/02-btc-authorization-domain-and-spv.md) | | **R8-M07** | Undefined `>= K` deep Bitcoin reorg behavior | **Closed (A8).** Specified fail-closed **`DEEP_REORG_HALT`** circuit breaker + `>= 144`-block rollback snapshots and canonical chain replay. | [Part 2 §4](./spec/02-btc-authorization-domain-and-spv.md) | | **R8-M08** | Throughput reconciliation (`7.37` vs `8.8`), unstated Bitcoin `0x02` DA ceiling, and `go-zenon` mainnet gap (`#299`, `#312`, `PR #138`) | **Closed (A11) + Pushback Noted.** *(Note: `4.4/8.8` 2-blk & `6.5/12.9` 1-blk were exact at observed `11.4s`/Momentum vs `7.37` at idealized `10s`.)* Published **two-column throughput table** pairing Zenon transport against Bitcoin L1's physical `0x02` DA ceiling (`166.7` blended `10 vB` leaves/s @ 100%; `416.7` existing `16 B` / `138.9` new `48 B`); added `#299`, `#312`, and mainnet `PTLC PR #138` activation to **Gate G6**. | [Part 3 §2.2](./spec/03-settlement-minted-zbtc-and-feeless-rails.md), [Part 5 §2.1, §5](./spec/05-go-zenon-upgrade-plan.md) | | **R8-M09** | Missing operational hard-BTC reserves & Bitcoin Core `>= 29.0` floor for `0`-sat P2A | **Closed (A9).** Published complete hard-BTC breakdown (**`12.80/18.80 BTC`** locked → **`14.75/21.25 BTC`** single-dispute operational baseline → `~17–26+ BTC` multi-dispute headroom), explicitly clarified `Cap_TVL_total = Cap_user + M × B_zbtc`, and pinned **Bitcoin Core `>= 29.0` (`v31.0` preferred)**. | [Part 1 §3.2, §6.1](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 5 §1](./spec/05-go-zenon-upgrade-plan.md) | | **R8-L01** | `"100% Bitcoin PoW finality"` contradicted probabilistic PoW | **Closed (A6).** Replaced with `"probabilistic PoW finality at depth K >= 18 under <50% honest hashrate"` across all files. | [SPEC §3.2, §4, §9](./SPEC.md), [Part 4 §2](./spec/04-bitcoin-anchoring-and-light-client.md) | | **R8-L02** | Active `v1` lacked generated `SHA256SUMS.txt` manifest | **Closed (A6).** `scripts/sync_public_artifacts.mjs` now generates deterministic `public/raw/SHA256SUMS.txt` covering all `v2` normative files, `CHANGELOG.md`, and `scripts/verify_spec_bounds.py` on every build (and verifies frozen `versions/v1/SHA256SUMS.txt` and `versions/v0/SHA256SUMS.txt`). | [SPEC](./SPEC.md), [`sync_public_artifacts.mjs`](./scripts/sync_public_artifacts.mjs) | ### Summary of Verified Pushbacks on `R8` (Gate G7 Local Repo Check) Direct line-level inspection of the local repository resolved every `CONFIRMED WITH QUALIFICATIONS` item from `R8`: 1. **`R8-M06`:** `spec/02:L67, L72` already rejected `len == 64` and required `totalCoinbaseBytes >= 65` (tightened to `65 <= len(strippedTx) <= 6,144`). 2. **`R8-M08`:** `4.4/8.8` (2-blk `42k` Plasma) and `6.5/12.9` (1-blk `28,480` Plasma) were exact at observed `11.4s`/Momentum (not an arithmetic error against `10s`); `v3.1.0-rfc` now prints both side by side with Bitcoin's `0x02` physical DA ceiling. 3. **`R8-C05`:** `spec/02:L115` already mandated BIP-141 `wtxid` verification against coinbase; `v3.1.0-rfc` closes the 3 real gaps (last `6a24aa21a9ed` output + fail-closed vs skip, full stripped-`vin` scan, complete `0x02` DA schema). 4. **`R8-H03`:** `v3.0.0-rfc` used `K = 14` (not `K = 10`); `v3.1.0-rfc` raises the floor to `K >= 18`, adds Budish sensitivity & interactive heaviest-chainwork comparison. 5. **BitVM3 vs BitVMX-CPU (Q12):** While BitVM3 cuts on-chain disprove size to `~93 vB`, non-reusable BitVM3 currently carries a `1-of-N` garbler trust assumption and `~2.2–11.2+ TB` one-time garbled-circuit DA across `2,240` rounds; Gate G2 evaluates both before final freeze. --- ## Historical Pivot: `v0` (`v2.5.0-rfc`) → `v1` (`v3.0.0-rfc`) Architecture Shift & `R7` Disposition `v1` (`v3.0.0-rfc`) completely replaced `v0`'s unviable BitVM2 + rotating-PoS-committee hybrid — **while explicitly REJECTING custodial `k`-of-`n` federated multisigs** — with the **Zero-Federation, Zero-Soft-Fork, Zero-ZNN-Custody-Coupling Phased Architecture** triggered by Consolidated Hostile Review [`R7`](./reviews/HOSTILE_REVIEW_R7_CONSOLIDATED.md) (4 Critical, 8 High, 15 Medium, 4 Low + `N-1..N-6`, `B1..B5`): ### `R7` Critical Findings (`C-1` – `C-4`) | ID | Finding Summary (`v0`) | Disposition in `v1` | Spec Reference | |---|---|---|---| | **C-1** | Security priced in ZNN at `10,500 ZNN/BTC` (40–70× above market `400k–727k`) | **Closed by removal.** `0%` ZNN in BTC safety; `10,500 ZNN/BTC` deleted. All Stage 1A collateral & operational reserves (`14.75–21.25 BTC` baseline) are hard BTC. | [SPEC §1, §4, §7](./SPEC.md), [Part 1 §6](./spec/01-bitcoin-taproot-vault-enforcement.md) | | **C-2** | Honest BLS certs over dishonest canonical Zenon state (unchallenged batch / censorship / upgrade) | **Closed by architectural inversion.** BLS Pillar committees and optimistic Zenon batches deleted; Stage 1A verifies an immutable Bitcoin-anchored ZK validity rollup (`vk_STF`, `0-of-N` Zenon trust) surviving `49%–100%` Zenon compromise. | [SPEC §3, §4](./SPEC.md), [Part 2 §3](./spec/02-btc-authorization-domain-and-spv.md), [Part 4 §1–2](./spec/04-bitcoin-anchoring-and-light-client.md) | | **C-3** | BitVM2 assert (`220 kvB`) & disprove (`≤ 95 kvB`) sizes 4.4–10× below published measurements | **Closed via `n = 8` `BitVMX` switch.** Proposition 2 shows minimal `M=3–5` Groth16 BitVM2 requires `~40–91 BTC` bonds (`13.30–18.175 BTC`/lane). Replaced with `n = 8` `BitVMX-CPU` (`RV32IM` wrapped-SNARK verifier) bisection (`7.44 kvB`/prover tx, 100% TRUC v3 on Core `>= 29.0`). | [Part 1 §1.2, §3.2, §6](./spec/01-bitcoin-taproot-vault-enforcement.md), [Checker](./scripts/verify_spec_bounds.py) | | **C-4** | Never-deleted `N`-of-`N` `Q_graph` can sweep everything or brick everything; contradicts C-07 & Wind-Down #8 | **Closed without federations.** Immutable `vk_STF` eliminates 30-day committee rotations so vault graphs never expire; ephemeral `Q_setup_d` (incl. depositor key) and `Q_lane` keys are **permanently deleted** after setup; custodial federations explicitly forbidden. | [Part 1 §1.1, §2.2, §3.1](./spec/01-bitcoin-taproot-vault-enforcement.md) | ### `R7` High Findings (`H-1` – `H-8`) | ID | Finding Summary (`v0`) | Disposition in `v1` | Spec Reference | |---|---|---|---| | **H-1** | Committee seats rented via free instant delegation at one snapshot | **Closed by removal.** Zenon Pillar finality committees completely eliminated from BTC custody (`spec/04`). | [Part 4 §1–2](./spec/04-bitcoin-anchoring-and-light-client.md) | | **H-2** | `≥ 10` committee seats withholding certs profitably burn honest operators | **Closed by removal.** No Pillar finality certificates required for operator reimbursement. | [Part 1 §3](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 4 §2](./spec/04-bitcoin-anchoring-and-light-client.md) | | **H-3** | Upgrade & Plasma authority = custody authority; single spork keys unlisted in §4 | **Closed.** Hard-pinned `vk_STF` gives Zenon `SporkAddress`/`CommunitySporkAddress` **`0` BTC custody blast radius** in Stage 1A; Stage 0 pins all 5 `SetPlasmaVariables` fields; Privileged Powers Table in `SPEC §4.1`. | [SPEC §4.1](./SPEC.md#41-complete-privileged-powers-table-h-3-closed-zero-custodial-authority), [Part 5 §2–3](./spec/05-go-zenon-upgrade-plan.md) | | **H-4** | Altruistic watcher fronts `1.45 BTC`/lane (`14.6 BTC` total) and loses against self-slasher/MEV | **Closed (hardened further in `R8-H02`).** Pre-committed `N = 7` `BitVMX` verifiers lock `F_chal = 0.40 BTC` in `ChalEscrow_{r,i}` (returned on win/abort) and EVERY active honest challenger collects **`0.15 BTC` in native Bitcoin L1 BTC** directly from `Stake_r` (`+0.0645 BTC` net EV @ `500 sat/vB`, `+0.0232 BTC` @ `750 sat/vB`, `0%` `zBTC` discount). | [Part 1 §4](./spec/01-bitcoin-taproot-vault-enforcement.md) | | **H-5** | Exit liveness missing from §4; exits throttled to `1.82 vaults/day` | **Closed transparently.** `1-of-M` (`M = 3–5`) operator liveness is Assumption #4 (`SPEC §4`, explicitly noting `0-of-M` locks native BTC per `R8-C06`); exact throughput (`0.077–0.128 BTC/d`) and 100% bank-run duration (`~94–104d` at `T_cooldown = 13.0d`; `~62–68d` w/ `{0.50, 0.50}`) published next to `Cap_TVL`. | [SPEC §4](./SPEC.md), [Part 1 §6](./spec/01-bitcoin-taproot-vault-enforcement.md) | | **H-6** | April 2024 fees & June 2021 slow blocks broke envelope; real slow-block tolerance was `1.287×` | **Closed (hardened further in `R8-H04`/`R8-H07`).** Zero absolute CLTV cliffs (relative CSVs only); Core `>= 29.0` TRUC v3 + `0`-sat `P2A` anchors + direct-to-miner rails; PTLC `>= 48h` / LN `>= 24h` Erlang-verified against `2.3×` slow blocks; sustained `500 sat/vB` 10-day bisection envelope stated honestly. | [Part 1 §3.2](./spec/01-bitcoin-taproot-vault-enforcement.md), [Part 3 §1](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | | **H-7** | Unpaid epoch handoff anchoring, missing mobile BTC header source & `minimumPostAnchorWork`, overclaimed "end at Bitcoin PoW" | **Closed.** Stage 1A canonical state, DA (`0x02`), and forced exits (`0x01`/`0x03`) live directly on Bitcoin L1 PoW (`probabilistic finality` at `K >= 18`); `SPEC §9` aligns public wording. | [SPEC §9](./SPEC.md), [Part 2 §3](./spec/02-btc-authorization-domain-and-spv.md), [Part 4 §2–3](./spec/04-bitcoin-anchoring-and-light-client.md) | | **H-8** | 21M pre-mint inside `SettlementContract` makes full supply the blast radius | **Closed by removal.** Stage 1A `zBTC` lives in the immutable Bitcoin-canonical Rollup SMT, never pre-minted inside a Zenon embedded contract (`TokenContract.IssueMinted` retired). | [SPEC §6](./SPEC.md), [Part 3 §2](./spec/03-settlement-minted-zbtc-and-feeless-rails.md) | ### `R7` Medium, Low & Convergence Findings (`M-1..M-15`, `L-1..L-4`, `N-1..N-6`, `B1..B5`) | ID | Finding Summary (`v0`) | Disposition in `v2` (`v3.1.0-rfc`) | |---|---|---| | **M-1, M-2, M-8, B4** | Dual-clock fronting slots, cheap slot-lapse collusion, timeout-only double-pay races | **Closed.** Atomic active-operator `(2M_active+1)`-leaf `ExitSlotUTXO` uses strictly Bitcoin CSV clocks, cyclic `(H(exitId)+r) mod M_active` priority, L1 UTXO exclusion, and hard-partitioned `B_grief` slashing (`spec/01 §5`). | | **M-3, B1, L-3** | U0 pinned to superseded `rc1`; `#239` FIFO panic stall; stale-ack fix `#227` | **Closed (Gate G6).** Gated on tagged mainnet `go-zenon` release containing `0aa299e`, `PTLC PR #138`, `DynamicPlasmaSpork`, and closure of `#239`, `#299`, `#312` (`spec/05 §2, §5`). | | **M-4** | PTLC 12-block refund race & LN HTLC deltas | **Closed (hardened in `R8-H07`).** `<72> OP_CSV`, automated block-72 RBF refund watchtower, `T_znn >= 48h`, outbound LN `Δ_safety_sec >= 24h`, Hold Invoice 5-min TTL (`spec/03 §1`). | | **M-5, M-6** | Free `BTC_TX_STREAM_CHUNK` spam & unproven Leaf 3B SHA-256 without `OP_CAT` | **Closed by removal.** Streaming `0x04` and Leaf 3B deleted; acyclic `vault_id` 256-bit Lamport `TakeTx` uses only `OP_HASH160` (`5,922 B` script, `258` peak stack, `~3.17 kvB` TRUC v3). | | **M-7, M-12, N-2** | Post-`RolloverTx` admission stranding & `CommitteeIdentityKey` standing twin of `Q_graph` | **Closed (hardened in `R8-C03`).** `RolloverTx` & `CommitteeIdentityKey` deleted; `AdmissionTicketUTXO` enforces `Cap_TVL` at L1 consensus before `DepositTx` confirms; `x_{i,d}` deleted (`spec/01 §2.2`). | | **M-9, M-10, B2** | `4,386 tx/s` overstated, `11.4s` Momentum, unpinned `SetPlasmaVariables` targets/denom | **Closed (hardened in `R8-M08`).** All 5 `SetPlasmaVariables` fields pinned; two-column throughput table pairs Zenon `11.4s` / `8 MiB` ceiling against Bitcoin L1's `0x02` physical DA ceiling (`spec/03 §2.2`, `spec/05 §2.2`). | | **M-11, L-1, L-2, N-1, N-3, N-4** | Unslashable certs, `<21` BLS Pillars, G-21 stall, sub-quorum freeze, chained sessions, `ChallengeDepositZnn` | **Closed by removal.** No Pillar finality committee, no 30-day BitVM rotation, and no optimistic Zenon challenge sessions exist in BTC custody (`spec/04 §2–3`). | | **M-13, M-14, M-15, L-4, N-5, N-6, B3, B5** | Precedence, TBD params, independent audit, `bigidea` claims, solvency conservation, frozen `v0` | **Closed & Enforced.** Part 1 is #1 authority (`SPEC §2.1`); `SPEC §9` aligns all public claims; `verify_spec_bounds.py` asserts exact `V_unassigned + V_assigned == C + L + E + R + A + B` across real reorgs and slashes; Gates G1–G7 + M-15 block mainnet; `versions/v0/` stays byte-identical (`SHA256SUMS.txt` verified in CI). | # Deterministic Consistency & Bounds Checker (`scripts/verify_spec_bounds.py`) ```python #!/usr/bin/env python3 """ Deterministic Consistency & Bounds Checker for the zBTC Protocol Specification v2 (v3.1.0-rfc — Zero-Federation Phased Architecture, R8 Hardened: Stage 0 Verify Bitcoin SPV Oracle + Erlang-Hardened PTLC/LN -> Stage 1A Right-Sized BitVMX (n=8, M=3..5, N=7, Core >= 29.0) + Sovereign ZK Rollup | Stage 1B clArk Alternative Gate -> Stage 2 Zero-TTP Scale & Upgrade). SCOPE & HONESTY DISCLOSURE: This script checks internal mathematical consistency using pure Python 3 stdlib ONLY: 1. Stage 0 coinbase midstate 1-/2-block SHA-256 final padding across all 64 remainders + >= 65 B filter (R8-M06) 2. Stage 0 honest go-zenon Plasma/wire ceilings, Dynamic Plasma 5-param pinning, & Bitcoin L1 0x02 DA cap (R8-M08) 3. Stage 0 exact Erlang/Poisson survival tails for PTLC (>= 48h) & LN HTLC (>= 24h) under 2.3x slowdown (R8-H07) 4. Proposition 2 complete hard-BTC capital accounting: locked vs operational baseline vs multi-dispute headroom (R8-M09) 5. Stage 1A BitVMX-CPU n=8 W-OTS + 10x153 vB P2A CPFP & Core >= 29.0 BIP-431 TRUC v3 compliance (R8-H04/H05) 6. Stage 1A widened timelocks (T_step=72 -> 1,584 < 1,728 < 1,872 < 2,016) & acyclic vault_id Lamport TakeTx (R8-C01) 7. Stage 1A native-L1 Stake_r ChalPayoutEscrow verifier EV @ 500 & 750 sat/vB, 16.53 kvB, lockup, 30% zBTC discount (R8-H02/N05) 8. Stage 1A exact 2^M Hall's Marriage Theorem checker + counterexample regression & cyclic (H(exitId)+r) mod M (R8-C04/M03) 9. Stage 1A multi-tier {0.50, 0.25, 0.25} bank-run exit bounds (T_cooldown=13.0d) & TransferCredit consolidation (R8-M04) 10. Stage 1A K >= 18 unpublished-fork heuristic (Cap_user + M*B_zbtc) & Budish winning-fork flow-cost sensitivity (R8-H03) 11. Stage 1B clArk active liquidity & log2(N) branch exit weights 12. Non-no-op randomized state-machine simulation separating fifo_assign & take_confirmed across T_take with explicit AssignedObligations (A) conservation (V_unassigned + V_assigned == C + L + E + R + A + B), AdmissionTicketUTXO cap mutual exclusion, k=20 single-block ExitSlotUTXO grief burst, TransferCredit, real Bitcoin reorgs, and slashes (R8-C02, R8-C03, R8-H01, R8-N05, R8-M04). Every modeled constant is explicitly prefixed by provenance: - SOURCED_ : Bitcoin BIPs, historical chain telemetry, or go-zenon origin/dev - POLICY_ : Explicit protocol design parameters - PRE_MAINNET_TARGET_ : BitVMX-CPU / rollup sizing targets to be empirically measured on Signet (Gates G1-G5) This script is a consistency & bounds checker — NOT an empirical Signet benchmark and NOT a substitute for independent cryptographic/implementation audits. Run: `python3 -I scripts/verify_spec_bounds.py` """ import hashlib import math import random import struct SAT = 100_000_000 # ============================================================================== # SOURCED CONSTANTS (Bitcoin BIPs, Historical Telemetry, go-zenon origin/dev) # ============================================================================== SOURCED_BIP431_TRUC_MAX_VB = 10_000 # BIP-431 TRUC v3 parent max vBytes SOURCED_BIP431_TRUC_CHILD_MAX_VB = 1_000 # BIP-431 TRUC v3 child max vBytes SOURCED_BTC_CORE_MIN_VERSION_P2A_ZERO = "29.0" # Core >= 29.0 required for 0-sat P2A ephemeral dust (R8-M09) SOURCED_BIP342_MAX_STACK_ITEMS = 1_000 # BIP-342 Tapscript max stack elements SOURCED_BIP342_MAX_PUSH_BYTES = 520 # BIP-342 Tapscript max push element size SOURCED_BIP141_MAX_STRIPPED_BLOCK_BYTES = 1_000_000 # Bitcoin consensus max non-witness block bytes SOURCED_BTC_MAX_BLOCK_WEIGHT = 4_000_000 # Bitcoin consensus 4 MWU = 1,000,000 vB/block SOURCED_BTC_TARGET_BLOCK_SECS = 600 # 10 min nominal Bitcoin block interval SOURCED_BTC_BLOCKS_PER_DAY = 144 # Nominal blocks/day SOURCED_JUNE2021_SLOW_WEEKLY_MULT = 2.0 # June 2021 China ban: ~1.95-2.0x 7d avg SOURCED_JUNE2021_SLOW_DAILY_MULT = 2.3 # June 2021 China ban: ~23 min/blk daily peak SOURCED_APR2024_MEDIAN_FEE_SATVB = 1_805 # April 2024 halving/Runes median peak SOURCED_P2A_CPFP_CHILD_VB = 153 # Standard 1-in-P2TR + 1-in-P2A -> 1-out-P2TR CPFP child (vB) # Bitcoin block subsidy schedule (BTC/block) across halvings SOURCED_BTC_SUBSIDY_BY_ERA = { "2024-2028": 3.125, "2028-2032": 1.5625, "2032-2036": 0.78125, "2036-2040": 0.390625, } # ZNN market-cap context (Nov 2026 observed range; 0% ZNN in BTC custody safety!) SOURCED_ZNN_MCAP_BTC_LOW = 25.0 SOURCED_ZNN_MCAP_BTC_HIGH = 33.0 # go-zenon origin/dev protocol constants SOURCED_ZNN_MAX_DATA_LENGTH = 16_384 # dev:vm/constants/plasma.go:67 SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA = 21_000 # dev:vm/constants/plasma.go SOURCED_ZNN_AB_BYTE_DATA_PLASMA = 68 # dev:vm/constants/plasma.go (DynamicPlasmaSpork) SOURCED_ZNN_EMBEDDED_SIMPLE_TIER = 52_500 # 2.5 * 21,000 SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER = 73_500 # 3.5 * 21,000 SOURCED_ZNN_PLASMA_PER_QSR = 2_100 # 1 QSR = 1 fusion unit = 2,100 Plasma @ price 1,000 SOURCED_ZNN_POW_DIFF_PER_PLASMA = 1_500 # dev:vm/constants/plasma.go SOURCED_ZNN_MIN_RESOURCE_PRICE = 1_000 # dev:dp/dp.go SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA = 4_200_000 # dev:vm/embedded/definition/plasma.go:97 SOURCED_ZNN_DP_UPPER_MAX_BASE_PLASMA = 2_100_000_000 # dev:vm/embedded/definition/plasma.go:63 SOURCED_ZNN_DP_LOWER_MAX_BASE_PLASMA = 210_000 # dev:vm/embedded/definition/plasma.go:66 SOURCED_ZNN_OBSERVED_MOMENTUM_SECS = 11.4 # dev:vm/embedded/definition/spork.go (11.35-11.46s) SOURCED_ZNN_CHAIN_BRIDGE_ROLLBACK = 30 # dev:protocol/chain_bridge.go:293 SOURCED_ZNN_MAX_MOMENTUM_CONTENT_BYTES = 8 * 1024 * 1024 # dev:verifier/momentum.go:93 (8 MiB) SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE = 10 * 1024 * 1024 # dev:protocol/protocol.go (10 MiB) SOURCED_ZNN_SOFT_RESPONSE_LIMIT = 2 * 1024 * 1024 # dev:protocol/protocol.go (2 MiB) SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE = ( SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE - SOURCED_ZNN_SOFT_RESPONSE_LIMIT - 4096 ) # 8,384,512 B (dev:protocol/protocol.go:70) SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW = 300 SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH = 350 # ============================================================================== # POLICY PARAMETERS (Stage 0, Stage 1A BitVMX v3.1.0-rfc, Stage 1B clArk) # ============================================================================== POLICY_PINNED_MAX_BASE_PLASMA_FLOOR = 2_100_000 # Pinned >= 2.1M Plasma/Momentum POLICY_PINNED_MAX_PRICE_CHANGE_PCT = 25 # MaxPriceChangePercent <= 25% POLICY_PINNED_MIN_TARGET_SHARE_PCT = 25 # Fused/Pow targets >= 25% of 2.1M floor (525,000) POLICY_PINNED_MIN_PRICE_DENOM = 8 # PriceChangeDenominator >= 8 (spec/05 §2.2) POLICY_STAGE0_MIN_STRIPPED_TX_BYTES = 65 # Rejects <= 64 B CVE-2017-12842 leaves (R8-M06) POLICY_STAGE0_MAX_STRIPPED_TX_BYTES = 6_144 # Stage 0 SPV Event Oracle tx cap POLICY_STAGE0_MAX_STORAGE_OPS = 24 # Per-call L1 storage op ceiling # Stage 0 Erlang-Hardened PTLC / LN non-custodial swap parameters (R8-H07) POLICY_PTLC_BTC_CSV_BLOCKS = 72 # Automated high-fee RBF refund watchtower fires at h_conf + 72 POLICY_PTLC_ZNN_DURATION_SECS = 172_800 # >= 48.0 hours (P(T_72 > 48h | 2.3x) < 1e-6!) POLICY_LN_DELTA_SAFETY_BLOCKS = 36 POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS = 86_400 # >= 24.0 hours (P(T_36 > 24h | 2.3x) < 2e-4!) # Stage 1A Right-Sized BitVMX (n=8) + Sovereign ZK Rollup parameters POLICY_BITVMX_N_BRANCH = 8 # n=8 (3 bits/round -> 7 intermediate hashes) POLICY_BITVMX_SEARCH_ROUNDS = 9 # 8^9 = 2^27 = 134,217,728 RV32IM wrapped-SNARK verifier ops POLICY_BITVMX_M_MIN = 3 # Minimal competitive operator count POLICY_BITVMX_M_MAX = 5 # Pilot operator count POLICY_BITVMX_L_LANES = 1 # Lanes per operator POLICY_BITVMX_N_VERIFIERS = 7 # Pre-committed online verifiers POLICY_BITVMX_R_ROUNDS = 64 # Pre-signed rounds per lane POLICY_STAGE2_TOTAL_LANES = 40 # Stage 2 scaled lane count (40 * 64 = 2,560 leaves) POLICY_VAULT_TIERS_SATS = (50_000_000, 25_000_000, 25_000_000) # {0.50, 0.25, 0.25} BTC per 1.0 BTC deposit POLICY_VAULT_ALT_SPLIT_SATS = (50_000_000, 50_000_000) # Optional {0.50, 0.50} split comparison POLICY_MAX_VAULT_DENOM_SATS = 50_000_000 # 0.50 BTC ceiling per vault UTXO POLICY_MIN_EXIT_SATS = 100_000 # 0.001 BTC normative dust floor (R8-M05) POLICY_NEW_LEAF_DEPOSIT_SATS = 500 # Refundable new-SMT-leaf deposit (R8-M01) POLICY_MAX_NEW_LEAVES_PER_EPOCH = 1_000 # <= 1,000 new SMT leaves per 6-block epoch (R8-M01) # Stage 1A Hard-Partitioned Per-Lane Bond & Native-L1 Verifier Economics (R8-H01, R8-H02, R8-N05) POLICY_BOND_BTC_SATS = 200_000_000 # 2.00 BTC L1 Stake_r bond POLICY_B_ZBTC_CUSTODY_SATS = 50_000_000 # 0.50 BTC maxVaultDenom Lamport restitution POLICY_B_ZBTC_EQUIV_BOUNTY_SATS = 5_000_000 # 0.05 BTC Lamport equivocation bounty POLICY_B_CUSTODY_TOTAL_SATS = ( POLICY_B_ZBTC_CUSTODY_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS ) # 0.55 BTC HARD-PARTITIONED B_custody (NEVER debited by grief!) POLICY_B_GRIEF_TOTAL_SATS = 5_000_000 # 0.05 BTC HARD-PARTITIONED B_grief (ExitSlotUTXO grief only!) POLICY_B_ZBTC_TOTAL_SATS = POLICY_B_CUSTODY_TOTAL_SATS + POLICY_B_GRIEF_TOTAL_SATS # 0.60 BTC total/lane POLICY_LANE_TOTAL_BOND_SATS = POLICY_BOND_BTC_SATS + POLICY_B_ZBTC_TOTAL_SATS # 2.60 BTC/lane POLICY_F_CHAL_SATS = 40_000_000 # 0.40 BTC verifier challenge escrow POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS = 15_000_000 # 0.15 BTC NATIVE L1 BTC payout per active challenger (R8-H02!) POLICY_MIN_L1_STAKE_BURN_SATS = ( POLICY_BOND_BTC_SATS - POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS ) # 0.95 BTC minimum immediate OP_RETURN burn when all 7 challenge! POLICY_EXIT_GRIEF_SLASH_SATS = 1_000_000 # 0.01 BTC per-exit grief penalty (pro-rata capped at B_grief!) POLICY_DESIGN_SUSTAINED_FEE_SATVB = 500 # 500 sat/vB primary sustained design envelope POLICY_STRESS_SUSTAINED_FEE_SATVB = 750 # 750 sat/vB stress-test verifier envelope POLICY_VERIFIER_LOCKUP_COST_SATS = 285_000 # 0.00285 BTC conservative capital lockup cost (R8-H02) POLICY_CRISIS_ZBTC_DISCOUNT = 0.30 # 30% crisis zBTC discount stress test (0% impact on native L1!) # Stage 1A Operational Reserve Accounting (R8-M09) POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC = 0.10 # 0.10 BTC * 7 = 0.70 BTC verifier CPFP reserve POLICY_OP_RESERVE_DA_BATCHER_BTC = 0.50 # 0.50 BTC DA batcher L1 fee float POLICY_OP_RESERVE_TOPUP_PER_OP_BTC = 0.25 # 0.25 * M BTC operator top-up/CPFP reserve # Stage 1A Widened Simultaneous-Challenge BitVMX Timelocks (T_step = 72 blks = 12h, R8-H04) POLICY_T_CHAL_WINDOW = 144 # Simultaneous [0, 144] challenge window (24h) POLICY_T_STEP = 72 # 12h per bisection step (widened from 48!) POLICY_T_TAKE = 1_728 # 12.0d (> max_dispute_end = 1,584; +144 blk margin!) POLICY_T_COOLDOWN = 1_872 # 13.0d (1,728 + 144-blk Lamport equivocation slash window) POLICY_T_RETIRE = 2_016 # 14.0d Stake retirement CSV POLICY_T_EXIT_CANCEL = 288 # 48h user unilateral EXIT_CANCEL leaf (restores zBTC only) POLICY_K_MIN_FLOOR = 18 # Hard minimum K >= 18 blocks (R8-H03) # Stage 1A Capital & TVL Profiles (Cap_TVL_total = Cap_user + M * B_zbtc) POLICY_STAGE1A_PROFILES = { "M=3 (<=10 user / 11.8 tot)": {"M": 3, "cap_user_btc": 10.0, "cap_total_btc": 11.80, "float_btc": 2.20, "K_2024": 18}, "M=5 (<=15 user / 18.0 tot)": {"M": 5, "cap_user_btc": 15.0, "cap_total_btc": 18.00, "float_btc": 3.00, "K_2024": 18}, } # Tiers keyed by Cap_user -> Cap_TVL_total (incl. M * 0.60 BTC B_zbtc: M=3,5,20,40) POLICY_TVL_TIERS_TOTAL_BTC = { 10: 11.80, 15: 18.00, 50: 62.00, 200: 224.00, } POLICY_CONFIGURED_K_BY_ERA = { "2024-2028": {10: 18, 15: 18, 50: 42, 200: 144}, "2028-2032": {10: 18, 15: 24, 50: 80, 200: 288}, "2032-2036": {10: 32, 15: 48, 50: 160, 200: 576}, } # ============================================================================== # PRE-MAINNET TARGETS (BitVMX-CPU / Rollup / BitVM2 / clArk — Signet-Gated) # ============================================================================== PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES = 110 # Signed rollup transfer in AccountBlock.Data PRE_MAINNET_TARGET_DEPOSIT_CERTBLOB_BYTES = 104 # Acyclic OP_DROP certBlob <= 520 B PRE_MAINNET_TARGET_WOTS_DIGIT_WU = 95.5 # Per base-16 W-OTS digit weight (WU) PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB = 250.0 # Per prover bisection tx non-WOTS overhead (vB) PRE_MAINNET_TARGET_START_TX_VB = 3_000.0 # Prover StartTx vBytes PRE_MAINNET_TARGET_FINAL_TRACE_TX_VB = 5_000.0 # Prover FinalTraceTx vBytes PRE_MAINNET_TARGET_CHALLENGE_TX_VB = 350.0 # Verifier ChallengeTx vBytes PRE_MAINNET_TARGET_VERIFIER_CHOICE_VB = 350.0 # Verifier 3-bit interval choice tx vBytes PRE_MAINNET_TARGET_EXECUTE_OPCODE_VB = 8_000.0 # Verifier final 1-opcode disprove tx vBytes PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB = 75_000 # Conservative prover base dispute cap (vB) PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB = 15_000 # Conservative verifier base dispute cap (vB) PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE = 10 # 10 P2A CPFP children per side (10 * 153 = 1,530 vB) PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW = 13.30 PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH = 18.175 PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC = (2.0, 5.0) PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS = (64, 128, 256, 512, 1024) # ============================================================================== # PURE PYTHON STDLIB MATH, CRYPTO & INVARIANT HELPERS # ============================================================================== def ceil_div(a: int, b: int) -> int: return (a + b - 1) // b def compact_size_len(n: int) -> int: if n < 253: return 1 if n <= 0xFFFF: return 3 if n <= 0xFFFFFFFF: return 5 return 9 def erlang_survival_prob(k_blocks: int, duration_secs: float, mean_block_secs: float) -> float: """ Exact Erlang(shape=k, rate=lambda) survival probability P(T_k > duration_secs) using pure Python stdlib (zero scipy dependency!): P(T_k > t) = P(Poisson(lambda * t) <= k - 1) = sum_{j=0}^{k-1} exp(-mu) * mu^j / j! Computed in log-space per term for full numerical stability. """ mu = duration_secs / mean_block_secs if mu <= 0.0: return 1.0 log_mu = math.log(mu) total = 0.0 for j in range(k_blocks): log_term = -mu + j * log_mu - math.lgamma(j + 1) total += math.exp(log_term) return min(1.0, max(0.0, total)) def erlang_quantile_hours(k_blocks: int, q: float, mean_block_secs: float) -> float: """Binary search exact Erlang quantile in hours (P(T_k <= t) = q).""" lo = 0.0 hi = k_blocks * mean_block_secs * 5.0 for _ in range(80): mid = 0.5 * (lo + hi) cdf = 1.0 - erlang_survival_prob(k_blocks, mid, mean_block_secs) if cdf < q: lo = mid else: hi = mid return (0.5 * (lo + hi)) / 3600.0 def abi_embedded_plasma(tier: int, abi_len: int) -> int: assert abi_len <= SOURCED_ZNN_MAX_DATA_LENGTH, f"ABI len {abi_len} exceeds 16 KiB" return tier + max(0, abi_len - 4) * SOURCED_ZNN_AB_BYTE_DATA_PLASMA # FIPS 180-4 SHA-256 single-block compression (for real coinbase midstate verification) _SHA256_IV = ( 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ) _SHA256_K = ( 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, ) def _rotr32(x: int, n: int) -> int: return ((x >> n) | ((x << (32 - n)) & 0xFFFFFFFF)) & 0xFFFFFFFF def sha256_compress(state: tuple[int, ...], block64: bytes) -> tuple[int, ...]: assert len(block64) == 64 w = list(struct.unpack(">16I", block64)) for i in range(16, 64): s0 = _rotr32(w[i - 15], 7) ^ _rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = _rotr32(w[i - 2], 17) ^ _rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10) w.append((w[i - 16] + s0 + w[i - 7] + s1) & 0xFFFFFFFF) a, b, c, d, e, f, g, h = state for i in range(64): S1 = _rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25) ch = (e & f) ^ ((~e & 0xFFFFFFFF) & g) t1 = (h + S1 + ch + _SHA256_K[i] + w[i]) & 0xFFFFFFFF S0 = _rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) t2 = (S0 + maj) & 0xFFFFFFFF h, g, f, e, d, c, b, a = g, f, e, (d + t1) & 0xFFFFFFFF, c, b, a, (t1 + t2) & 0xFFFFFFFF return tuple((s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e, f, g, h))) def complete_midstate_double_sha256(midstate_bytes: bytes, tail: bytes, total_len: int) -> tuple[bytes, int]: assert len(midstate_bytes) == 32 assert total_len >= POLICY_STAGE0_MIN_STRIPPED_TX_BYTES, ( "CVE-2017-12842: totalCoinbaseBytes must be >= 65 (64-byte leaf forbidden)" ) rem = total_len % 64 assert len(tail) == rem and len(tail) < 64 padded = bytearray(tail) padded.append(0x80) while len(padded) % 64 != 56: padded.append(0x00) padded.extend(struct.pack(">Q", total_len * 8)) blocks = len(padded) // 64 assert blocks in (1, 2) state = struct.unpack(">8I", midstate_bytes) for idx in range(blocks): state = sha256_compress(state, bytes(padded[idx * 64 : (idx + 1) * 64])) first_round = struct.pack(">8I", *state) return hashlib.sha256(first_round).digest(), blocks def compute_acyclic_vault_id( funding_txid: bytes, funding_vout: int, vault_vout: int, amount_sats: int, op_bitmask: int, ) -> bytes: """Normative R8-C01 acyclic vault_id bound strictly to already-confirmed U_dep_wallet.""" assert len(funding_txid) == 32 payload = ( b"zbtc:vault-id:v1" + funding_txid + struct.pack(">IIQQ", funding_vout, vault_vout, amount_sats, op_bitmask) ) return hashlib.sha256(payload).digest() def check_halls_marriage( vault_masks: list[int], usable_rounds_by_op: list[int], headroom_factor: float = 1.0, ) -> tuple[bool, int, int, int]: """ Exact 2^M Hall's Marriage Theorem verification (R8-C04): For every non-empty subset T of {0..M-1}: |{v in V_live : E(v) <= T}| <= floor(headroom_factor * sum_{i in T} r_i^usable) Returns (passes, failing_subset_mask, demand, supply). """ m = len(usable_rounds_by_op) assert 1 <= m <= 12 for mask in range(1, 1 << m): demand = sum(1 for vm in vault_masks if vm != 0 and (vm & ~mask) == 0) supply_raw = sum(usable_rounds_by_op[i] for i in range(m) if (mask >> i) & 1) supply = int(math.floor(headroom_factor * supply_raw)) if demand > supply: return False, mask, demand, supply return True, 0, 0, 0 def cyclic_exit_priority(exit_id: bytes, m_active: int) -> list[int]: """Normative R8-M03 collision-free cyclic priority k_r = (H(exitId) + r) mod M_active.""" assert m_active >= 1 h0 = int.from_bytes(hashlib.sha256(exit_id).digest()[:8], "big") return [(h0 + r) % m_active for r in range(m_active)] def dp_next_price( current_price: int, used_plasma: int, target_plasma: int, max_change_pct: int, denom: int, ) -> int: delta = used_plasma - target_plasma num = delta * current_price if num >= 0: change = (num // target_plasma) // denom else: change = -((-num // target_plasma) // denom) nxt = current_price + change max_nxt = (current_price * (100 + max_change_pct)) // 100 min_nxt = (current_price * (100 - max_change_pct)) // 100 if nxt > max_nxt: nxt = max_nxt if nxt < min_nxt: nxt = min_nxt if nxt < SOURCED_ZNN_MIN_RESOURCE_PRICE: nxt = SOURCED_ZNN_MIN_RESOURCE_PRICE return nxt # ============================================================================== # REAL, NON-NO-OP 2,000-STEP STAGE 1A SOLVENCY & ADVERSARIAL SIMULATION (v3.1.0-rfc) # ============================================================================== def run_stage1a_solvency_sim(seed: int = 20261128, steps: int = 2_000) -> dict[str, int]: """ Adversarial state-machine simulation of Stage 1A BitVMX (n=8, M=5, N=7) v3.1.0-rfc: - Explicit AssignedObligations (A) namespace separating fifo_assign & take_confirmed across T_take (R8-C02!) - Exact conservation: V_unassigned + V_assigned == C + L + E + R + A + B at EVERY step! - Denomination-matched AdmissionTicketUTXO Cap_TVL L1 mutual exclusion + deposit race test (R8-C03!) - Exact 2^M Hall's Marriage verification on deposit admission & operator slash (R8-C04!) - Hard-partitioned B_custody (0.55 BTC) vs B_grief (0.05 BTC) + k=20 single-block ExitSlotUTXO grief burst proving ZERO B_custody overflow & ZERO verifier payout impact (R8-H01, R8-N05!) - Signed TransferCredit residual consolidation for < 0.25 BTC credits (R8-M04!) - Explicit 0x07 RELEASE_ASSIGNMENT + Leaf 2M EXIT_CANCEL + dual-input Disprove slash + cross-operator Lamport slash - Genuine Bitcoin reorgs (popping 1..K-1 unconfirmed blocks & discarding orphaned events!) """ rng = random.Random(seed) K = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][15] # 18 blocks cap_user_sats = int(15.0 * SAT) cap_total_sats = int(18.0 * SAT) # 15.0 user + 3.0 operator B_zbtc (plus operator free_zbtc buffer) all_ops_mask = (1 << POLICY_BITVMX_M_MAX) - 1 # 0b11111 # Denomination-matched AdmissionTicketUTXO pool (R8-C03): # Genesis tickets strictly cap total live vaults <= 20.0 BTC (15 user + 5 operator initial 1.0 BTC vaults) ticket_pool = {50_000_000: 20, 25_000_000: 40} # 20*0.50 + 40*0.25 = 20.0 BTC exact L1 consensus cap! # Canonical K-deep rollup state users: dict[str, int] = { "alice": 0, "bob": 0, "mike": 0, "carol": 0, "dave": 0, "insurance_pool": 0, "challenger_bounty_pool": 0, } rollup_locks: dict[int, int] = {} # L namespace unassigned_vaults: dict[int, dict] = {} # vault_id -> {"sats", "mask"} assigned_vaults: dict[int, dict] = {} # vault_id -> {"sats", "mask", "op_id", "assigned_h"} assigned_obligations: dict[int, int] = {} # A namespace: vault_id -> sats next_vault_id = 1 operators: dict[int, dict] = {} for op_id in range(POLICY_BITVMX_M_MAX): # Each operator deposits 1.00 BTC (consuming 2 x Ticket_050) -> 0.55 B_custody + 0.05 B_grief + 0.40 free_zbtc for _ in range(2): assert ticket_pool[50_000_000] >= 1 ticket_pool[50_000_000] -= 1 unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask} next_vault_id += 1 operators[op_id] = { "b_custody": POLICY_B_CUSTODY_TOTAL_SATS, # 0.55 BTC hard-partitioned "b_grief": POLICY_B_GRIEF_TOTAL_SATS, # 0.05 BTC hard-partitioned "free_zbtc": 40_000_000, "credit": 0, "rounds_left": POLICY_BITVMX_R_ROUNDS, "suspended": False, } pending_exits: dict[int, dict] = {} next_exit_id = 1 finalized_height = 100 tip_blocks: list[dict] = [] unconf_spent_exits: set[int] = set() unconf_taken_vaults: set[int] = set() unconf_released_vaults: set[int] = set() counts: dict[str, int] = { k: 0 for k in ( "deposit", "deposit_race_blocked_by_ticket", "transfer", "forced_exit", "front_paid", "front_grief", "front_grief_burst_k20", "exit_cancel", "fifo_assign", "take_confirmed", "release_assignment", "transfer_credit", "disprove_dual_slash", "lamport_equivocation_slash", "topup_op", "mine_block", "reorg", "reorg_blocks_reverted", "reorg_events_reverted", ) } def rebuild_unconf_locks() -> None: unconf_spent_exits.clear() unconf_taken_vaults.clear() unconf_released_vaults.clear() for blk in tip_blocks: for ev in blk["events"]: kind = ev["kind"] if kind in ("front_paid", "front_grief", "exit_cancel"): unconf_spent_exits.add(ev["exit_id"]) elif kind == "front_grief_burst": for eid in ev["exit_ids"]: unconf_spent_exits.add(eid) elif kind in ("take_confirmed", "lamport_equivocation_slash"): unconf_taken_vaults.add(ev["vault_id"]) elif kind == "release_assignment": unconf_released_vaults.add(ev["vault_id"]) def run_deterministic_fifo_assign(blk_height: int) -> None: """ Deterministically moves R[op] -> A[v] and V_unassigned -> V_assigned (R8-C02), keeping V_unassigned + V_assigned == C + L + E + R + A + B invariant across T_take! """ for oid in sorted(operators.keys()): op = operators[oid] if op["rounds_left"] <= 0: continue # Assign oldest eligible vault while credit covers it while True: eligible_vids = [ vid for vid in sorted(unassigned_vaults.keys()) if ((unassigned_vaults[vid]["mask"] >> oid) & 1) and op["credit"] >= unassigned_vaults[vid]["sats"] and op["rounds_left"] > 0 ] if not eligible_vids: break vid = eligible_vids[0] vinfo = unassigned_vaults.pop(vid) vamt = vinfo["sats"] op["credit"] -= vamt assigned_vaults[vid] = { "sats": vamt, "mask": vinfo["mask"], "op_id": oid, "assigned_h": blk_height, } assigned_obligations[vid] = vamt counts["fifo_assign"] += 1 def apply_finalized_event(ev: dict, blk_height: int) -> None: kind = ev["kind"] if kind == "deposit": # Enforce L1 AdmissionTicketUTXO mutual exclusion (R8-C03) needed = {50_000_000: 0, 25_000_000: 0} for _, vamt in ev["vaults"]: needed[vamt] += 1 if ticket_pool[50_000_000] < needed[50_000_000] or ticket_pool[25_000_000] < needed[25_000_000]: # Loser deposit rejected at L1 consensus before U_dep_wallet is spent! counts["deposit_race_blocked_by_ticket"] += 1 return for denom, qty in needed.items(): ticket_pool[denom] -= qty for vid, vamt in ev["vaults"]: unassigned_vaults[vid] = {"sats": vamt, "mask": ev["mask"]} users[ev["user"]] += sum(vamt for _, vamt in ev["vaults"]) counts["deposit"] += 1 elif kind == "forced_exit": u = ev["user"] amt = ev["gross"] assert amt >= POLICY_MIN_EXIT_SATS if users[u] >= amt: users[u] -= amt pending_exits[ev["exit_id"]] = {"user": u, "gross": amt, "created_h": blk_height} counts["forced_exit"] += 1 elif kind == "front_paid": eid = ev["exit_id"] if eid in pending_exits: ex = pending_exits.pop(eid) operators[ev["op_id"]]["credit"] += ex["gross"] counts["front_paid"] += 1 run_deterministic_fifo_assign(blk_height) elif kind == "front_grief": eid = ev["exit_id"] op = operators[ev["op_id"]] if eid in pending_exits: ex = pending_exits.pop(eid) users[ex["user"]] += ex["gross"] # Hard-partitioned B_grief penalty: NEVER touches B_custody (R8-H01 / R8-N05)! pen = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"]) op["b_grief"] -= pen users[ex["user"]] += pen op["suspended"] = True assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS or op["suspended"] counts["front_grief"] += 1 elif kind == "front_grief_burst": # Concurrent k-exit grief burst in ONE Bitcoin block (R8-H01 / R8-N05 proof!) op = operators[ev["op_id"]] b_custody_before = op["b_custody"] live_eids = [eid for eid in ev["exit_ids"] if eid in pending_exits] if live_eids: per_victim = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"] // len(live_eids)) for eid in live_eids: ex = pending_exits.pop(eid) users[ex["user"]] += ex["gross"] + per_victim op["b_grief"] -= per_victim op["suspended"] = True assert op["b_custody"] == b_custody_before, "B_custody touched by ExitSlotUTXO grief burst!" assert op["b_grief"] >= 0 counts["front_grief_burst_k20"] += 1 elif kind == "exit_cancel": eid = ev["exit_id"] if eid in pending_exits and blk_height >= pending_exits[eid]["created_h"] + POLICY_T_EXIT_CANCEL: ex = pending_exits.pop(eid) users[ex["user"]] += ex["gross"] counts["exit_cancel"] += 1 elif kind == "take_confirmed": # Separate from fifo_assign! Confirms after T_take gap, retiring V_assigned & A AND recycling ticket! vid = ev["vault_id"] if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]: vinfo = assigned_vaults.pop(vid) vamt = assigned_obligations.pop(vid) assert vamt == vinfo["sats"] ticket_pool[vamt] += 1 # Recycle denomination-matched AdmissionTicketUTXO! operators[ev["op_id"]]["rounds_left"] = max(0, operators[ev["op_id"]]["rounds_left"] - 1) counts["take_confirmed"] += 1 elif kind == "release_assignment": # 0x07 RELEASE_ASSIGNMENT: V_assigned -> V_unassigned, A[v] -> R[op] vid = ev["vault_id"] if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]: vinfo = assigned_vaults.pop(vid) vamt = assigned_obligations.pop(vid) unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]} operators[ev["op_id"]]["credit"] += vamt counts["release_assignment"] += 1 elif kind == "transfer_credit": src, dst, amt = ev["from_op"], ev["to_op"], ev["amount"] if operators[src]["credit"] >= amt: operators[src]["credit"] -= amt operators[dst]["credit"] += amt counts["transfer_credit"] += 1 run_deterministic_fifo_assign(blk_height) elif kind == "disprove_dual_slash": # Dual-input Disprove spends Stake_r + VaultConnector_r -> 0 BTC leaves vault! # Native L1 verifier bounties paid from Stake_r; L2 B_custody slashed to insurance_pool. op = operators[ev["op_id"]] if op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS: # If any vault was assigned to this op's challenged round, return V_assigned -> V_unassigned & A -> R for vid in [v for v, info in assigned_vaults.items() if info["op_id"] == ev["op_id"]][:1]: vinfo = assigned_vaults.pop(vid) vamt = assigned_obligations.pop(vid) unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]} op["credit"] += vamt op["b_custody"] -= POLICY_B_CUSTODY_TOTAL_SATS users["insurance_pool"] += POLICY_B_CUSTODY_TOTAL_SATS op["suspended"] = True counts["disprove_dual_slash"] += 1 elif kind == "lamport_equivocation_slash": # Rogue operator stole vault v (either unassigned OR assigned to innocent O_k!) vid = ev["vault_id"] op = operators[ev["op_id"]] if vid in unassigned_vaults: vamt = unassigned_vaults[vid]["sats"] if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS: unassigned_vaults.pop(vid) ticket_pool[vamt] += 1 op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS) users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS op["suspended"] = True counts["lamport_equivocation_slash"] += 1 elif vid in assigned_vaults: vinfo = assigned_vaults[vid] vamt = vinfo["sats"] if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS: assigned_vaults.pop(vid) assigned_obligations.pop(vid) ticket_pool[vamt] += 1 # Restore innocent assignee O_k 100% whole via R[O_k] += vamt! operators[vinfo["op_id"]]["credit"] += vamt op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS) users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS op["suspended"] = True counts["lamport_equivocation_slash"] += 1 def assert_solvency(label: str) -> None: v_unassigned = sum(v["sats"] for v in unassigned_vaults.values()) v_assigned = sum(v["sats"] for v in assigned_vaults.values()) lhs = v_unassigned + v_assigned c_total = sum(users.values()) + sum(op["free_zbtc"] for op in operators.values()) l_total = sum(rollup_locks.values()) e_total = sum(ex["gross"] for ex in pending_exits.values()) r_total = sum(op["credit"] for op in operators.values()) a_total = sum(assigned_obligations.values()) b_total = sum(op["b_custody"] + op["b_grief"] for op in operators.values()) rhs = c_total + l_total + e_total + r_total + a_total + b_total assert lhs == rhs, f"[{label}] Conservation mismatch! V={lhs} != C+L+E+R+A+B={rhs}" assert v_assigned == a_total, f"[{label}] V_assigned={v_assigned} != A={a_total}" # Ticket + live vault conservation: total minted tickets == 20*0.50 + 40*0.25 = 20.0 BTC ALWAYS! ticket_value = ticket_pool[50_000_000] * 50_000_000 + ticket_pool[25_000_000] * 25_000_000 assert lhs + ticket_value == 20 * SAT, f"[{label}] Ticket conservation broken: {lhs} + {ticket_value}" for oid, op in operators.items(): assert op["b_custody"] >= 0 and op["b_grief"] >= 0 if not op["suspended"]: assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS assert op["b_grief"] == POLICY_B_GRIEF_TOTAL_SATS def mine_one_block(events: list[dict]) -> None: nonlocal finalized_height next_h = finalized_height + len(tip_blocks) + 1 tip_blocks.append({"height": next_h, "events": events}) counts["mine_block"] += 1 while len(tip_blocks) >= K: fin_blk = tip_blocks.pop(0) finalized_height = fin_blk["height"] for ev in fin_blk["events"]: apply_finalized_event(ev, finalized_height) rebuild_unconf_locks() def current_tip_height() -> int: return finalized_height + len(tip_blocks) assert_solvency("init") # ------------------------------------------------------------------ # 1. DETERMINISTIC BOB & MIKE TRACES WITH EXPLICIT T_take GAP (A > 0!) # ------------------------------------------------------------------ bob_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] next_vault_id += 3 alice_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] next_vault_id += 3 mine_one_block([ {"kind": "deposit", "user": "bob", "vaults": bob_vaults, "mask": all_ops_mask}, {"kind": "deposit", "user": "alice", "vaults": alice_vaults, "mask": all_ops_mask}, ]) for _ in range(K - 1): mine_one_block([]) assert users["bob"] == SAT and users["alice"] == SAT assert_solvency("after_bob_alice_deposits") # Bob spends 0.50 zBTC to Carol, exits 0.50 BTC -> FIFO assigns (A = 0.50 BTC!) -> TakeTx confirms later! users["bob"] -= 50_000_000 users["carol"] += 50_000_000 counts["transfer"] += 1 bob_eid = next_exit_id next_exit_id += 1 mine_one_block([{"kind": "forced_exit", "user": "bob", "gross": 50_000_000, "exit_id": bob_eid}]) for _ in range(K - 1): mine_one_block([]) mine_one_block([{"kind": "front_paid", "exit_id": bob_eid, "op_id": 0}]) for _ in range(K - 1): mine_one_block([]) # Verify R8-C02: during the T_take gap, A == 0.50 BTC > 0 AND V == C+L+E+R+A+B holds! assert sum(assigned_obligations.values()) == 50_000_000 assert_solvency("bob_mid_T_take_gap_A_nonzero") assigned_bob_vid = next(iter(assigned_vaults.keys())) mine_one_block([{"kind": "take_confirmed", "op_id": 0, "vault_id": assigned_bob_vid}]) for _ in range(K - 1): mine_one_block([]) assert sum(assigned_obligations.values()) == 0 assert_solvency("after_bob_0.5_take_confirmed") # Mike scenario (Alice 1 + Bob2 1 -> Mike 2 -> Mike exits 0.25 BTC) bob2_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] next_vault_id += 3 mine_one_block([{"kind": "deposit", "user": "bob", "vaults": bob2_vaults, "mask": all_ops_mask}]) for _ in range(K - 1): mine_one_block([]) users["alice"] -= SAT users["bob"] -= SAT users["mike"] += 2 * SAT counts["transfer"] += 2 mike_eid = next_exit_id next_exit_id += 1 mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 25_000_000, "exit_id": mike_eid}]) for _ in range(K - 1): mine_one_block([]) mine_one_block([{"kind": "front_paid", "exit_id": mike_eid, "op_id": 1}]) for _ in range(K - 1): mine_one_block([]) assert sum(assigned_obligations.values()) == 25_000_000 assert_solvency("mike_mid_T_take_gap_A_nonzero") assigned_mike_vid = next(iter(assigned_vaults.keys())) mine_one_block([{"kind": "take_confirmed", "op_id": 1, "vault_id": assigned_mike_vid}]) for _ in range(K - 1): mine_one_block([]) assert users["mike"] == 175_000_000 and sum(assigned_obligations.values()) == 0 assert_solvency("after_mike_0.25_take_confirmed") # ------------------------------------------------------------------ # 2. DETERMINISTIC R8-H01 / R8-N05 k=20 CONCURRENT GRIEF BURST TEST # ------------------------------------------------------------------ burst_eids = [] for _ in range(20): eid = next_exit_id next_exit_id += 1 burst_eids.append(eid) mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 5_000_000, "exit_id": eid}]) for _ in range(K): mine_one_block([]) b_cust_before = operators[2]["b_custody"] mine_one_block([{"kind": "front_grief_burst", "op_id": 2, "exit_ids": burst_eids}]) for _ in range(K): mine_one_block([]) assert operators[2]["b_custody"] == b_cust_before == POLICY_B_CUSTODY_TOTAL_SATS assert operators[2]["b_grief"] == 0 and operators[2]["suspended"] assert_solvency("after_k20_grief_burst") # ------------------------------------------------------------------ # 3. DETERMINISTIC R8-M04 TRANSFER_CREDIT RESIDUAL CONSOLIDATION TEST # ------------------------------------------------------------------ # Give ops 3 & 4 each 0.15 BTC (< 0.25 BTC min vault), then consolidate via TransferCredit -> triggers FIFO assign! e_res1, e_res2 = next_exit_id, next_exit_id + 1 next_exit_id += 2 mine_one_block([ {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res1}, {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res2}, ]) for _ in range(K): mine_one_block([]) mine_one_block([ {"kind": "front_paid", "exit_id": e_res1, "op_id": 3}, {"kind": "front_paid", "exit_id": e_res2, "op_id": 4}, ]) for _ in range(K): mine_one_block([]) assert operators[3]["credit"] == 15_000_000 and operators[4]["credit"] == 15_000_000 mine_one_block([{"kind": "transfer_credit", "from_op": 3, "to_op": 4, "amount": 15_000_000}]) for _ in range(K): mine_one_block([]) assert operators[3]["credit"] == 0 and operators[4]["credit"] == 5_000_000 # 0.30 -> assigned 0.25 vault, 0.05 left! assert_solvency("after_transfer_credit") # ------------------------------------------------------------------ # 4. 2,000-STEP ADVERSARIAL RANDOMIZED SIMULATION (WITH REAL REORGS!) # ------------------------------------------------------------------ actions = [ "deposit", "transfer", "forced_exit", "front_paid", "front_grief", "exit_cancel", "take_confirmed", "release_assignment", "transfer_credit", "disprove_dual_slash", "lamport_equivocation_slash", "topup_op", "mine_block", "reorg", ] weights = [12, 16, 12, 12, 5, 6, 12, 5, 5, 4, 4, 10, 24, 10] normal_users = ["alice", "bob", "mike", "carol", "dave"] for step in range(steps): act = rng.choices(actions, weights=weights, k=1)[0] if act == "deposit": # Deliberately allow attempting deposits even near cap to exercise ticket mutual-exclusion rejection! u = rng.choice(normal_users) new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] next_vault_id += 3 mine_one_block([{"kind": "deposit", "user": u, "vaults": new_vs, "mask": all_ops_mask}]) elif act == "transfer": rich = [u for u in normal_users if users[u] >= POLICY_MIN_EXIT_SATS] if rich: src = rng.choice(rich) dst = rng.choice([u for u in normal_users if u != src]) amt = rng.randint(POLICY_MIN_EXIT_SATS, min(users[src], 50_000_000)) users[src] -= amt users[dst] += amt counts["transfer"] += 1 elif act == "forced_exit": rich = [u for u in normal_users if users[u] >= 10_000_000] if rich: u = rng.choice(rich) choices = [10_000_000, 25_000_000, 50_000_000] valid = [c for c in choices if users[u] >= c] amt = rng.choice(valid) eid = next_exit_id next_exit_id += 1 mine_one_block([{"kind": "forced_exit", "user": u, "gross": amt, "exit_id": eid}]) elif act == "front_paid": open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] active_ops = [oid for oid, op in operators.items() if not op["suspended"]] if open_exits and active_ops: eid = rng.choice(open_exits) oid = rng.choice(active_ops) unconf_spent_exits.add(eid) mine_one_block([{"kind": "front_paid", "exit_id": eid, "op_id": oid}]) elif act == "front_grief": open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] active_ops = [oid for oid, op in operators.items() if not op["suspended"] and op["b_grief"] > 0] if open_exits and active_ops: eid = rng.choice(open_exits) oid = rng.choice(active_ops) unconf_spent_exits.add(eid) mine_one_block([{"kind": "front_grief", "exit_id": eid, "op_id": oid}]) elif act == "exit_cancel": cur_h = current_tip_height() expired = [ eid for eid, ex in pending_exits.items() if eid not in unconf_spent_exits and cur_h >= ex["created_h"] + POLICY_T_EXIT_CANCEL ] if expired: eid = rng.choice(expired) unconf_spent_exits.add(eid) mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) elif act == "take_confirmed": ready = [ (vid, info["op_id"]) for vid, info in assigned_vaults.items() if vid not in unconf_taken_vaults and vid not in unconf_released_vaults ] if ready: vid, oid = rng.choice(ready) unconf_taken_vaults.add(vid) mine_one_block([{"kind": "take_confirmed", "op_id": oid, "vault_id": vid}]) elif act == "release_assignment": ready = [ (vid, info["op_id"]) for vid, info in assigned_vaults.items() if vid not in unconf_taken_vaults and vid not in unconf_released_vaults ] if ready: vid, oid = rng.choice(ready) unconf_released_vaults.add(vid) mine_one_block([{"kind": "release_assignment", "op_id": oid, "vault_id": vid}]) elif act == "transfer_credit": donors = [oid for oid, op in operators.items() if 0 < op["credit"] < 25_000_000] if donors: src = rng.choice(donors) dst = rng.choice([i for i in operators if i != src]) mine_one_block([{"kind": "transfer_credit", "from_op": src, "to_op": dst, "amount": operators[src]["credit"]}]) elif act == "disprove_dual_slash": active_ops = [oid for oid, op in operators.items() if not op["suspended"]] if active_ops: oid = rng.choice(active_ops) mine_one_block([{"kind": "disprove_dual_slash", "op_id": oid}]) elif act == "lamport_equivocation_slash": all_vids = [ vid for vid in list(unassigned_vaults.keys()) + list(assigned_vaults.keys()) if vid not in unconf_taken_vaults ] active_ops = [ oid for oid, op in operators.items() if not op["suspended"] and op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS ] if all_vids and active_ops: oid = rng.choice(active_ops) vid = rng.choice(all_vids) unconf_taken_vaults.add(vid) mine_one_block([{"kind": "lamport_equivocation_slash", "op_id": oid, "vault_id": vid}]) elif act == "topup_op": susp = [oid for oid, op in operators.items() if op["suspended"]] if susp: oid = rng.choice(susp) op = operators[oid] need_c = max(0, POLICY_B_CUSTODY_TOTAL_SATS - op["b_custody"]) need_g = max(0, POLICY_B_GRIEF_TOTAL_SATS - op["b_grief"]) needed = need_c + need_g if op["free_zbtc"] >= needed: op["free_zbtc"] -= needed op["b_custody"] += need_c op["b_grief"] += need_g op["suspended"] = False counts["topup_op"] += 1 elif ticket_pool[50_000_000] >= 2: ticket_pool[50_000_000] -= 2 for _ in range(2): unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask} next_vault_id += 1 op["free_zbtc"] += SAT - needed op["b_custody"] += need_c op["b_grief"] += need_g op["suspended"] = False counts["topup_op"] += 1 elif act == "mine_block": mine_one_block([]) elif act == "reorg": if tip_blocks: depth = rng.randint(1, min(K - 1, len(tip_blocks))) orphaned = tip_blocks[-depth:] del tip_blocks[-depth:] ev_reverted = sum(len(b["events"]) for b in orphaned) counts["reorg"] += 1 counts["reorg_blocks_reverted"] += depth counts["reorg_events_reverted"] += ev_reverted rebuild_unconf_locks() for _ in range(depth): mine_one_block([]) assert_solvency(f"step_{step}_{act}") # Guarantee EXIT_CANCEL path is exercised if random steps didn't hit a 288-block idle exit if counts["exit_cancel"] == 0: u = next((u for u in normal_users if users[u] >= 25_000_000), "insurance_pool") eid = next_exit_id next_exit_id += 1 mine_one_block([{"kind": "forced_exit", "user": u, "gross": 25_000_000, "exit_id": eid}]) for _ in range(K + POLICY_T_EXIT_CANCEL): mine_one_block([]) mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) for _ in range(K): mine_one_block([]) assert_solvency("post_exit_cancel") # Guarantee ticket-cap deposit-race rejection was exercised if counts["deposit_race_blocked_by_ticket"] == 0: # Attempt a massive burst of deposits past the remaining ticket cap for _ in range(25): new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] next_vault_id += 3 mine_one_block([{"kind": "deposit", "user": "alice", "vaults": new_vs, "mask": all_ops_mask}]) for _ in range(K): mine_one_block([]) assert_solvency("post_ticket_race") # Flush remaining tip blocks to K-deep finality for _ in range(K): mine_one_block([]) assert_solvency("final") return counts # ============================================================================== # MAIN ASSERTION SUITE # ============================================================================== def main() -> None: print("================================================================================") print("zBTC v2 (v3.1.0-rfc — R8 HARDENED) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER") print("Note: Pure Python 3 stdlib. Checks internal consistency against SOURCED_,") print(" POLICY_, and PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark.") print("================================================================================") # -------------------------------------------------------------------------- # 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK PADDING & >= 65 B FILTER (R8-M06) # -------------------------------------------------------------------------- print("\n=== 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING & >= 65 B FILTER ===") one_blk_count, two_blk_count = 0, 0 for rem in range(64): total_len = 128 + rem cb_bytes = bytes((i * 37 + rem) & 0xFF for i in range(total_len)) st = sha256_compress(sha256_compress(_SHA256_IV, cb_bytes[0:64]), cb_bytes[64:128]) midstate = struct.pack(">8I", *st) got_txid, final_blks = complete_midstate_double_sha256(midstate, cb_bytes[128:], total_len) assert got_txid == hashlib.sha256(hashlib.sha256(cb_bytes).digest()).digest() if rem < 56: assert final_blks == 1 one_blk_count += 1 else: assert final_blks == 2 two_blk_count += 1 assert one_blk_count == 56 and two_blk_count == 8 for bad_len in (0, 32, 63, 64): try: complete_midstate_double_sha256(b"\x00" * 32, b"\x00" * (bad_len % 64), bad_len) raise AssertionError(f"Length {bad_len} must be rejected!") except AssertionError as e: assert "CVE-2017-12842" in str(e) print( f" Verified 64/64 remainders vs hashlib double-SHA256 ({one_blk_count} 1-blk, {two_blk_count} 2-blk = 12.5%); " f"all len <= 64 rejected (min strippedTx = {POLICY_STAGE0_MIN_STRIPPED_TX_BYTES} B)." ) # -------------------------------------------------------------------------- # 2. STAGE 0: go-zenon THROUGHPUT, SPV ORACLE & BITCOIN L1 0x02 DA CEILING (R8-M08) # -------------------------------------------------------------------------- print("\n=== 2. STAGE 0: go-zenon PLASMA / 8 MiB CEILING vs BITCOIN L1 0x02 DA CAP ===") rollup_tx_plasma = SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA + PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES * SOURCED_ZNN_AB_BYTE_DATA_PLASMA assert rollup_tx_plasma == 28_480 assert ceil_div(rollup_tx_plasma, SOURCED_ZNN_PLASMA_PER_QSR) == 14 tps_floor_2blk = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS tps_default_2blk = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS rollup_tps_floor_114 = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS rollup_tps_default_114 = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS rollup_tps_floor_10s = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / 10.0 real_tps_low = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS real_tps_high = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS assert 4.3 < tps_floor_2blk < 4.5 and 8.7 < tps_default_2blk < 8.9 assert 6.3 < rollup_tps_floor_114 < 6.6 and 12.8 < rollup_tps_default_114 < 13.1 assert 7.36 < rollup_tps_floor_10s < 7.38 assert 1_000 < real_tps_low < 1_100 and 1_200 < real_tps_high < 1_260 # Bitcoin L1 physical 0x02 mutated-leaf DA ceilings (R8-M08) btc_max_vb_per_sec = (SOURCED_BTC_MAX_BLOCK_WEIGHT / 4.0) / SOURCED_BTC_TARGET_BLOCK_SECS # 1,666.67 vB/s da_blended_10vb_100pct = btc_max_vb_per_sec / 10.0 # 166.67 leaves/s @ 100% Bitcoin blockspace da_existing_4vb_100pct = btc_max_vb_per_sec / 4.0 # 416.67 existing 16B leaves/s @ 100% da_new_12vb_100pct = btc_max_vb_per_sec / 12.0 # 138.89 new 48B leaves/s @ 100% da_epoch_new_leaf_cap_per_sec = POLICY_MAX_NEW_LEAVES_PER_EPOCH / (6.0 * SOURCED_BTC_TARGET_BLOCK_SECS) assert abs(da_blended_10vb_100pct - 166.6666667) < 1e-4 assert abs(da_existing_4vb_100pct - 416.6666667) < 1e-4 assert da_epoch_new_leaf_cap_per_sec < 0.30 # Stage 0 SPV Oracle ABI + Dynamic Plasma 5-param pinning prove_payload = 8 + 4 + 4 + 32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES + 16 * 32 + 63 + 16 * 32 prove_abi = (4 + 8 * 32) + (32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES) + (32 + 16 * 32) + (32 + 64) + (32 + 16 * 32) assert prove_payload == 7_279 and prove_abi == 7_620 prove_plasma = abi_embedded_plasma(SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER, prove_abi) assert prove_plasma == 591_388 and POLICY_PINNED_MAX_BASE_PLASMA_FLOOR >= 3 * prove_plasma assert POLICY_PINNED_MAX_BASE_PLASMA_FLOOR // SOURCED_ZNN_EMBEDDED_SIMPLE_TIER == 40 price_unpinned, price_pinned = SOURCED_ZNN_MIN_RESOURCE_PRICE, SOURCED_ZNN_MIN_RESOURCE_PRICE pinned_target = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR * POLICY_PINNED_MIN_TARGET_SHARE_PCT) // 100 assert pinned_target == 525_000 for _ in range(52): price_unpinned = dp_next_price(price_unpinned, 21_000, 1, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, 1) price_pinned = dp_next_price(price_pinned, 21_000, pinned_target, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, POLICY_PINNED_MIN_PRICE_DENOM) assert price_unpinned / 1_000 > 100_000 and price_pinned == 1_000 print( f" Zenon @ 11.4s: 2-blk={tps_floor_2blk:.1f}/{tps_default_2blk:.1f} tx/s | " f"1-blk rollup={rollup_tps_floor_114:.1f}/{rollup_tps_default_114:.1f} tx/s ({rollup_tps_floor_10s:.2f} @ 10s) | " f"8 MiB cap={real_tps_low:,.0f}-{real_tps_high:,.0f} tx/s" ) print( f" Bitcoin L1 0x02 DA cap @ 100% blockspace: blended(10vB)={da_blended_10vb_100pct:.1f} leaves/s " f"(1%={da_blended_10vb_100pct/100:.2f}/s) | existing(4vB)={da_existing_4vb_100pct:.1f}/s | " f"new(12vB)={da_new_12vb_100pct:.1f}/s | spam cap={POLICY_MAX_NEW_LEAVES_PER_EPOCH}/6-blk ({da_epoch_new_leaf_cap_per_sec:.2f}/s, {POLICY_NEW_LEAF_DEPOSIT_SATS}-sat deposit)" ) # -------------------------------------------------------------------------- # 3. STAGE 0: EXACT ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) (R8-H07) # -------------------------------------------------------------------------- print("\n=== 3. STAGE 0: EXACT STDLIB ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) ===") mean_1x = SOURCED_BTC_TARGET_BLOCK_SECS mean_2p3x = SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT # 1,380 s/blk # Regression-verify R8-H07's exact failure probabilities on old v3.0.0 values: old_ptlc_fail = erlang_survival_prob(72, 30 * 3600, mean_2p3x) old_ln_fail = erlang_survival_prob(36, 6 * 3600, mean_1x) assert abs(old_ptlc_fail - 0.2234) < 0.002, f"Expected ~22.34%, got {old_ptlc_fail:.4%}" assert abs(old_ln_fail - 0.4778) < 0.002, f"Expected ~47.78%, got {old_ln_fail:.4%}" # Verify hardened v3.1.0-rfc margins: new_ptlc_fail = erlang_survival_prob(POLICY_PTLC_BTC_CSV_BLOCKS, POLICY_PTLC_ZNN_DURATION_SECS, mean_2p3x) ptlc_p999_h = erlang_quantile_hours(POLICY_PTLC_BTC_CSV_BLOCKS, 0.999, mean_2p3x) new_ln_fail_2p3x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_2p3x) new_ln_fail_1x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_1x) ln_p999_h = erlang_quantile_hours(POLICY_LN_DELTA_SAFETY_BLOCKS, 0.999, mean_2p3x) assert new_ptlc_fail < 1e-6 and ptlc_p999_h < 39.0 assert new_ln_fail_2p3x < 2e-4 and new_ln_fail_1x < 1e-18 and ln_p999_h < 22.5 print( f" PTLC (72 blks @ 2.3x): old 30h fail={old_ptlc_fail:.2%} -> NEW 48h fail={new_ptlc_fail:.2e} " f"(p99.9={ptlc_p999_h:.2f}h, margin={48.0 - ptlc_p999_h:.2f}h; block-72 RBF watchtower)" ) print( f" LN Outbound (36 blks): old 6h@1x fail={old_ln_fail:.2%} -> NEW 24h@2.3x fail={new_ln_fail_2p3x:.2e} " f"(p99.9={ln_p999_h:.2f}h, @1x fail={new_ln_fail_1x:.2e})" ) # -------------------------------------------------------------------------- # 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL ACCOUNTING (R8-M09, R8-H02) # -------------------------------------------------------------------------- print("\n=== 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL (LOCKED vs OPERATIONAL vs MULTI-DISPUTE) ===") bitvm2_m3_low = 3 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW bitvm2_m5_high = 5 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH assert bitvm2_m3_low > SOURCED_ZNN_MCAP_BTC_HIGH verifier_standby_btc = (POLICY_BITVMX_N_VERIFIERS * POLICY_F_CHAL_SATS) / SAT verifier_cpfp_res_btc = POLICY_BITVMX_N_VERIFIERS * POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC assert abs(verifier_standby_btc - 2.80) < 1e-9 and abs(verifier_cpfp_res_btc - 0.70) < 1e-9 for label, prof in POLICY_STAGE1A_PROFILES.items(): m = prof["M"] bonds_btc = (m * POLICY_BITVMX_L_LANES * POLICY_LANE_TOTAL_BOND_SATS) / SAT locked_btc = bonds_btc + prof["float_btc"] + verifier_standby_btc op_reserves = verifier_cpfp_res_btc + POLICY_OP_RESERVE_DA_BATCHER_BTC + m * POLICY_OP_RESERVE_TOPUP_PER_OP_BTC op_baseline = locked_btc + op_reserves per_verifier_m_disputes = m * ((POLICY_F_CHAL_SATS / SAT) + 0.08265) pct_low = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_HIGH pct_high = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_LOW if m == 3: assert abs(locked_btc - 12.80) < 1e-9 and abs(op_baseline - 14.75) < 1e-9 if m == 5: assert abs(locked_btc - 18.80) < 1e-9 and abs(op_baseline - 21.25) < 1e-9 print( f" {label:28s}: locked={locked_btc:5.2f} + op_res={op_reserves:4.2f} = {op_baseline:5.2f} BTC " f"({pct_low:.1f}%-{pct_high:.1f}% ZNN mcap) | M-dispute/honest-V={per_verifier_m_disputes:.2f} BTC" ) print(f" BitVM2 bonds-only contrast (M=3..5): {bitvm2_m3_low:.2f}-{bitvm2_m5_high:.3f} BTC | Core floor >= {SOURCED_BTC_CORE_MIN_VERSION_P2A_ZERO}") # -------------------------------------------------------------------------- # 5. STAGE 1A: BitVMX n=8 BISECTION, 10x153 vB CPFP & TRUC v3 (R8-H04/H05) # -------------------------------------------------------------------------- print("\n=== 5. STAGE 1A: BitVMX-CPU n=8 WRAPPED-SNARK VERIFIER & P2A CPFP TRUC v3 ===") digits_per_prover_tx = (POLICY_BITVMX_N_BRANCH - 1) * (40 + 3) assert digits_per_prover_tx == 301 prover_step_vb = math.ceil(digits_per_prover_tx * PRE_MAINNET_TARGET_WOTS_DIGIT_WU) / 4.0 + PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB assert abs(prover_step_vb - 7_436.5) < 1e-9 assert prover_step_vb <= SOURCED_BIP431_TRUC_MAX_VB assert prover_step_vb > SOURCED_BIP431_TRUC_CHILD_MAX_VB # Confirms zero unconfirmed TRUC child chaining! cpfp_side_vb = PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE * SOURCED_P2A_CPFP_CHILD_VB assert cpfp_side_vb == 1_530 and SOURCED_P2A_CPFP_CHILD_VB <= SOURCED_BIP431_TRUC_CHILD_MAX_VB prover_total_with_cpfp_vb = PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB + cpfp_side_vb # 76,530 vB verifier_total_with_cpfp_vb = PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB + cpfp_side_vb # 16,530 vB assert prover_total_with_cpfp_vb == 76_530 and verifier_total_with_cpfp_vb == 16_530 prover_fee_500 = prover_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB prover_breakeven = POLICY_F_CHAL_SATS // prover_total_with_cpfp_vb verifier_fee_500 = verifier_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB verifier_fee_750 = verifier_total_with_cpfp_vb * POLICY_STRESS_SUSTAINED_FEE_SATVB assert prover_fee_500 == 38_265_000 <= POLICY_F_CHAL_SATS and prover_breakeven == 522 assert verifier_fee_500 == 8_265_000 and verifier_fee_750 == 12_397_500 seq_steps = 1 + 2 * POLICY_BITVMX_SEARCH_ROUNDS + 1 assert seq_steps == 20 and POLICY_BITVMX_N_BRANCH ** POLICY_BITVMX_SEARCH_ROUNDS == 134_217_728 print( f" Prover step={prover_step_vb:,.1f} vB <= 10k TRUC parent (>1k child -> confirmed parents only!) | " f"Prover w/ 10x153 CPFP={prover_total_with_cpfp_vb:,} vB ({prover_fee_500/SAT:.5f} BTC <= 0.40, BE={prover_breakeven} sat/vB)" ) print( f" Verifier w/ 10x153 CPFP={verifier_total_with_cpfp_vb:,} vB: @500={verifier_fee_500/SAT:.5f} BTC, @750={verifier_fee_750/SAT:.5f} BTC" ) # -------------------------------------------------------------------------- # 6. STAGE 1A: WIDENED TIMELOCKS & ACYCLIC vault_id LAMPORT TakeTx (R8-C01) # -------------------------------------------------------------------------- print("\n=== 6. STAGE 1A: WIDENED TIMELOCKS (T_step=72) & ACYCLIC vault_id LAMPORT TakeTx ===") max_dispute_end = POLICY_T_CHAL_WINDOW + seq_steps * POLICY_T_STEP assert max_dispute_end == 1_584 assert POLICY_T_TAKE == 1_728 and POLICY_T_TAKE - max_dispute_end == 144 assert POLICY_T_COOLDOWN == 1_872 and POLICY_T_COOLDOWN - POLICY_T_TAKE == 144 assert POLICY_T_RETIRE == 2_016 and POLICY_T_RETIRE - POLICY_T_COOLDOWN == 144 # Acyclic vault_id determinism & uniqueness across distinct vouts of same confirmed U_dep_wallet: funding_txid = hashlib.sha256(b"confirmed_U_dep_wallet_txid").digest() vid_0 = compute_acyclic_vault_id(funding_txid, 0, 0, 50_000_000, 0b11111) vid_1 = compute_acyclic_vault_id(funding_txid, 0, 1, 25_000_000, 0b11111) vid_2 = compute_acyclic_vault_id(funding_txid, 0, 2, 25_000_000, 0b11111) assert len({vid_0, vid_1, vid_2}) == 3 and all(len(v) == 32 for v in (vid_0, vid_1, vid_2)) # Exact Lamport TakeTx size INCLUDING recycled AdmissionTicketUTXO at vout[1]! lamport_script_bytes = 256 * 23 + 34 # 5,922 B lamport_preimages_bytes = 256 * 21 # 5,376 B cb_stage1a, cb_stage2 = 1 + 32 + 32 * 9, 1 + 32 + 32 * 12 # 321 / 417 B assert lamport_script_bytes == 5_922 and lamport_preimages_bytes == 5_376 and cb_stage1a == 321 and cb_stage2 == 417 # Non-witness: 10 + 2*41 (U_d + VaultConnector) + 43 (P_Op) + 43 (recycled Ticket) + 13 (P2A) = 191 B take_non_wit = 10 + 2 * 41 + 43 + 43 + 13 take_wit_s1 = compact_size_len(259) + 65 + lamport_preimages_bytes + compact_size_len(lamport_script_bytes) + lamport_script_bytes + compact_size_len(cb_stage1a) + cb_stage1a + 110 take_wit_s2 = compact_size_len(259) + 65 + lamport_preimages_bytes + compact_size_len(lamport_script_bytes) + lamport_script_bytes + compact_size_len(cb_stage2) + cb_stage2 + 110 take_vb_s1 = (take_non_wit * 4 + take_wit_s1) / 4.0 take_vb_s2 = (take_non_wit * 4 + take_wit_s2) / 4.0 assert take_vb_s1 <= 3_200 and take_vb_s2 <= 3_200 <= SOURCED_BIP431_TRUC_MAX_VB assert take_vb_s1 > SOURCED_BIP431_TRUC_CHILD_MAX_VB # Confirmed VaultConnector_r only! print( f" Timelocks: [0,{POLICY_T_CHAL_WINDOW}] -> max_dispute={max_dispute_end} < T_take={POLICY_T_TAKE} (12d) " f"< T_cool={POLICY_T_COOLDOWN} (13d) < Retire={POLICY_T_RETIRE} (14d)" ) print( f" Acyclic vault_id Lamport TakeTx (w/ recycled Ticket): depth9={take_vb_s1:,.2f} vB / depth12={take_vb_s2:,.2f} vB " f"(<=3,200 <=10,000 TRUC parent; peak_stack=258 < 1,000)" ) # -------------------------------------------------------------------------- # 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (R8-H02, R8-N05 CLOSED!) # -------------------------------------------------------------------------- print("\n=== 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (0% zBTC CRISIS DISCOUNT) ===") assert POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS + POLICY_MIN_L1_STAKE_BURN_SATS == POLICY_BOND_BTC_SATS assert POLICY_MIN_L1_STAKE_BURN_SATS == 95_000_000 # 0.95 BTC min burn! # Native L1 payout = 0.15 BTC -> 0% haircut even at 30% (or 100%) zBTC crisis discount! ev_500 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_500 - POLICY_VERIFIER_LOCKUP_COST_SATS ev_750 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_750 - POLICY_VERIFIER_LOCKUP_COST_SATS verifier_breakeven_satvb = (POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - POLICY_VERIFIER_LOCKUP_COST_SATS) // verifier_total_with_cpfp_vb assert ev_500 == 6_450_000 > 0 # +0.06450 BTC @ 500 sat/vB! assert ev_750 == 2_317_500 > 0 # +0.023175 BTC @ 750 sat/vB! assert verifier_breakeven_satvb == 890 for k_collude in range(POLICY_BITVMX_N_VERIFIERS): honest_n = POLICY_BITVMX_N_VERIFIERS - k_collude l1_recapture = k_collude * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS l1_only_pnl = -POLICY_BOND_BTC_SATS + l1_recapture # -2.00 to -1.10 BTC on L1 ALONE! total_pnl = l1_only_pnl - POLICY_B_CUSTODY_TOTAL_SATS assert l1_only_pnl <= -110_000_000 and total_pnl <= -165_000_000 if k_collude == 0: assert l1_only_pnl == -200_000_000 and total_pnl == -255_000_000 if k_collude == 6: assert l1_only_pnl == -110_000_000 and total_pnl == -165_000_000 print( f" k_collude={k_collude} (honest={honest_n}): L1_payout=0.1500 BTC (0% zBTC discount!) | " f"EV@500={ev_500/SAT:+.5f}, EV@750={ev_750/SAT:+.5f} (BE={verifier_breakeven_satvb} sat/vB) | " f"Cartel L1={l1_only_pnl/SAT:+.2f} / Tot={total_pnl/SAT:+.2f} BTC" ) # -------------------------------------------------------------------------- # 8. STAGE 1A: EXACT 2^M HALL'S MARRIAGE & CYCLIC PRIORITY (R8-C04, R8-M03) # -------------------------------------------------------------------------- print("\n=== 8. STAGE 1A: 2^M HALL'S MARRIAGE CHECKER & CYCLIC EXIT PRIORITY ===") # Demonstrate R8-C04 stranding counterexample: global cap passes (30 <= 0.5 * 220 = 110), # yet 30 vaults with opBitmask={0,1} (0b00011) exceed O_0+O_1 remaining rounds (10+10=20)! counterex_vaults = [0b00011] * 30 counterex_rounds = [10, 10, 64, 64, 64] assert len(counterex_vaults) <= 0.50 * sum(counterex_rounds) # Global scalar check falsely passed! ok_bad, bad_mask, bad_dem, bad_sup = check_halls_marriage(counterex_vaults, counterex_rounds, headroom_factor=1.0) assert not ok_bad and bad_mask == 0b00011 and bad_dem == 30 and bad_sup == 20 # Valid Stage 1A uniform full-committee cohort passes even at 0.50 headroom: ok_good, _, _, _ = check_halls_marriage([0b11111] * 45, [64] * 5, headroom_factor=0.50) assert ok_good # Verify R8-M03 cyclic permutation has 0% collisions across 1,000 random exitIds for M=3..20: for m_act in (3, 5, 10, 20): for i in range(200): perm = cyclic_exit_priority(f"exit_{m_act}_{i}".encode(), m_act) assert len(perm) == m_act and len(set(perm)) == m_act print( f" Hall's 2^M counterexample CAUGHT (subset 0b{bad_mask:05b}: demand={bad_dem} > supply={bad_sup}, " f"despite global 30 <= 110); uniform 45-vault M=5 cohort PASSES at 0.50 headroom." ) print(" Cyclic priority k_r = (H(exitId) + r) mod M_active: 0.0% collisions verified across 800 tests (M=3,5,10,20).") # -------------------------------------------------------------------------- # 9. STAGE 1A: MULTI-TIER BANK-RUN DURATION (T_cooldown = 13.0d) # -------------------------------------------------------------------------- print("\n=== 9. STAGE 1A: MULTI-TIER VAULTS & 100% BANK-RUN DURATION (T_cooldown = 13.0d) ===") cooldown_days = POLICY_T_COOLDOWN / SOURCED_BTC_BLOCKS_PER_DAY assert abs(cooldown_days - 13.0) < 1e-9 avg_multi = (sum(POLICY_VAULT_TIERS_SATS) / len(POLICY_VAULT_TIERS_SATS)) / SAT avg_half = (sum(POLICY_VAULT_ALT_SPLIT_SATS) / len(POLICY_VAULT_ALT_SPLIT_SATS)) / SAT for label, prof in POLICY_STAGE1A_PROFILES.items(): m, cap_u, flt = prof["M"], prof["cap_user_btc"], prof["float_btc"] v_per_d = m / cooldown_days btc_per_d_multi = v_per_d * avg_multi btc_per_d_half = v_per_d * avg_half cont_multi = (cap_u - flt) / btc_per_d_multi cont_half = (cap_u - flt) / btc_per_d_half rem_v = int(round(cap_u / avg_multi)) - int(flt // avg_multi) batch_multi = math.ceil(rem_v / m) * cooldown_days if m == 3: assert 101.0 <= cont_multi <= 102.0 and batch_multi == 104.0 and 67.0 <= cont_half <= 68.5 if m == 5: assert 93.0 <= cont_multi <= 94.5 and batch_multi == 104.0 and 62.0 <= cont_half <= 63.0 print( f" {label:28s}: {v_per_d:.3f} v/d ({btc_per_d_multi:.3f} BTC/d) | " f"100% run=~{cont_multi:.1f}d (batch={batch_multi:.0f}d) [~{cont_half:.1f}d w/ {{0.50,0.50}}]" ) # -------------------------------------------------------------------------- # 10. K >= 18 UNPUBLISHED-FORK HEURISTIC & BUDISH SENSITIVITY (R8-H03) # -------------------------------------------------------------------------- print("\n=== 10. K >= 18 UNPUBLISHED-FORK HEURISTIC (Cap_user + M*B_zbtc) & BUDISH SENSITIVITY ===") for cap_u, cap_tot in POLICY_TVL_TIERS_TOTAL_BTC.items(): k_2024 = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][cap_u] assert k_2024 >= POLICY_K_MIN_FLOOR row = [] for era, sub in SOURCED_BTC_SUBSIDY_BY_ERA.items(): k_min = max(POLICY_K_MIN_FLOOR, int(math.floor((2.0 * cap_tot) / sub)) + 1) assert 0.50 * k_min * sub > cap_tot if era in POLICY_CONFIGURED_K_BY_ERA: k_cfg = POLICY_CONFIGURED_K_BY_ERA[era][cap_u] assert k_cfg >= k_min and 0.50 * k_cfg * sub > cap_tot row.append(f"{era}:K>={k_min}") print(f" User={cap_u:3d} / Total={cap_tot:6.2f} BTC (2024 K={k_2024:3d}): " + " | ".join(row)) # Print Budish winning-fork direct net flow-cost sensitivity at K=18, 2024-2028 (56.25 BTC nominal subsidy): nom_k18 = 18 * SOURCED_BTC_SUBSIDY_BY_ERA["2024-2028"] budish_str = " | ".join(f"kappa={int(k*100)}%:{k*nom_k18:.2f} BTC" for k in (0.05, 0.15, 0.30, 0.50)) print(f" Budish winning-fork direct flow-cost @ K=18 (excl. BTC-price crash): {budish_str}") # -------------------------------------------------------------------------- # 11. STAGE 1B (clArk) ALTERNATIVE GATE # -------------------------------------------------------------------------- print("\n=== 11. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS ===") clark_low, clark_high = PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC assert clark_high < 14.75 for n_vtxo in PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS: depth = int(math.log2(n_vtxo)) total_vb = depth * 167.0 + 154.0 assert total_vb < SOURCED_BIP431_TRUC_MAX_VB print( f" N={n_vtxo:4d} (depth={depth:2d}): exit={total_vb:6.0f} vB | " f"@100={int(total_vb*100):,} sats | @500={int(total_vb*500):,} sats" ) # -------------------------------------------------------------------------- # 12. REAL 2,000-STEP STAGE 1A SIMULATION (V = C + L + E + R + A + B) # -------------------------------------------------------------------------- print("\n=== 12. REAL 2,000-STEP STAGE 1A SIMULATION (EXPLICIT A, TICKETS, k=20 GRIEF, REORGS) ===") counts = run_stage1a_solvency_sim(seed=20261128, steps=2_000) for k, v in counts.items(): assert v > 0, f"Event type {k} was never exercised: {counts}" assert counts["reorg_blocks_reverted"] >= counts["reorg"] > 0 and counts["reorg_events_reverted"] > 0 print(" Bob, Mike, k=20 grief burst, TransferCredit, Ticket cap race & 2,000 adversarial steps PASSED V=C+L+E+R+A+B:") print(" " + ", ".join(f"{k}={v}" for k, v in counts.items())) print("\nALL v2 (v3.1.0-rfc R8-HARDENED ZERO-FEDERATION) CONSISTENCY, ERLANG, HALL, EV & SOLVENCY CHECKS PASSED.") if __name__ == "__main__": main() ``` # Verified Output of `python3 -I scripts/verify_spec_bounds.py` ```text ================================================================================ zBTC v2 (v3.1.0-rfc — R8 HARDENED) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER Note: Pure Python 3 stdlib. Checks internal consistency against SOURCED_, POLICY_, and PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark. ================================================================================ === 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING & >= 65 B FILTER === Verified 64/64 remainders vs hashlib double-SHA256 (56 1-blk, 8 2-blk = 12.5%); all len <= 64 rejected (min strippedTx = 65 B). === 2. STAGE 0: go-zenon PLASMA / 8 MiB CEILING vs BITCOIN L1 0x02 DA CAP === Zenon @ 11.4s: 2-blk=4.4/8.8 tx/s | 1-blk rollup=6.5/12.9 tx/s (7.37 @ 10s) | 8 MiB cap=1,051-1,226 tx/s Bitcoin L1 0x02 DA cap @ 100% blockspace: blended(10vB)=166.7 leaves/s (1%=1.67/s) | existing(4vB)=416.7/s | new(12vB)=138.9/s | spam cap=1000/6-blk (0.28/s, 500-sat deposit) === 3. STAGE 0: EXACT STDLIB ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) === PTLC (72 blks @ 2.3x): old 30h fail=22.47% -> NEW 48h fail=9.49e-08 (p99.9=38.75h, margin=9.25h; block-72 RBF watchtower) LN Outbound (36 blks): old 6h@1x fail=47.78% -> NEW 24h@2.3x fail=1.04e-04 (p99.9=22.01h, @1x fail=1.29e-27) === 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL (LOCKED vs OPERATIONAL vs MULTI-DISPUTE) === M=3 (<=10 user / 11.8 tot) : locked=12.80 + op_res=1.95 = 14.75 BTC (44.7%-59.0% ZNN mcap) | M-dispute/honest-V=1.45 BTC M=5 (<=15 user / 18.0 tot) : locked=18.80 + op_res=2.45 = 21.25 BTC (64.4%-85.0% ZNN mcap) | M-dispute/honest-V=2.41 BTC BitVM2 bonds-only contrast (M=3..5): 39.90-90.875 BTC | Core floor >= 29.0 === 5. STAGE 1A: BitVMX-CPU n=8 WRAPPED-SNARK VERIFIER & P2A CPFP TRUC v3 === Prover step=7,436.5 vB <= 10k TRUC parent (>1k child -> confirmed parents only!) | Prover w/ 10x153 CPFP=76,530 vB (0.38265 BTC <= 0.40, BE=522 sat/vB) Verifier w/ 10x153 CPFP=16,530 vB: @500=0.08265 BTC, @750=0.12398 BTC === 6. STAGE 1A: WIDENED TIMELOCKS (T_step=72) & ACYCLIC vault_id LAMPORT TakeTx === Timelocks: [0,144] -> max_dispute=1584 < T_take=1728 (12d) < T_cool=1872 (13d) < Retire=2016 (14d) Acyclic vault_id Lamport TakeTx (w/ recycled Ticket): depth9=3,141.75 vB / depth12=3,165.75 vB (<=3,200 <=10,000 TRUC parent; peak_stack=258 < 1,000) === 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (0% zBTC CRISIS DISCOUNT) === k_collude=0 (honest=7): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-2.00 / Tot=-2.55 BTC k_collude=1 (honest=6): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.85 / Tot=-2.40 BTC k_collude=2 (honest=5): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.70 / Tot=-2.25 BTC k_collude=3 (honest=4): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.55 / Tot=-2.10 BTC k_collude=4 (honest=3): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.40 / Tot=-1.95 BTC k_collude=5 (honest=2): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.25 / Tot=-1.80 BTC k_collude=6 (honest=1): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.10 / Tot=-1.65 BTC === 8. STAGE 1A: 2^M HALL'S MARRIAGE CHECKER & CYCLIC EXIT PRIORITY === Hall's 2^M counterexample CAUGHT (subset 0b00011: demand=30 > supply=20, despite global 30 <= 110); uniform 45-vault M=5 cohort PASSES at 0.50 headroom. Cyclic priority k_r = (H(exitId) + r) mod M_active: 0.0% collisions verified across 800 tests (M=3,5,10,20). === 9. STAGE 1A: MULTI-TIER VAULTS & 100% BANK-RUN DURATION (T_cooldown = 13.0d) === M=3 (<=10 user / 11.8 tot) : 0.231 v/d (0.077 BTC/d) | 100% run=~101.4d (batch=104d) [~67.6d w/ {0.50,0.50}] M=5 (<=15 user / 18.0 tot) : 0.385 v/d (0.128 BTC/d) | 100% run=~93.6d (batch=104d) [~62.4d w/ {0.50,0.50}] === 10. K >= 18 UNPUBLISHED-FORK HEURISTIC (Cap_user + M*B_zbtc) & BUDISH SENSITIVITY === User= 10 / Total= 11.80 BTC (2024 K= 18): 2024-2028:K>=18 | 2028-2032:K>=18 | 2032-2036:K>=31 | 2036-2040:K>=61 User= 15 / Total= 18.00 BTC (2024 K= 18): 2024-2028:K>=18 | 2028-2032:K>=24 | 2032-2036:K>=47 | 2036-2040:K>=93 User= 50 / Total= 62.00 BTC (2024 K= 42): 2024-2028:K>=40 | 2028-2032:K>=80 | 2032-2036:K>=159 | 2036-2040:K>=318 User=200 / Total=224.00 BTC (2024 K=144): 2024-2028:K>=144 | 2028-2032:K>=287 | 2032-2036:K>=574 | 2036-2040:K>=1147 Budish winning-fork direct flow-cost @ K=18 (excl. BTC-price crash): kappa=5%:2.81 BTC | kappa=15%:8.44 BTC | kappa=30%:16.88 BTC | kappa=50%:28.12 BTC === 11. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS === N= 64 (depth= 6): exit= 1156 vB | @100=115,600 sats | @500=578,000 sats N= 128 (depth= 7): exit= 1323 vB | @100=132,300 sats | @500=661,500 sats N= 256 (depth= 8): exit= 1490 vB | @100=149,000 sats | @500=745,000 sats N= 512 (depth= 9): exit= 1657 vB | @100=165,700 sats | @500=828,500 sats N=1024 (depth=10): exit= 1824 vB | @100=182,400 sats | @500=912,000 sats === 12. REAL 2,000-STEP STAGE 1A SIMULATION (EXPLICIT A, TICKETS, k=20 GRIEF, REORGS) === Bob, Mike, k=20 grief burst, TransferCredit, Ticket cap race & 2,000 adversarial steps PASSED V=C+L+E+R+A+B: deposit=15, deposit_race_blocked_by_ticket=39, transfer=254, forced_exit=59, front_paid=19, front_grief=7, front_grief_burst_k20=1, exit_cancel=2, fifo_assign=21, take_confirmed=14, release_assignment=4, transfer_credit=14, disprove_dual_slash=6, lamport_equivocation_slash=3, topup_op=10, mine_block=2551, reorg=145, reorg_blocks_reverted=1319, reorg_events_reverted=439 ALL v2 (v3.1.0-rfc R8-HARDENED ZERO-FEDERATION) CONSISTENCY, ERLANG, HALL, EV & SOLVENCY CHECKS PASSED. ```