@qntx/wallet-chains 0.12.0 → 0.14.0

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.
Files changed (62) hide show
  1. package/README.md +13 -10
  2. package/dist/{account-ref-D2rW_qlI.mjs → account-ref-BFTeEyHt.mjs} +2 -2
  3. package/dist/{account-ref-D2rW_qlI.mjs.map → account-ref-BFTeEyHt.mjs.map} +1 -1
  4. package/dist/assemble-8GvNDony.mjs +405 -0
  5. package/dist/assemble-8GvNDony.mjs.map +1 -0
  6. package/dist/assemble-B3sO9Fvc.mjs +629 -0
  7. package/dist/assemble-B3sO9Fvc.mjs.map +1 -0
  8. package/dist/assemble-BdiPo0ZX.mjs +32 -0
  9. package/dist/assemble-BdiPo0ZX.mjs.map +1 -0
  10. package/dist/assets-sg2_Z3nZ.mjs +200 -0
  11. package/dist/assets-sg2_Z3nZ.mjs.map +1 -0
  12. package/dist/bitcoin-sign.d.mts +3 -0
  13. package/dist/bitcoin-sign.mjs +52 -18
  14. package/dist/bitcoin-sign.mjs.map +1 -1
  15. package/dist/bitcoin.d.mts +123 -7
  16. package/dist/bitcoin.mjs +162 -69
  17. package/dist/bitcoin.mjs.map +1 -1
  18. package/dist/evm-sign.d.mts +3 -1
  19. package/dist/evm-sign.mjs +25 -82
  20. package/dist/evm-sign.mjs.map +1 -1
  21. package/dist/evm.d.mts +252 -22
  22. package/dist/evm.mjs +2460 -448
  23. package/dist/evm.mjs.map +1 -1
  24. package/dist/families-BlgplKAJ.mjs +412 -0
  25. package/dist/families-BlgplKAJ.mjs.map +1 -0
  26. package/dist/index-CIRaHKpx.d.mts +941 -0
  27. package/dist/index.d.mts +2 -2
  28. package/dist/index.mjs +1 -1
  29. package/dist/networks.d.mts +29 -0
  30. package/dist/networks.mjs +245 -0
  31. package/dist/networks.mjs.map +1 -0
  32. package/dist/plan-wCnxHqRu.mjs +1311 -0
  33. package/dist/plan-wCnxHqRu.mjs.map +1 -0
  34. package/dist/solana-sign.d.mts +3 -0
  35. package/dist/solana-sign.mjs +23 -10
  36. package/dist/solana-sign.mjs.map +1 -1
  37. package/dist/solana.d.mts +136 -24
  38. package/dist/solana.mjs +1244 -63
  39. package/dist/solana.mjs.map +1 -1
  40. package/dist/src-CHB_z45M.mjs +387 -0
  41. package/dist/src-CHB_z45M.mjs.map +1 -0
  42. package/dist/tasks-7AFv3PQn.mjs +86 -0
  43. package/dist/tasks-7AFv3PQn.mjs.map +1 -0
  44. package/dist/token-call-DH22g8BL.mjs +914 -0
  45. package/dist/token-call-DH22g8BL.mjs.map +1 -0
  46. package/dist/tron-sign.d.mts +10 -0
  47. package/dist/tron-sign.mjs +36 -0
  48. package/dist/tron-sign.mjs.map +1 -0
  49. package/dist/tron.d.mts +328 -0
  50. package/dist/tron.mjs +1484 -0
  51. package/dist/tron.mjs.map +1 -0
  52. package/dist/typed-data-CE9h4U0F.d.mts +51 -0
  53. package/dist/typed-data-DRtKULsH.mjs +466 -0
  54. package/dist/typed-data-DRtKULsH.mjs.map +1 -0
  55. package/package.json +17 -10
  56. package/dist/index-DYwm4-Ec.d.mts +0 -256
  57. package/dist/message-ChhEZ0lx.mjs +0 -188
  58. package/dist/message-ChhEZ0lx.mjs.map +0 -1
  59. package/dist/src-8NZeEnrW.mjs +0 -67
  60. package/dist/src-8NZeEnrW.mjs.map +0 -1
  61. package/dist/typed-data-J5g2WemC.mjs +0 -227
  62. package/dist/typed-data-J5g2WemC.mjs.map +0 -1
