diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21d8516..6f15e59 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,12 +34,10 @@ jobs: - name: Verify committed SHA-256 checksums run: sha256sum -c SHA256SUMS.txt - - name: Run 16-test cryptographic, consensus & adversarial security suite + - name: Run 17-test cryptographic, consensus & adversarial security suite run: node tests/test_vault.js - name: Verify offline clean rebuild & zero unexpected drift run: | python3 build.py - sha256sum -c SHA256SUMS.txt - node tests/test_vault.js git diff --exit-code clawback.html index.html sw.js SHA256SUMS.txt diff --git a/README.md b/README.md index 71c11c5..e3ea558 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Test the entire lifecycle in 20 seconds using disposable keys and the real `secp --- ### 2. Whole-Wallet & Multi-Slot Vault Creator (Camera QR · microSD `.psbt` · `xpub`/`zpub`) -Sweep a single Native SegWit UTXO or your entire wallet into **1 to 5 independent Vault Slots** in a single non-RBF Funding TX—so spending a small slice never unvaults your entire reserve. Legacy `1…` / `3…` funding inputs are hard-blocked automatically to prevent `scriptSig` TXID malleability: +Sweep a single Native SegWit UTXO or your entire wallet into **1, 2 or 3 preset slot layouts (or any number of custom slots)** in a single non-RBF Funding TX—so spending a small slice never unvaults your entire reserve. Legacy `1…` / `3…` funding inputs are hard-blocked automatically to prevent `scriptSig` TXID malleability:

Clawback Create Vault — Whole-Wallet UTXOs, Primary Key, SeedSigner Bunker, and 3-Slot Layout @@ -93,7 +93,7 @@ Sweep a single Native SegWit UTXO or your entire wallet into **1 to 5 independen --- ### 3. Ephemeral Key Destruction, Mandatory Backup Gate & Miniscript Descriptors -Every slot generates a one-time ephemeral key, pre-signs the **Unvault Partial PSBT** + **3 finalized Clawback fee tiers (`15 / 50 / 200 sat/vB`)**, audits every signature, and **zeroes the ephemeral key in RAM** before unlocking the Funding PSBT. Exports checksummed **BIP-380 Output Descriptors** for Sparrow and Bitcoin Core: +Every slot generates a one-time ephemeral key, pre-signs the **Unvault Partial PSBT** + **up to 4 finalized Clawback fee tiers (`15 / 50 / 200 / 500 sat/vB`; the 500 tier is skipped on slots where it would be too large a share of the slot)**, audits every signature, and **zeroes the ephemeral key in RAM** before unlocking the Funding PSBT. Exports checksummed **BIP-380 Output Descriptors** for Sparrow and Bitcoin Core:

Clawback Vault Sealed — Audit Passed, Ephemeral Keys Zeroed in RAM, Mandatory Backup Gate, and Per-Slot Descriptors @@ -159,8 +159,9 @@ Copy `clawback.html` to a USB drive, open it on an offline laptop or Tails live ```bash git clone https://github.com/Random21m/clawback.git cd clawback +sha256sum -c SHA256SUMS.txt # verify the committed files first python3 build.py -sha256sum -c SHA256SUMS.txt +git diff --exit-code clawback.html index.html sw.js SHA256SUMS.txt # rebuild must be byte-identical node tests/test_vault.js ``` @@ -190,7 +191,7 @@ node tests/test_vault.js ### Independent Verification & Rehearsals Clawback's transaction engine has been verified against both our strict consensus suite and independent third-party Bitcoin libraries: -* **16/16 Strict Consensus & Adversarial Security Tests (`node tests/test_vault.js`):** Official Bitcoin Core SHA-256, HASH160, BIP-32, Bech32m, and BIP-380 checksum vectors; hard-block of Legacy `1…`/`3…` funding inputs; full `BIP32_DERIVATION` propagation across all 3 PSBTs; strict `MINIMALIF` / `CLEANSTACK` / `BIP-66 DER` / `LOW_S` / `BIP-68 CSV` script evaluator (including early-spend rejection); adversarial tamper & 1-of-2 script backdoor detection; Coldcard BBQr mod-8 lossless multi-frame PSBT round-trip. +* **17/17 Strict Consensus & Adversarial Security Tests (`node tests/test_vault.js`):** Official Bitcoin Core SHA-256, HASH160, BIP-32, Bech32m, and BIP-380 checksum vectors; hard-block of Legacy `1…`/`3…` funding inputs; full `BIP32_DERIVATION` propagation across all 3 PSBTs; strict `MINIMALIF` / `CLEANSTACK` / `BIP-66 DER` / `LOW_S` / `BIP-68 CSV` script evaluator (including early-spend rejection); adversarial tamper & 1-of-2 script backdoor detection; Coldcard BBQr mod-8 lossless multi-frame PSBT round-trip. * **Independent Cross-Library Stress Fuzz:** Verified bit-for-bit across **60 fuzzed vaults / 120 slots / 180 PSBTs / 452 Clawbacks / 120 BBQr round-trips** against **`@scure/btc-signer`** (independently parsing, signing, and finalizing Funding PSBTs and 2-of-2 Unvault Partial PSBTs with identical TXIDs), **`@scure/bip32`**, **`@noble/curves/secp256k1`** (`lowS: true`), and **live `mempool.space`** Mainnet & Signet Esplora APIs. --- diff --git a/SECURITY.md b/SECURITY.md index a40f405..9e03784 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,6 +7,9 @@ 4. **Use a completely separate key/seed for your Clawback Bunker.** Never claw back to the same seed/wallet that controls your normal spending key. 5. **Test on Signet / Testnet4 first.** Use the built-in Live Simulator and Signet mode to rehearse unvaulting and clawing back before vaulting real mainnet Bitcoin. +## Reporting a Vulnerability +Please report suspected vulnerabilities privately via GitHub's **Security → Report a vulnerability** (private vulnerability reporting) on this repository, and do not open a public issue for fund-impacting bugs. Include the affected commit/SHA-256, reproduction steps and impact. + ## What Is Safe to Store Online * **Panic-Only JSON / QR:** Contains only public watch addresses and finalized `Clawback TX` hexes hardcoded to pay your bunker address. Even if stolen, an attacker cannot redirect a single sat. * **Vault Package JSON:** Because the vault uses 2-of-2 (`Primary Key + Ephemeral Key`), stealing the Vault Package alone still cannot trigger an unvault without your primary hardware wallet. diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index b80dda1..e02fc53 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,4 +1,4 @@ -3b0a5dd8d41a8abe7ca7cf35bb5ab4c5c90364bd3c5f123708e6088a687c7607 clawback.html -0fd1cd3e152bfe1808b045d2544ec35216c464df6e72439ef9e3be7457f3b99b index.html -2d4644df6a41a9afdf48dd4dc93263c2c945cb82fd2ba561ac70e4b971a5c32f sw.js +9684e3922a93f225051d290309ba54b3d7290be824e6b17a62551fc01370e135 clawback.html +fea46b1c9617b99be3e38eeef30f707697b4d485aca79d4c1d28a6558d782975 index.html +b48459f1b5730ccc3656689b5f9cb470f0a94268528d40d00058f291c0569bbf sw.js c98a5d9112489acd8d72a90b9227883d757384ecc971b75f877becd3417fcbf9 manifest.webmanifest diff --git a/TUTORIAL.md b/TUTORIAL.md index 7b41f53..544eeb4 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -306,7 +306,7 @@ Clawback solves this with **Multi-Slot Vaults**: a single Funding TX splits your 1. Open **Sparrow Wallet** in Signet mode (`sparrow --network signet`) and create two test wallets: * `Test-Primary` (Native SegWit `tb1q…`, linked to your Coldcard or software test key) * `Test-Bunker` (separate seed, e.g., SeedSigner test seed → copy 1 fresh `tb1q…` address) -2. Fund `Test-Primary` with free Signet sats (e.g., `0.005 sBTC` / `500,000 sats`). +2. Fund `Test-Primary` with free Signet sats (e.g., `0.005` signet BTC / `500,000 sats`). 3. In Clawback **Tab 2: Create Vault**: * Set Network = **`Signet (tb1…)`**, Delay = **`6 blocks (≈1 hr)`**, Slot Layout = **`2 Slots (25% / 75%)`**. * Load your `Test-Primary` UTXO (via Sparrow unsigned `.psbt` or watch-only `vpub`/`tpub`), enter your `Test-Primary` spend key and `Test-Bunker` address, and click **`Build Vault & Destroy Ephemeral Key`**. @@ -348,7 +348,7 @@ You have **three ways** to load funding inputs—all strictly enforce **Native S 3. Clawback automatically extracts every Native SegWit UTXO, verifies none are Legacy `1…`/`3…`, and preserves every input's exact **`BIP32_DERIVATION` (`0x06`)** fingerprint and path so Coldcard/SeedSigner will sign the final Funding PSBT natively. * **Method B — Whole-Wallet Watch-Only `xpub` / `zpub` Scan *(Online / Own-Node Mode)*:** 1. Paste or camera-scan your watch-only `[fingerprint/84h/0h/0h]zpub…` (or `xpub…`) into the Watch-Only field and click **`Scan UTXOs`**. - 2. Clawback scans receive (`m/0/0..19`) and change (`m/1/0..9`) branches via your configured Esplora endpoint, populates every spendable UTXO with its exact BIP-32 derivation path, and automatically fills a fresh unused Primary Spend Public Key and Change Address. + 2. Clawback scans receive (`m/0/i`, up to index 100, stopping after 20 consecutive unused addresses) and change (`m/1/i`, up to 50, stopping after 10 consecutive unused) branches via your configured Esplora endpoint, populates every spendable UTXO with its exact BIP-32 derivation path, and automatically fills a fresh unused Primary Spend Public Key and Change Address. * **Method C — Manual UTXO Entry:** 1. Click **`+ Add UTXO`** and enter `TXID`, `vout`, and `Amount (sats)` for each Native SegWit UTXO you wish to sweep. @@ -406,7 +406,7 @@ Switch to **Tab 3: Watchtower & Panic** on your daily phone (installed as a PWA) 2. **Zero Private Key Guarantee:** `panic-only.json` contains **zero seeds, zero private keys, and zero spending authority**—only your public Vault addresses and finalized Clawback hex transactions locked exclusively to your bunker. ### 8.2 Connecting Your Own Umbrel / Start9 / Local Mempool Node (Full Privacy) -By default, Clawback queries `mempool.space` only when you click **`Check All Vaults`** (never in the background). To keep your public Vault addresses 100% private from third-party APIs: +By default, Clawback queries `mempool.space` only when you click **`Check All Vaults`** (never in the background unless you enable the opt-in **Auto: 60s** toggle). To keep your public Vault addresses 100% private from third-party APIs: 1. Enter your local Esplora / Mempool API endpoint into **Optional Custom Esplora / Self-Hosted Mempool URL**, for example: * Umbrel Mempool app: `http://umbrel.local:3006/api` * Start9 Mempool service: `https://.local/api` @@ -534,7 +534,7 @@ Clawback creates **zero proprietary formats** and **zero software lock-in**. Eve ### 12.3 Engineering FAQ **Q: Does Clawback ever connect to the internet automatically?** -No. The single-file `clawback.html` makes zero network calls on load and has zero external CDNs or telemetry. Network requests occur *only* when you explicitly click **Scan UTXOs**, **Check All Vaults**, or **Broadcast Clawback Now**—and you can point all three exclusively at your own local Umbrel/Start9 node. +No. The single-file `clawback.html` makes zero network calls on load and has zero external CDNs or telemetry. Network requests occur *only* when you explicitly click **Scan UTXOs**, **Check All Vaults**, or **Broadcast Clawback Now** (or enable the opt-in **Auto: 60s** Watchtower toggle)—and you can point all three exclusively at your own local Umbrel/Start9 node. **Q: What if I lose my phone with the Watchtower app on it?** Nothing is lost and nothing is compromised. Your phone only stored watch-only public addresses and pre-signed Clawback hexes hardcoded to pay your bunker. Re-import `panic-only.json` on your new phone in 10 seconds. @@ -547,7 +547,7 @@ Because `P2WSH` + Canonical Miniscript (`wsh(or_i(and_v(v:pk(...),older(...)),pk **Q: How do I verify a build locally from scratch?** ```bash -python3 build.py && sha256sum -c SHA256SUMS.txt && node tests/test_vault.js +python3 build.py && git diff --exit-code clawback.html index.html sw.js SHA256SUMS.txt && node tests/test_vault.js ``` Every cryptographic check, official Bitcoin Core test vector, and theme invariant runs locally in under two seconds. diff --git a/clawback.html b/clawback.html index 1c3a0b5..cb77e18 100644 --- a/clawback.html +++ b/clawback.html @@ -4,6 +4,7 @@ + Clawback @@ -13812,6 +13813,18 @@

