@bsv/expo-wallet-toolbox 0.19.0 → 0.21.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 (141) hide show
  1. package/CHANGELOG.md +154 -30
  2. package/README.md +79 -79
  3. package/core/backup/RemoteSyncReader.ts +26 -24
  4. package/core/backup/appData.ts +9 -8
  5. package/core/backup/codec.ts +21 -18
  6. package/core/backup/constants.ts +5 -5
  7. package/core/backup/contactsBackup.ts +8 -8
  8. package/core/backup/cursor.ts +12 -7
  9. package/core/backup/derive.ts +3 -3
  10. package/core/backup/deviceId.ts +2 -2
  11. package/core/backup/erase.ts +2 -2
  12. package/core/backup/preference.ts +2 -2
  13. package/core/backup/push.ts +10 -12
  14. package/core/backup/restore.ts +22 -14
  15. package/core/backup/restoreOnImport.ts +3 -2
  16. package/core/config.tsx +17 -13
  17. package/core/constants.ts +34 -11
  18. package/core/contacts/contactsStore.ts +4 -3
  19. package/core/context/WalletConnectionContext.tsx +294 -212
  20. package/core/context/WalletContext.tsx +132 -97
  21. package/core/context/defaultWalletSettings.ts +4 -2
  22. package/core/demo/demoLedger.ts +1 -5
  23. package/core/directpay/DirectPayManager.ts +148 -29
  24. package/core/directpay/DirectPayProvider.tsx +26 -26
  25. package/core/directpay/payFlow.ts +10 -1
  26. package/core/directpay/receive.ts +2 -1
  27. package/core/directpay/settings.ts +56 -9
  28. package/core/directpay/types.ts +11 -2
  29. package/core/directpay/webrtpay.ts +4 -0
  30. package/core/headers/checkpoints.ts +10 -1
  31. package/core/headers/headerStore.ts +13 -2
  32. package/core/hooks/useConfirmationSound.ts +3 -3
  33. package/core/hooks/useHaptics.ts +23 -6
  34. package/core/i18n/translations.tsx +382 -209
  35. package/core/index.ts +2 -0
  36. package/core/localpay/codec.ts +12 -6
  37. package/core/localpay/deviceCaps.ts +4 -14
  38. package/core/localpay/pending.ts +2 -1
  39. package/core/localpay/qr.ts +1 -1
  40. package/core/localpay/settlementAck.ts +1 -4
  41. package/core/localpay/transport/ble.ts +2 -2
  42. package/core/localpay/transport/socket.ts +1 -1
  43. package/core/mandala/abortGuard.ts +1 -1
  44. package/core/mandala/drain.ts +3 -0
  45. package/core/mandala/permissionModule.ts +3 -2
  46. package/core/mandala/resendTransfer.ts +4 -1
  47. package/core/mandala/runtime.ts +4 -4
  48. package/core/monitor/TaskBackupPush.ts +10 -13
  49. package/core/net/chainMatch.ts +8 -5
  50. package/core/networks.ts +145 -0
  51. package/core/parsePeerPayURI.ts +4 -1
  52. package/core/pay/beefRepair.ts +6 -3
  53. package/core/pay/creditErrors.ts +37 -1
  54. package/core/pay/rails/address.ts +10 -6
  55. package/core/pay/rails/direct.ts +6 -2
  56. package/core/pay/rails/handle.ts +84 -11
  57. package/core/pay/rails/index.ts +18 -2
  58. package/core/pay/receiveHistory.ts +8 -8
  59. package/core/peerpay/handleResendRequests.ts +11 -18
  60. package/core/peerpay/inboxAttempts.ts +1 -4
  61. package/core/peerpay/rebuildToken.ts +12 -9
  62. package/core/profiles/profileStore.ts +2 -1
  63. package/core/profiles/removalProblems.ts +3 -1
  64. package/core/services/arcTokenStorage.ts +2 -1
  65. package/core/services/arcadeBroadcastProvider.ts +7 -17
  66. package/core/services/secrets/envelope.ts +1 -6
  67. package/core/services/secrets/hkdf.ts +1 -6
  68. package/core/services/secrets/index.ts +3 -22
  69. package/core/services/usdFxRates.ts +1 -4
  70. package/core/services/vault/VaultKeyService.ts +2 -1
  71. package/core/services/vault/chainRecovery.ts +48 -21
  72. package/core/services/vault/metaAuthority.ts +4 -1
  73. package/core/services/vault/r1comb.ts +113 -51
  74. package/core/services/vault/session.ts +5 -1
  75. package/core/services/vault/transfers.ts +699 -576
  76. package/core/services/vault/vaultStore.ts +12 -10
  77. package/core/services/walletArgLimits.ts +1 -2
  78. package/core/services/walletConnectionValidation.ts +44 -28
  79. package/core/services/walletServiceConfig.ts +9 -40
  80. package/core/storage/StorageExpoSQLite.ts +7 -21
  81. package/core/storage/methods/listActionsSql.ts +81 -67
  82. package/core/storage/methods/listOutputsSql.ts +21 -16
  83. package/core/storage/methods/reviewStatusSql.ts +1 -4
  84. package/core/stores/ConnectionStore.ts +1 -1
  85. package/core/theme/ThemeContext.tsx +12 -16
  86. package/core/theme/motion.ts +3 -3
  87. package/core/theme/tokens.ts +6 -6
  88. package/core/toolboxConfig.ts +23 -0
  89. package/core/walletDbRegistry.ts +7 -5
  90. package/core/walletRepair/runWalletCheck.ts +1 -4
  91. package/package.json +2 -2
  92. package/ui/components/pay/AddressReceive.tsx +3 -3
  93. package/ui/components/pay/HandleReceive.tsx +21 -15
  94. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  95. package/ui/components/pay/NearbyFlow.tsx +575 -507
  96. package/ui/components/pay/OfflineNotice.tsx +1 -3
  97. package/ui/components/pay/PayCellRow.tsx +1 -4
  98. package/ui/components/pay/PayForm.tsx +1 -3
  99. package/ui/components/pay/RequestHub.tsx +14 -6
  100. package/ui/components/pay/UniversalSend.tsx +79 -27
  101. package/ui/components/pay/tokenSendCopy.ts +1 -2
  102. package/ui/components/pay/useRecipientInput.ts +2 -2
  103. package/ui/components/security/WalletLockNotice.tsx +1 -3
  104. package/ui/components/ui/AlertCard.tsx +44 -45
  105. package/ui/components/ui/BlurChrome.tsx +4 -15
  106. package/ui/components/ui/Celebration.tsx +3 -3
  107. package/ui/components/ui/ChoiceSheet.ts +1 -3
  108. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  109. package/ui/components/ui/GroupedList.tsx +13 -31
  110. package/ui/components/ui/IconButton.tsx +6 -9
  111. package/ui/components/ui/ListRow.tsx +19 -25
  112. package/ui/components/ui/PresenceRow.tsx +4 -4
  113. package/ui/components/ui/PressableScale.tsx +24 -20
  114. package/ui/components/ui/Toast.tsx +23 -16
  115. package/ui/components/vault/KeyChooser.tsx +9 -6
  116. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  117. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  118. package/ui/components/wallet/ActivityRow.tsx +3 -2
  119. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  120. package/ui/components/wallet/Balance.tsx +4 -1
  121. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  122. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  123. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  124. package/ui/components/wallet/tokenEviction.ts +4 -1
  125. package/ui/hooks/useMandala.ts +1 -7
  126. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  127. package/ui/hooks/useSpendableBalance.ts +2 -2
  128. package/ui/hooks/useVaultCoverage.ts +7 -1
  129. package/ui/index.ts +9 -1
  130. package/ui/resolveIdentity.ts +20 -8
  131. package/ui/screens/ConnectionsScreen.tsx +44 -18
  132. package/ui/screens/LogsScreen.tsx +24 -22
  133. package/ui/screens/PairScreen.tsx +85 -54
  134. package/ui/screens/PayScreen.tsx +5 -1
  135. package/ui/screens/ProfileScreen.tsx +0 -3
  136. package/ui/screens/TrustScreen.tsx +125 -80
  137. package/ui/screens/VaultScreen.tsx +19 -7
  138. package/ui/screens/VaultTransferScreen.tsx +5 -1
  139. package/ui/screens/WalletCheckScreen.tsx +14 -17
  140. package/ui/screens/WalletConfigScreen.tsx +414 -376
  141. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -13,9 +13,21 @@