@@ -1,5 +1,6 @@
1
- import { a as BitcoinTemplate, b as Verifiability, l as DisplayIntent, v as SignRequest } from "./index-DYwm4-Ec.mjs";
1
+ import { F as SignRequest, G as Verifiability, c as BitcoinTemplate, i as Assembled, m as EcdsaTask, p as DisplayIntent, s as Bip340Task, z as TaskKey } from "./index-CIRaHKpx.mjs";
2
2
  import { NETWORK } from "@scure/btc-signer/utils.js";
3
+ import { Transaction } from "@scure/btc-signer/transaction.js";
3
4
  type BitcoinNetwork = {
4
5
  readonly caip2: string;
5
6
  readonly genesis: string;
@@ -26,22 +27,137 @@ export declare function bitcoinAddressFromXpub(xpub: string, template: BitcoinAc
26
27
  */
27
28
  export declare function bitcoinPubkeyFromXpub(xpub: string, template: BitcoinAccountTemplate, network: string, change: 0 | 1, index: number): Uint8Array;
28
29
  /**
29
- * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script
30
- * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving
31
- * change) — not a display hint.
30
+ * Which own-key outputs a signing prompt may hide as change. An output on this group's keys is
31
+ * discoverable only when the wallet's gap-limited scan can reach it — anything else is shown as a
32
+ * send to the caller's own address at an unusual path, with a warning. The reach bound comes from
33
+ * the kernel's sealed change mark, never from the PSBT: an untrusted request can name any input
34
+ * path, so signed inputs may raise the mark only for requests the wallet itself built (`origin:
35
+ * "internal"`). An external request still hides change inside the window — the scan reaches it
36
+ * either way — but commits no raise at all: neither its inputs nor the indexes it hid are sealed
37
+ * into the mark.
38
+ */
39
+ /**
40
+ * BIP-44 §Address gap limit — the trailing run of unused addresses a wallet scans.
41
+ * (https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#address-gap-limit)
42
+ */
43
+ export declare const BITCOIN_GAP_LIMIT = 20;
44
+ /** The highest change-chain index a scan may reach — a hard bound on scan work. */
45
+ export declare const BITCOIN_SCAN_LIMIT = 2000;
46
+ /** Who built a `bitcoin.psbt` request: the wallet engine itself, or an outside caller. */
47
+ type BitcoinRequestOrigin = "internal" | "external";
48
+ /** The `change`/`index` tail of an account path `m/purpose'/coin'/group'/change/index`. */
49
+ type BitcoinPathTail = {
50
+ readonly purpose: number;
51
+ readonly change: number;
52
+ readonly index: number;
53
+ };
54
+ /**
55
+ * The kernel-sealed change mark for the next classification: `stored`, raised to the highest
56
+ * change-chain index among the same-purpose signed inputs — but only for a request the wallet
57
+ * itself built. An external request can name any input path, so its inputs never raise the mark.
58
+ */
59
+ export declare const requestChangeMark: (stored: number, purpose: number, signed: ReadonlyArray<BitcoinPathTail>, origin: BitcoinRequestOrigin) => number;
60
+ /**
61
+ * The own-key outputs of a PSBT, classified by the caller that independently verified them:
62
+ * `change` maps script hex to nothing — it is hidden from the prompt; `unusual` maps script hex to
63
+ * the output's `m/…` path text — it is shown as an outflow to the caller's own address;
64
+ * `unconfirmed` holds script hexes whose key sits on an entry the signer never confirmed on the
65
+ * device — shown as a plain send with a danger warning, never as "your own address".
66
+ */
67
+ type BitcoinOwn = {
68
+ readonly change: ReadonlySet<string>;
69
+ readonly unusual: ReadonlyMap<string, string>;
70
+ readonly unconfirmed: ReadonlySet<string>;
71
+ };
72
+ export declare const EMPTY_BITCOIN_OWN: BitcoinOwn;
73
+ /**
74
+ * An output is discoverable change only on the change chain (`/1/i`), under a purpose at least one
75
+ * signed input shares, at an index inside what the gap-limited scan reaches: the sealed change mark
76
+ * plus the gap limit, bounded by the scan limit.
77
+ */
78
+ export declare const isDiscoverableChange: (output: BitcoinPathTail, signed: ReadonlyArray<BitcoinPathTail>, mark: number) => boolean;
79
+ /** The last change-chain index the gap-limited scan covers for a sealed mark. */
80
+ export declare const changeScanReach: (mark: number) => number;
81
+ /**
82
+ * Decodes a normalized bitcoin.psbt request for display. `own` is the caller's independently
83
+ * verified classification of the account's own-key outputs — `change` script hexes are hidden,
84
+ * `unusual` script hexes become outflows to the caller's own address carrying the path text and one
85
+ * warning each, `unconfirmed` script hexes are plain outflows with a danger warning — not a display
86
+ * hint.
32
87
  */
33
88
  export declare const decodeBitcoinPsbt: (request: Extract<SignRequest, {
34
89
  kind: "bitcoin.psbt";
35
- }>, ownScripts?: ReadonlySet<string>) => DisplayIntent;
90
+ }>, own?: BitcoinOwn) => DisplayIntent;
36
91
  export declare const verifiabilityBitcoin: (request: Extract<SignRequest, {
37
92
  kind: "bitcoin.psbt";
38
- }>, ownScripts?: ReadonlySet<string>) => Verifiability;
93
+ }>, own?: BitcoinOwn) => Verifiability;
94
+ /**
95
+ * Whether `signed` is the PSBT `requested` asked to sign: the same unsigned transaction and, on
96
+ * every input, the same prevout data the signatures commit to. A kernel that signs another
97
+ * transaction, or the same one over altered amounts, fails this before any signature is checked.
98
+ */
99
+ export declare const samePsbtContent: (requested: Uint8Array, signed: Uint8Array) => boolean;
39
100
  export declare const verifyBitcoinPsbtSignatures: (signedPsbt: Uint8Array, sign: ReadonlyArray<number>, xpub: string, template: BitcoinAccountTemplate, network: string) => boolean;
