// Bitcoin multisig core: key handling, descriptors and address derivation. // Pure functions only (no network, no DOM) so they can be unit-tested. import { HDKey } from '@scure/bip32'; import { base58check, hex } from '@scure/base'; import { sha256 } from '@noble/hashes/sha2.js'; import * as btc from '@scure/btc-signer'; export type ScriptType = 'p2tr' | 'p2wsh' | 'p2sh-p2wsh' | 'p2sh'; export type BtcNetwork = 'mainnet' | 'testnet' | 'signet'; export interface Cosigner { name: string; /** master key fingerprint, 8 lowercase hex chars */ fingerprint: string; /** derivation path of the account xpub, e.g. m/48'/0'/0'/2' */ path: string; /** account xpub, normalised to xpub/tpub version bytes */ xpub: string; /** how the key was added: ledger | trezor | file | manual ... */ source?: string; } export interface BtcVault { kind: 'btc'; id: string; name: string; network: BtcNetwork; scriptType: ScriptType; m: number; cosigners: Cosigner[]; createdAt: number; /** Ledger wallet-policy registration HMACs, keyed by cosigner fingerprint */ ledgerHmacs?: Record; /** signer/threshold change: the vault this one replaces, or replaced it */ migratedFrom?: string; migratedTo?: string; } export const SCRIPT_TYPES: Record = { p2tr: { label: 'Taproot multisig', short: 'P2TR', blurb: 'tr(NUMS, sortedmulti_a). Newest format: bc1p… addresses, smallest spends for large quorums, and the script stays hidden until a coin is spent.', bip48: 3, }, p2wsh: { label: 'Native SegWit multisig', short: 'P2WSH', blurb: 'wsh(sortedmulti). The industry standard (bc1q… addresses). Supported by almost every hardware and software wallet.', bip48: 2, }, 'p2sh-p2wsh': { label: 'Nested SegWit multisig', short: 'P2SH-P2WSH', blurb: 'sh(wsh(sortedmulti)). SegWit savings wrapped in a 3… address, for exchanges or payers that cannot send to bc1 addresses.', bip48: 1, }, p2sh: { label: 'Legacy multisig', short: 'P2SH', blurb: 'sh(sortedmulti), BIP45. Highest fees; only for compatibility with old setups.', bip48: null, }, }; export const NETWORKS: Record = { mainnet: { label: 'Bitcoin', coin: 0, params: btc.NETWORK, esplora: 'https://mempool.space/api', explorer: 'https://mempool.space' }, testnet: { label: 'Testnet4', coin: 1, params: btc.TEST_NETWORK, esplora: 'https://mempool.space/testnet4/api', explorer: 'https://mempool.space/testnet4' }, signet: { label: 'Signet', coin: 1, params: btc.TEST_NETWORK, esplora: 'https://mempool.space/signet/api', explorer: 'https://mempool.space/signet' }, }; /** BIP341 "H" point: provably no private key, so taproot can only be spent via the multisig leaf. */ export const NUMS_H = '50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0'; export const MAX_COSIGNERS = 15; // consensus/standardness limit for CHECKMULTISIG scripts export function defaultPath(scriptType: ScriptType, network: BtcNetwork): string { const t = SCRIPT_TYPES[scriptType].bip48; if (t === null) return "m/45'"; return `m/48'/${NETWORKS[network].coin}'/0'/${t}'`; } // ---------------------------------------------------------------- xpubs const VERSIONS: Record = { '0488b21e': { net: 'main' }, // xpub '049d7cb2': { net: 'main' }, // ypub '04b24746': { net: 'main' }, // zpub '0295b43f': { net: 'main' }, // Ypub '02aa7ed3': { net: 'main' }, // Zpub '043587cf': { net: 'test' }, // tpub '044a5262': { net: 'test' }, // upub '045f1cf6': { net: 'test' }, // vpub '024289ef': { net: 'test' }, // Upub '02575483': { net: 'test' }, // Vpub }; const XPUB = 0x0488b21e; const TPUB = 0x043587cf; const b58 = base58check(sha256); /** Accepts xpub/ypub/zpub/Ypub/Zpub (or test equivalents) and returns xpub/tpub. */ export function normalizeXpub(input: string, network: BtcNetwork): string { const s = input.trim(); let raw: Uint8Array; try { raw = b58.decode(s); } catch { throw new Error('Not a valid extended public key (bad base58 checksum).'); } if (raw.length !== 78) throw new Error('Not a valid extended public key (wrong length).'); const ver = hex.encode(raw.slice(0, 4)); const info = VERSIONS[ver]; if (!info) { if (['0488ade4', '04358394'].includes(ver)) { throw new Error('That is a PRIVATE key (xprv/tprv). Never paste private keys anywhere. Sanario only needs the public key.'); } throw new Error('Unknown extended key version.'); } const wantMain = network === 'mainnet'; if ((info.net === 'main') !== wantMain) throw new Error(`This key is for ${info.net === 'main' ? 'mainnet' : 'testnet'}, but the vault is on ${network}.`); const out = raw.slice(); new DataView(out.buffer).setUint32(0, wantMain ? XPUB : TPUB); const key = b58.encode(out); HDKey.fromExtendedKey(key, versions(network)); // validates the point return key; } export function versions(network: BtcNetwork) { return network === 'mainnet' ? { private: 0x0488ade4, public: XPUB } : { private: 0x04358394, public: TPUB }; } export function parsePath(path: string): number[] { const parts = path.trim().replace(/^m\/?/, '').split('/').filter(Boolean); return parts.map((p) => { const hard = /['hH]$/.test(p); const n = Number(hard ? p.slice(0, -1) : p); if (!Number.isInteger(n) || n < 0 || n >= 0x80000000) throw new Error(`Bad derivation path: ${path}`); return hard ? n + 0x80000000 : n; }); } export function normalizePath(path: string): string { return 'm' + parsePath(path).map((i) => '/' + (i >= 0x80000000 ? `${i - 0x80000000}'` : `${i}`)).join(''); } export function normalizeFingerprint(fp: string): string { const f = fp.trim().toLowerCase(); if (!/^[0-9a-f]{8}$/.test(f)) throw new Error('Fingerprint must be 8 hex characters.'); return f; } export function validateVault(v: Pick): string | null { const n = v.cosigners.length; if (n < 2) return 'Add at least 2 cosigners.'; if (n > MAX_COSIGNERS && v.scriptType !== 'p2tr') return `At most ${MAX_COSIGNERS} cosigners for this script type.`; if (n > 20) return 'At most 20 cosigners.'; if (v.m < 1 || v.m > n) return `Threshold must be between 1 and ${n}.`; if (v.m === 1) return 'A 1-of-N vault lets any single key move funds. Use at least 2.'; const seen = new Set(); for (const c of v.cosigners) { if (seen.has(c.xpub)) return `Cosigner "${c.name}" uses a key that is already in the vault.`; seen.add(c.xpub); } return null; } // ----------------------------------------------------------- derivation export interface KeyAtIndex { pubkey: Uint8Array; // 33-byte compressed fingerprint: number; path: number[]; // full path from master cosigner: number; // index in vault.cosigners } export function deriveKeys(vault: BtcVault, change: 0 | 1, index: number): KeyAtIndex[] { return vault.cosigners.map((c, i) => { const node = HDKey.fromExtendedKey(c.xpub, versions(vault.network)).deriveChild(change).deriveChild(index); return { pubkey: node.publicKey!, fingerprint: parseInt(c.fingerprint, 16), path: [...parsePath(c.path), change, index], cosigner: i, }; }); } const cmp = (a: Uint8Array, b: Uint8Array) => { for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i]; return a.length - b.length; }; export interface DerivedAddress { address: string; change: 0 | 1; index: number; script: Uint8Array; // output script keys: KeyAtIndex[]; // sorted the way the script sorts them witnessScript?: Uint8Array; redeemScript?: Uint8Array; // taproot tapInternalKey?: Uint8Array; tapLeafScript?: any; leafScript?: Uint8Array; tapMerkleRoot?: Uint8Array; } export function deriveAddress(vault: BtcVault, change: 0 | 1, index: number): DerivedAddress { const net = NETWORKS[vault.network].params; const keys = deriveKeys(vault, change, index); if (vault.scriptType === 'p2tr') { const sorted = [...keys].sort((a, b) => cmp(a.pubkey.slice(1), b.pubkey.slice(1))); const leaf = btc.p2tr_ms(vault.m, sorted.map((k) => k.pubkey.slice(1))); const p = btc.p2tr(hex.decode(NUMS_H), { script: leaf.script }, net, true); return { address: p.address!, change, index, script: p.script, keys: sorted, tapInternalKey: p.tapInternalKey, tapLeafScript: p.tapLeafScript, leafScript: leaf.script, tapMerkleRoot: p.tapMerkleRoot, }; } const sorted = [...keys].sort((a, b) => cmp(a.pubkey, b.pubkey)); // BIP67 sortedmulti const ms = btc.p2ms(vault.m, sorted.map((k) => k.pubkey)); if (vault.scriptType === 'p2wsh') { const p = btc.p2wsh(ms, net); return { address: p.address!, change, index, script: p.script, keys: sorted, witnessScript: p.witnessScript }; } if (vault.scriptType === 'p2sh-p2wsh') { const w = btc.p2wsh(ms, net); const p = btc.p2sh(w, net); return { address: p.address!, change, index, script: p.script, keys: sorted, witnessScript: w.witnessScript, redeemScript: p.redeemScript }; } const p = btc.p2sh(ms, net); return { address: p.address!, change, index, script: p.script, keys: sorted, redeemScript: p.redeemScript }; } // ---------------------------------------------------------- descriptors const INPUT_CHARSET = '0123456789()[],\'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#"\\ '; const CHECKSUM_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; function polymod(c: bigint, val: number): bigint { const c0 = c >> 35n; c = ((c & 0x7ffffffffn) << 5n) ^ BigInt(val); if (c0 & 1n) c ^= 0xf5dee51989n; if (c0 & 2n) c ^= 0xa9fdca3312n; if (c0 & 4n) c ^= 0x1bab10e32dn; if (c0 & 8n) c ^= 0x3706b1677an; if (c0 & 16n) c ^= 0x644d626ffdn; return c; } /** BIP380 descriptor checksum. */ export function descriptorChecksum(desc: string): string { let c = 1n, cls = 0, clscount = 0; for (const ch of desc) { const pos = INPUT_CHARSET.indexOf(ch); if (pos === -1) throw new Error('Invalid descriptor character: ' + ch); c = polymod(c, pos & 31); cls = cls * 3 + (pos >> 5); if (++clscount === 3) { c = polymod(c, cls); cls = 0; clscount = 0; } } if (clscount > 0) c = polymod(c, cls); for (let j = 0; j < 8; j++) c = polymod(c, 0); c ^= 1n; let out = ''; for (let j = 0; j < 8; j++) out += CHECKSUM_CHARSET[Number((c >> (5n * BigInt(7 - j))) & 31n)]; return out; } const originPath = (path: string) => normalizePath(path).replace(/^m/, '').replace(/'/g, 'h'); function keyExpr(c: Cosigner, suffix: string) { return `[${c.fingerprint}${originPath(c.path)}]${c.xpub}/${suffix}`; } /** Output descriptor; suffix "0/*" (receive), "1/*" (change) or "<0;1>/*" (multipath). */ export function descriptor(vault: BtcVault, suffix = '<0;1>/*', withChecksum = true): string { const keys = vault.cosigners.map((c) => keyExpr(c, suffix)).join(','); let d: string; switch (vault.scriptType) { case 'p2tr': d = `tr(${NUMS_H},sortedmulti_a(${vault.m},${keys}))`; break; case 'p2wsh': d = `wsh(sortedmulti(${vault.m},${keys}))`; break; case 'p2sh-p2wsh': d = `sh(wsh(sortedmulti(${vault.m},${keys})))`; break; case 'p2sh': d = `sh(sortedmulti(${vault.m},${keys}))`; break; } return withChecksum ? `${d}#${descriptorChecksum(d)}` : d; } /** BIP-388 wallet policy (used by Ledger). Not available for taproot-with-NUMS. */ export function walletPolicy(vault: BtcVault): { template: string; keys: string[] } | null { const ph = vault.cosigners.map((_, i) => `@${i}/**`).join(','); const keys = vault.cosigners.map((c) => `[${c.fingerprint}${normalizePath(c.path).replace(/^m/, '')}]${c.xpub}`); switch (vault.scriptType) { case 'p2wsh': return { template: `wsh(sortedmulti(${vault.m},${ph}))`, keys }; case 'p2sh-p2wsh': return { template: `sh(wsh(sortedmulti(${vault.m},${ph})))`, keys }; case 'p2sh': return { template: `sh(sortedmulti(${vault.m},${ph}))`, keys }; default: return null; } } /** Coldcard-style multisig file, importable by Sparrow, Nunchuk, Keystone, Passport, Jade, BitBox, Specter, Coldcard. */ export function multisigConfigFile(vault: BtcVault): string | null { const fmt = { p2wsh: 'P2WSH', 'p2sh-p2wsh': 'P2SH-P2WSH', p2sh: 'P2SH', p2tr: null }[vault.scriptType]; if (!fmt) return null; const lines = [ `# Sanario multisig setup file`, `# Keep a copy with every cosigner's backup. It holds only PUBLIC keys,`, `# but you need it (plus ${vault.m} of the ${vault.cosigners.length} seeds) to recover funds.`, `Name: ${vault.name.replace(/[^\x20-\x7e]/g, '').slice(0, 20) || 'Sanario'}`, `Policy: ${vault.m} of ${vault.cosigners.length}`, `Format: ${fmt}`, '', ]; for (const c of vault.cosigners) { lines.push(`Derivation: ${normalizePath(c.path)}`); lines.push(`${c.fingerprint.toUpperCase()}: ${c.xpub}`); lines.push(''); } return lines.join('\n'); } /** Rough virtual size of one input spending this vault (signed). */ export function inputVbytes(vault: BtcVault): number { const m = vault.m, n = vault.cosigners.length; const msScript = 3 + 34 * n; // OP_m OP_n OP_CHECKMULTISIG switch (vault.scriptType) { case 'p2wsh': return 41 + (1 + 1 + 73 * m + 3 + msScript) / 4; case 'p2sh-p2wsh': return 41 + 35 + (1 + 1 + 73 * m + 3 + msScript) / 4; case 'p2sh': return 41 + 3 + 1 + 74 * m + 3 + msScript; case 'p2tr': { const leaf = 34 * n + 2; return 41 + (1 + m * 65 + (n - m) + 3 + leaf + 1 + 33) / 4; } } } export function outputVbytes(script: Uint8Array): number { return 8 + 1 + script.length; } export function addressToScript(address: string, network: BtcNetwork): Uint8Array { return btc.OutScript.encode(btc.Address(NETWORKS[network].params).decode(address.trim())); } export function isValidAddress(address: string, network: BtcNetwork): boolean { try { addressToScript(address, network); return true; } catch { return false; } } export const formatBtc = (sats: bigint | number) => { const s = BigInt(sats); const neg = s < 0n; const a = neg ? -s : s; const whole = a / 100_000_000n; const frac = (a % 100_000_000n).toString().padStart(8, '0'); return `${neg ? '-' : ''}${whole}.${frac}`; }; export function parseBtc(input: string): bigint { const s = input.trim(); if (!/^\d+(\.\d{0,8})?$/.test(s)) throw new Error('Enter an amount like 0.015 (max 8 decimals).'); const [w, f = ''] = s.split('.'); return BigInt(w) * 100_000_000n + BigInt(f.padEnd(8, '0') || '0'); }