13
13
  * SECURITY: nothing secret passes through this module — public keys, per-output
14
14
  * salts, signatures the card already produced, and script bytes.
15
15
  */
16
- import { Hash, LockingScript, OP, PrivateKey, Script, Spend, Transaction, TransactionSignature, UnlockingScript, Utils } from '@bsv/sdk'
16
+ import {
17
+ Hash,
18
+ LockingScript,
19
+ OP,
20
+ PrivateKey,
21
+ Script,
22
+ Spend,
23
+ Transaction,
24
+ TransactionSignature,
25
+ UnlockingScript,
26
+ Utils
27
+ } from '@bsv/sdk'
17
28
  import { p256 } from '@noble/curves/nist.js'
18
29
  import { VaultError } from './types'
30
+ import { isAppChain, type AppChain } from '../../networks'
19
31
 
20
32
  // ───────────────────────── comb geometry and sizes (spec §2) ─────────────────────────
21
33
  export const COMB_ROWS = 6
@@ -78,7 +90,7 @@ const leToBig = (b: number[]): bigint => beToBig([...b].reverse())
78
90
  const invalid = (message: string): VaultError => new VaultError('template-invalid', message)
79
91
 
80
92
  /** Network recorded beside a Vault output and checked against wallet scope. */
81
- export type VaultSaltChain = 'main' | 'test' | 'teratest'
93
+ export type VaultSaltChain = AppChain
82
94
 