Support Clawback

return Math.ceil(weight / 4); } + // Only standard, relayable, non-anyone-can-spend destinations are acceptable + // for the clawback bunker: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. + function isStandardSpk(spk) { + const n = spk.length; + if (n === 22 && spk[0] === 0x00 && spk[1] === 0x14) return true; + if (n === 34 && spk[0] === 0x00 && spk[1] === 0x20) return true; + if (n === 34 && spk[0] === 0x51 && spk[1] === 0x20) return true; + if (n === 25 && spk[0] === 0x76 && spk[1] === 0xa9 && spk[2] === 0x14 && spk[23] === 0x88 && spk[24] === 0xac) return true; + if (n === 23 && spk[0] === 0xa9 && spk[1] === 0x14 && spk[22] === 0x87) return true; + return false; + } + function parseTx(bytes) { let off = 0; const version = C.readUInt32LE(bytes, off); @@ -14195,6 +14208,9 @@

Support Clawback

throw new Error("Invalid 33-byte compressed user spending public key"); } const clawbackSpk = C.addressToScriptPubKey(clawbackAddress, network); + if (!isStandardSpk(clawbackSpk)) { + throw new Error("Bunker address must be P2PKH, P2SH, P2WPKH, P2WSH or P2TR (witness v2+ outputs are anyone-can-spend / non-standard)"); + } // Prevent clawing back to the exact same key (P2WPKH, P2PKH, or P2SH-P2WPKH) as Primary Spend Key const userPkh = C.hash160(userPubBytes); @@ -14220,7 +14236,11 @@