40
101
  /**
41
102
  * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer
42
103
  * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.
43
104
  */
44
105
  export declare const verifyBitcoinMessage: (address: string, message: string, signatureBase64: string, network: string) => boolean;
106
+ /**
107
+ * Legacy "Bitcoin Signed Message" verification for a P2PKH address: recover the public key from the
108
+ * compact signature (header = 27 + recovery, +4 when the key is compressed) and compare its P2PKH
109
+ * address with `address`.
110
+ */
111
+ export declare const verifyLegacyBitcoinMessage: (address: string, message: string, signatureBase64: string, network: string) => boolean;
112
+ /** The double-SHA256 digest a legacy "Bitcoin Signed Message" signature commits to. */
113
+ export declare const legacyMessageHash: (message: string) => Uint8Array;
114
+ type BitcoinPsbtPlan = {
115
+ readonly kind: "bitcoin.psbt";
116
+ readonly psbt: Uint8Array;
117
+ /**
118
+ * Script hexes of the outputs the prompt hides as discoverable change. A device signer can strip
119
+ * the wallet's derivation entries from the other outputs so its display matches the prompt;
120
+ * undefined means no classification was computed.
121
+ */
122
+ readonly hiddenChange?: ReadonlySet<string>;
123
+ readonly inputs: ReadonlyArray<{
124
+ readonly index: number;
125
+ /** The 33-byte compressed signing key (the internal key for taproot). */
126
+ readonly publicKey: Uint8Array;
127
+ readonly sighash: number;
128
+ }>;
129
+ readonly tasks: ReadonlyArray<EcdsaTask | Bip340Task>;
130
+ };
131
+ type BitcoinMessagePlan = {
132
+ readonly kind: "bitcoin.message";
133
+ readonly format: "bip322-simple" | "legacy";
134
+ /** The 33-byte compressed signing key. */
135
+ readonly publicKey: Uint8Array;
136
+ readonly tasks: readonly [EcdsaTask | Bip340Task];
137
+ };
138
+ /**
139
+ * The PSBT plan: one task per `{index, key}` entry, in the given order. The input sighash must be
140
+ * the type's default or SIGHASH_SINGLE|ANYONECANPAY with a same-index output — the allow-list the
141
+ * previous signer applied.
142
+ */
143
+ export declare const planBitcoinPsbt: (psbt: Uint8Array, inputs: ReadonlyArray<{
144
+ readonly index: number;
145
+ readonly key: TaskKey;
146
+ }>) => BitcoinPsbtPlan;
147
+ /**
148
+ * The message plan: the address must decode to the key's own output — P2PKH for `legacy`, P2WPKH or
149
+ * the key's tweaked P2TR for `bip322-simple`.
150
+ */
151
+ export declare const planBitcoinMessage: (request: {
152
+ readonly network: string;
153
+ readonly address: string;
154
+ readonly message: string;
155
+ readonly format: "bip322-simple" | "legacy";
156
+ }, key: TaskKey) => BitcoinMessagePlan;
157
+ /** The artefact `signIdx` produced: partialSig DER‖sighash, or tapKeySig sig[‖sighash]. */
158
+ export declare const assembleBitcoinPsbt: (plan: BitcoinPsbtPlan, signatures: ReadonlyArray<Uint8Array>) => Assembled<Uint8Array, BitcoinPsbtPlan>;
159
+ /** The `smp` witness encoding for bip322-simple, the compact base64 signature for legacy. */
160
+ export declare const assembleBitcoinMessage: (plan: BitcoinMessagePlan, signatures: ReadonlyArray<Uint8Array>) => Assembled<string, BitcoinMessagePlan>;
45
161
  /** The decoded `address` fields needed by message signers. */
