@qntx/wallet-chains 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,465 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-DtIS0ZWB.mjs";
3
+ import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
4
+ import { Address, OutScript, p2pkh, p2sh, p2tr, p2wpkh } from "@scure/btc-signer/payment.js";
5
+ import { SigHash, Transaction, getInputType } from "@scure/btc-signer/transaction.js";
6
+ import { HDKey } from "@scure/bip32";
7
+ import { base64 } from "@scure/base";
8
+ //#region src/bitcoin/psbt.ts
9
+ /**
10
+ * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what
11
+ * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network
12
+ * marker.
13
+ */
14
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ /**
16
+ * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are
17
+ * { hashes, der: { fingerprint, path } }.
18
+ */
19
+ const derivationPaths = (map) => {
20
+ const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$2(map) ? Object.values(map) : [];
21
+ const paths = [];
22
+ for (const entry of entries) {
23
+ const value = Array.isArray(entry) ? entry[1] : entry;
24
+ if (!isRecord$2(value)) continue;
25
+ const { path } = isRecord$2(value["der"]) ? value["der"] : value;
26
+ if (Array.isArray(path) && path.every((p) => typeof p === "number")) paths.push(path);
27
+ }
28
+ return paths;
29
+ };
30
+ const checkPaths = (paths, where, coinType) => {
31
+ for (const path of paths) if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType) throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
32
+ };
33
+ const checkDerivations = (tx, coinType) => {
34
+ for (let i = 0; i < tx.inputsLength; i++) {
35
+ const input = tx.getInput(i);
36
+ checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
37
+ checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
38
+ }
39
+ for (let i = 0; i < tx.outputsLength; i++) {
40
+ const output = tx.getOutput(i);
41
+ checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
42
+ checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
43
+ }
44
+ };
45
+ const DEFAULT_SIGHASH = 0;
46
+ const SIGHASH_ALL = 1;
47
+ const isTaprootInput = (input) => input.tapInternalKey !== void 0 || getInputType(input).type === "taproot";
48
+ /**
49
+ * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).
50
+ * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its
51
+ * outpoint.
52
+ */
53
+ const normalizeBitcoinPsbt = (psbt, sign, network) => {
54
+ const net = bitcoinNetwork(network);
55
+ let tx;
56
+ try {
57
+ tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
58
+ } catch {
59
+ throw new ChainError("invalid-request", "PSBT failed to decode");
60
+ }
61
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0)) throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
62
+ const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
63
+ const last = unique.at(-1);
64
+ if (unique.length !== sign.length || last === void 0 || last >= tx.inputsLength) throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
65
+ checkDerivations(tx, net.coinType);
66
+ for (const idx of unique) {
67
+ const input = tx.getInput(idx);
68
+ if (input.witnessUtxo === void 0 && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
69
+ if (input.bip32Derivation === void 0 && input.tapBip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
70
+ const { type } = getInputType(input);
71
+ if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
72
+ const sighash = input.sighashType;
73
+ if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
74
+ }
75
+ return {
76
+ psbt: tx.toPSBT(0),
77
+ sign: unique
78
+ };
79
+ };
80
+ //#endregion
81
+ //#region src/bitcoin/account.ts
82
+ /** Public-derivation helpers for account-level extended keys — no secrets involved. */
83
+ /**
84
+ * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or
85
+ * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.
86
+ */
87
+ function bitcoinAddressFromXpub(xpub, template, network, change, index) {
88
+ if (!Number.isInteger(index) || index < 0) throw new ChainError("invalid-request", "index must be a non-negative integer");
89
+ const net = bitcoinNetwork(network);
90
+ let node;
91
+ try {
92
+ node = HDKey.fromExtendedKey(xpub, net.bip32);
93
+ } catch (error) {
94
+ throw new ChainError("invalid-request", `xpub: ${error instanceof Error ? error.message : String(error)}`);
95
+ }
96
+ const pub = node.derive(`m/${change}/${index}`).publicKey;
97
+ if (pub === null) throw new ChainError("invalid-request", "xpub carries no public key");
98
+ const address = template === "btc.bip84" ? p2wpkh(pub, net.params).address : template === "btc.bip49" ? p2sh(p2wpkh(pub, net.params), net.params).address : template === "btc.bip44" ? p2pkh(pub, net.params).address : p2tr(pub.subarray(1), void 0, net.params).address;
99
+ if (address === void 0) throw new ChainError("invalid-request", "could not encode the derived address");
100
+ return address;
101
+ }
102
+ /**
103
+ * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level
104
+ * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel
105
+ * can re-derive it.
106
+ */
107
+ function bitcoinPubkeyFromXpub(xpub, template, network, change, index) {
108
+ if (!Number.isInteger(index) || index < 0) throw new ChainError("invalid-request", "index must be a non-negative integer");
109
+ const net = bitcoinNetwork(network);
110
+ let node;
111
+ try {
112
+ node = HDKey.fromExtendedKey(xpub, net.bip32);
113
+ } catch (error) {
114
+ throw new ChainError("invalid-request", `xpub: ${error instanceof Error ? error.message : String(error)}`);
115
+ }
116
+ const pub = node.derive(`m/${change}/${index}`).publicKey;
117
+ if (pub === null) throw new ChainError("invalid-request", "xpub carries no public key");
118
+ return template === "btc.bip86" ? pub.subarray(1) : pub;
119
+ }
120
+ //#endregion
121
+ //#region src/bitcoin/decode.ts
122
+ const SATS = "sats";
123
+ const OP_RETURN = 106;
124
+ const bytesToHex = (bytes) => {
125
+ let out = "";
126
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
127
+ return out;
128
+ };
129
+ /** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */
130
+ const decodeOutput = (script, amount) => {
131
+ const hex = bytesToHex(script);
132
+ if (script[0] === OP_RETURN) return {
133
+ amount,
134
+ script: hex,
135
+ opReturn: true
136
+ };
137
+ return {
138
+ amount,
139
+ script: hex,
140
+ opReturn: false
141
+ };
142
+ };
143
+ /**
144
+ * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script
145
+ * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving
146
+ * change) — not a display hint.
147
+ */
148
+ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
149
+ const tx = Transaction.fromPSBT(request.psbt);
150
+ const coder = Address(bitcoinNetwork(request.network).params);
151
+ const signed = new Set(request.sign);
152
+ const outflows = [];
153
+ let canFee = true;
154
+ let outSum = 0n;
155
+ for (let i = 0; i < tx.outputsLength; i++) {
156
+ const output = tx.getOutput(i);
157
+ const { script } = output;
158
+ const { amount } = output;
159
+ if (script === void 0 || amount === void 0) continue;
160
+ const decoded = decodeOutput(script, amount);
161
+ outSum += amount;
162
+ if (decoded.opReturn || ownScripts.has(decoded.script)) continue;
163
+ let addr;
164
+ try {
165
+ const out = OutScript.decode(script);
166
+ addr = out === void 0 ? void 0 : coder.encode(out);
167
+ } catch {
168
+ addr = void 0;
169
+ }
170
+ outflows.push({
171
+ to: addr ?? decoded.script,
172
+ amount: {
173
+ asset: SATS,
174
+ amount: amount.toString(10)
175
+ },
176
+ verified: addr !== void 0
177
+ });
178
+ }
179
+ let inSum = 0n;
180
+ for (let i = 0; i < tx.inputsLength; i++) {
181
+ const input = tx.getInput(i);
182
+ if (input.witnessUtxo === void 0) canFee = false;
183
+ else inSum += input.witnessUtxo.amount;
184
+ }
185
+ const external = tx.inputsLength - signed.size > 0;
186
+ const undecodable = outflows.some((o) => !o.verified);
187
+ const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
188
+ return {
189
+ family: "bitcoin",
190
+ network: request.network,
191
+ summary: outflows.length > 0 ? "transfer" : "contract-call",
192
+ outflows,
193
+ approvals: [],
194
+ fee: canFee ? { max: {
195
+ asset: SATS,
196
+ amount: (inSum - outSum).toString(10)
197
+ } } : void 0,
198
+ warnings: [],
199
+ verifiability
200
+ };
201
+ };
202
+ const verifiabilityBitcoin = (request, ownScripts = /* @__PURE__ */ new Set()) => decodeBitcoinPsbt(request, ownScripts).verifiability;
203
+ //#endregion
204
+ //#region src/bitcoin/verify.ts
205
+ /**
206
+ * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the
207
+ * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.
208
+ * `/bitcoin` entry only — no private key material.
209
+ */
210
+ const isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);
211
+ /** Derive the child's public key from the account xpub at `change/index` (non-hardened). */
212
+ const childPub = (xpub, network, change, index) => {
213
+ const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32).deriveChild(change).deriveChild(index);
214
+ if (child.publicKey === null || child.publicKey === void 0) throw new Error("xpub cannot derive this child");
215
+ return child.publicKey;
216
+ };
217
+ /** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */
218
+ const derivationOf = (map) => {
219
+ const out = [];
220
+ const readEntry = (key, value) => {
221
+ const der = isRecord$1(value) && isRecord$1(value["der"]) ? value["der"] : value;
222
+ const { path } = isRecord$1(der) ? der : {};
223
+ if (key instanceof Uint8Array && Array.isArray(path) && path.every((p) => typeof p === "number")) out.push({
224
+ pubkey: key,
225
+ path
226
+ });
227
+ };
228
+ if (map instanceof Map) for (const [key, value] of map) readEntry(key, value);
229
+ else if (Array.isArray(map)) {
230
+ for (const entry of map) if (Array.isArray(entry) && entry.length === 2) readEntry(entry[0], entry[1]);
231
+ }
232
+ return out;
233
+ };
234
+ /** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */
235
+ const tailOf = (path) => {
236
+ const change = path.at(-2);
237
+ const index = path.at(-1);
238
+ if (change !== 0 && change !== 1 || index === void 0 || index < 0 || index >= 2147483648) return;
239
+ return {
240
+ change,
241
+ index
242
+ };
243
+ };
244
+ const eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
245
+ /**
246
+ * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's
247
+ * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must
248
+ * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).
249
+ */
250
+ const preimageLegacy = (tx, idx, scriptCode, sighashType) => {
251
+ const f = Reflect.get(tx, "preimageLegacy");
252
+ if (typeof f !== "function") return /* @__PURE__ */ new Uint8Array(0);
253
+ const out = Reflect.apply(f, tx, [
254
+ idx,
255
+ scriptCode,
256
+ sighashType
257
+ ]);
258
+ return out instanceof Uint8Array ? out : /* @__PURE__ */ new Uint8Array(0);
259
+ };
260
+ const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network) => {
261
+ try {
262
+ const tx = Transaction.fromPSBT(signedPsbt);
263
+ const taproot = template === "btc.bip86";
264
+ for (const idx of sign) {
265
+ const input = tx.getInput(idx);
266
+ const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(({ path }) => tailOf(path) !== void 0);
267
+ const tail = claimed === void 0 ? void 0 : tailOf(claimed.path);
268
+ if (claimed === void 0 || tail === void 0) return false;
269
+ const vout = input.index;
270
+ const nw = input.nonWitnessUtxo;
271
+ const legacyOut = nw === void 0 || vout === void 0 ? void 0 : nw.outputs[vout];
272
+ const prevout = input.witnessUtxo ?? legacyOut;
273
+ if (prevout === void 0) return false;
274
+ const prevScript = prevout.script;
275
+ const prevAmount = prevout.amount;
276
+ const pub = childPub(xpub, network, tail.change, tail.index);
277
+ if (taproot) {
278
+ const xonly = pub.slice(1);
279
+ const rawSig = input.tapKeySig;
280
+ if (!eq(claimed.pubkey, xonly) || !(rawSig instanceof Uint8Array) || rawSig.length !== 64 && rawSig.length !== 65) return false;
281
+ const sighashType = rawSig.length === 65 ? rawSig[64] ?? SigHash.DEFAULT : SigHash.DEFAULT;
282
+ const sig = rawSig.slice(0, 64);
283
+ const scripts = [];
284
+ const amounts = [];
285
+ let complete = true;
286
+ for (let i = 0; i < tx.inputsLength; i++) {
287
+ const w = tx.getInput(i).witnessUtxo;
288
+ if (w === void 0) {
289
+ complete = false;
290
+ break;
291
+ }
292
+ scripts.push(w.script);
293
+ amounts.push(w.amount);
294
+ }
295
+ if (!complete || !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), xonly)) return false;
296
+ } else {
297
+ const partial = input.partialSig;
298
+ const found = Array.isArray(partial) ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub)) : void 0;
299
+ const rawSig = Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : void 0;
300
+ if (!eq(claimed.pubkey, pub) || rawSig === void 0 || rawSig.length === 0) return false;
301
+ const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;
302
+ const effective = input.redeemScript ?? prevScript;
303
+ const decoded = OutScript.decode(effective);
304
+ const scriptCode = decoded !== void 0 && decoded.type === "wpkh" ? OutScript.encode({
305
+ type: "pkh",
306
+ hash: decoded.hash
307
+ }) : effective;
308
+ const hash = input.nonWitnessUtxo === void 0 ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount) : preimageLegacy(tx, idx, scriptCode, sighashType);
309
+ if (!secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), hash, pub, { prehash: false })) return false;
310
+ }
311
+ }
312
+ return true;
313
+ } catch {
314
+ return false;
315
+ }
316
+ };
317
+ /** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */
318
+ const witnessOf = (sig) => {
319
+ if (!sig.startsWith("smp")) return;
320
+ const raw = base64.decode(sig.slice(3));
321
+ if (raw === void 0 || raw.length === 0) return;
322
+ const items = [];
323
+ let off = 1;
324
+ for (let i = 0; i < (raw[0] ?? 0); i++) {
325
+ const len = raw[off];
326
+ if (len === void 0 || off + 1 + len > raw.length) return;
327
+ items.push(raw.slice(off + 1, off + 1 + len));
328
+ off += 1 + len;
329
+ }
330
+ return off === raw.length ? items : void 0;
331
+ };
332
+ /**
333
+ * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer
334
+ * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.
335
+ */
336
+ const verifyBitcoinMessage = (address, message, signatureBase64, network) => {
337
+ try {
338
+ const net = bitcoinNetwork(network);
339
+ const scriptPubKey = OutScript.encode(Address(net.params).decode(address));
340
+ const witness = witnessOf(signatureBase64);
341
+ if (witness === void 0 || witness.length === 0) return false;
342
+ const tx = new Transaction({
343
+ version: 0,
344
+ lockTime: 0,
345
+ allowUnknownOutputs: true
346
+ });
347
+ tx.addInput({
348
+ txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),
349
+ index: 0,
350
+ sequence: 0,
351
+ witnessUtxo: {
352
+ script: scriptPubKey,
353
+ amount: 0n
354
+ }
355
+ });
356
+ tx.addOutput({
357
+ script: Uint8Array.of(106),
358
+ amount: 0n
359
+ });
360
+ if (scriptPubKey.at(0) === 81) {
361
+ const [rawSig] = witness;
362
+ const xonly = scriptPubKey.slice(2);
363
+ if (rawSig === void 0 || xonly.length !== 32 || rawSig.length !== 64 && rawSig.length !== 65) return false;
364
+ const sighashType = rawSig.length === 65 ? rawSig.at(64) ?? SigHash.DEFAULT : SigHash.DEFAULT;
365
+ return schnorr.verify(rawSig.slice(0, 64), tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]), xonly);
366
+ }
367
+ const [rawSig, pub] = witness;
368
+ if (rawSig === void 0 || pub === void 0 || pub.length !== 33 || rawSig.length === 0) return false;
369
+ const sighashType = rawSig.at(-1) ?? SigHash.ALL;
370
+ const decoded = OutScript.decode(scriptPubKey);
371
+ const scriptCode = decoded !== void 0 && decoded.type === "wpkh" ? OutScript.encode({
372
+ type: "pkh",
373
+ hash: decoded.hash
374
+ }) : scriptPubKey;
375
+ return secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), tx.preimageWitnessV0(0, scriptCode, sighashType, 0n), pub, { prehash: false });
376
+ } catch {
377
+ return false;
378
+ }
379
+ };
380
+ //#endregion
381
+ //#region src/bitcoin/index.ts
382
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
383
+ const isAccountRef = (value) => {
384
+ if (!isRecord(value) || typeof value["kind"] !== "string") return false;
385
+ if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
386
+ return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
387
+ };
388
+ const common = (request) => {
389
+ const { network } = request;
390
+ const { account } = request;
391
+ if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
392
+ if (!isAccountRef(account)) throw new ChainError("invalid-request", "request.account must be an AccountRef");
393
+ bitcoinNetwork(network);
394
+ return {
395
+ network,
396
+ account
397
+ };
398
+ };
399
+ const messageTarget = (address, network, format) => {
400
+ if (typeof address !== "string") throw new ChainError("invalid-request", "address must be a string");
401
+ const net = bitcoinNetwork(network);
402
+ let decoded;
403
+ try {
404
+ decoded = Address(net.params).decode(address);
405
+ } catch {
406
+ throw new ChainError("invalid-address", "address does not belong to this network");
407
+ }
408
+ if (format === "bip322-simple") {
409
+ if (decoded.type !== "wpkh" && decoded.type !== "tr") throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
410
+ } else if (format === "legacy") {
411
+ if (decoded.type !== "pkh") throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
412
+ } else throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
413
+ const scriptPubKey = OutScript.encode(decoded);
414
+ return {
415
+ type: decoded.type,
416
+ address,
417
+ format,
418
+ scriptPubKey
419
+ };
420
+ };
421
+ /**
422
+ * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical
423
+ * re-serialization.
424
+ */
425
+ const normalizeBitcoin = (request) => {
426
+ if (!isRecord(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
427
+ const { network, account } = common(request);
428
+ if (request["kind"] === "bitcoin.psbt") {
429
+ const { psbt } = request;
430
+ if (!(psbt instanceof Uint8Array)) throw new ChainError("invalid-request", "psbt must be bytes");
431
+ const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
432
+ return {
433
+ kind: "bitcoin.psbt",
434
+ network,
435
+ account,
436
+ psbt: normalized.psbt,
437
+ sign: normalized.sign
438
+ };
439
+ }
440
+ if (request["kind"] === "bitcoin.message") {
441
+ const { format } = request;
442
+ const target = messageTarget(request["address"], network, format);
443
+ const { message, change, index } = request;
444
+ if (typeof message !== "string") throw new ChainError("invalid-request", "message must be a string");
445
+ if (change !== 0 && change !== 1) throw new ChainError("invalid-request", "change must be 0 or 1");
446
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648) throw new ChainError("invalid-request", "index must be a non-hardened path index");
447
+ return {
448
+ kind: "bitcoin.message",
449
+ network,
450
+ account,
451
+ address: target.address,
452
+ message,
453
+ format: target.format,
454
+ change,
455
+ index
456
+ };
457
+ }
458
+ throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
459
+ };
460
+ /** Decodes the message `address` into the scriptPubKey the signer needs. */
461
+ const decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
462
+ //#endregion
463
+ export { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, decodeBitcoinPsbt, decodeMessageTarget, normalizeBitcoin, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures };
464
+
465
+ //# sourceMappingURL=bitcoin.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitcoin.mjs","names":["isRecord","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<number> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (\n !Array.isArray(sign) ||\n sign.length === 0 ||\n !sign.every((i) => Number.isSafeInteger(i) && i >= 0)\n ) {\n throw new ChainError(\"invalid-request\", \"sign must be a non-empty array of input indices\");\n }\n const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);\n const last = unique.at(-1);\n if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const idx of unique) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\n \"invalid-request\",\n `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`,\n );\n }\n if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH);\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n }\n return { psbt: tx.toPSBT(0), sign: unique };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2pkh, p2sh, p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nexport type BitcoinAccountTemplate = \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : template === \"btc.bip49\"\n ? p2sh(p2wpkh(pub, net.params), net.params).address\n : template === \"btc.bip44\"\n ? p2pkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n\n/**\n * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level\n * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel\n * can re-derive it.\n */\nexport function bitcoinPubkeyFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): Uint8Array {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const pub = node.derive(`m/${change}/${index}`).publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n // bip44/bip49 keep the compressed key — the signing kernel needs it for\n // redeemScript/scriptSig; only bip86 derives to the x-only key.\n return template === \"btc.bip86\" ? pub.subarray(1) : pub;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst OP_RETURN = 0x6a;\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = Transaction.fromPSBT(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign);\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const verifiability: Verifiability = external ? \"opaque\" : undecodable ? \"partial\" : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee: canFee ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } } : undefined,\n warnings: [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nconst preimageLegacy = (\n tx: Transaction,\n idx: number,\n scriptCode: Uint8Array,\n sighashType: number,\n): Uint8Array => {\n const f: unknown = Reflect.get(tx, \"preimageLegacy\");\n if (typeof f !== \"function\") {\n return new Uint8Array(0);\n }\n const out: unknown = Reflect.apply(f, tx, [idx, scriptCode, sighashType]);\n return out instanceof Uint8Array ? out : new Uint8Array(0);\n};\n\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const vout = input.index;\n const nw:\n | {\n readonly outputs: ReadonlyArray<{\n readonly script: Uint8Array;\n readonly amount: bigint;\n }>;\n }\n | undefined = input.nonWitnessUtxo;\n const legacyOut = nw === undefined || vout === undefined ? undefined : nw.outputs[vout];\n const prevout = input.witnessUtxo ?? legacyOut;\n if (prevout === undefined) {\n return false;\n }\n const prevScript: Uint8Array = prevout.script;\n const prevAmount: bigint = prevout.amount;\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), xonly)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n // bip49 prevouts are P2SH — the BIP143 scriptCode is the inner P2WPKH\n // redeem script, canonicalized to the equivalent P2PKH script.\n const effective: Uint8Array = input.redeemScript ?? prevScript;\n const decoded = OutScript.decode(effective);\n const scriptCode: Uint8Array =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : effective;\n // P2PKH inputs sign the legacy (non-segwit) preimage — btc-signer exposes it as a\n // private method; the public witness preimages do not apply to non-witness inputs.\n const hash =\n input.nonWitnessUtxo === undefined\n ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount)\n : preimageLegacy(tx, idx, scriptCode, sighashType);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub, bitcoinPubkeyFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isAccountRef = (value: unknown): value is AccountRef => {\n if (!isRecord(value) || typeof value[\"kind\"] !== \"string\") {\n return false;\n }\n if (value[\"kind\"] === \"hd\") {\n return (\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"template\"] === \"string\"\n );\n }\n return (\n value[\"kind\"] === \"imported\" &&\n typeof value[\"keyId\"] === \"string\" &&\n typeof value[\"family\"] === \"string\"\n );\n};\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const { network } = request;\n const { account } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n if (!isAccountRef(account)) {\n throw new ChainError(\"invalid-request\", \"request.account must be an AccountRef\");\n }\n bitcoinNetwork(network);\n return { network, account };\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (request: unknown): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n const { network, account } = common(request);\n if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { psbt } = request;\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return { kind: \"bitcoin.psbt\", network, account, psbt: normalized.psbt, sign: normalized.sign };\n }\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UA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AAE,WAAW;EACnB,MAAM,SAAS,cAAc,QAAQ,YAAY,SAAS,MAAM;EAEhE,MAAM,EAAE,SAAS,QAAQ,UAAU;EACnC,IAAI,OAAO,YAAY,UACrB,MAAM,IAAI,WAAW,mBAAmB,0BAA0B;EAEpE,IAAI,WAAW,KAAK,WAAW,GAC7B,MAAM,IAAI,WAAW,mBAAmB,uBAAuB;EAEjE,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,KACR,SAAS,YAET,MAAM,IAAI,WAAW,mBAAmB,yCAAyC;EAEnF,OAAO;GACL,MAAM;GACN;GACA;GACA,SAAS,OAAO;GAChB;GACA,QAAQ,OAAO;GACf;GACA;EACF;CACF;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF;;AAGA,MAAa,uBACX,YACkB,cAAc,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM"}
@@ -0,0 +1,10 @@
1
+ import { EvmTransaction } from "./index.mjs";
2
+ //#region src/evm/sign.d.ts
3
+ /** Signs a normalized transaction; returns the serialized signed envelope. */
4
+ export declare const signEvmTransaction: (tx: EvmTransaction, privateKey: Uint8Array) => Uint8Array;
5
+ /** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
6
+ export declare const signEvmPersonalMessage: (message: Uint8Array, privateKey: Uint8Array) => Uint8Array;
7
+ /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
8
+ export declare const signEvmTypedData: (typedData: string, privateKey: Uint8Array) => Uint8Array;
9
+ //#endregion
10
+ //# sourceMappingURL=evm-sign.d.mts.map
@@ -0,0 +1,94 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { t as parseTypedData } from "./typed-data-C6XANSQF.mjs";
3
+ import * as TypedData from "ox/TypedData";
4
+ import * as Hex from "ox/Hex";
5
+ import * as PersonalMessage from "ox/PersonalMessage";
6
+ import * as Secp256k1 from "ox/Secp256k1";
7
+ import * as Signature from "ox/Signature";
8
+ import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
9
+ import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
10
+ import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
11
+ //#region src/evm/sign.ts
12
+ /**
13
+ * /evm/sign — deterministic (RFC 6979) ECDSA signing over the chain's canonical payloads. Inputs
14
+ * must already be normalized: the kernel calls `normalizeEvm` first and rejects on a ChainError. No
15
+ * key caching; the caller wipes key bytes.
16
+ */
17
+ /** Validates a string is `0x`-hex and narrows it for ox's branded type. */
18
+ function assertHex(value, field) {
19
+ if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be 0x-prefixed bytes`);
20
+ }
21
+ const hex = (value, field) => {
22
+ assertHex(value, field);
23
+ return value;
24
+ };
25
+ const key = (privateKey) => {
26
+ if (privateKey.length !== 32) throw new ChainError("invalid-request", "private key must be 32 bytes");
27
+ return Hex.fromBytes(privateKey);
28
+ };
29
+ const accessEntry = (entry) => ({
30
+ address: hex(entry.address, "accessList.address"),
31
+ storageKeys: entry.storageKeys.map((k) => hex(k, "accessList.storageKeys"))
32
+ });
33
+ const sign = (payload, privateKey) => Secp256k1.sign({
34
+ payload,
35
+ privateKey,
36
+ as: "Object"
37
+ });
38
+ /** Signs a normalized transaction; returns the serialized signed envelope. */
39
+ const signEvmTransaction = (tx, privateKey) => {
40
+ const privateKeyHex = key(privateKey);
41
+ const base = {
42
+ chainId: tx.chainId,
43
+ to: tx.to === void 0 ? void 0 : hex(tx.to, "to"),
44
+ data: hex(tx.data, "data"),
45
+ value: BigInt(tx.value),
46
+ nonce: BigInt(tx.nonce),
47
+ gas: BigInt(tx.gas)
48
+ };
49
+ if (tx.type === "legacy") {
50
+ const envelope = {
51
+ ...base,
52
+ type: "legacy",
53
+ gasPrice: BigInt(tx.gasPrice)
54
+ };
55
+ const signature = sign(TxEnvelopeLegacy.getSignPayload(envelope), privateKeyHex);
56
+ return Hex.toBytes(TxEnvelopeLegacy.serialize(envelope, { signature }));
57
+ }
58
+ if (tx.type === "eip2930") {
59
+ const envelope = {
60
+ ...base,
61
+ type: "eip2930",
62
+ gasPrice: BigInt(tx.gasPrice),
63
+ accessList: tx.accessList.map(accessEntry)
64
+ };
65
+ const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);
66
+ return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));
67
+ }
68
+ const envelope = {
69
+ ...base,
70
+ type: "eip1559",
71
+ accessList: tx.accessList.map(accessEntry),
72
+ maxFeePerGas: BigInt(tx.maxFeePerGas),
73
+ maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas)
74
+ };
75
+ const signature = sign(TxEnvelopeEip1559.getSignPayload(envelope), privateKeyHex);
76
+ return Hex.toBytes(TxEnvelopeEip1559.serialize(envelope, { signature }));
77
+ };
78
+ /** 65-byte r‖s‖v; `Signature.toBytes` emits v = 27 + yParity already. */
79
+ const rs_v = (signature) => Signature.toBytes(signature);
80
+ /** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
81
+ const signEvmPersonalMessage = (message, privateKey) => {
82
+ const payload = PersonalMessage.getSignPayload(Hex.fromBytes(message));
83
+ return rs_v(Signature.from(sign(payload, key(privateKey))));
84
+ };
85
+ /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
86
+ const signEvmTypedData = (typedData, privateKey) => {
87
+ const { json } = parseTypedData(typedData, "eip155:1");
88
+ const payload = TypedData.getSignPayload(json);
89
+ return rs_v(Signature.from(sign(payload, key(privateKey))));
90
+ };
91
+ //#endregion
92
+ export { signEvmPersonalMessage, signEvmTransaction, signEvmTypedData };
93
+
94
+ //# sourceMappingURL=evm-sign.mjs.map