Support Clawback

throw new Error(`UTXO #${idx + 1} has an invalid 64-char txid`); } const normTxid = u.txid.trim().toLowerCase(); - const normVout = Number(u.vout) >>> 0; + const rawVout = typeof u.vout === "string" && /^\d+$/.test(u.vout.trim()) ? Number(u.vout) : u.vout; + if (!Number.isSafeInteger(rawVout) || rawVout < 0 || rawVout > 0xffffffff) { + throw new Error(`UTXO #${idx + 1} has an invalid vout (must be a non-negative integer)`); + } + const normVout = rawVout; const outKey = `${normTxid}:${normVout}`; if (seenOutpoints.has(outKey)) { throw new Error(`Duplicate funding UTXO detected (${normTxid.slice(0, 12)}…:${normVout})`); @@ -14692,6 +14712,7 @@

Support Clawback

// Support auditing Panic-Only watch packages (clawback-panic/v1) with full ECDSA + locktime checks if (pkg.schema === "clawback-panic/v1") { const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); checks.push(`Panic-Only Package · Network: ${pkg.network.toUpperCase()} · Funding TXID: ${String(pkg.fundingTxid || "").slice(0, 12)}…`); for (const slot of pkg.slots) { if (!Number.isInteger(slot.slotIndex) || slot.slotIndex < 0) { @@ -14789,6 +14810,7 @@

Support Clawback

checks.push(`All ${fundingPsbt.inputs.length} funding input(s) verified Native SegWit & non-RBF`); const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); const userPubBytes = C.hexToBytes(pkg.userSpendPubKeyHex); if (!C.isValidCompressedPubKey(userPubBytes)) { errors.push("Invalid 33-byte compressed userSpendPubKeyHex"); @@ -14870,7 +14892,8 @@

Support Clawback

unvaultTx.inputs.length !== 1 || unvaultTx.outputs.length !== 1 || unvaultTx.inputs[0].txid !== calcFundingTxid || - unvaultTx.inputs[0].vout !== slot.vout + unvaultTx.inputs[0].vout !== slot.vout || + unvaultTx.inputs[0].sequence !== 0xfffffffd ) { errors.push(`Slot #${slot.slotIndex + 1}: Unvault TX structure/outpoint/locktime invalid`); } @@ -14915,6 +14938,9 @@

