@qntx/wallet-worker 0.10.0 → 0.12.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.
@@ -72,7 +72,7 @@ import {
72
72
  // src/worker/node.ts
73
73
  import { readFile } from "node:fs/promises";
74
74
  import { parentPort, workerData } from "node:worker_threads";
75
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/util-BcRBO6o-.mjs
75
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/util-D8wUYmm0.mjs
76
76
  var NostrError = class extends Error {
77
77
  name = "NostrError";
78
78
  };
@@ -141,7 +141,7 @@ function hasLoneSurrogate(value) {
141
141
  return false;
142
142
  }
143
143
 
144
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/kind-I2Tvbe82.mjs
144
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/kind-BAnfDHdg.mjs
145
145
  var Kind = {
146
146
  Metadata: 0,
147
147
  TextNote: 1,
@@ -173,7 +173,7 @@ var Kind = {
173
173
  StarterPack: 39089
174
174
  };
175
175
 
176
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/event-DHtcm0jM.mjs
176
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/event-B__SmruU.mjs
177
177
  function isTag(value) {
178
178
  if (!Array.isArray(value) || value.length === 0)
179
179
  return false;
@@ -254,7 +254,7 @@ function getEventHash(event) {
254
254
  return bytesToHex$1(sha256(utf8Encoder.encode(serialized)));
255
255
  }
256
256
 
257
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/key-Bt0ow7mI.mjs
257
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/key-BxwA02Gx.mjs
258
258
  var SecretKey = class SecretKey {
259
259
  #bytes;
260
260
  constructor(bytes) {
@@ -383,7 +383,7 @@ function signEvent(unsigned, secretKey, auxRand) {
383
383
  return event;
384
384
  }
385
385
 
386
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/verifier-DBSPHzGg.mjs
386
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/verifier-iQR5ivRF.mjs
387
387
  function createEventVerifier(backend) {
388
388
  return (event) => {
389
389
  if (isMarkedVerified(event))
@@ -403,7 +403,7 @@ function createEventVerifier(backend) {
403
403
  };
404
404
  }
405
405
  var verifyEvent = createEventVerifier(nobleBackend);
406
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/error-CoP2myne.mjs
406
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/error-Cord_cbw.mjs
407
407
  var SignerDisposedError = class extends NostrError {
408
408
  name = "SignerDisposedError";
409
409
  };
@@ -862,7 +862,7 @@ var cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, functio
862
862
  };
863
863
  });
864
864
 
865
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/nips/nip04.mjs
865
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/nips/nip04.mjs
866
866
  function normalizeSharedSecret(privkey, pubkey, backend) {
867
867
  assertHex32(pubkey, "public key");
868
868
  const sharedX = backend.ecdhX(privkey, hexToBytes$1(lowerAscii(pubkey)));
@@ -1536,7 +1536,7 @@ var hkdf = (hash, ikm, salt, info, length) => {
1536
1536
  return expand(hash, HMAC.digest(), info, length, HMAC);
1537
1537
  };
1538
1538
 
1539
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/nips/nip44.mjs
1539
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/nips/nip44.mjs
1540
1540
  var minPlaintextSize = 1;
1541
1541
  var maxPlaintextSize = 4294967295;
1542
1542
  var extendedPrefixThreshold = 65536;
@@ -1662,7 +1662,7 @@ function decrypt3(payload, conversationKey, opts) {
1662
1662
  return unpad(chacha20(chacha_key, chacha_nonce, ciphertext));
1663
1663
  }
1664
1664
 
1665
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/nips/nip59.mjs
1665
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/nips/nip59.mjs
1666
1666
  var Nip59Error = class extends NostrError {
1667
1667
  name = "Nip59Error";
1668
1668
  };
@@ -1735,7 +1735,7 @@ async function unwrap(crypto2, giftWrap, options) {
1735
1735
  return rumor;
1736
1736
  }
1737
1737
 
1738
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/signer-DQzjm3pt.mjs
1738
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/signer-Y3gcghwd.mjs
1739
1739
  var KeysSigner = class {
1740
1740
  #keys;
1741
1741
  #convKeys = /* @__PURE__ */ new Map;
@@ -1822,15 +1822,17 @@ class KernelError extends Error {
1822
1822
  code;
1823
1823
  retryAt;
1824
1824
  corrupted;
1825
- constructor(code, message, retryAt, corrupted = false) {
1825
+ detail;
1826
+ constructor(code, message, retryAt, corrupted = false, detail) {
1826
1827
  super(message);
1827
1828
  this.name = "KernelError";
1828
1829
  this.code = code;
1829
1830
  this.retryAt = retryAt;
1830
1831
  this.corrupted = corrupted;
1832
+ this.detail = detail;
1831
1833
  }
1832
1834
  }
1833
- // ../wallet/dist/core-D-NCx1CQ.mjs
1835
+ // ../wallet/dist/core-DDfzuSIa.mjs
1834
1836
  var ValidationError = class extends Error {
1835
1837
  name = "ValidationError";
1836
1838
  };
@@ -2049,7 +2051,7 @@ var walletInfo = obj({
2049
2051
  createdAt: safeTime
2050
2052
  });
2051
2053
  var passphraseBytes = bytes(1, 1024);
2052
- var walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-unavailable"), literal("factor-invalidated"), literal("wrong-password"), literal("wrong-passkey"), literal("rate-limited"), literal("invalid-input"), literal("not-found"), literal("already-exists"), literal("conflict"), literal("unsupported"), literal("unavailable"), literal("integrity"), literal("approval-required"), literal("crashed"));
2054
+ var walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-invalidated"), literal("no-device-credential"), literal("passkey-not-configured"), literal("passkey-prf-unsupported"), literal("wrong-password"), literal("wrong-passkey"), literal("rate-limited"), literal("invalid-input"), literal("not-found"), literal("already-exists"), literal("conflict"), literal("unsupported"), literal("unavailable"), literal("integrity"), literal("approval-required"), literal("crashed"));
2053
2055
  var createdResult = obj({
2054
2056
  wallet: walletInfo,
2055
2057
  session: sessionId
@@ -2210,7 +2212,7 @@ var CORE_METHODS = {
2210
2212
  }
2211
2213
  };
2212
2214
 
2213
- // ../wallet/dist/protocol-DDz4nlYK.mjs
2215
+ // ../wallet/dist/protocol-C8x0H3Rr.mjs
2214
2216
  var MAX_FACTOR_CHARS = 512;
2215
2217
  var MAX_STRING_BYTES = 64000;
2216
2218
  var MAX_PAYLOAD_CHARS = 1400000;
@@ -2245,6 +2247,7 @@ var backupInfo = obj({
2245
2247
  createdAt: safeTime
2246
2248
  });
2247
2249
  var template = union(literal("evm.bip44"), literal("solana.bip44-change"), union(literal("btc.bip44"), literal("btc.bip49"), literal("btc.bip84")), literal("btc.bip86"));
2250
+ var btcTemplate = union(literal("btc.bip44"), literal("btc.bip49"), literal("btc.bip84"), literal("btc.bip86"));
2248
2251
  var caip2 = str(200, /^[a-z0-9-]{3,64}:[0-9a-zA-Z-]{1,128}$/);
2249
2252
  var addressResult = (t) => obj({
2250
2253
  template: literal(t),
@@ -2328,9 +2331,16 @@ var signRequest = union(obj({
2328
2331
  }), obj({
2329
2332
  kind: literal("bitcoin.psbt"),
2330
2333
  network: caip2,
2331
- account: accountRef,
2334
+ account: obj({
2335
+ kind: literal("hd"),
2336
+ walletId,
2337
+ groupIndex
2338
+ }),
2332
2339
  psbt: bytes(1, 131072),
2333
- sign: arr(int(0, 1024), 1024)
2340
+ sign: arr(obj({
2341
+ index: int(0, 1024),
2342
+ template: btcTemplate
2343
+ }), 1024)
2334
2344
  }), obj({
2335
2345
  kind: literal("bitcoin.message"),
2336
2346
  network: caip2,
@@ -2972,7 +2982,8 @@ var METHODS = {
2972
2982
  var lockReason = union(literal("cold-start"), literal("user"), literal("idle"), literal("background"), literal("expired"), literal("crashed"), literal("invalidated"));
2973
2983
  var errorPayload = obj({
2974
2984
  code: walletErrorCode,
2975
- retryAt: opt(safeTime)
2985
+ retryAt: opt(safeTime),
2986
+ detail: opt(str(80, /^[A-Za-z0-9_.:-]+$/))
2976
2987
  });
2977
2988
  var kernelEvent = union(obj({
2978
2989
  v: literal(2),
@@ -2987,7 +2998,7 @@ var kernelEvent = union(obj({
2987
2998
  // ../wallet-kernel/src/platform.ts
2988
2999
  function requirePasskey(platform) {
2989
3000
  if (platform.passkey === undefined) {
2990
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies in the host");
3001
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies in the host");
2991
3002
  }
2992
3003
  return platform.passkey;
2993
3004
  }
@@ -3024,12 +3035,12 @@ function serializeCeremonies(platform) {
3024
3035
  }
3025
3036
  function assertFactorKindAvailable(platform, kind) {
3026
3037
  if (platform.keystore !== undefined !== (kind === "hardware")) {
3027
- throw new KernelError("factor-unavailable", "this factor kind is not available here");
3038
+ throw new KernelError("unsupported", "this factor kind is not available here");
3028
3039
  }
3029
3040
  }
3030
3041
  function requireKeystore(platform) {
3031
3042
  if (platform.keystore === undefined) {
3032
- throw new KernelError("factor-unavailable", "this platform has no hardware keystore");
3043
+ throw new KernelError("unsupported", "this platform has no hardware keystore");
3033
3044
  }
3034
3045
  return platform.keystore;
3035
3046
  }
@@ -4332,7 +4343,7 @@ async function unlock(platform, image, factor, commit) {
4332
4343
  if (factor.kind === "hardware") {
4333
4344
  const stored = image.factors.find((f) => f.kind === "hardware");
4334
4345
  if (stored === undefined) {
4335
- throw new KernelError("factor-unavailable", "no hardware factor exists");
4346
+ throw new KernelError("not-found", "no hardware factor exists");
4336
4347
  }
4337
4348
  const kek = await kekFor(platform, factor, stored, corePromptFor(platform.keystore, "unlock"));
4338
4349
  try {
@@ -4424,7 +4435,7 @@ async function verifyFactor(platform, image, factor, dek, prompt) {
4424
4435
  throw new KernelError(candidates.length > 0 ? "wrong-password" : "invalid-input", "password did not verify");
4425
4436
  }
4426
4437
  if (factor.kind === "hardware") {
4427
- throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("factor-unavailable", "no hardware factor exists");
4438
+ throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("not-found", "no hardware factor exists");
4428
4439
  }
4429
4440
  throw new KernelError("wrong-passkey", "passkey did not verify");
4430
4441
  }
@@ -7427,7 +7438,7 @@ function walletPrfOf(result) {
7427
7438
  if (result.first !== undefined) {
7428
7439
  wipe(result.first);
7429
7440
  }
7430
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7441
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7431
7442
  }
7432
7443
  return { prfWallet: result.first, synced: result.synced };
7433
7444
  }
@@ -7460,7 +7471,7 @@ async function walletCeremony(ctx, params) {
7460
7471
  }
7461
7472
  async function createWithPasskey(ctx, params, requestSession) {
7462
7473
  if (ctx.platform.passkey !== undefined !== (params.ceremony === "kernel")) {
7463
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7474
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7464
7475
  }
7465
7476
  const gated = gate(ctx, params.factor, requestSession);
7466
7477
  let prf;
@@ -7644,7 +7655,7 @@ function backupMaterialOf(result) {
7644
7655
  result.second?.fill(0);
7645
7656
  if (!result.userVerified || result.first?.length !== 32) {
7646
7657
  result.first?.fill(0);
7647
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7658
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7648
7659
  }
7649
7660
  return { kind: "passkey", credentialId: result.credentialId, prfBackup: result.first };
7650
7661
  }
@@ -7653,7 +7664,7 @@ async function backupMaterial(ctx, factor, allowCredentials) {
7653
7664
  return factor;
7654
7665
  }
7655
7666
  if (ctx.platform.passkey !== undefined !== (factor.ceremony === "kernel")) {
7656
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7667
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7657
7668
  }
7658
7669
  if (factor.ceremony === "host") {
7659
7670
  return factor;
@@ -9737,6 +9748,13 @@ var checkDerivations = (tx, coinType) => {
9737
9748
  };
9738
9749
  var DEFAULT_SIGHASH = 0;
9739
9750
  var SIGHASH_ALL = 1;
9751
+ var TEMPLATES = /* @__PURE__ */ new Set([
9752
+ "btc.bip44",
9753
+ "btc.bip49",
9754
+ "btc.bip84",
9755
+ "btc.bip86"
9756
+ ]);
9757
+ var isSignEntry = (value) => isRecord$1(value) && typeof value["index"] === "number" && Number.isSafeInteger(value["index"]) && value["index"] >= 0 && typeof value["template"] === "string" && TEMPLATES.has(value["template"]);
9740
9758
  var isTaprootInput = (input) => input.tapInternalKey !== undefined || getInputType(input).type === "taproot";
9741
9759
  var normalizeBitcoinPsbt = (psbt, sign, network) => {
9742
9760
  const net = bitcoinNetwork(network);
@@ -9746,18 +9764,19 @@ var normalizeBitcoinPsbt = (psbt, sign, network) => {
9746
9764
  } catch {
9747
9765
  throw new ChainError("invalid-request", "PSBT failed to decode");
9748
9766
  }
9749
- if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0))
9750
- throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
9751
- const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
9752
- const last = unique.at(-1);
9753
- if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength)
9767
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every(isSignEntry))
9768
+ throw new ChainError("invalid-request", "sign must be a non-empty array of {index, template} entries");
9769
+ const sorted = [...sign].sort((a, b) => a.index - b.index);
9770
+ const indices = new Set(sorted.map((s) => s.index));
9771
+ const last = sorted.at(-1)?.index;
9772
+ if (indices.size !== sorted.length || last === undefined || last >= tx.inputsLength)
9754
9773
  throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
9755
9774
  checkDerivations(tx, net.coinType);
9756
- for (const idx of unique) {
9775
+ for (const { index: idx, template } of sorted) {
9757
9776
  const input = tx.getInput(idx);
9758
9777
  if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined)
9759
9778
  throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
9760
- if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined)
9779
+ if (template === "btc.bip86" ? input.tapBip32Derivation === undefined : input.bip32Derivation === undefined)
9761
9780
  throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
9762
9781
  const { type } = getInputType(input);
9763
9782
  if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === undefined)
@@ -9770,7 +9789,7 @@ var normalizeBitcoinPsbt = (psbt, sign, network) => {
9770
9789
  }
9771
9790
  return {
9772
9791
  psbt: tx.toPSBT(0),
9773
- sign: unique
9792
+ sign: sorted
9774
9793
  };
9775
9794
  };
9776
9795
  var SATS = "sats";
@@ -9806,7 +9825,7 @@ var decodeOutput = (script, amount) => {
9806
9825
  var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
9807
9826
  const tx = parsePsbt(request.psbt);
9808
9827
  const coder = Address(bitcoinNetwork(request.network).params);
9809
- const signed = new Set(request.sign);
9828
+ const signed = new Set(request.sign.map((s) => s.index));
9810
9829
  const outflows = [];
9811
9830
  let canFee = true;
9812
9831
  let outSum = 0n;
@@ -9846,7 +9865,7 @@ var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
9846
9865
  }
9847
9866
  const external = tx.inputsLength - signed.size > 0;
9848
9867
  const undecodable = outflows.some((o) => !o.verified);
9849
- const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
9868
+ const listing = request.sign.some((s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
9850
9869
  const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
9851
9870
  return {
9852
9871
  family: "bitcoin",
@@ -9899,20 +9918,32 @@ var messageTarget = (address, network, format) => {
9899
9918
  var normalizeBitcoin = (request) => {
9900
9919
  if (!isRecord2(request) || typeof request["kind"] !== "string")
9901
9920
  throw new ChainError("invalid-request", "request must be an object with a kind");
9902
- const { network, account } = common(request);
9903
9921
  if (request["kind"] === "bitcoin.psbt") {
9904
- const { psbt } = request;
9922
+ const { network, account, psbt } = request;
9923
+ if (typeof network !== "string")
9924
+ throw new ChainError("invalid-request", "request.network must be a string");
9925
+ bitcoinNetwork(network);
9926
+ if (!isRecord2(account) || account["kind"] !== "hd")
9927
+ throw new ChainError("invalid-request", "request.account must be a wallet group");
9928
+ const { walletId, groupIndex } = account;
9929
+ if (typeof walletId !== "string" || typeof groupIndex !== "number" || !Number.isSafeInteger(groupIndex) || groupIndex < 0)
9930
+ throw new ChainError("invalid-request", "request.account must be a wallet group");
9905
9931
  if (!(psbt instanceof Uint8Array))
9906
9932
  throw new ChainError("invalid-request", "psbt must be bytes");
9907
9933
  const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
9908
9934
  return {
9909
9935
  kind: "bitcoin.psbt",
9910
9936
  network,
9911
- account,
9937
+ account: {
9938
+ kind: "hd",
9939
+ walletId,
9940
+ groupIndex
9941
+ },
9912
9942
  psbt: normalized.psbt,
9913
9943
  sign: normalized.sign
9914
9944
  };
9915
9945
  }
9946
+ const { network, account } = common(request);
9916
9947
  if (request["kind"] === "bitcoin.message") {
9917
9948
  const { format } = request;
9918
9949
  const target = messageTarget(request["address"], network, format);
@@ -16732,6 +16763,18 @@ function mapChainError(error) {
16732
16763
  // ../wallet-kernel/src/modules/chains/bitcoin.ts
16733
16764
  var isPath2 = (path) => Array.isArray(path) && path.every((p) => typeof p === "number");
16734
16765
  var hex = (bytes) => bytes.reduce((acc, b) => acc + b.toString(16).padStart(2, "0"), "");
16766
+ var PURPOSES = [44, 49, 84, 86];
16767
+ var contextFor = (b, purpose) => {
16768
+ let ctx = b.purposes.get(purpose);
16769
+ if (ctx === undefined) {
16770
+ ctx = {
16771
+ accountNode: b.master.derive(`m/${purpose}'/${b.coinType}'/${b.groupIndex}'`),
16772
+ children: []
16773
+ };
16774
+ b.purposes.set(purpose, ctx);
16775
+ }
16776
+ return ctx;
16777
+ };
16735
16778
  var derivationOf = (owner, fingerprint, purpose) => {
16736
16779
  if (purpose === 86) {
16737
16780
  const claimed = (der) => der.fingerprint === fingerprint && isPath2(der.path);
@@ -16751,46 +16794,52 @@ var derivationOf = (owner, fingerprint, purpose) => {
16751
16794
  };
16752
16795
  var expectedPub = (purpose, pub) => purpose === 86 ? pub.slice(1) : pub;
16753
16796
  var expectedScript = (purpose, pub) => purpose === 86 ? p2tr(pub.slice(1)).script : purpose === 49 ? p2sh(p2wpkh(pub)).script : purpose === 44 ? p2pkh(pub).script : p2wpkh(pub).script;
16754
- var childAt = (b, path) => {
16797
+ var childAt = (b, purpose, path) => {
16755
16798
  const [purposePath, coinPath, groupPath, change, index] = path;
16756
- if (path.length !== 5 || purposePath !== b.purpose + b.hardened || coinPath !== b.coinType + b.hardened || groupPath !== b.account.groupIndex + b.hardened || change === undefined || index === undefined || change !== 0 && change !== 1 || index < 0 || index >= b.hardened) {
16799
+ if (path.length !== 5 || purposePath !== purpose + b.hardened || coinPath !== b.coinType + b.hardened || groupPath !== b.groupIndex + b.hardened || change === undefined || index === undefined || change !== 0 && change !== 1 || index < 0 || index >= b.hardened) {
16757
16800
  throw new KernelError("invalid-input", "derivation path is not this account's");
16758
16801
  }
16759
- const child = b.accountNode.deriveChild(change).deriveChild(index);
16760
- b.children.push(child);
16802
+ const ctx = contextFor(b, purpose);
16803
+ const child = ctx.accountNode.deriveChild(change).deriveChild(index);
16804
+ ctx.children.push(child);
16761
16805
  return child;
16762
16806
  };
16763
- var bitcoinInput = (b, tx, idx) => {
16807
+ var bitcoinInput = (b, tx, entry) => {
16808
+ const purpose = BTC_PURPOSE[entry.template];
16809
+ if (purpose === undefined) {
16810
+ throw new KernelError("invalid-input", "sign template is not a bitcoin account template");
16811
+ }
16812
+ const { index: idx } = entry;
16764
16813
  const input = tx.getInput(idx);
16765
- const entry = derivationOf(input, b.master.fingerprint, b.purpose);
16766
- if (entry === undefined) {
16814
+ const der = derivationOf(input, b.master.fingerprint, purpose);
16815
+ if (der === undefined) {
16767
16816
  throw new KernelError("invalid-input", `input ${idx}: derivation entry is not this account's`);
16768
16817
  }
16769
- const child = childAt(b, entry.path);
16818
+ const child = childAt(b, purpose, der.path);
16770
16819
  const pub = child.publicKey;
16771
16820
  const priv = child.privateKey;
16772
16821
  if (pub === null || priv === null) {
16773
16822
  throw new KernelError("integrity", "no key at derivation path");
16774
16823
  }
16775
- if (!deepEqual(entry.pubkey, expectedPub(b.purpose, pub))) {
16824
+ if (!deepEqual(der.pubkey, expectedPub(purpose, pub))) {
16776
16825
  throw new KernelError("invalid-input", `input ${idx}: derivation pubkey is not ours`);
16777
16826
  }
16778
- if (b.purpose === 44) {
16827
+ if (purpose === 44) {
16779
16828
  if (input.nonWitnessUtxo === undefined) {
16780
16829
  throw new KernelError("invalid-input", `input ${idx}: P2PKH spend requires nonWitnessUtxo`);
16781
16830
  }
16782
16831
  const vout = input.index;
16783
16832
  const outs = input.nonWitnessUtxo.outputs;
16784
16833
  const prevScript = vout === undefined ? undefined : outs[vout]?.script;
16785
- if (prevScript === undefined || !deepEqual(prevScript, expectedScript(b.purpose, pub))) {
16834
+ if (prevScript === undefined || !deepEqual(prevScript, expectedScript(purpose, pub))) {
16786
16835
  throw new KernelError("invalid-input", `input ${idx}: nonWitnessUtxo prevout is not this key's`);
16787
16836
  }
16788
16837
  } else {
16789
16838
  const prevout = input.witnessUtxo;
16790
- if (prevout === undefined || !deepEqual(prevout.script, expectedScript(b.purpose, pub))) {
16839
+ if (prevout === undefined || !deepEqual(prevout.script, expectedScript(purpose, pub))) {
16791
16840
  throw new KernelError("invalid-input", `input ${idx}: prevout script is not this key's`);
16792
16841
  }
16793
- if (b.purpose === 49 && (input.redeemScript === undefined || !deepEqual(input.redeemScript, p2wpkh(pub).script))) {
16842
+ if (purpose === 49 && (input.redeemScript === undefined || !deepEqual(input.redeemScript, p2wpkh(pub).script))) {
16794
16843
  throw new KernelError("invalid-input", `input ${idx}: redeemScript is not this key's`);
16795
16844
  }
16796
16845
  }
@@ -16803,25 +16852,27 @@ var bitcoinOwnScripts = (b, tx) => {
16803
16852
  if (output.script === undefined) {
16804
16853
  continue;
16805
16854
  }
16806
- const entry = derivationOf(output, b.master.fingerprint, b.purpose);
16807
- if (entry === undefined) {
16808
- continue;
16809
- }
16810
- try {
16811
- const child = childAt(b, entry.path);
16812
- const pub = child.publicKey;
16813
- if (pub !== null && deepEqual(output.script, expectedScript(b.purpose, pub))) {
16814
- ownScripts.add(hex(output.script));
16855
+ for (const purpose of PURPOSES) {
16856
+ const entry = derivationOf(output, b.master.fingerprint, purpose);
16857
+ if (entry === undefined) {
16858
+ continue;
16859
+ }
16860
+ try {
16861
+ const child = childAt(b, purpose, entry.path);
16862
+ const pub = child.publicKey;
16863
+ if (pub !== null && deepEqual(output.script, expectedScript(purpose, pub))) {
16864
+ ownScripts.add(hex(output.script));
16865
+ }
16866
+ } catch {
16867
+ continue;
16815
16868
  }
16816
- } catch {
16817
- continue;
16818
16869
  }
16819
16870
  }
16820
16871
  return ownScripts;
16821
16872
  };
16822
16873
  var executeBitcoinPsbt = (b, request, random, intentOnly) => {
16823
16874
  const tx = Transaction.fromPSBT(request.psbt);
16824
- const inputs = request.sign.map((idx) => bitcoinInput(b, tx, idx));
16875
+ const inputs = request.sign.map((entry) => bitcoinInput(b, tx, entry));
16825
16876
  const ownScripts = bitcoinOwnScripts(b, tx);
16826
16877
  let normalized;
16827
16878
  try {
@@ -16846,14 +16897,14 @@ var executeBitcoinPsbt = (b, request, random, intentOnly) => {
16846
16897
  signedPsbt: signBitcoinPsbt(request.psbt, inputs, () => random(32))
16847
16898
  };
16848
16899
  };
16849
- var executeBitcoinMessage = (b, request, random, intentOnly) => {
16850
- if (request.format === "legacy" && b.account.template !== "btc.bip44") {
16900
+ var executeBitcoinMessage = (b, purpose, request, random, intentOnly) => {
16901
+ if (request.format === "legacy" && purpose !== 44) {
16851
16902
  throw new KernelError("unsupported", "legacy message format is btc.bip44-only");
16852
16903
  }
16853
- const child = childAt(b, [
16854
- b.purpose + b.hardened,
16904
+ const child = childAt(b, purpose, [
16905
+ purpose + b.hardened,
16855
16906
  b.coinType + b.hardened,
16856
- b.account.groupIndex + b.hardened,
16907
+ b.groupIndex + b.hardened,
16857
16908
  request.change,
16858
16909
  request.index
16859
16910
  ]);
@@ -16862,7 +16913,7 @@ var executeBitcoinMessage = (b, request, random, intentOnly) => {
16862
16913
  if (pub === null || priv === null) {
16863
16914
  throw new KernelError("integrity", "no key at derivation path");
16864
16915
  }
16865
- const derived = b.purpose === 86 ? p2tr(pub.slice(1), undefined, b.net.params).address : b.purpose === 49 ? p2sh(p2wpkh(pub, b.net.params), b.net.params).address : b.purpose === 44 ? p2pkh(pub, b.net.params).address : p2wpkh(pub, b.net.params).address;
16916
+ const derived = purpose === 86 ? p2tr(pub.slice(1), undefined, b.net.params).address : purpose === 49 ? p2sh(p2wpkh(pub, b.net.params), b.net.params).address : purpose === 44 ? p2pkh(pub, b.net.params).address : p2wpkh(pub, b.net.params).address;
16866
16917
  if (derived !== request.address) {
16867
16918
  throw new KernelError("invalid-input", "address is not ours");
16868
16919
  }
@@ -16891,34 +16942,33 @@ var executeBitcoinMessage = (b, request, random, intentOnly) => {
16891
16942
  var executeBitcoin = (random, request, account, seed, intentOnly) => {
16892
16943
  const net = bitcoinNetwork(request.network);
16893
16944
  const master = HDKey.fromMasterSeed(seed, net.bip32);
16945
+ const b = {
16946
+ master,
16947
+ purposes: new Map,
16948
+ coinType: net.coinType,
16949
+ hardened: 2147483648,
16950
+ groupIndex: account.groupIndex,
16951
+ net
16952
+ };
16894
16953
  try {
16895
- const purpose = BTC_PURPOSE[account.template] ?? 84;
16896
- const { coinType } = net;
16897
- const hardened = 2147483648;
16898
- const accountNode = master.derive(`m/${purpose}'/${coinType}'/${account.groupIndex}'`);
16899
- const children = [];
16900
- const b = {
16901
- master,
16902
- accountNode,
16903
- children,
16904
- purpose,
16905
- coinType,
16906
- hardened,
16907
- account,
16908
- net
16909
- };
16910
- try {
16911
- if (request.kind === "bitcoin.psbt") {
16912
- return executeBitcoinPsbt(b, request, random, intentOnly);
16913
- }
16914
- return executeBitcoinMessage(b, request, random, intentOnly);
16915
- } finally {
16916
- for (const child of children) {
16954
+ if (request.kind === "bitcoin.psbt") {
16955
+ return executeBitcoinPsbt(b, request, random, intentOnly);
16956
+ }
16957
+ if (request.account.kind !== "hd") {
16958
+ throw new KernelError("unsupported", "imported accounts are not yet supported");
16959
+ }
16960
+ const purpose = BTC_PURPOSE[request.account.template];
16961
+ if (purpose === undefined) {
16962
+ throw new KernelError("invalid-input", "account template is not a bitcoin template");
16963
+ }
16964
+ return executeBitcoinMessage(b, purpose, request, random, intentOnly);
16965
+ } finally {
16966
+ for (const ctx of b.purposes.values()) {
16967
+ for (const child of ctx.children) {
16917
16968
  child.wipePrivateData();
16918
16969
  }
16919
- accountNode.wipePrivateData();
16970
+ ctx.accountNode.wipePrivateData();
16920
16971
  }
16921
- } finally {
16922
16972
  master.wipePrivateData();
16923
16973
  }
16924
16974
  };
@@ -17177,23 +17227,35 @@ var chainSign = async (ctx, params, session) => {
17177
17227
  if (account.kind !== "hd") {
17178
17228
  throw new KernelError("unsupported", "imported accounts are not yet supported");
17179
17229
  }
17180
- const [family] = request.kind.split(".", 1);
17181
- const expected = family === "evm" ? ["evm.bip44"] : family === "solana" ? ["solana.bip44-change"] : ["btc.bip44", "btc.bip49", "btc.bip84", "btc.bip86"];
17182
- if (!expected.includes(account.template)) {
17183
- throw new KernelError("invalid-input", "account template does not match the request family");
17230
+ if (request.kind === "bitcoin.psbt") {
17231
+ if (request.sign.some((s) => BTC_PURPOSE[s.template] === undefined)) {
17232
+ throw new KernelError("invalid-input", "sign template is not a bitcoin account template");
17233
+ }
17234
+ } else {
17235
+ const [family] = request.kind.split(".", 1);
17236
+ const expected = family === "evm" ? ["evm.bip44"] : family === "solana" ? ["solana.bip44-change"] : ["btc.bip44", "btc.bip49", "btc.bip84", "btc.bip86"];
17237
+ if (!("template" in account) || !expected.includes(account.template)) {
17238
+ throw new KernelError("invalid-input", "account template does not match the request family");
17239
+ }
17184
17240
  }
17185
17241
  const record = ctx.image.records.find((entry) => entry.kind === "entropy" && entry.id === account.walletId);
17186
17242
  if (record === undefined) {
17187
17243
  throw new KernelError("not-found", "no such wallet");
17188
17244
  }
17189
17245
  const execute = (seed, intentOnly) => {
17190
- if (request.kind === "evm.transaction" || request.kind === "evm.personal-message" || request.kind === "evm.typed-data") {
17191
- return executeEvm(request, account, seed, intentOnly);
17246
+ if (request.kind === "bitcoin.psbt") {
17247
+ return executeBitcoin(ctx.platform.random, request, request.account, seed, intentOnly);
17248
+ }
17249
+ if (request.account.kind !== "hd") {
17250
+ throw new KernelError("unsupported", "imported accounts are not yet supported");
17192
17251
  }
17193
- if (request.kind === "bitcoin.psbt" || request.kind === "bitcoin.message") {
17194
- return executeBitcoin(ctx.platform.random, request, account, seed, intentOnly);
17252
+ if (request.kind === "bitcoin.message") {
17253
+ return executeBitcoin(ctx.platform.random, request, request.account, seed, intentOnly);
17254
+ }
17255
+ if (request.kind === "evm.transaction" || request.kind === "evm.personal-message" || request.kind === "evm.typed-data") {
17256
+ return executeEvm(request, request.account, seed, intentOnly);
17195
17257
  }
17196
- return executeSolana(request, account, seed, intentOnly);
17258
+ return executeSolana(request, request.account, seed, intentOnly);
17197
17259
  };
17198
17260
  const withSeed = async (run) => withWalletSeed(ctx.platform.pbkdf2, dek, record, run);
17199
17261
  const prepared = await withSeed((seed) => execute(seed, true));
@@ -17246,7 +17308,7 @@ function nostrKeyAt(master, index) {
17246
17308
  }
17247
17309
  }
17248
17310
 
17249
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/nips/nip19.mjs
17311
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/nips/nip19.mjs
17250
17312
  var Bech32MaxSize2 = 5000;
17251
17313
  function encodeBech32(prefix, data) {
17252
17314
  const words = bech32.toWords(data);
@@ -17419,7 +17481,7 @@ async function scryptAsync(password, salt, opts) {
17419
17481
  return scryptOutput(password, dkLen, B, V, tmp);
17420
17482
  }
17421
17483
 
17422
- // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/nips/nip49.mjs
17484
+ // ../../node_modules/.bun/@qntx+nostr@0.15.4+cb72dcd9952e90a1/node_modules/@qntx/nostr/dist/nips/nip49.mjs
17423
17485
  var VERSION2 = 2;
17424
17486
  var SALT_LEN = 16;
17425
17487
  var NONCE_LEN = 24;
@@ -18718,7 +18780,11 @@ function startKernel(host, port) {
18718
18780
  integrityFailure = true;
18719
18781
  setHealth("corrupted");
18720
18782
  }
18721
- const err = error instanceof KernelError ? error.retryAt === undefined ? { code: error.code } : { code: error.code, retryAt: error.retryAt } : { code: "integrity" };
18783
+ const err = error instanceof KernelError ? {
18784
+ code: error.code,
18785
+ ...error.retryAt === undefined ? {} : { retryAt: error.retryAt },
18786
+ ...error.detail === undefined ? {} : { detail: error.detail }
18787
+ } : { code: "integrity" };
18722
18788
  return { v: PROTOCOL_VERSION, id, err };
18723
18789
  }
18724
18790
  };