'use client'; // Trezor via Trezor Connect (popup + Trezor Bridge / WebUSB). // Bitcoin: native & nested SegWit and legacy multisig (Trezor firmware does not sign taproot multisig). // Ethereum: EIP-712 typed-data signing. import * as btc from '@scure/btc-signer'; import { hex } from '@scure/base'; import type { BtcVault, BtcNetwork } from '../btc/core.ts'; import { parsePath, normalizePath, deriveAddress } from '../btc/core.ts'; import { parsePsbt, toBase64 } from '../btc/psbt.ts'; let ready: Promise | null = null; async function connect() { const { default: TrezorConnect } = await import('@trezor/connect-web'); if (!ready) { ready = TrezorConnect.init({ manifest: { appName: 'Sanario', appUrl: typeof window !== 'undefined' ? window.location.origin : 'https://sanario.xyz', email: process.env.NEXT_PUBLIC_TREZOR_MANIFEST_EMAIL || 'security@sanario.xyz', }, }).then(() => TrezorConnect).catch((e: any) => { ready = null; throw e; }); } return ready; } function unwrap(r: { success: boolean; payload: any }): T { if (!r.success) throw new Error(r.payload?.error || 'Trezor request failed'); return r.payload as T; } const coinOf = (n: BtcNetwork) => (n === 'mainnet' ? 'btc' : 'test'); export async function trezorBtcXpub(path: string, network: BtcNetwork): Promise<{ fingerprint: string; xpub: string }> { const T = await connect(); // The depth-1 key's parent fingerprint is the master fingerprint. const first = normalizePath(path).split('/').slice(0, 2).join('/'); const res = unwrap(await T.getPublicKey({ bundle: [ { path: first, coin: coinOf(network), showOnTrezor: false }, { path: normalizePath(path), coin: coinOf(network), showOnTrezor: false }, ], })); const fingerprint = (res[0].fingerprint >>> 0).toString(16).padStart(8, '0'); return { fingerprint, xpub: res[1].xpub }; } function scriptTypes(vault: BtcVault) { switch (vault.scriptType) { case 'p2wsh': return { input: 'SPENDWITNESS', output: 'PAYTOWITNESS' } as const; case 'p2sh-p2wsh': return { input: 'SPENDP2SHWITNESS', output: 'PAYTOP2SHWITNESS' } as const; case 'p2sh': return { input: 'SPENDMULTISIG', output: 'PAYTOMULTISIG' } as const; default: throw new Error('Trezor firmware cannot sign taproot multisig. Use a Ledger or a taproot-capable coordinator for this vault.'); } } function multisigFor(vault: BtcVault, change: number, index: number) { // pubkeys_order LEXICOGRAPHIC (1) makes the device sort like sortedmulti return { pubkeys: vault.cosigners.map((c) => ({ node: c.xpub, address_n: [change, index] })), signatures: vault.cosigners.map(() => ''), m: vault.m, pubkeys_order: 1, }; } function refTx(rawHex: string) { const t = btc.RawTx.decode(hex.decode(rawHex)); const id = btc.Transaction.fromRaw(hex.decode(rawHex), { allowUnknownOutputs: true, allowUnknownInputs: true, disableScriptCheck: true }).id; return { hash: id, version: t.version, lock_time: t.lockTime, inputs: t.inputs.map((i) => ({ prev_hash: hex.encode(i.txid), prev_index: i.index, script_sig: hex.encode(i.finalScriptSig), sequence: i.sequence })), bin_outputs: t.outputs.map((o) => ({ amount: o.amount.toString(), script_pubkey: hex.encode(o.script) })), }; } /** Signs all inputs with the connected Trezor and merges its signatures into the PSBT. */ export async function trezorSignPsbt(vault: BtcVault, psbtB64: string): Promise<{ psbt: string; fingerprint: string }> { const types = scriptTypes(vault); const T = await connect(); const tx = parsePsbt(psbtB64); const net = vault.network === 'mainnet' ? btc.NETWORK : btc.TEST_NETWORK; // Which cosigner is this device? Ask for its fingerprint first. const probePath = normalizePath(vault.cosigners[0].path).split('/').slice(0, 2).join('/'); const probe = unwrap(await T.getPublicKey({ path: probePath, coin: coinOf(vault.network), showOnTrezor: false })); const fingerprint = (probe.fingerprint >>> 0).toString(16).padStart(8, '0'); const me = vault.cosigners.find((c) => c.fingerprint === fingerprint); if (!me) throw new Error('This Trezor is not one of the vault cosigners (fingerprint ' + fingerprint + ').'); const myPath = parsePath(me.path); const inputs: any[] = []; const refTxs: any[] = []; const positions: { change: number; index: number }[] = []; for (let i = 0; i < tx.inputsLength; i++) { const inp = tx.getInput(i); const der = (inp.bip32Derivation || []).find(([, d]) => d.fingerprint === parseInt(fingerprint, 16)); if (!der) throw new Error(`Input ${i} has no derivation for this device.`); const p = der[1].path; const change = p[p.length - 2], index = p[p.length - 1]; positions.push({ change, index }); const amount = inp.witnessUtxo?.amount ?? inp.nonWitnessUtxo!.outputs[inp.index!].amount; inputs.push({ address_n: [...myPath, change, index], prev_hash: hex.encode(inp.txid!), prev_index: inp.index, amount: amount.toString(), sequence: inp.sequence, script_type: types.input, multisig: multisigFor(vault, change, index), }); if (inp.nonWitnessUtxo) refTxs.push(refTx(hex.encode(btc.RawTx.encode(inp.nonWitnessUtxo)))); } const outputs: any[] = []; for (let i = 0; i < tx.outputsLength; i++) { const o = tx.getOutput(i); const der = (o.bip32Derivation || []).find(([, d]) => d.fingerprint === parseInt(fingerprint, 16)); if (der) { const p = der[1].path; const change = p[p.length - 2], index = p[p.length - 1]; if (hex.encode(deriveAddress(vault, change as 0 | 1, index).script) === hex.encode(o.script!)) { outputs.push({ address_n: [...myPath, change, index], amount: o.amount!.toString(), script_type: types.output, multisig: multisigFor(vault, change, index) }); continue; } } outputs.push({ address: btc.Address(net).encode(btc.OutScript.decode(o.script!)), amount: o.amount!.toString(), script_type: 'PAYTOADDRESS' }); } const res = unwrap<{ signatures: string[] }>(await T.signTransaction({ coin: coinOf(vault.network), inputs, outputs, refTxs, version: tx.version, locktime: tx.lockTime, push: false, })); res.signatures.forEach((sigHex, i) => { if (!sigHex) return; const { change, index } = positions[i]; const key = deriveAddress(vault, change as 0 | 1, index).keys.find((k) => k.fingerprint === parseInt(fingerprint, 16))!; const sig = new Uint8Array([...hex.decode(sigHex), btc.SigHash.ALL]); tx.updateInput(i, { partialSig: [[key.pubkey, sig]] }, true); }); return { psbt: toBase64(tx), fingerprint }; } // ------------------------------------------------------------- Ethereum export async function trezorEthAddress(path: string): Promise { const T = await connect(); return unwrap<{ address: string }>(await T.ethereumGetAddress({ path, showOnTrezor: false })).address; } export async function trezorEthSignTyped(path: string, typedData: any, domainHash: string, structHash: string): Promise { const T = await connect(); const r = unwrap<{ signature: string }>(await T.ethereumSignTypedData({ path, data: typedData, metamask_v4_compat: true, // Trezor Model One can only sign the hashes; newer models show the full message domain_separator_hash: domainHash.replace(/^0x/, ''), message_hash: structHash.replace(/^0x/, ''), })); return r.signature.startsWith('0x') ? r.signature : '0x' + r.signature; }