83
95
  /**
84
96
  * Canonical `createHmac` data for a Vault output: the enrolled YubiKey serial
@@ -112,7 +124,14 @@ export function pushData(data: number[]): number[] {
112
124
  if (d.length <= 75) return [d.length, ...d]
113
125
  if (d.length <= 0xff) return [OP.OP_PUSHDATA1, d.length, ...d]
114
126
  if (d.length <= 0xffff) return [OP.OP_PUSHDATA2, d.length & 0xff, d.length >>> 8, ...d]
115
- return [OP.OP_PUSHDATA4, d.length & 0xff, (d.length >>> 8) & 0xff, (d.length >>> 16) & 0xff, (d.length >>> 24) & 0xff, ...d]
127
+ return [
128
+ OP.OP_PUSHDATA4,
129
+ d.length & 0xff,
130
+ (d.length >>> 8) & 0xff,
131
+ (d.length >>> 16) & 0xff,
132
+ (d.length >>> 24) & 0xff,
133
+ ...d
134
+ ]
116
135
  }
117
136
 
118
137
  /** Minimal script-number encoding (sign-magnitude little-endian) == BigNumber.toSm('little'). */
@@ -203,7 +222,10 @@ export function compressPubkey(sec1Hex: string): string {
203
222
  }
204
223
 
205
224
  // ───────────────────────── comb tables (spec §2.1) ─────────────────────────
206
- export interface AffinePoint { x: bigint; y: bigint }
225
+ export interface AffinePoint {
226
+ x: bigint
227
+ y: bigint
228
+ }
207
229
  type P256Point = ReturnType<typeof p256.Point.fromHex>
208
230
 
