'use client'; // Ledger over WebHID (Chrome / Edge / Brave / Opera). // Bitcoin: "Bitcoin" (or "Bitcoin Test") app >= 2.1 using BIP-388 wallet policies. // Ethereum: "Ethereum" app, EIP-712 hashed-message signing. import { Buffer } from 'buffer'; import { hex } from '@scure/base'; import type { BtcVault, BtcNetwork } from '../btc/core.ts'; import { walletPolicy, normalizePath } from '../btc/core.ts'; import { parsePsbt, toBase64 } from '../btc/psbt.ts'; if (typeof window !== 'undefined' && !(window as any).Buffer) (window as any).Buffer = Buffer; async function transport() { if (typeof navigator === 'undefined' || !(navigator as any).hid) { throw new Error('Your browser has no WebHID. Use Chrome, Edge or Brave on desktop to connect a Ledger.'); } const { default: TransportWebHID } = await import('@ledgerhq/hw-transport-webhid'); return TransportWebHID.create(); } function explain(e: any): Error { const code = e?.statusCode; if (code === 0x6985 || code === 0x5501) return new Error('Rejected on the Ledger.'); if (code === 0x6e01 || code === 0x6d00 || code === 0x6e00 || code === 0x6511) return new Error('Open the right app on your Ledger (Bitcoin / Bitcoin Test / Ethereum) and try again.'); if (code === 0x5515) return new Error('Unlock your Ledger with its PIN and try again.'); return e instanceof Error ? e : new Error(String(e)); } async function btcClient() { const { AppClient } = await import('ledger-bitcoin'); const t = await transport(); return { client: new AppClient(t as any), close: () => t.close() }; } /** Read master fingerprint + account xpub for `path`. Nothing secret leaves the device. */ export async function ledgerBtcXpub(path: string, _network: BtcNetwork): Promise<{ fingerprint: string; xpub: string }> { const { client, close } = await btcClient(); try { const fingerprint = await client.getMasterFingerprint(); const xpub = await client.getExtendedPubkey(normalizePath(path), false); return { fingerprint, xpub }; } catch (e) { throw explain(e); } finally { await close(); } } async function policyFor(vault: BtcVault) { const { WalletPolicy } = await import('ledger-bitcoin'); const p = walletPolicy(vault); if (!p) throw new Error('Ledger cannot sign this taproot vault directly yet. Export the PSBT and sign it in a taproot-capable coordinator (e.g. Bitcoin Core).'); return new WalletPolicy(vault.name.slice(0, 16) || 'Sanario', p.template, p.keys); } /** Registers the multisig on the Ledger; the user verifies every xpub on the device screen. Returns the HMAC to store. */ export async function ledgerRegisterVault(vault: BtcVault): Promise<{ fingerprint: string; hmac: string }> { const policy = await policyFor(vault); const { client, close } = await btcClient(); try { const fingerprint = await client.getMasterFingerprint(); if (!vault.cosigners.some((c) => c.fingerprint === fingerprint)) throw new Error('This Ledger is not one of the vault cosigners.'); const [, hmac] = await client.registerWallet(policy); return { fingerprint, hmac: hex.encode(hmac) }; } catch (e) { throw explain(e); } finally { await close(); } } /** Shows a receive address on the Ledger screen so it can be compared with the app. */ export async function ledgerShowAddress(vault: BtcVault, hmacs: Record, change: 0 | 1, index: number): Promise { const policy = await policyFor(vault); const { client, close } = await btcClient(); try { const fp = await client.getMasterFingerprint(); if (!hmacs[fp]) throw new Error('This Ledger has not registered the vault yet (Settings → Register on Ledger).'); return await client.getWalletAddress(policy, Buffer.from(hmacs[fp], 'hex'), change, index, true); } catch (e) { throw explain(e); } finally { await close(); } } /** Signs every input this Ledger can sign; returns the updated PSBT (base64). */ export async function ledgerSignPsbt(vault: BtcVault, psbtB64: string, hmacs: Record): Promise<{ psbt: string; fingerprint: string }> { const policy = await policyFor(vault); const { client, close } = await btcClient(); try { const fingerprint = await client.getMasterFingerprint(); const hmac = hmacs[fingerprint]; if (!hmac) throw new Error('Register the vault on this Ledger first (Vault → Cosigners → "Register on Ledger").'); const tx = parsePsbt(psbtB64); const v2 = Buffer.from(tx.toPSBT(2)); const sigs = await client.signPsbt(v2, policy, Buffer.from(hmac, 'hex')); for (const [idx, ps] of sigs) { tx.updateInput(idx, { partialSig: [[new Uint8Array(ps.pubkey), new Uint8Array(ps.signature)]] }, true); } return { psbt: toBase64(tx), fingerprint }; } catch (e) { throw explain(e); } finally { await close(); } } // ------------------------------------------------------------- Ethereum export async function ledgerEthAddress(path: string): Promise { const { default: Eth } = await import('@ledgerhq/hw-app-eth'); const t = await transport(); try { const r = await new Eth(t as any).getAddress(path.replace(/^m\//, ''), false); return r.address; } catch (e) { throw explain(e); } finally { await t.close(); } } /** EIP-712 signature from a hashed domain + struct (works on every Ledger model). */ export async function ledgerEthSignTyped(path: string, domainHash: string, structHash: string): Promise { const { default: Eth } = await import('@ledgerhq/hw-app-eth'); const t = await transport(); try { const r = await new Eth(t as any).signEIP712HashedMessage(path.replace(/^m\//, ''), domainHash.replace(/^0x/, ''), structHash.replace(/^0x/, '')); const v = (typeof r.v === 'number' ? r.v : parseInt(r.v as any, 16)); return '0x' + r.r + r.s + v.toString(16).padStart(2, '0'); } catch (e) { throw explain(e); } finally { await t.close(); } }