Support Clawback

errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback TX structure or locktime invalid`); continue; } + if (cbTx.version !== 2 || cbTx.inputs[0].sequence !== 0xfffffffd) { + errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback must be version 2 with sequence 0xfffffffd (no relative lock, RBF-signalling)`); + } if (cbTx.inputs[0].txid !== calcUnvaultTxid || cbTx.inputs[0].vout !== 0) { errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback input does not spend Unvault TX`); } @@ -15498,12 +15524,31 @@

Support Clawback

return apiGetJson(`${base}/v1/fees/recommended`); } + function requireStats(st) { + if (!st || typeof st !== "object" || !Number.isFinite(st.tx_count)) { + throw new Error("Unexpected API response (address stats missing) - refusing to treat address as unused"); + } + return st; + } + + function assertValidApiUtxo(u) { + if ( + !u || typeof u.txid !== "string" || !/^[0-9a-f]{64}$/i.test(u.txid) || + !Number.isSafeInteger(u.vout) || u.vout < 0 || + !Number.isSafeInteger(u.value) || u.value < 0 + ) { + throw new Error("Rejected malformed UTXO in API response"); + } + } + async function fetchAddressUtxos(address, networkId, customUrl = "") { // Validate address & network BEFORE sending any HTTP request const spk = C.addressToScriptPubKey(address, networkId); const spkHex = C.bytesToHex(spk); const base = getApiBase(networkId, customUrl); const utxos = await apiGetJson(`${base}/address/${encodeURIComponent(address)}/utxo`); + if (!Array.isArray(utxos)) throw new Error("Unexpected API response (UTXO list is not an array)"); + utxos.forEach(assertValidApiUtxo); return utxos.map((u) => ({ txid: u.txid, vout: u.vout, @@ -15564,8 +15609,8 @@

Support Clawback

const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning receive #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + @@ -15606,8 +15651,8 @@

Support Clawback

const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning change #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + @@ -16563,7 +16608,7 @@

Support Clawback

row.className = "utxo-row"; row.innerHTML = ` - + `; diff --git a/index.html b/index.html index 6ef1b23..88d22b6 100644 --- a/index.html +++ b/index.html @@ -4,6 +4,7 @@ + Clawback @@ -13815,6 +13816,18 @@

Support Clawback

return Math.ceil(weight / 4); } + // Only standard, relayable, non-anyone-can-spend destinations are acceptable + // for the clawback bunker: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. + function isStandardSpk(spk) { + const n = spk.length; + if (n === 22 && spk[0] === 0x00 && spk[1] === 0x14) return true; + if (n === 34 && spk[0] === 0x00 && spk[1] === 0x20) return true; + if (n === 34 && spk[0] === 0x51 && spk[1] === 0x20) return true; + if (n === 25 && spk[0] === 0x76 && spk[1] === 0xa9 && spk[2] === 0x14 && spk[23] === 0x88 && spk[24] === 0xac) return true; + if (n === 23 && spk[0] === 0xa9 && spk[1] === 0x14 && spk[22] === 0x87) return true; + return false; + } + function parseTx(bytes) { let off = 0; const version = C.readUInt32LE(bytes, off); @@ -14198,6 +14211,9 @@

Support Clawback

throw new Error("Invalid 33-byte compressed user spending public key"); } const clawbackSpk = C.addressToScriptPubKey(clawbackAddress, network); + if (!isStandardSpk(clawbackSpk)) { + throw new Error("Bunker address must be P2PKH, P2SH, P2WPKH, P2WSH or P2TR (witness v2+ outputs are anyone-can-spend / non-standard)"); + } // Prevent clawing back to the exact same key (P2WPKH, P2PKH, or P2SH-P2WPKH) as Primary Spend Key const userPkh = C.hash160(userPubBytes); @@ -14223,7 +14239,11 @@

Support Clawback

throw new Error(`UTXO #${idx + 1} has an invalid 64-char txid`); } const normTxid = u.txid.trim().toLowerCase(); - const normVout = Number(u.vout) >>> 0; + const rawVout = typeof u.vout === "string" && /^\d+$/.test(u.vout.trim()) ? Number(u.vout) : u.vout; + if (!Number.isSafeInteger(rawVout) || rawVout < 0 || rawVout > 0xffffffff) { + throw new Error(`UTXO #${idx + 1} has an invalid vout (must be a non-negative integer)`); + } + const normVout = rawVout; const outKey = `${normTxid}:${normVout}`; if (seenOutpoints.has(outKey)) { throw new Error(`Duplicate funding UTXO detected (${normTxid.slice(0, 12)}…:${normVout})`); @@ -14695,6 +14715,7 @@

Support Clawback

// Support auditing Panic-Only watch packages (clawback-panic/v1) with full ECDSA + locktime checks if (pkg.schema === "clawback-panic/v1") { const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); checks.push(`Panic-Only Package · Network: ${pkg.network.toUpperCase()} · Funding TXID: ${String(pkg.fundingTxid || "").slice(0, 12)}…`); for (const slot of pkg.slots) { if (!Number.isInteger(slot.slotIndex) || slot.slotIndex < 0) { @@ -14792,6 +14813,7 @@

Support Clawback

checks.push(`All ${fundingPsbt.inputs.length} funding input(s) verified Native SegWit & non-RBF`); const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); const userPubBytes = C.hexToBytes(pkg.userSpendPubKeyHex); if (!C.isValidCompressedPubKey(userPubBytes)) { errors.push("Invalid 33-byte compressed userSpendPubKeyHex"); @@ -14873,7 +14895,8 @@

Support Clawback

unvaultTx.inputs.length !== 1 || unvaultTx.outputs.length !== 1 || unvaultTx.inputs[0].txid !== calcFundingTxid || - unvaultTx.inputs[0].vout !== slot.vout + unvaultTx.inputs[0].vout !== slot.vout || + unvaultTx.inputs[0].sequence !== 0xfffffffd ) { errors.push(`Slot #${slot.slotIndex + 1}: Unvault TX structure/outpoint/locktime invalid`); } @@ -14918,6 +14941,9 @@