209
231
  /**
@@ -308,18 +330,22 @@ function emitHeaderBeforeSalt(): number[] {
308
330
  // H0: bind withdrawals to transaction version 1 at consensus level, then
309
331
  // e = unsigned-LE(hash256(preimage)); preimage -> alt. OP_PUSH_TX later binds
310
332
  // this exact preimage to the transaction being evaluated.
311
- out.push(...asm(`
333
+ out.push(
334
+ ...asm(`
312
335
  OP_OVER 4 OP_SPLIT OP_DROP <01000000> OP_EQUALVERIFY
313
336
  OP_OVER OP_HASH256 <00> OP_CAT OP_BIN2NUM
314
337
  2 OP_ROLL OP_TOALTSTACK OP_SWAP OP_TOALTSTACK
315
- `))
338
+ `)
339
+ )
316
340
  // H1: n -> alt; enforce canonical r, low-S s and sInv before any modular
317
341
  // arithmetic; s*sInv == 1; u1 = e*sInv; u2 = r*sInv. The r checks are
318
342
  // consensus-critical: without 1 <= r < p and r != n, CRT can give r one
319
343
  // residue modulo n for scalar multiplication and another modulo p for the
320
344
  // final affine-x check, permitting a signature-free spend.
321
345
  // [.. s sInv u1]: u1(0) sInv(1) s(2) Q63(3) .. Q0(2+K) u1'(3+K) u2'(4+K) r(5+K)
322
- out.push(...asm(`
346
+ out.push(
347
+ ...asm(
348
+ `
323
349
  {N} OP_TOALTSTACK
324
350
  2 OP_PICK 1 {HALFP1} OP_WITHIN OP_VERIFY
325
351
  OP_OVER 1 OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_WITHIN OP_VERIFY
@@ -329,7 +355,10 @@ function emitHeaderBeforeSalt(): number[] {
329
355
  OP_OVER OP_MUL MODP
330
356
  {RDEPTH} OP_PICK 2 OP_PICK OP_MUL MODP
331
357
  2 OP_ROLL OP_DROP 2 OP_ROLL OP_DROP
332
- `, { N: P256_N, HALFP1: P256_LOW_S_MAX + 1n, P: P256_P, RDEPTH: K_Q + 5 }))
358
+ `,
359
+ { N: P256_N, HALFP1: P256_LOW_S_MAX + 1n, P: P256_P, RDEPTH: K_Q + 5 }
360
+ )
361
+ )
333
362
  // H2: recode u2 then u1 -> [.. Q63 u1' u2']
334
363
  const one = 'OP_DUP 2 OP_MOD OP_NOTIF {N} OP_ADD OP_ENDIF {C} OP_ADD 2 OP_DIV OP_SWAP'
335
364
  out.push(...asm(`${one} ${one}`, { N: P256_N, C: RECODE_CONST }))
@@ -345,7 +374,11 @@ function emitHeaderAfterSalt(): number[] {
345
374
  if (headerAfterSaltCache !== null) return headerAfterSaltCache
346
375
  // alt enters [preimage salt n]. Preserve n above preimage for emitPreloop,
347
376
  // while returning salt to the main stack for its exact byte-length check.
348
- const out: number[] = [...asm('OP_FROMALTSTACK OP_FROMALTSTACK OP_SWAP OP_TOALTSTACK OP_SIZE {SALT_BYTES} OP_NUMEQUALVERIFY', { SALT_BYTES })]
377
+ const out: number[] = [
378
+ ...asm('OP_FROMALTSTACK OP_FROMALTSTACK OP_SWAP OP_TOALTSTACK OP_SIZE {SALT_BYTES} OP_NUMEQUALVERIFY', {
379
+ SALT_BYTES
380
+ })
381
+ ]
349
382
  for (let m = 0; m < K_Q; m++) out.push(...asm('{D} OP_PICK {W} OP_NUM2BIN OP_CAT', { D: K_Q - m, W: COORD_WIDTH }))
350
383
  out.push(OP.OP_HASH160)
351
384
  headerAfterSaltCache = out
@@ -364,7 +397,8 @@ function emitH5(commitments: number[][]): number[] {
364
397
  out.push(...asm('{C} OP_EQUALVERIFY', { C: commitments[0] }))
365
398
  return out
366
399
  }
367
- for (let i = 0; i < commitments.length - 1; i++) out.push(...asm('OP_DUP {C} OP_EQUAL OP_SWAP', { C: commitments[i] }))
400
+ for (let i = 0; i < commitments.length - 1; i++)
401
+ out.push(...asm('OP_DUP {C} OP_EQUAL OP_SWAP', { C: commitments[i] }))
368
402
  out.push(...asm('{C} OP_EQUAL', { C: commitments[commitments.length - 1] }))
369
403
  for (let i = 0; i < commitments.length - 1; i++) out.push(OP.OP_BOOLOR)
370
404
  out.push(OP.OP_VERIFY)
@@ -483,8 +517,8 @@ export function completeMixedAddScript(): number[] {
483
517
  }
484
518
 
485
519
  /** Stack layout beneath the accumulator: [r u2' u1' C[0..K-1]] with K = 128 table coordinates (Q[0..63] then G[0..63]). */
486
- const K_CONSTS = 2 * 2 * TABLE_SIZE // 128
487
- const BELOW = 3 + K_CONSTS // 131 items under the accumulator (X Y Z)
520
+ const K_CONSTS = 2 * 2 * TABLE_SIZE // 128
521
+ const BELOW = 3 + K_CONSTS // 131 items under the accumulator (X Y Z)
488
522
  // With [.. X Y Z] on top (BELOW + 3 items): stack index 1 (= u2') is at depth 132, index 2 (= u1') at 131.
489
523
  const scalarDepth = (half: 0 | 1): number => BELOW + 1 - half
490
524
  // C[m] sits at depth 132 − m once [.. X Y Z sign j] is on top; half 0 -> C[0..63] (= Q), half 1 -> C[64..127] (= G).