46
162
  export type MessageTarget = {
47
163
  readonly type: string;
@@ -58,5 +174,5 @@ export declare const normalizeBitcoin: (request: unknown) => SignRequest;
58
174
  export declare const decodeMessageTarget: (request: Extract<SignRequest, {
59
175
  kind: "bitcoin.message";
60
176
  }>) => MessageTarget;
61
- export type { BitcoinAccountTemplate };
177
+ export type { BitcoinAccountTemplate, BitcoinMessagePlan, BitcoinOwn, BitcoinPathTail, BitcoinPsbtPlan, BitcoinRequestOrigin };
62
178
  //# sourceMappingURL=bitcoin.d.mts.map
package/dist/bitcoin.mjs CHANGED
@@ -1,12 +1,14 @@
1
- import { t as ChainError } from "./src-8NZeEnrW.mjs";
2
- import { n as requestBase, t as isRecord$2 } from "./account-ref-D2rW_qlI.mjs";
3
- import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-ChhEZ0lx.mjs";
1
+ import { t as ChainError } from "./src-CHB_z45M.mjs";
2
+ import { n as requestBase, t as isRecord$2 } from "./account-ref-BFTeEyHt.mjs";
3
+ import { withNativeAmountMeta } from "./networks.mjs";
4
+ import { a as bip322ToSign, c as bitcoinNetwork, i as planBitcoinPsbt, n as assembleBitcoinPsbt, o as legacyMessageHash, r as planBitcoinMessage, s as BITCOIN_NETWORKS, t as assembleBitcoinMessage } from "./assemble-8GvNDony.mjs";
4
5
  import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
5
6
  import { Address, OutScript, p2pkh, p2sh, p2tr, p2wpkh } from "@scure/btc-signer/payment.js";
6
- import { taprootTweakPubkey } from "@scure/btc-signer/utils.js";
7
+ import { equalBytes, taprootTweakPubkey } from "@scure/btc-signer/utils.js";
7
8
  import { SigHash, Transaction, getInputType } from "@scure/btc-signer/transaction.js";
8
9
  import { HDKey } from "@scure/bip32";
9
10
  import { base64 } from "@scure/base";
11
+ import { RawTx } from "@scure/btc-signer/script.js";
10
12
  // src/bitcoin/psbt.ts
11
13
  /**
12
14
  * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what
@@ -55,9 +57,12 @@ const TEMPLATES = /* @__PURE__ */ new Set([
55
57
  const isSignEntry = (value) => isRecord$1(value) && typeof value["index"] === "number" && Number.isSafeInteger(value["index"]) && value["index"] >= 0 && typeof value["template"] === "string" && TEMPLATES.has(value["template"]);
56
58
  const isTaprootInput = (input) => input.tapInternalKey !== void 0 || getInputType(input).type === "taproot";
57
59
  /**
58
- * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).
59
- * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its
60
- * outpoint. The returned `sign` is sorted ascending by index — a normalized request is canonical.
60
+ * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller). Every
61
+ * non-taproot signed input must carry the full previous transaction: a BIP-143 signature commits
62
+ * only to its own input's amount, so a `witnessUtxo`-only amount is unverifiable. btc-signer checks
63
+ * each `nonWitnessUtxo` hashes to the input's txid and agrees with any `witnessUtxo` present
64
+ * (`strictPrevoutValidation`). The returned `sign` is sorted ascending by index — a normalized
65
+ * request is canonical.
61
66
  */
62
67
  const normalizeBitcoinPsbt = (psbt, sign, network) => {
63
68
  const net = bitcoinNetwork(network);
@@ -77,8 +82,7 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
77
82
  const input = tx.getInput(idx);
78
83
  if (input.witnessUtxo === void 0 && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
79
84
  if (template === "btc.bip86" ? input.tapBip32Derivation === void 0 : input.bip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
80
- const { type } = getInputType(input);
81
- if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
85
+ if (template !== "btc.bip86" && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} must carry nonWitnessUtxo`);
82
86
  const sighash = input.sighashType;
83
87
  if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH || sighash === 131)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
84
88
  if (sighash === 131 && idx >= tx.outputsLength) throw new ChainError("unsupported", `input ${idx} uses SIGHASH_SINGLE without a same-index output`);
@@ -123,10 +127,56 @@ function bitcoinPubkeyFromXpub(xpub, template, network, change, index) {
123
127
  const pub = xpubChild(xpub, network, change, index);
124
128
  return template === "btc.bip86" ? pub.subarray(1) : pub;
125
129
  }
130
+ // src/bitcoin/own.ts
131
+ /**
132
+ * Which own-key outputs a signing prompt may hide as change. An output on this group's keys is
133
+ * discoverable only when the wallet's gap-limited scan can reach it — anything else is shown as a
134
+ * send to the caller's own address at an unusual path, with a warning. The reach bound comes from
135
+ * the kernel's sealed change mark, never from the PSBT: an untrusted request can name any input
136
+ * path, so signed inputs may raise the mark only for requests the wallet itself built (`origin:
137
+ * "internal"`). An external request still hides change inside the window — the scan reaches it
138
+ * either way — but commits no raise at all: neither its inputs nor the indexes it hid are sealed
139
+ * into the mark.
140
+ */
141
+ /**
142
+ * BIP-44 §Address gap limit — the trailing run of unused addresses a wallet scans.
143
+ * (https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#address-gap-limit)
144
+ */
145
+ const BITCOIN_GAP_LIMIT = 20;
146
+ /** The highest change-chain index a scan may reach — a hard bound on scan work. */
147
+ const BITCOIN_SCAN_LIMIT = 2e3;
148
+ /**
149
+ * The kernel-sealed change mark for the next classification: `stored`, raised to the highest
150
+ * change-chain index among the same-purpose signed inputs — but only for a request the wallet
151
+ * itself built. An external request can name any input path, so its inputs never raise the mark.
152
+ */
153
+ const requestChangeMark = (stored, purpose, signed, origin) => {
154
+ let mark = stored;
155
+ if (origin === "internal") {
156
+ for (const input of signed) if (input.purpose === purpose && input.change === 1 && input.index > mark) mark = input.index;
157
+ }
158
+ return mark;
159
+ };
160
+ const EMPTY_BITCOIN_OWN = {
161
+ change: /* @__PURE__ */ new Set(),
162
+ unusual: /* @__PURE__ */ new Map(),
163
+ unconfirmed: /* @__PURE__ */ new Set()
164
+ };
165
+ /**
166
+ * An output is discoverable change only on the change chain (`/1/i`), under a purpose at least one
167
+ * signed input shares, at an index inside what the gap-limited scan reaches: the sealed change mark
168
+ * plus the gap limit, bounded by the scan limit.
169
+ */
170
+ const isDiscoverableChange = (output, signed, mark) => output.change === 1 && signed.some((input) => input.purpose === output.purpose) && output.index <= mark + 20 && output.index < 2e3;
171
+ /** The last change-chain index the gap-limited scan covers for a sealed mark. */
172
+ const changeScanReach = (mark) => Math.min(mark + 20, 1999);
126
173
  // src/bitcoin/decode.ts
127
174
  const SATS = "sats";
128
175
  const SIGHASH_SINGLE_ANYONECANPAY = 131;
129
176
  const OP_RETURN = 106;
177
+ /** Bitcoin Core `CScript::IsUnspendable`: OP_RETURN first, or over MAX_SCRIPT_SIZE. */
178
+ const MAX_SCRIPT_SIZE = 1e4;
179
+ const unspendable = (script) => script[0] === OP_RETURN || script.length > MAX_SCRIPT_SIZE;
130
180
  /** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */
131
181
  const parsePsbt = (psbt) => {
132
182
  try {
@@ -140,40 +190,39 @@ const bytesToHex = (bytes) => {
140
190
  for (const b of bytes) out += b.toString(16).padStart(2, "0");
141
191
  return out;
142
192
  };
143
- /** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */
144
- const decodeOutput = (script, amount) => {
145
- const hex = bytesToHex(script);
146
- if (script[0] === OP_RETURN) return {
147
- amount,
148
- script: hex,
149
- opReturn: true
150
- };
151
- return {
152
- amount,
153
- script: hex,
154
- opReturn: false
155
- };
156
- };
157
193
  /**
158
- * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script
159
- * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving
160
- * change) — not a display hint.
194
+ * Decodes a normalized bitcoin.psbt request for display. `own` is the caller's independently
195
+ * verified classification of the account's own-key outputs — `change` script hexes are hidden,
196
+ * `unusual` script hexes become outflows to the caller's own address carrying the path text and one
197
+ * warning each, `unconfirmed` script hexes are plain outflows with a danger warning — not a display
198
+ * hint.
161
199
  */
162
- const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
200
+ const decodeBitcoinPsbt = (request, own = EMPTY_BITCOIN_OWN) => {
163
201
  const tx = parsePsbt(request.psbt);
164
202
  const coder = Address(bitcoinNetwork(request.network).params);
165
203
  const signed = new Set(request.sign.map((s) => s.index));
166
204
  const outflows = [];
205
+ const ownWarnings = [];
167
206
  let canFee = true;
168
207
  let outSum = 0n;
169
208
  for (let i = 0; i < tx.outputsLength; i++) {
170
- const output = tx.getOutput(i);
171
- const { script } = output;
172
- const { amount } = output;
173
- if (script === void 0 || amount === void 0) continue;
174
- const decoded = decodeOutput(script, amount);
209
+ const { script, amount } = tx.getOutput(i);
210
+ if (script === void 0 || amount === void 0) throw new ChainError("invalid-request", "PSBT output without script or amount");
211
+ const scriptHex = bytesToHex(script);
175
212
  outSum += amount;
176
- if (decoded.opReturn || ownScripts.has(decoded.script)) continue;
213
+ if (own.change.has(scriptHex)) continue;
214
+ if (unspendable(script)) {
215
+ if (amount > 0n) outflows.push({
216
+ to: scriptHex,
217
+ amount: {
218
+ asset: SATS,
219
+ amount: amount.toString(10)
220
+ },
221
+ verified: true,
222
+ burn: true
223
+ });
224
+ continue;
225
+ }
177
226
  let addr;
178
227
  try {
179
228
  const out = OutScript.decode(script);
@@ -181,48 +230,67 @@ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
181
230
  } catch {
182
231
  addr = void 0;
183
232
  }
233
+ const ownPath = own.unusual.get(scriptHex);
234
+ if (ownPath !== void 0) ownWarnings.push({
235
+ kind: "unusual-own-output",
236
+ message: ownPath
237
+ });
238
+ if (own.unconfirmed.has(scriptHex)) ownWarnings.push({
239
+ kind: "unconfirmed-signer-output",
240
+ message: addr ?? scriptHex,
241
+ level: "danger"
242
+ });
184
243
  outflows.push({
185
- to: addr ?? decoded.script,
244
+ to: addr ?? scriptHex,
186
245
  amount: {
187
246
  asset: SATS,
188
247
  amount: amount.toString(10)
189
248
  },
190
- verified: addr !== void 0
249
+ verified: ownPath !== void 0 || addr !== void 0,
250
+ ...ownPath === void 0 ? {} : { ownPath }
191
251
  });
192
252
  }
253
+ const amountsCommitted = request.sign.some((s) => isTaprootInput(tx.getInput(s.index)) && tx.getInput(s.index).sighashType !== SIGHASH_SINGLE_ANYONECANPAY);
193
254
  let inSum = 0n;
194
255
  for (let i = 0; i < tx.inputsLength; i++) {
195
256
  const input = tx.getInput(i);
196
- if (input.witnessUtxo === void 0) canFee = false;
197
- else inSum += input.witnessUtxo.amount;
257
+ const nonWitness = input.nonWitnessUtxo;
258
+ if (nonWitness !== void 0) {
259
+ const prev = input.index === void 0 ? void 0 : nonWitness.outputs[input.index];
260
+ if (prev === void 0) canFee = false;
261
+ else inSum += prev.amount;
262
+ } else if (amountsCommitted && input.witnessUtxo !== void 0) inSum += input.witnessUtxo.amount;
263
+ else canFee = false;
198
264
  }
199
265
  const external = tx.inputsLength - signed.size > 0;
200
266
  const undecodable = outflows.some((o) => !o.verified);
201
267
  const listing = request.sign.some((s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
202
- const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
203
- return {
268
+ if (canFee && !listing && inSum < outSum) throw new ChainError("invalid-request", "PSBT outputs exceed its inputs");
269
+ const fee = canFee && !listing ? { max: {
270
+ asset: SATS,
271
+ amount: (inSum - outSum).toString(10)
272
+ } } : void 0;
273
+ const verifiability = external ? "opaque" : listing || undecodable || fee === void 0 ? "partial" : "full";
274
+ return withNativeAmountMeta({
204
275
  family: "bitcoin",
205
276
  network: request.network,
206
277
  summary: outflows.length > 0 ? "transfer" : "contract-call",
207
278
  outflows,
208
279
  approvals: [],
209
- fee: canFee && !listing ? { max: {
210
- asset: SATS,
211
- amount: (inSum - outSum).toString(10)
212
- } } : void 0,
213
- warnings: listing ? [{
280
+ fee,
281
+ warnings: [...ownWarnings, ...listing ? [{
214
282
  kind: "sighash-single-anyonecanpay",
215
283
  message: "signed inputs bind only their same-index outputs; the rest of the transaction can change"
216
- }] : [],
284
+ }] : []],
217
285
  verifiability
218
- };
286
+ }, request.network, SATS, 8);
219
287
  };
220
- const verifiabilityBitcoin = (request, ownScripts = /* @__PURE__ */ new Set()) => decodeBitcoinPsbt(request, ownScripts).verifiability;
288
+ const verifiabilityBitcoin = (request, own = EMPTY_BITCOIN_OWN) => decodeBitcoinPsbt(request, own).verifiability;
221
289
  // src/bitcoin/verify.ts
222
290
  /**
223
291
  * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the
224
- * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.
225
- * `/bitcoin` entry only — no private key material.
292
+ * request and the account's xpub — a kernel returning someone else's signature, or a signature over
293
+ * other content, fails closed with `integrity`. `/bitcoin` entry only — no private key material.
226
294
  */
227
295
  const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);
228
296
  /** Derive the child's public key from the account xpub at `change/index` (non-hardened). */
@@ -259,6 +327,28 @@ const tailOf = (path) => {
259
327
  };
260
328
  };
261
329
  const eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
330
+ const samePrevout = (a, b) => {
331
+ const [x, y] = [a.witnessUtxo, b.witnessUtxo];
332
+ const witness = x === void 0 || y === void 0 ? x === y : x.amount === y.amount && equalBytes(x.script, y.script);
333
+ const [m, n] = [a.nonWitnessUtxo, b.nonWitnessUtxo];
334
+ const full = m === void 0 || n === void 0 ? m === n : equalBytes(RawTx.encode(m), RawTx.encode(n));
335
+ return witness && full;
336
+ };
337
+ /**
338
+ * Whether `signed` is the PSBT `requested` asked to sign: the same unsigned transaction and, on
339
+ * every input, the same prevout data the signatures commit to. A kernel that signs another
340
+ * transaction, or the same one over altered amounts, fails this before any signature is checked.
341
+ */
342
+ const samePsbtContent = (requested, signed) => {
343
+ try {
344
+ const want = Transaction.fromPSBT(requested);
345
+ const got = Transaction.fromPSBT(signed);
346
+ if (!equalBytes(want.unsignedTx, got.unsignedTx)) return false;
347
+ return Array.from({ length: want.inputsLength }, (_, i) => i).every((i) => samePrevout(want.getInput(i), got.getInput(i)));
348
+ } catch {
349
+ return false;
350
+ }
351
+ };
262
352
  /**
263
353
  * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's
264
354
  * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must
@@ -323,7 +413,7 @@ const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network)
323
413
  type: "pkh",
324
414
  hash: decoded.hash
325
415
  }) : effective;
326
- const hash = input.nonWitnessUtxo === void 0 ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount) : preimageLegacy(tx, idx, scriptCode, sighashType);
416
+ const hash = decoded !== void 0 && (decoded.type === "wpkh" || decoded.type === "wsh") ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount) : preimageLegacy(tx, idx, scriptCode, sighashType);
327
417
  if (!secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), hash, pub, { prehash: false })) return false;
328
418
  }
329
419
  }
@@ -357,24 +447,7 @@ const verifyBitcoinMessage = (address, message, signatureBase64, network) => {
357
447
  const scriptPubKey = OutScript.encode(Address(net.params).decode(address));
358
448
  const witness = witnessOf(signatureBase64);
359
449
  if (witness === void 0 || witness.length === 0) return false;
360
- const tx = new Transaction({
361
- version: 0,
362
- lockTime: 0,
363
- allowUnknownOutputs: true
364
- });
365
- tx.addInput({
366
- txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),
367
- index: 0,
368
- sequence: 0,
369
- witnessUtxo: {
370
- script: scriptPubKey,
371
- amount: 0n
372
- }
373
- });
374
- tx.addOutput({
375
- script: Uint8Array.of(106),
376
- amount: 0n
377
- });
450
+ const tx = bip322ToSign(scriptPubKey, message);
378
451
  if (scriptPubKey.at(0) === 81) {
379
452
  const [rawSig] = witness;
380
453
  const xonly = scriptPubKey.slice(2);
@@ -395,6 +468,23 @@ const verifyBitcoinMessage = (address, message, signatureBase64, network) => {
395
468
  return false;
396
469
  }
397
470
  };
471
+ /**
472
+ * Legacy "Bitcoin Signed Message" verification for a P2PKH address: recover the public key from the
473
+ * compact signature (header = 27 + recovery, +4 when the key is compressed) and compare its P2PKH
474
+ * address with `address`.
475
+ */
476
+ const verifyLegacyBitcoinMessage = (address, message, signatureBase64, network) => {
477
+ try {
478
+ const raw = base64.decode(signatureBase64);
479
+ const [header] = raw;
480
+ if (raw.length !== 65 || header === void 0 || header < 27 || header > 34) return false;
481
+ const recovered = secp256k1.recoverPublicKey(Uint8Array.of((header - 27) % 4, ...raw.slice(1)), legacyMessageHash(message), { prehash: false });
482
+ const pub = secp256k1.Point.fromBytes(recovered).toBytes(header >= 31);
483
+ return p2pkh(pub, bitcoinNetwork(network).params).address === address;
484
+ } catch {
485
+ return false;
486
+ }
487
+ };
398
488
  // src/bitcoin/index.ts
399
489
  const common = (request) => {
400
490
  const base = requestBase(request);
@@ -436,6 +526,8 @@ const normalizeBitcoin = (request) => {
436
526
  if (!isRecord$2(account) || account["kind"] !== "hd") throw new ChainError("invalid-request", "request.account must be a wallet group");
437
527
  const { walletId, groupIndex } = account;
438
528
  if (typeof walletId !== "string" || typeof groupIndex !== "number" || !Number.isSafeInteger(groupIndex) || groupIndex < 0) throw new ChainError("invalid-request", "request.account must be a wallet group");
529
+ const { origin } = request;
530
+ if (origin !== "internal" && origin !== "external") throw new ChainError("invalid-request", "request.origin must be internal or external");
439
531
  if (!(psbt instanceof Uint8Array)) throw new ChainError("invalid-request", "psbt must be bytes");
440
532
  const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
441
533
  return {
@@ -446,6 +538,7 @@ const normalizeBitcoin = (request) => {
446
538
  walletId,
447
539
  groupIndex
448
540
  },
541
+ origin,
449
542
  psbt: normalized.psbt,
450
543
  sign: normalized.sign
451
544
  };
@@ -473,6 +566,6 @@ const normalizeBitcoin = (request) => {
473
566
  };
474
567
  /** Decodes the message `address` into the scriptPubKey the signer needs. */
475
568
  const decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
476
- export { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, decodeBitcoinPsbt, decodeMessageTarget, normalizeBitcoin, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures };
569
+ export { BITCOIN_GAP_LIMIT, BITCOIN_NETWORKS, BITCOIN_SCAN_LIMIT, EMPTY_BITCOIN_OWN, assembleBitcoinMessage, assembleBitcoinPsbt, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, changeScanReach, decodeBitcoinPsbt, decodeMessageTarget, isDiscoverableChange, legacyMessageHash, normalizeBitcoin, planBitcoinMessage, planBitcoinPsbt, requestChangeMark, samePsbtContent, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures, verifyLegacyBitcoinMessage };
477
570
 
478
571
  //# sourceMappingURL=bitcoin.mjs.map