Support Clawback

errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback TX structure or locktime invalid`); continue; } + if (cbTx.version !== 2 || cbTx.inputs[0].sequence !== 0xfffffffd) { + errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback must be version 2 with sequence 0xfffffffd (no relative lock, RBF-signalling)`); + } if (cbTx.inputs[0].txid !== calcUnvaultTxid || cbTx.inputs[0].vout !== 0) { errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback input does not spend Unvault TX`); } @@ -15501,12 +15527,31 @@

Support Clawback

return apiGetJson(`${base}/v1/fees/recommended`); } + function requireStats(st) { + if (!st || typeof st !== "object" || !Number.isFinite(st.tx_count)) { + throw new Error("Unexpected API response (address stats missing) - refusing to treat address as unused"); + } + return st; + } + + function assertValidApiUtxo(u) { + if ( + !u || typeof u.txid !== "string" || !/^[0-9a-f]{64}$/i.test(u.txid) || + !Number.isSafeInteger(u.vout) || u.vout < 0 || + !Number.isSafeInteger(u.value) || u.value < 0 + ) { + throw new Error("Rejected malformed UTXO in API response"); + } + } + async function fetchAddressUtxos(address, networkId, customUrl = "") { // Validate address & network BEFORE sending any HTTP request const spk = C.addressToScriptPubKey(address, networkId); const spkHex = C.bytesToHex(spk); const base = getApiBase(networkId, customUrl); const utxos = await apiGetJson(`${base}/address/${encodeURIComponent(address)}/utxo`); + if (!Array.isArray(utxos)) throw new Error("Unexpected API response (UTXO list is not an array)"); + utxos.forEach(assertValidApiUtxo); return utxos.map((u) => ({ txid: u.txid, vout: u.vout, @@ -15567,8 +15612,8 @@

Support Clawback

const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning receive #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + @@ -15609,8 +15654,8 @@

Support Clawback

const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning change #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + @@ -16566,7 +16611,7 @@

Support Clawback

row.className = "utxo-row"; row.innerHTML = ` - + `; diff --git a/scripts/make_video.mjs b/scripts/make_video.mjs index 91a334e..45c806a 100644 --- a/scripts/make_video.mjs +++ b/scripts/make_video.mjs @@ -58,7 +58,7 @@ const CHAPTERS = [ title: "2-of-2 P2WSH Vault + Mandatory Consensus Quarantine (1 Hour to 180 Days)", padTail: 0.5, narration: - "When you open Clawback, you can test the real secp256k1 vault engine immediately in the Live Simulator. Your coins lock inside a two-of-two P2WSH vault combining your primary Coldcard key with an ephemeral key that is permanently wiped from memory before funding. Even if an attacker steals your Coldcard, your PIN, and your vault file, Bitcoin consensus freezes the coins inside your chosen quarantine window... from one day up to one hundred eighty days.", + "When you open Clawback, you can test the real secp256k1 vault engine immediately in the Live Simulator. Your coins lock inside a two-of-two P2WSH vault combining your primary Coldcard key with an ephemeral key that is permanently wiped from memory before funding. Even if an attacker steals your Coldcard, your PIN, and your vault file, Bitcoin consensus freezes the coins inside your chosen quarantine window... from one hour up to one hundred eighty days.", }, { id: "02-clawback-sweep", diff --git a/src/app.js b/src/app.js index 9e48786..1af4c1a 100644 --- a/src/app.js +++ b/src/app.js @@ -648,7 +648,7 @@ ${cb.rawHex} row.className = "utxo-row"; row.innerHTML = ` - + `; diff --git a/src/index.html b/src/index.html index 06ce6c6..1a8f2dd 100644 --- a/src/index.html +++ b/src/index.html @@ -4,6 +4,7 @@ + Clawback diff --git a/src/vault.js b/src/vault.js index e84faf0..6abef35 100644 --- a/src/vault.js +++ b/src/vault.js @@ -81,6 +81,18 @@ return Math.ceil(weight / 4); } + // Only standard, relayable, non-anyone-can-spend destinations are acceptable + // for the clawback bunker: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. + function isStandardSpk(spk) { + const n = spk.length; + if (n === 22 && spk[0] === 0x00 && spk[1] === 0x14) return true; + if (n === 34 && spk[0] === 0x00 && spk[1] === 0x20) return true; + if (n === 34 && spk[0] === 0x51 && spk[1] === 0x20) return true; + if (n === 25 && spk[0] === 0x76 && spk[1] === 0xa9 && spk[2] === 0x14 && spk[23] === 0x88 && spk[24] === 0xac) return true; + if (n === 23 && spk[0] === 0xa9 && spk[1] === 0x14 && spk[22] === 0x87) return true; + return false; + } + function parseTx(bytes) { let off = 0; const version = C.readUInt32LE(bytes, off); @@ -464,6 +476,9 @@ throw new Error("Invalid 33-byte compressed user spending public key"); } const clawbackSpk = C.addressToScriptPubKey(clawbackAddress, network); + if (!isStandardSpk(clawbackSpk)) { + throw new Error("Bunker address must be P2PKH, P2SH, P2WPKH, P2WSH or P2TR (witness v2+ outputs are anyone-can-spend / non-standard)"); + } // Prevent clawing back to the exact same key (P2WPKH, P2PKH, or P2SH-P2WPKH) as Primary Spend Key const userPkh = C.hash160(userPubBytes); @@ -489,7 +504,11 @@ throw new Error(`UTXO #${idx + 1} has an invalid 64-char txid`); } const normTxid = u.txid.trim().toLowerCase(); - const normVout = Number(u.vout) >>> 0; + const rawVout = typeof u.vout === "string" && /^\d+$/.test(u.vout.trim()) ? Number(u.vout) : u.vout; + if (!Number.isSafeInteger(rawVout) || rawVout < 0 || rawVout > 0xffffffff) { + throw new Error(`UTXO #${idx + 1} has an invalid vout (must be a non-negative integer)`); + } + const normVout = rawVout; const outKey = `${normTxid}:${normVout}`; if (seenOutpoints.has(outKey)) { throw new Error(`Duplicate funding UTXO detected (${normTxid.slice(0, 12)}…:${normVout})`); @@ -961,6 +980,7 @@ // Support auditing Panic-Only watch packages (clawback-panic/v1) with full ECDSA + locktime checks if (pkg.schema === "clawback-panic/v1") { const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); checks.push(`Panic-Only Package · Network: ${pkg.network.toUpperCase()} · Funding TXID: ${String(pkg.fundingTxid || "").slice(0, 12)}…`); for (const slot of pkg.slots) { if (!Number.isInteger(slot.slotIndex) || slot.slotIndex < 0) { @@ -1058,6 +1078,7 @@ checks.push(`All ${fundingPsbt.inputs.length} funding input(s) verified Native SegWit & non-RBF`); const expectedClawbackSpk = C.addressToScriptPubKey(pkg.clawbackAddress, pkg.network); + if (!isStandardSpk(expectedClawbackSpk)) errors.push("Bunker address is not a standard spendable output type (P2PKH/P2SH/P2WPKH/P2WSH/P2TR)"); const userPubBytes = C.hexToBytes(pkg.userSpendPubKeyHex); if (!C.isValidCompressedPubKey(userPubBytes)) { errors.push("Invalid 33-byte compressed userSpendPubKeyHex"); @@ -1139,7 +1160,8 @@ unvaultTx.inputs.length !== 1 || unvaultTx.outputs.length !== 1 || unvaultTx.inputs[0].txid !== calcFundingTxid || - unvaultTx.inputs[0].vout !== slot.vout + unvaultTx.inputs[0].vout !== slot.vout || + unvaultTx.inputs[0].sequence !== 0xfffffffd ) { errors.push(`Slot #${slot.slotIndex + 1}: Unvault TX structure/outpoint/locktime invalid`); } @@ -1184,6 +1206,9 @@ errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback TX structure or locktime invalid`); continue; } + if (cbTx.version !== 2 || cbTx.inputs[0].sequence !== 0xfffffffd) { + errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback must be version 2 with sequence 0xfffffffd (no relative lock, RBF-signalling)`); + } if (cbTx.inputs[0].txid !== calcUnvaultTxid || cbTx.inputs[0].vout !== 0) { errors.push(`Slot #${slot.slotIndex + 1} (${tierKey}): Clawback input does not spend Unvault TX`); } diff --git a/src/watchtower.js b/src/watchtower.js index 8bc1af3..a86cefb 100644 --- a/src/watchtower.js +++ b/src/watchtower.js @@ -101,12 +101,31 @@ return apiGetJson(`${base}/v1/fees/recommended`); } + function requireStats(st) { + if (!st || typeof st !== "object" || !Number.isFinite(st.tx_count)) { + throw new Error("Unexpected API response (address stats missing) - refusing to treat address as unused"); + } + return st; + } + + function assertValidApiUtxo(u) { + if ( + !u || typeof u.txid !== "string" || !/^[0-9a-f]{64}$/i.test(u.txid) || + !Number.isSafeInteger(u.vout) || u.vout < 0 || + !Number.isSafeInteger(u.value) || u.value < 0 + ) { + throw new Error("Rejected malformed UTXO in API response"); + } + } + async function fetchAddressUtxos(address, networkId, customUrl = "") { // Validate address & network BEFORE sending any HTTP request const spk = C.addressToScriptPubKey(address, networkId); const spkHex = C.bytesToHex(spk); const base = getApiBase(networkId, customUrl); const utxos = await apiGetJson(`${base}/address/${encodeURIComponent(address)}/utxo`); + if (!Array.isArray(utxos)) throw new Error("Unexpected API response (UTXO list is not an array)"); + utxos.forEach(assertValidApiUtxo); return utxos.map((u) => ({ txid: u.txid, vout: u.vout, @@ -167,8 +186,8 @@ const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning receive #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + @@ -209,8 +228,8 @@ const addr = C.p2wpkhAddressFromPubKey(child.pubKey, networkId); if (onProgress) onProgress(`Scanning change #${i} (${addr.slice(0, 12)}…)`); const info = await apiGetJson(`${base}/address/${encodeURIComponent(addr)}`); - const cStats = info.chain_stats || {}; - const mStats = info.mempool_stats || {}; + const cStats = requireStats(info.chain_stats); + const mStats = requireStats(info.mempool_stats); const txCount = (cStats.tx_count || 0) + (mStats.tx_count || 0); const unspentCount = ((cStats.funded_txo_count || 0) - (cStats.spent_txo_count || 0)) + diff --git a/sw.js b/sw.js index d667d4d..a2f5575 100644 --- a/sw.js +++ b/sw.js @@ -1,4 +1,4 @@ -const CACHE_NAME = "clawback-pwa-8fe9856b"; +const CACHE_NAME = "clawback-pwa-d6d1675e"; const STATIC_ASSETS = [ "./manifest.webmanifest", "./assets/logo.svg", @@ -18,7 +18,7 @@ self.addEventListener("install", (event) => { self.addEventListener("activate", (event) => { event.waitUntil( caches.keys() - .then((keys) => Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))) + .then((keys) => Promise.all(keys.filter((k) => k.startsWith("clawback-pwa-") && k !== CACHE_NAME).map((k) => caches.delete(k)))) .then(() => self.clients.claim()) ); }); diff --git a/tests/test_vault.js b/tests/test_vault.js index c3f922a..50098f9 100644 --- a/tests/test_vault.js +++ b/tests/test_vault.js @@ -304,11 +304,24 @@ test("Tampered Clawback destination or signature is caught by independent audito const tampered = JSON.parse(JSON.stringify(multiPkg)); // Flip one hex nibble in slot 0 standard clawback rawHex const orig = tampered.slots[0].clawbacks.standard.rawHex; - const flipped = orig.slice(0, -4) + (orig.slice(-4, -3) === "0" ? "1" : "0") + orig.slice(-3); + // Flip a nibble inside the output scriptPubKey (destination), NOT the trailing locktime + const spkHex = C.bytesToHex(V.parseTx(C.hexToBytes(orig)).outputs[0].scriptPubKey); + const at = orig.indexOf(spkHex) + 8; + const flipped = orig.slice(0, at) + (orig[at] === "0" ? "1" : "0") + orig.slice(at + 1); tampered.slots[0].clawbacks.standard.rawHex = flipped; const res = V.verifyVaultPackage(tampered); assert.strictEqual(res.valid, false); - assert.ok(res.errors.length > 0); + assert.ok(res.errors.some((e) => /bunker|destination|TXID/i.test(e)), "destination tamper must be flagged: " + res.errors.join(" | ")); + // Separately tamper the witness signature (first witness item DER bytes) + const sigTampered = JSON.parse(JSON.stringify(multiPkg)); + const tx = V.parseTx(C.hexToBytes(sigTampered.slots[0].clawbacks.standard.rawHex)); + const sigHex = C.bytesToHex(tx.inputs[0].witness[0]); + const raw2 = sigTampered.slots[0].clawbacks.standard.rawHex; + const sAt = raw2.indexOf(sigHex) + 20; + sigTampered.slots[0].clawbacks.standard.rawHex = raw2.slice(0, sAt) + (raw2[sAt] === "0" ? "1" : "0") + raw2.slice(sAt + 1); + const res2 = V.verifyVaultPackage(sigTampered); + assert.strictEqual(res2.valid, false); + assert.ok(res2.errors.some((e) => /ECDSA|signature|TXID/i.test(e)), "signature tamper must be flagged: " + res2.errors.join(" | ")); }); test("Completing 2-of-2 Unvault TX and Post-Quarantine OP_IF Spend TX verify cryptographically", () => { @@ -471,9 +484,46 @@ test("Adversarial security regressions: BIP-66 DER, High-S, msgHash=0, witness v const raw = badPanic.slots[0].clawbacks.standard.rawHex; // Flip a byte inside the DER witness signature of panic-only Clawback TX const rawBytes = C.hexToBytes(raw); - rawBytes[rawBytes.length - 10] ^= 0x01; - badPanic.slots[0].clawbacks.standard.rawHex = C.bytesToHex(rawBytes); - assert.strictEqual(V.verifyVaultPackage(badPanic).valid, false, "Tampered panic-only ECDSA sig must fail audit"); + const ptx = V.parseTx(rawBytes); + const psig = C.bytesToHex(ptx.inputs[0].witness[0]); + const praw = C.bytesToHex(rawBytes); + const pAt = praw.indexOf(psig) + 20; + badPanic.slots[0].clawbacks.standard.rawHex = praw.slice(0, pAt) + (praw[pAt] === "0" ? "1" : "0") + praw.slice(pAt + 1); + const pres = V.verifyVaultPackage(badPanic); + assert.strictEqual(pres.valid, false, "Tampered panic-only ECDSA sig must fail audit"); + assert.ok(pres.errors.some((e) => /ECDSA|signature|TXID/i.test(e)), "must fail on the signature, got: " + pres.errors.join(" | ")); +}); + +test("Hardening: rejects anyone-can-spend bunker (witness v2+), bad vout, and verifier flags clawback version/sequence tamper", () => { + const priv = C.generatePrivateKey(); + const pub = C.privToPub(priv); + const selfAddr = C.p2wpkhAddressFromPubKey(pub, "mainnet"); + const base = { + network: "mainnet", + utxos: [{ txid: "66".repeat(32), vout: 0, amount: 500000, address: selfAddr }], + userSpendPubHex: C.bytesToHex(pub), + csvBlocks: 144, + }; + // Witness v2 (bech32m, 20-byte program) is anyone-can-spend / non-standard + const v2Addr = C.encodeSegwitAddress("bc", 2, new Uint8Array(20).fill(7)); + assert.throws(() => V.createVaultPackage({ ...base, clawbackAddress: v2Addr }), /Bunker address must be/); + + const bunker = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"; + for (const bad of [-1, 1.7, "x", undefined, NaN]) { + assert.throws( + () => V.createVaultPackage({ ...base, utxos: [{ ...base.utxos[0], vout: bad }], clawbackAddress: bunker }), + /invalid vout/, + "vout " + String(bad) + ); + } + + // Verifier: clawback with a BIP-68 relative lock sequence must be flagged + const t = JSON.parse(JSON.stringify(multiPkg)); + const tx = V.parseTx(C.hexToBytes(t.slots[0].clawbacks.standard.rawHex)); + tx.inputs[0].sequence = 144; + const res = V.verifyVaultPackage({ ...t, slots: t.slots.map((s, i) => i === 0 ? { ...s, clawbacks: { ...s.clawbacks, standard: { ...s.clawbacks.standard, rawHex: C.bytesToHex(V.serializeTx(tx)) } } } : s) }); + assert.strictEqual(res.valid, false); + assert.ok(res.errors.some((e) => /sequence 0xfffffffd/.test(e)), res.errors.join(" | ")); }); // 3. Built Artifacts, Discreet Theme (Dark Only · Not Black · Zero Orange), & Red Crab Assets