@@ -494,7 +528,10 @@ export const shiftFor = (c: number, k: number): number => COMB_COLS * (COMB_ROWS
494
528
 
495
529
  function emitAdd(half: 0 | 1, c: number): number[] {
496
530
  const params: Record<string, AsmParam> = {
497
- DEPTH0: scalarDepth(half), DEPTH1: scalarDepth(half) + 1, DEPTH2: scalarDepth(half) + 2, BASE: tableBase(half)
531
+ DEPTH0: scalarDepth(half),
532
+ DEPTH1: scalarDepth(half) + 1,
533
+ DEPTH2: scalarDepth(half) + 2,
534
+ BASE: tableBase(half)
498
535
  }
499
536
  for (let k = 0; k < COMB_ROWS; k++) params[`SHIFT${k}`] = shiftFor(c, k)
500
537
  return [...asm(DIGITS_AND_LOOKUP, params), ...completeMixedAddScript()]
@@ -505,8 +542,8 @@ function emitCombLoop(): number[] {
505
542
  const out: number[] = []
506
543
  for (let c = 0; c < COMB_COLS; c++) {
507
544
  out.push(...asm(DOUBLE))
508
- out.push(...emitAdd(0, c)) // index-1 scalar (u2') with C[0..63] (Q)
509
- out.push(...emitAdd(1, c)) // index-2 scalar (u1') with C[64..127] (G)
545
+ out.push(...emitAdd(0, c)) // index-1 scalar (u2') with C[0..63] (Q)
546
+ out.push(...emitAdd(1, c)) // index-2 scalar (u1') with C[64..127] (G)
510
547
  }
511
548
  return out
512
549
  }
@@ -548,14 +585,17 @@ function pushTxPubKey(constant: bigint): number[] {
548
585
  */
549
586
  function emitTail(): number[] {
550
587
  // r (item index 0) with [.. X Y Z Z^2] on top (BELOW + 4 items) is at depth BELOW + 3 = 134
551
- const rCheck = asm(`
588
+ const rCheck = asm(
589
+ `
552
590
  OP_DUP 0 OP_NUMEQUAL OP_NOTIF
553
591
  OP_DUP OP_DUP OP_MUL MODP
554
592
  {RDEPTH} OP_PICK OP_OVER OP_MUL MODP
555
593
  4 OP_PICK OP_NUMEQUAL
556
594
  OP_ELSE 0 OP_ENDIF OP_VERIFY
557
595
  OP_FROMALTSTACK OP_DROP
558
- `, { RDEPTH: BELOW + 3 })
596
+ `,
597
+ { RDEPTH: BELOW + 3 }
598
+ )
559
599
  // stack now holds BELOW + 4 items (r u2' u1' C[] X Y Z Z^2): drop them all
560
600
  const leftover = BELOW + 4
561
601
  const clear: number[] = [
@@ -565,7 +605,8 @@ function emitTail(): number[] {
565
605
  // e_k1 = BE(hash256(preimage)); normally s = lowS((e_k1 + C1) mod n_k1).
566
606
  // If that is zero, use C2 and its public key, for which s is exactly 1.
567
607
  const rev31 = new Array<string>(31).fill('OP_SWAP OP_CAT').join(' ')
568
- const pushTx = asm(`
608
+ const pushTx = asm(
609
+ `
569
610
  OP_FROMALTSTACK {SIGHASH} OP_TOALTSTACK OP_HASH256
570
611
  ${new Array<string>(31).fill('1 OP_SPLIT').join(' ')}
571
612
  ${rev31}
@@ -585,19 +626,23 @@ function emitTail(): number[] {
585
626
  <30> OP_SWAP OP_CAT
586
627
  OP_FROMALTSTACK OP_CAT
587
628
  OP_SWAP OP_CODESEPARATOR OP_CHECKSIG
588
- `, {
589
- SIGHASH: [R1C_SIGHASH], NK: SECP_N,
590
- DERPREFIX: [...derIntBytes(SECP_GX), 0x02], // 02 20 <Gx> 02 (s INTEGER tag appended)
591
- PUBKEY1: pushTxPubKey(PUSH_TX_C1),
592
- PUBKEY2: pushTxPubKey(PUSH_TX_C2)
593
- })
629
+ `,
630
+ {
631
+ SIGHASH: [R1C_SIGHASH],
632
+ NK: SECP_N,
633
+ DERPREFIX: [...derIntBytes(SECP_GX), 0x02], // 02 20 <Gx> 02 (s INTEGER tag appended)
634
+ PUBKEY1: pushTxPubKey(PUSH_TX_C1),
635
+ PUBKEY2: pushTxPubKey(PUSH_TX_C2)
636
+ }
637
+ )
594
638
  return [...rCheck, ...clear, ...pushTx]
595
639
  }
596
640
 
597
641
  let sharedSuffixCache: number[] | null = null
598
642
  /** G table + pre-loop + complete comb loop + total covenant tail: 44,388 B. Computed once. */
599
643
  export function sharedSuffix(): number[] {
600
- if (sharedSuffixCache === null) sharedSuffixCache = [...emitGTable(), ...emitPreloop(), ...emitCombLoop(), ...emitTail()]
644
+ if (sharedSuffixCache === null)
645
+ sharedSuffixCache = [...emitGTable(), ...emitPreloop(), ...emitCombLoop(), ...emitTail()]
601
646
  return sharedSuffixCache.slice()
602
647
  }
603
648
 
@@ -607,7 +652,8 @@ function parseCommitments(commitments: unknown): number[][] {
607
652
  throw invalid(`buildLock: commitments must be 1..${R1C_MAX_KEYS} hash160 hex strings`)
608
653
  }
609
654
  const lower: string[] = commitments.map(c => {
610
- if (typeof c !== 'string' || !/^[0-9a-fA-F]{40}$/.test(c)) throw invalid('buildLock: commitment must be 40 hex chars')
655
+ if (typeof c !== 'string' || !/^[0-9a-fA-F]{40}$/.test(c))
656
+ throw invalid('buildLock: commitment must be 40 hex chars')
611
657
  return c.toLowerCase()
612
658
  })
613
659
  if (new Set(lower).size !== lower.length) throw invalid('buildLock: duplicate commitment')
@@ -664,7 +710,8 @@ function requirePreimage(preimage: number[], where: string): void {
664
710
  throw invalid(`${where}: preimage must be ${R1C_PREIMAGE_LEN} bytes`)
665
711
  }
666
712
  const version = new Utils.Reader(preimage.slice(0, 4)).readUInt32LE()
667
- if (version !== 1) throw invalid(`${where}: vault withdrawals require transaction version 1; this preimage carries version ${version}`)
713
+ if (version !== 1)
714
+ throw invalid(`${where}: vault withdrawals require transaction version 1; this preimage carries version ${version}`)
668
715
  }
669
716
 
670
717
  /** Version-1 BIP143 preimage, subscript `ac`, scope 0x41, for input `inputIndex` of `tx` whose source output carried `sourceSatoshis`. */
@@ -673,7 +720,8 @@ export function sighashPreimage(tx: Transaction, inputIndex: number, sourceSatos
673
720
  if (input === undefined) throw invalid(`sighashPreimage: input ${inputIndex} does not exist`)
674
721
  const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
675
722
  if (sourceTXID === undefined) throw invalid('sighashPreimage: input needs sourceTXID or sourceTransaction')
676
- if (!Number.isSafeInteger(sourceSatoshis) || sourceSatoshis < 0) throw invalid('sighashPreimage: sourceSatoshis must be a non-negative integer')
723
+ if (!Number.isSafeInteger(sourceSatoshis) || sourceSatoshis < 0)
724
+ throw invalid('sighashPreimage: sourceSatoshis must be a non-negative integer')
677
725
  const preimage = TransactionSignature.format({
678
726
  sourceTXID,
679
727
  sourceOutputIndex: input.sourceOutputIndex,
@@ -725,7 +773,9 @@ export function pushTxDerCheck(preimage: number[]): { ok: boolean; s: bigint } {
725
773
  // ───────────────────────── DER ─────────────────────────
726
774
  /** Strict DER `SEQUENCE { INTEGER r, INTEGER s }` → (r, s), both in [1, n−1]. Short-form lengths only (max 72 B). */
727
775
  export function decodeDerSignature(der: number[]): { r: bigint; s: bigint } {
728
- const fail = (why: string): never => { throw invalid(`decodeDerSignature: ${why}`) }
776
+ const fail = (why: string): never => {
777
+ throw invalid(`decodeDerSignature: ${why}`)
778
+ }
729
779
  if (!Array.isArray(der) || der.length < 8 || der.length > 72) fail('length')
730
780
  if (der[0] !== 0x30) fail('not a SEQUENCE')
731
781
  if (der[1] !== der.length - 2) fail('bad SEQUENCE length')
@@ -779,7 +829,9 @@ export function fullR(a: { preimage: number[]; rSig: bigint; s: bigint; pubkeyHe
779
829
  const sInv = modinv(s, P256_N)
780
830
  const u1 = mod(e * sInv, P256_N)
781
831
  const u2 = mod(a.rSig * sInv, P256_N)
782
- const R = (u1 === 0n ? p256.Point.ZERO : p256.Point.BASE.multiply(u1)).add(u2 === 0n ? p256.Point.ZERO : Q.multiply(u2))
832
+ const R = (u1 === 0n ? p256.Point.ZERO : p256.Point.BASE.multiply(u1)).add(
833
+ u2 === 0n ? p256.Point.ZERO : Q.multiply(u2)
834
+ )
783
835
  if (R.is0()) return null
784
836
  return R.toAffine().x
785
837
  }
@@ -791,7 +843,12 @@ export function fullR(a: { preimage: number[]; rSig: bigint; s: bigint; pubkeyHe
791
843
  * bad key / DER, R = O. It does NOT verify the signature against Q: the interpreter is the arbiter
792
844
  * (Plan 2 runs verifyVaultInput on every input before signAction).
793
845
  */
794
- export function buildUnlock(a: { preimage: number[]; derSig: number[]; pubkeyHex33: string; saltHex64: string }): UnlockingScript {
846
+ export function buildUnlock(a: {
847
+ preimage: number[]
848
+ derSig: number[]
849
+ pubkeyHex33: string
850
+ saltHex64: string
851
+ }): UnlockingScript {
795
852
  const { preimage } = a
796
853
  requirePreimage(preimage, 'buildUnlock')
797
854
  const key = compressPubkey(a.pubkeyHex33)
@@ -806,7 +863,7 @@ export function buildUnlock(a: { preimage: number[]; derSig: number[]; pubkeyHex
806
863
  const e = leToBig(Hash.hash256(preimage))
807
864
  const sInv = modinv(s, P256_N)
808
865
  const u1 = mod(e * sInv, P256_N)
809
- const u2 = mod(Rx * sInv, P256_N) // the lock derives u2 from the PUSHED r (≡ rSig mod n), so recode that
866
+ const u2 = mod(Rx * sInv, P256_N) // the lock derives u2 from the PUSHED r (≡ rSig mod n), so recode that
810
867
  const bytes: number[] = [...encNum(Rx), ...encNum(recode(u2)), ...encNum(recode(u1))]
811
868
  for (const { x, y } of combTable(key)) bytes.push(...encNum(x), ...encNum(y))
812
869
  bytes.push(...encNum(s), ...encNum(sInv), ...pushData(preimage), ...pushData(saltBytes(a.saltHex64)))
@@ -924,15 +981,13 @@ export function decodeVaultInstructionsV6(ci?: string): VaultInstructionsV6 | nu
924
981
  }
925
982
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
926
983
  const p = parsed as Record<string, unknown>
927
- if (!exactFields(p, ['v', 'type', 'salt', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys'])) return null
984
+ if (!exactFields(p, ['v', 'type', 'salt', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys']))
985
+ return null
928
986
  if (p.v !== 6 || p.type !== 'R1C') return null
929
987
  if (typeof p.salt !== 'string' || !/^[0-9a-f]{64}$/.test(p.salt)) return null
930
988
  if (typeof p.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(p.vaultId)) return null
931
- if (
932
- typeof p.saltKeyId !== 'string' ||
933
- !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)
934
- ) return null
935
- if (p.chain !== 'main' && p.chain !== 'test' && p.chain !== 'teratest') return null
989
+ if (typeof p.saltKeyId !== 'string' || !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)) return null
990
+ if (!isAppChain(p.chain)) return null
936
991
  const saltIndex = Number(p.saltKeyId)
937
992
  if (!positiveSafeInteger(saltIndex)) return null
938
993
  if (!positiveSafeInteger(p.revision) || !positiveSafeInteger(p.createdAt)) return null
@@ -946,9 +1001,13 @@ export function decodeVaultInstructionsV6(ci?: string): VaultInstructionsV6 | nu
946
1001
  if (k.slot !== 0x82) return null
947
1002
  if (typeof k.pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(k.pubkey)) return null
948
1003
  if (
949
- typeof k.nickname !== 'string' || k.nickname.length < 1 || k.nickname.length > 64 ||
950
- k.nickname !== k.nickname.trim() || /[\u0000-\u001f\u007f]/.test(k.nickname)
951
- ) return null
1004
+ typeof k.nickname !== 'string' ||
1005
+ k.nickname.length < 1 ||
1006
+ k.nickname.length > 64 ||
1007
+ k.nickname !== k.nickname.trim() ||
1008
+ /[\u0000-\u001f\u007f]/.test(k.nickname)
1009
+ )
1010
+ return null
952
1011
  if (!positiveSafeInteger(k.enrolledAt)) return null
953
1012
  try {
954
1013
  if (compressPubkey(k.pubkey) !== k.pubkey) return null
@@ -1002,7 +1061,8 @@ export function encodeVaultInstructions(i: VaultInstructionsV6): string {
1002
1061
  enrolledAt: k.enrolledAt
1003
1062
  }))
1004
1063
  })
1005
- if (decodeVaultInstructionsV6(s) === null) throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
1064
+ if (decodeVaultInstructionsV6(s) === null)
1065
+ throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
1006
1066
  return s
1007
1067
  }
1008
1068
 
@@ -1025,11 +1085,8 @@ export function decodeVaultInstructionsV7(ci?: string): VaultInstructionsV7 | nu
1025
1085
  if (!exactFields(p, ['v', 'type', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys'])) return null
1026
1086
  if (p.v !== 7 || p.type !== 'R1C') return null
1027
1087
  if (typeof p.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(p.vaultId)) return null
1028
- if (
1029
- typeof p.saltKeyId !== 'string' ||
1030
- !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)
1031
- ) return null
1032
- if (p.chain !== 'main' && p.chain !== 'test' && p.chain !== 'teratest') return null
1088
+ if (typeof p.saltKeyId !== 'string' || !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)) return null
1089
+ if (!isAppChain(p.chain)) return null
1033
1090
  const saltIndex = Number(p.saltKeyId)
1034
1091
  if (!positiveSafeInteger(saltIndex)) return null
1035
1092
  if (!positiveSafeInteger(p.revision) || !positiveSafeInteger(p.createdAt)) return null
@@ -1043,9 +1100,13 @@ export function decodeVaultInstructionsV7(ci?: string): VaultInstructionsV7 | nu
1043
1100
  if (k.slot !== 0x82) return null
1044
1101
  if (typeof k.pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(k.pubkey)) return null
1045
1102
  if (
1046
- typeof k.nickname !== 'string' || k.nickname.length < 1 || k.nickname.length > 64 ||
1047
- k.nickname !== k.nickname.trim() || /[\u0000-\u001f\u007f]/.test(k.nickname)
1048
- ) return null
1103
+ typeof k.nickname !== 'string' ||
1104
+ k.nickname.length < 1 ||
1105
+ k.nickname.length > 64 ||
1106
+ k.nickname !== k.nickname.trim() ||
1107
+ /[\u0000-\u001f\u007f]/.test(k.nickname)
1108
+ )
1109
+ return null
1049
1110
  if (!positiveSafeInteger(k.enrolledAt)) return null
1050
1111
  try {
1051
1112
  if (compressPubkey(k.pubkey) !== k.pubkey) return null
@@ -1097,7 +1158,8 @@ export function encodeVaultInstructionsV7(i: VaultInstructionsV7): string {
1097
1158
  enrolledAt: k.enrolledAt
1098
1159
  }))
1099
1160
  })
1100
- if (decodeVaultInstructionsV7(s) === null) throw invalid('encodeVaultInstructionsV7: record would not decode as canonical v7 vault metadata')
1161
+ if (decodeVaultInstructionsV7(s) === null)
1162
+ throw invalid('encodeVaultInstructionsV7: record would not decode as canonical v7 vault metadata')
1101
1163
  return s
1102
1164
  }
1103
1165
 
@@ -21,7 +21,11 @@
21
21
  * swallows several failure paths, so no delegate fix makes this redundant).
22
22
  */
23
23
  import { VaultDriver } from './driver'
24
- import { acquireVaultHardwareLease, currentVaultHardwareGeneration, isCurrentVaultHardwareGeneration } from './hardwareLease'
24
+ import {
25
+ acquireVaultHardwareLease,
26
+ currentVaultHardwareGeneration,
27
+ isCurrentVaultHardwareGeneration
28
+ } from './hardwareLease'
25
29
  import { VaultError } from './types'
26
30
 
27
31
  /**