@bsv/expo-wallet-toolbox 0.7.0 → 0.9.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 (151) hide show
  1. package/CHANGELOG.md +1745 -0
  2. package/README.md +47 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +631 -162
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/syncHeaders.ts +12 -1
  24. package/core/i18n/translations.tsx +953 -25
  25. package/core/identity/handleRegistry/client.ts +31 -2
  26. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  27. package/core/identity/handleRegistry/resolver.ts +71 -3
  28. package/core/index.ts +33 -3
  29. package/core/localpay/build.ts +225 -24
  30. package/core/localpay/pending.ts +110 -7
  31. package/core/localpay/pendingAbortAuthority.ts +95 -0
  32. package/core/localpay/pendingAborts.ts +264 -28
  33. package/core/localpay/session.ts +42 -17
  34. package/core/localpay/settlementAck.ts +10 -1
  35. package/core/localpay/transport/socket.ts +52 -3
  36. package/core/localpay/verify.ts +100 -10
  37. package/core/mandala/abortGuard.ts +96 -20
  38. package/core/mandala/createRuntime.ts +206 -33
  39. package/core/mandala/drain.ts +89 -11
  40. package/core/mandala/inboxPrehold.ts +186 -0
  41. package/core/mandala/permissionModule.ts +202 -20
  42. package/core/mandala/settlementStore.ts +24 -2
  43. package/core/mandala/types.ts +40 -5
  44. package/core/monitor/TaskBackupPush.ts +14 -0
  45. package/core/monitor/TaskDrainOutbox.ts +14 -0
  46. package/core/monitor/TaskSendOffline.ts +14 -0
  47. package/core/net/publicDestination.ts +91 -0
  48. package/core/net/validateArcUrl.ts +22 -0
  49. package/core/offline/cancelParked.ts +134 -13
  50. package/core/offline/payerHold.ts +100 -24
  51. package/core/offline/plan.ts +36 -7
  52. package/core/pay/beefRepair.ts +6 -2
  53. package/core/pay/damagedInbox.ts +24 -0
  54. package/core/pay/rails/address.ts +107 -12
  55. package/core/pay/rails/handle.ts +117 -22
  56. package/core/pay/rails/index.ts +45 -7
  57. package/core/pay/rails/nativeIntent.ts +61 -0
  58. package/core/pay/receiveHistory.ts +93 -0
  59. package/core/pay/recordProof.ts +19 -1
  60. package/core/pay/refreshProofGuard.ts +42 -1
  61. package/core/pay/watchlist.ts +5 -2
  62. package/core/peerpay/control.ts +17 -18
  63. package/core/peerpay/handleResendRequests.ts +58 -4
  64. package/core/peerpay/outbox.ts +3 -1
  65. package/core/recovery/backupMaterial.ts +61 -0
  66. package/core/recovery/createWallet.ts +95 -0
  67. package/core/recovery/recoverWallet.ts +120 -0
  68. package/core/recovery/restoreWallet.ts +170 -0
  69. package/core/recovery/secret.ts +92 -0
  70. package/core/recovery/shareCollector.ts +71 -0
  71. package/core/recovery/shareParsing.ts +87 -0
  72. package/core/recovery/shares.ts +116 -0
  73. package/core/recovery/useRecoveryDeps.ts +70 -0
  74. package/core/services/arcTokenStorage.ts +52 -0
  75. package/core/services/arcadeBroadcastProvider.ts +232 -48
  76. package/core/services/autoApprovePolicy.ts +105 -0
  77. package/core/services/callbackToken.ts +19 -0
  78. package/core/services/capWalletArgs.ts +14 -2
  79. package/core/services/connectionAuthority.ts +98 -0
  80. package/core/services/exchangeRate.ts +35 -12
  81. package/core/services/externalOrigin.ts +11 -0
  82. package/core/services/secrets/kek.ts +126 -29
  83. package/core/services/secrets/migration.ts +16 -4
  84. package/core/services/secrets/store.ts +42 -14
  85. package/core/services/vault/VaultKeyService.ts +228 -45
  86. package/core/services/vault/chainRecovery.ts +483 -0
  87. package/core/services/vault/driver.ts +9 -1
  88. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  89. package/core/services/vault/guard.ts +218 -32
  90. package/core/services/vault/hardwareLease.ts +19 -0
  91. package/core/services/vault/metaAuthority.ts +210 -0
  92. package/core/services/vault/pivReset.ts +64 -23
  93. package/core/services/vault/r1comb.ts +139 -3
  94. package/core/services/vault/session.ts +25 -4
  95. package/core/services/vault/transfers.ts +866 -170
  96. package/core/services/vault/types.ts +19 -4
  97. package/core/services/vault/vaultStore.ts +256 -29
  98. package/core/services/walletArgLimits.ts +45 -2
  99. package/core/services/walletConnectionValidation.ts +76 -6
  100. package/core/services/walletServiceConfig.ts +10 -8
  101. package/core/storage/StorageExpoSQLite.ts +47 -13
  102. package/core/storage/methods/findSql.ts +21 -2
  103. package/core/storage/methods/offlineActions.ts +10 -1
  104. package/core/storage/methods/processOfflineActions.ts +116 -23
  105. package/core/storage/schema/createTables.ts +126 -2
  106. package/core/stores/ConnectionStore.ts +34 -0
  107. package/core/toolboxConfig.ts +45 -11
  108. package/core/walletDbRegistry.ts +63 -0
  109. package/core/walletMonitor.ts +17 -1
  110. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  111. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  112. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  113. package/package.json +2 -2
  114. package/ui/backupShares.ts +26 -169
  115. package/ui/components/pay/AddressReceive.tsx +13 -6
  116. package/ui/components/pay/AssetPicker.tsx +30 -9
  117. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  118. package/ui/components/pay/NearbyFlow.tsx +480 -243
  119. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  120. package/ui/components/pay/UniversalSend.tsx +167 -73
  121. package/ui/components/ui/AlertCard.tsx +38 -5
  122. package/ui/components/ui/PermissionSheet.tsx +197 -66
  123. package/ui/components/vault/EnrollWizard.tsx +61 -13
  124. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  125. package/ui/components/wallet/ActivityRow.tsx +5 -3
  126. package/ui/components/wallet/AmountInput.tsx +8 -2
  127. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  128. package/ui/components/wallet/Balance.tsx +42 -23
  129. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  130. package/ui/exportTransactions.ts +36 -4
  131. package/ui/hooks/useExportWalletData.ts +25 -2
  132. package/ui/importDatabases.ts +339 -24
  133. package/ui/index.ts +9 -3
  134. package/ui/isImageUrl.ts +6 -0
  135. package/ui/printRecoveryShares.ts +9 -10
  136. package/ui/recoveryPrompts.ts +91 -0
  137. package/ui/resolveIdentity.ts +31 -9
  138. package/ui/screens/ConnectionsScreen.tsx +86 -19
  139. package/ui/screens/IdentifierScreen.tsx +30 -8
  140. package/ui/screens/PairScreen.tsx +74 -2
  141. package/ui/screens/SettingsScreen.tsx +10 -4
  142. package/ui/screens/TrustScreen.tsx +99 -4
  143. package/ui/screens/VaultScreen.tsx +410 -61
  144. package/ui/screens/VaultTransferScreen.tsx +59 -7
  145. package/ui/screens/WalletCheckScreen.tsx +17 -6
  146. package/ui/screens/WalletConfigScreen.tsx +82 -28
  147. package/ui/screens/WalletHomeScreen.tsx +179 -88
  148. package/ui/screens/detailActionKeys.ts +55 -0
  149. package/ui/tokenFormat.ts +44 -4
  150. package/ui/txStatus.ts +5 -0
  151. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -16,6 +16,13 @@ import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
16
16
  import { FT_PROTOCOL_ID } from './verify'
17
17
  import type { Ack } from './types'
18
18
  import { MANDALA_ACTION_LABEL, MANDALA_BASKET, assembleBundle, type BundleStore } from '../mandala/bundle'
19
+ // XR-037: bundle.ts's MANDALA_ACTION_LABEL ('mandala') is the home-screen
20
+ // row-recognition label; permissionModule.ts exports a DIFFERENT constant
21
+ // under the SAME name ('p mandala token-spend') — the only label that
22
+ // P-routes a listActions query to MandalaTokenModule's consent gate (label
23
+ // routing is listActions' only signal; the shared 'p mandala' BASKET does
24
+ // not make listActions route here). A real token action must carry both.
25
+ import { MANDALA_ACTION_LABEL as MANDALA_TOKEN_SPEND_LABEL } from '../mandala/permissionModule'
19
26
  import { getOnline } from '../net/online'
20
27
 
21
28
  /** The toolbox's per-txid verdict on a `sendWith` release. */
@@ -163,6 +170,17 @@ export interface TokenBuildDeps {
163
170
  basket?: string
164
171
  /** Opaque serialized VerifiableCertificates to carry, if the asset needs any. */
165
172
  certificates?: Uint8Array[]
173
+ /**
174
+ * This device's own configured overlay for the asset (XR-104), never the
175
+ * payee's. `buildTokenPaymentFrame` anchors `session.asset`'s
176
+ * overlayIdentityKey/overlayUrl — the payee's own claim, decoded off the
177
+ * wire — to these before selecting a coin or revealing any linkage, so a
178
+ * scanned request cannot direct `revealSpecificKeyLinkage`'s
179
+ * SpecificKeyLinkage disclosure to a verifier of its own choosing. Required
180
+ * so the check cannot be silently skipped by a caller that forgets to set it.
181
+ */
182
+ overlayIdentityKey: string
183
+ overlayUrl: string
166
184
  }
167
185
 
168
186
  /**
@@ -243,7 +261,17 @@ export async function buildPaymentFrame(
243
261
  /** The payer's note. Becomes the action's description in place of the fixed
244
262
  * fallback, and rides on the frame so the payee's own activity row can show
245
263
  * it too. */
246
- note?: string
264
+ note?: string,
265
+ /**
266
+ * XR-088: persists a reference whose own release (inside
267
+ * `releasingOnFailure`, below) failed after a build error, so it can be
268
+ * retried on the next wallet build instead of only being logged. Optional
269
+ * so a caller that has not wired it keeps today's log-only behaviour
270
+ * exactly — this is additive hardening, not a new requirement. The real
271
+ * app wires it to the same `queuePendingAbort` its decline path
272
+ * (`finalizeDelivery`) already uses.
273
+ */
274
+ queueFailedAbort?: (reference: string) => Promise<void>
247
275
  ): Promise<BuiltPayment> {
248
276
  if (!isRequestableAmount(amount)) {
249
277
  throw new Error('amount must be a positive whole number of satoshis')
@@ -255,7 +283,7 @@ export async function buildPaymentFrame(
255
283
  if (session.amount !== undefined && session.amount !== amount) {
256
284
  throw new Error('amount does not match the payee’s request')
257
285
  }
258
- return buildTokenPaymentFrame(wallet, session, session.asset, originator, amount, token, note)
286
+ return buildTokenPaymentFrame(wallet, session, session.asset, originator, amount, token, note, queueFailedAbort)
259
287
  }
260
288
  // A payee that named a figure is stating a binding term of the request, and
261
289
  // its settle path refuses anything else. Catching the disagreement here — on
@@ -324,7 +352,7 @@ export async function buildPaymentFrame(
324
352
 
325
353
  const reference = result.signableTransaction?.reference
326
354
 
327
- return await releasingOnFailure(wallet, reference, originator, async () => {
355
+ return await releasingOnFailure(wallet, reference, originator, queueFailedAbort, async () => {
328
356
  // With signAndProcess disabled, createAction returns an unsigned
329
357
  // `signableTransaction` rather than a final `tx`. We have no caller-supplied
330
358
  // inputs — all inputs are wallet-funded — so finalize by signing with empty
@@ -383,6 +411,8 @@ async function releasingOnFailure<T>(
383
411
  wallet: PayingWallet,
384
412
  reference: string | undefined,
385
413
  originator: string,
414
+ /** XR-088: see `buildPaymentFrame`'s own doc for this same parameter. */
415
+ queueFailedAbort: ((reference: string) => Promise<void>) | undefined,
386
416
  steps: () => Promise<T>
387
417
  ): Promise<T> {
388
418
  try {
@@ -394,6 +424,12 @@ async function releasingOnFailure<T>(
394
424
  if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
395
425
  } catch (abortError) {
396
426
  console.warn('[localpay] could not release the failed build:', messageOf(abortError))
427
+ // Best-effort, same as finalizeDelivery's decline path: a failure to
428
+ // queue must not mask the original build error this function is
429
+ // about to rethrow.
430
+ if (queueFailedAbort) {
431
+ await queueFailedAbort(reference).catch(() => undefined)
432
+ }
397
433
  }
398
434
  }
399
435
  throw e
@@ -502,12 +538,24 @@ async function buildTokenPaymentFrame(
502
538
  originator: string,
503
539
  amount: number,
504
540
  deps: TokenBuildDeps,
505
- note?: string
541
+ note?: string,
542
+ /** XR-088: see `buildPaymentFrame`'s own doc for this same parameter. */
543
+ queueFailedAbort?: (reference: string) => Promise<void>
506
544
  ): Promise<BuiltPayment> {
507
545
  if (!wallet.listOutputs) throw new Error('this wallet cannot list token outputs')
508
546
  if (!wallet.createSignature) throw new Error('this wallet cannot sign token inputs')
509
547
  if (!wallet.revealSpecificKeyLinkage) throw new Error('this wallet cannot reveal token linkage')
510
548
 
549
+ // XR-104: `asset` is `session.asset` — the PAYEE's own claim, decoded off
550
+ // the wire with no anchor of its own. Refuse before any coin is selected,
551
+ // any output built, or any linkage revealed: NearbyFlow's own comparison
552
+ // (its sole production caller) already refuses this case, but this
553
+ // exported, documented-single-import-site function must not depend on an
554
+ // upstream caller remembering to check first.
555
+ if (asset.overlayIdentityKey !== deps.overlayIdentityKey || asset.overlayUrl !== deps.overlayUrl) {
556
+ throw new Error('token asset overlay does not match this device’s configured overlay')
557
+ }
558
+
511
559
  const basket = deps.basket ?? MANDALA_BASKET
512
560
  const keyID = `${session.derivationPrefix} ${session.derivationSuffix}`
513
561
 
@@ -595,7 +643,7 @@ async function buildTokenPaymentFrame(
595
643
  // payee's key over "+0 sats" (2026-09-16). The payee key stays on as a
596
644
  // label for the resend path.
597
645
  description: note?.trim() || 'Sent token',
598
- labels: [PEERPAY_LABEL, session.identityKey, MANDALA_ACTION_LABEL],
646
+ labels: [PEERPAY_LABEL, session.identityKey, MANDALA_ACTION_LABEL, MANDALA_TOKEN_SPEND_LABEL],
599
647
  inputBEEF: sourceBeef.toBinary(),
600
648
  inputs: selected.map(coin => ({
601
649
  outpoint: coin.outpoint,
@@ -612,7 +660,7 @@ async function buildTokenPaymentFrame(
612
660
  if (!signable?.tx) throw new Error('createAction returned no signable token transaction')
613
661
  const signableTx = signable.tx
614
662
 
615
- return await releasingOnFailure(wallet, signable.reference, originator, async () => {
663
+ return await releasingOnFailure(wallet, signable.reference, originator, queueFailedAbort, async () => {
616
664
  const unsigned = Transaction.fromBEEF(signableTx)
617
665
 
618
666
  // Input order is caller order — `randomizeOutputs` shuffles outputs only, and
@@ -653,7 +701,11 @@ async function buildTokenPaymentFrame(
653
701
  const bundle = await assembleBundle({
654
702
  tipTx,
655
703
  assetId: asset.id,
656
- overlayIdentityKey: asset.overlayIdentityKey,
704
+ // deps.overlayIdentityKey, not asset.overlayIdentityKey (XR-104): the
705
+ // two are equal here by construction (checked above), but sourcing
706
+ // from deps means a future refactor that drops or reorders that check
707
+ // still cannot hand a session-controlled value to the bundle.
708
+ overlayIdentityKey: deps.overlayIdentityKey,
657
709
  store: deps.store
658
710
  })
659
711
  const tipLinkage = await mintTipLinkage(wallet, {
@@ -661,7 +713,10 @@ async function buildTokenPaymentFrame(
661
713
  payeeLinkage: payee.linkage,
662
714
  changeKeyID: change > 0 ? changeKeyID : undefined,
663
715
  changeCounterparty: identityKey,
664
- overlayIdentityKey: asset.overlayIdentityKey,
716
+ // Same reasoning: this is `revealSpecificKeyLinkage`'s `verifier`, the
717
+ // exact disclosure target XR-104 is about — it must come from this
718
+ // device's configuration, never from the payee's request.
719
+ overlayIdentityKey: deps.overlayIdentityKey,
665
720
  originator
666
721
  })
667
722
 
@@ -677,8 +732,9 @@ async function buildTokenPaymentFrame(
677
732
  derivationSuffix: session.derivationSuffix,
678
733
  token: {
679
734
  assetId: asset.id,
680
- overlayUrl: asset.overlayUrl,
681
- overlayIdentityKey: asset.overlayIdentityKey,
735
+ // deps, not asset — see the anchor check and comments above.
736
+ overlayUrl: deps.overlayUrl,
737
+ overlayIdentityKey: deps.overlayIdentityKey,
682
738
  certificates: deps.certificates ?? [],
683
739
  // The tip goes first: it is the one entry every recipient of this frame
684
740
  // needs, whatever else the chain behind it looks like.
@@ -806,10 +862,7 @@ async function mintTipLinkage(
806
862
  ): Promise<Uint8Array> {
807
863
  const reveal = wallet.revealSpecificKeyLinkage as NonNullable<PayingWallet['revealSpecificKeyLinkage']>
808
864
  const forOverlay = (keyID: string, counterparty: string) =>
809
- reveal(
810
- { counterparty, verifier: args.overlayIdentityKey, protocolID: FT_PROTOCOL_ID, keyID },
811
- args.originator
812
- )
865
+ reveal({ counterparty, verifier: args.overlayIdentityKey, protocolID: FT_PROTOCOL_ID, keyID }, args.originator)
813
866
 
814
867
  const outputs: { index: number; linkage: unknown }[] = [{ index: 0, linkage: args.payeeLinkage }]
815
868
  if (args.changeKeyID !== undefined) {
@@ -928,20 +981,148 @@ export async function finalizeDelivery(
928
981
  hold: (txid: string) => Promise<void>
929
982
  /** Persist a failed decline-abort so wallet build can retry it. */
930
983
  queueFailedAbort?: (reference: string) => Promise<void>
984
+ /**
985
+ * P1-3: a negative ack is the payee's own unverifiable claim that nothing
986
+ * was queued — this codebase's abort-chain-protection only refuses an
987
+ * abort while a service is reachable AND the chain already knows the tx
988
+ * (see core/mandala/abortGuard.ts), so a decline made offline, or a
989
+ * dishonest one, still frees these inputs regardless. Policy is
990
+ * detect-and-warn, never block: called for every decline this function
991
+ * has a txid for (BSV or token, the guard chain protects neither),
992
+ * whether or not the abort itself succeeded, so a later reappearance of
993
+ * this exact txid on chain can be surfaced instead of missed. See
994
+ * core/localpay/pendingAborts.ts's queueDeclinedAbortWatch /
995
+ * verifyDeclinedAborts.
996
+ */
997
+ watchDeclinedAbort?: (entry: { txid: string; reference: string }) => Promise<void>
998
+ /**
999
+ * XR-103: a negative ack is the payee's own unverifiable claim that
1000
+ * nothing was queued (see `watchDeclinedAbort` above) — but if this exact
1001
+ * txid is ALREADY known to the network at the moment of the decline, the
1002
+ * payee did in fact spend these inputs and is simply lying about it now.
1003
+ * Aborting in that case would free inputs this wallet no longer owns and
1004
+ * let the payer re-spend them into a real double-spend against the
1005
+ * payment that just landed. The same call this codebase already makes for
1006
+ * the identical question elsewhere (core/offline/cancelParked.ts's
1007
+ * `chainAlreadyKnows`, core/localpay/pendingAborts.ts's
1008
+ * `verifyDeclinedAborts`). Optional and best-effort: a missing dep or a
1009
+ * failed probe falls back to the existing detect-and-warn abort below,
1010
+ * never blocks it — this only narrows the window, it does not replace the
1011
+ * watch.
1012
+ */
1013
+ checkChainStatus?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
1014
+ /**
1015
+ * XR-095/XR-103: before releasing inputs on a decline, ask the chain
1016
+ * directly whether it already knows this exact txid — mirrors
1017
+ * core/offline/cancelParked.ts's `chainAlreadyKnows`, run only while
1018
+ * online (a failed/offline probe means this cannot be asked). A `true`
1019
+ * answer means the payee's copy is already out, so aborting would race a
1020
+ * double-spend against them; the release is skipped instead.
1021
+ *
1022
+ * A `false` answer is NOT proof of the opposite: `getStatusForTxids` has
1023
+ * no "confirmed absent" status, only 'mined'/'known'/'unknown', so `false`
1024
+ * here means "unresolved", not "safe". That falls through to
1025
+ * `parkUnverifiable` below exactly like being offline does — see there.
1026
+ * Optional so a caller that has not wired it keeps today's
1027
+ * abort-on-every-decline behaviour exactly — this is additive hardening,
1028
+ * not a new requirement. Checked after `checkChainStatus` above: that
1029
+ * probe already covers the "already known" case up front, so this is the
1030
+ * second, independent layer for a caller that wires both, or the only one
1031
+ * for a caller that wires just this pair.
1032
+ */
1033
+ chainAlreadyKnows?: (txid: string) => Promise<boolean>
1034
+ /**
1035
+ * XR-095/XR-103: durably keeps this decline's inputs reserved instead of
1036
+ * releasing them, for every case `chainAlreadyKnows` cannot rule out —
1037
+ * genuinely offline (cannot ask at all), or online but the chain answers
1038
+ * 'unknown'/anything short of confirmed known-or-mined (asked, and still
1039
+ * cannot rule out the payee broadcasting moments later). Fail closed:
1040
+ * same "keep reserved, resolve later" shape as `parkSentPaymentOffline`,
1041
+ * which the payer can safely unwind afterward through
1042
+ * `cancelParkedPayment`'s own chain-status gate once back online. Only
1043
+ * consulted when `chainAlreadyKnows` is also supplied — a caller opting
1044
+ * into the online check gets the offline half too. Not wiring this keeps
1045
+ * today's release-on-any-decline behaviour exactly, for a caller that has
1046
+ * not adopted it.
1047
+ */
1048
+ parkUnverifiable?: (txid: string) => Promise<void>
931
1049
  }
932
1050
  ): Promise<DeliveryOutcome> {
933
1051
  if (!ack.ok) {
1052
+ if (built.txid && deps.checkChainStatus && (await chainAlreadyKnowsTxid(deps.checkChainStatus, built.txid))) {
1053
+ // The decline was a lie: the network already has this transaction.
1054
+ // Never release inputs that are, in fact, already spent — persist the
1055
+ // same way a positive ack would (best-effort; a failure here must not
1056
+ // turn a real payment into a reported failure) and report it as sent.
1057
+ if (typeof deps.hold === 'function') {
1058
+ await deps.hold(built.txid).catch(() => undefined)
1059
+ }
1060
+ return {
1061
+ kind: 'sent',
1062
+ broadcast: 'ok',
1063
+ detail: 'the payee declined, but this transaction was already found on the network'
1064
+ }
1065
+ }
934
1066
  if (built.reference) {
935
- // A failed abort is a stuck UTXO, not a lost payment, and must not
936
- // displace the decline reason the caller is about to show. `{ aborted:
937
- // false }` is a failure too — queue it for replay on the next wallet build.
938
- try {
939
- const result = await wallet.abortAction({ reference: built.reference }, originator)
940
- if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
941
- } catch (e: unknown) {
942
- console.warn('[localpay] abortAction failed:', messageOf(e))
943
- if (deps.queueFailedAbort) {
944
- await deps.queueFailedAbort(built.reference).catch(() => undefined)
1067
+ let skipRelease = false
1068
+ if (built.txid && deps.chainAlreadyKnows) {
1069
+ let onlineNow = true
1070
+ try {
1071
+ onlineNow = await (deps.online ?? getOnline)()
1072
+ } catch (e) {
1073
+ console.warn('[localpay] connectivity probe failed, assuming online:', messageOf(e))
1074
+ }
1075
+ // XR-103: `getStatusForTxids` — what `chainAlreadyKnows` is built on —
1076
+ // has no "confirmed absent" verdict, only 'mined'/'known'/'unknown'.
1077
+ // A `false` result here is therefore never proof the payee has not
1078
+ // broadcast; it only means this device could not confirm that they
1079
+ // have, YET. Releasing on that answer while online raced a lying (or
1080
+ // merely early) decline exactly like releasing while offline did —
1081
+ // both are now the same "cannot confirm" outcome, and both park
1082
+ // instead of releasing.
1083
+ const txid = built.txid
1084
+ const tryPark = async (): Promise<boolean> => {
1085
+ if (!deps.parkUnverifiable) return false
1086
+ try {
1087
+ await deps.parkUnverifiable(txid)
1088
+ return true
1089
+ } catch (e) {
1090
+ console.warn('[localpay] could not park the unverifiable decline, releasing instead:', messageOf(e))
1091
+ return false
1092
+ }
1093
+ }
1094
+ if (onlineNow) {
1095
+ let confirmedKnown = false
1096
+ try {
1097
+ confirmedKnown = await deps.chainAlreadyKnows(txid)
1098
+ } catch (e) {
1099
+ console.warn('[localpay] chain-status check failed, treating as unresolved:', messageOf(e))
1100
+ }
1101
+ skipRelease = confirmedKnown ? true : await tryPark()
1102
+ } else {
1103
+ skipRelease = await tryPark()
1104
+ }
1105
+ }
1106
+
1107
+ if (!skipRelease) {
1108
+ // A failed abort is a stuck UTXO, not a lost payment, and must not
1109
+ // displace the decline reason the caller is about to show. `{ aborted:
1110
+ // false }` is a failure too — queue it for replay on the next wallet build.
1111
+ try {
1112
+ const result = await wallet.abortAction({ reference: built.reference }, originator)
1113
+ if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
1114
+ } catch (e: unknown) {
1115
+ console.warn('[localpay] abortAction failed:', messageOf(e))
1116
+ if (deps.queueFailedAbort) {
1117
+ await deps.queueFailedAbort(built.reference).catch(() => undefined)
1118
+ }
1119
+ }
1120
+ // Watched regardless of whether the abort above succeeded: either way
1121
+ // these inputs are now free, and the only question left is whether the
1122
+ // payee's decline was honest. A failure to record the watch must not
1123
+ // turn an otherwise-normal decline into a reported failure.
1124
+ if (built.txid && deps.watchDeclinedAbort) {
1125
+ await deps.watchDeclinedAbort({ txid: built.txid, reference: built.reference }).catch(() => undefined)
945
1126
  }
946
1127
  }
947
1128
  }
@@ -1030,3 +1211,23 @@ export async function finalizeDelivery(
1030
1211
  function messageOf(e: unknown): string {
1031
1212
  return e instanceof Error && e.message ? e.message : String(e)
1032
1213
  }
1214
+
1215
+ /**
1216
+ * XR-103. Mirrors core/offline/cancelParked.ts's `chainAlreadyKnows` /
1217
+ * core/storage/methods/processOfflineActions.ts's `networkAlreadyHas`: a
1218
+ * failed or malformed probe is treated as "not known" so it falls back to the
1219
+ * existing decline-abort behaviour rather than blocking it.
1220
+ */
1221
+ async function chainAlreadyKnowsTxid(
1222
+ checkChainStatus: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>,
1223
+ txid: string
1224
+ ): Promise<boolean> {
1225
+ try {
1226
+ const r = await checkChainStatus([txid])
1227
+ const status = r.results?.find(x => x.txid === txid)?.status
1228
+ return status === 'mined' || status === 'known'
1229
+ } catch (e) {
1230
+ console.warn(`[localpay] could not ask the network about ${txid}, treating as unknown:`, messageOf(e))
1231
+ return false
1232
+ }
1233
+ }
@@ -1,6 +1,11 @@
1
1
  import { Beef } from '@bsv/sdk'
2
2
  import type { PaymentFrame, TokenPayment } from './codec'
3
3
  import { MANDALA_ACTION_LABEL, MANDALA_BASKET } from '../mandala/bundle'
4
+ // XR-037: see build.ts's identical import for why these two same-named
5
+ // exports are both needed — bundle.ts's is the home-screen row label,
6
+ // permissionModule.ts's is the one that P-routes a listActions query to
7
+ // MandalaTokenModule's consent gate.
8
+ import { MANDALA_ACTION_LABEL as MANDALA_TOKEN_SPEND_LABEL } from '../mandala/permissionModule'
4
9
  import type { AdmissionEntryWire } from '../mandala/types'
5
10
  import { isRetriableInternalizeFailure } from '../mandala/drain'
6
11
 
@@ -47,6 +52,35 @@ export function isPendingExhausted(p: PendingPayment): boolean {
47
52
  return p.status === 'failed' && (p.attempts ?? 0) >= MAX_PENDING_ATTEMPTS
48
53
  }
49
54
 
55
+ /**
56
+ * XR-101. internalizeAction's real contract (validateStringLength in
57
+ * @bsv/sdk's validationHelpers) THROWS WERR_INVALID_PARAMETER — never
58
+ * truncates — for a `description` over 2000 UTF-8 bytes. The peer `note` this
59
+ * builds the description from arrives over the wire with no length cap of its
60
+ * own (the 280-char TextInput limit is a UI convenience, not a decoder check),
61
+ * so an oversized note used to fail internalizeAction on every retry until
62
+ * `MAX_PENDING_ATTEMPTS` tripped, permanently stranding an already-accepted
63
+ * payment. Capping here keeps a real payment creditable regardless of note
64
+ * length, without rejecting the frame outright.
65
+ */
66
+ export const MAX_INTERNALIZE_DESCRIPTION_BYTES = 2000
67
+
68
+ const descriptionEncoder = new TextEncoder()
69
+ const descriptionDecoder = new TextDecoder()
70
+
71
+ /**
72
+ * Truncates on the UTF-8 byte boundary, not the JS string index — slicing by
73
+ * character count alone can still overshoot the byte ceiling for non-ASCII
74
+ * text. A multi-byte character cut in half at the boundary decodes back as
75
+ * U+FFFD under TextDecoder's default lenient mode rather than throwing, which
76
+ * is fine here: this is a display fallback, not the payment amount.
77
+ */
78
+ export function truncateUtf8Bytes(s: string, maxBytes: number): string {
79
+ const bytes = descriptionEncoder.encode(s)
80
+ if (bytes.length <= maxBytes) return s
81
+ return descriptionDecoder.decode(bytes.slice(0, maxBytes))
82
+ }
83
+
50
84
  export interface PendingSummary {
51
85
  /** Still worth retrying. */
52
86
  waiting: number
@@ -184,8 +218,17 @@ async function readAll(storage: KVStorage): Promise<PendingPayment[]> {
184
218
  }
185
219
  try {
186
220
  const parsed = JSON.parse(raw) as unknown
221
+ if (!Array.isArray(parsed)) {
222
+ // XR-092: a syntactically valid non-array (an object, string, number,
223
+ // or null) is just as wrong-shaped as invalid JSON. Silently reading it
224
+ // as an empty queue cleared the corruption notice and left `writeAll`'s
225
+ // very next save free to destructively overwrite whatever this value
226
+ // actually held. Thrown here so it takes the exact same quarantine path
227
+ // as a JSON.parse failure, below — never treated as "nothing pending".
228
+ throw new Error('localpay_pending is not an array')
229
+ }
187
230
  pendingCorruptNotice = false
188
- return Array.isArray(parsed) ? (parsed as Serialised[]).map(fromWire) : []
231
+ return (parsed as Serialised[]).map(fromWire)
189
232
  } catch {
190
233
  pendingCorruptNotice = true
191
234
  try {
@@ -255,6 +298,59 @@ export async function savePending(
255
298
  })
256
299
  }
257
300
 
301
+ /**
302
+ * XR-098: atomically claims a session for exactly one delivery.
303
+ *
304
+ * `isSessionSpent`, `savePending` and `markSessionSpent` used to be three
305
+ * separate operations — the first unlocked, the other two each under their
306
+ * own `withQueueLock` — so a caller's own "check, then persist, then burn"
307
+ * sequence was not atomic: two concurrent deliveries for the same session
308
+ * (radio racing a QR scan of the same static code, or any other overlap)
309
+ * could each observe `isSessionSpent` false before either had written
310
+ * anything, and both would durably queue a payment for a session meant to be
311
+ * spent exactly once. Folding the check, the persist and the burn into ONE
312
+ * `withQueueLock` critical section makes the claim indivisible: whichever
313
+ * call actually runs first inside the lock is the only one that can ever see
314
+ * this session unspent again. Calls the un-locked primitives directly
315
+ * (`readSpent`, `readAll`, `writeAll`) rather than `isSessionSpent` /
316
+ * `savePending` / `markSessionSpent` themselves — nesting `withQueueLock`
317
+ * inside itself would deadlock.
318
+ */
319
+ export async function claimAndSavePending(
320
+ storage: KVStorage,
321
+ sessionId: Uint8Array,
322
+ frame: PaymentFrame,
323
+ receivedVia?: string
324
+ ): Promise<{ claimed: true; entry: PendingPayment } | { claimed: false }> {
325
+ return withQueueLock(async () => {
326
+ const key = sessionKey(sessionId)
327
+ const spent = await readSpent(storage)
328
+ if (spent.includes(key)) return { claimed: false }
329
+
330
+ const entry: PendingPayment = {
331
+ id: `${Date.now()}_${frame.senderIdentityKey.slice(0, 8)}`,
332
+ receivedAt: new Date().toISOString(),
333
+ frame,
334
+ status: 'pending',
335
+ receivedVia
336
+ }
337
+ const existing = await readAll(storage)
338
+ await writeAll(storage, [...existing, entry])
339
+ // Only after the entry is durably written — same ordering the caller
340
+ // relied on before this was atomic. Best-effort, same as
341
+ // `markSessionSpent`'s own callers already treated it: the frame is
342
+ // already queued, so a failure here is not a payment failure and must
343
+ // not be reported as one — internalizeAction is idempotent on a repeat
344
+ // of the same output, so a replay from here cannot double-credit.
345
+ try {
346
+ await storage.setKeyValue(SPENT_KEY, JSON.stringify([...spent, key]))
347
+ } catch (e) {
348
+ console.warn('[localpay] claimAndSavePending could not mark the session spent:', messageOf(e))
349
+ }
350
+ return { claimed: true, entry }
351
+ })
352
+ }
353
+
258
354
  export async function getPending(storage: KVStorage): Promise<PendingPayment[]> {
259
355
  return readAll(storage)
260
356
  }
@@ -351,9 +447,7 @@ export async function updateStatus(
351
447
  // being retried. A structurally bad BEEF is deliberately NOT
352
448
  // matched by `isRetriableInternalizeFailure` and still counts.
353
449
  attempts:
354
- status === 'failed' && !isRetriableInternalizeFailure(failureReason)
355
- ? (p.attempts ?? 0) + 1
356
- : p.attempts
450
+ status === 'failed' && !isRetriableInternalizeFailure(failureReason) ? (p.attempts ?? 0) + 1 : p.attempts
357
451
  }
358
452
  : p
359
453
  )
@@ -507,8 +601,14 @@ export async function processPending(
507
601
  // rendered as a BSV row over "+0 sats" (2026-09-16). A sender's note
508
602
  // on the frame overrides this fixed wording, same as the message-box
509
603
  // rail's PeerPay note.
510
- description: (p.frame.note?.trim() || (p.frame.kind === 'token' ? 'Received token' : 'Received BSV')).padEnd(5),
511
- labels: p.frame.kind === 'token' ? [PEERPAY_LABEL, MANDALA_ACTION_LABEL] : [PEERPAY_LABEL]
604
+ description: truncateUtf8Bytes(
605
+ (p.frame.note?.trim() || (p.frame.kind === 'token' ? 'Received token' : 'Received BSV')).padEnd(5),
606
+ MAX_INTERNALIZE_DESCRIPTION_BYTES
607
+ ),
608
+ labels:
609
+ p.frame.kind === 'token'
610
+ ? [PEERPAY_LABEL, MANDALA_ACTION_LABEL, MANDALA_TOKEN_SPEND_LABEL]
611
+ : [PEERPAY_LABEL]
512
612
  },
513
613
  originator
514
614
  )
@@ -531,7 +631,10 @@ export async function processPending(
531
631
  // The drain owns the `token_settlements` row independently and
532
632
  // re-reads its own tables on every online tick, so a lost write here
533
633
  // costs a later reconciliation pass, not the payment.
534
- console.warn('[localpay] token credited but settlement write failed:', e instanceof Error ? e.message : String(e))
634
+ console.warn(
635
+ '[localpay] token credited but settlement write failed:',
636
+ e instanceof Error ? e.message : String(e)
637
+ )
535
638
  }
536
639
  }
537
640
 
@@ -0,0 +1,95 @@
1
+ /**
2
+ * XR-102 (non-Vault residual): pending-abort entry authenticity.
3
+ *
4
+ * `pending_aborts` is a plain KV record. `guard.ts`'s `VAULT_ABORT_REPLAY_MARKER`
5
+ * (also XR-102) already stops a replayed entry from bypassing the
6
+ * vault-inventory check for a Vault reference -- but that check only exists
7
+ * for Vault outpoints/references/txids. An ordinary localpay/PeerPay noSend
8
+ * reference has no such inventory entry and no mandala settlement row either,
9
+ * so a raw KV edit naming one was still replayed and aborted with zero proof
10
+ * this wallet ever recorded a real decline for it.
11
+ *
12
+ * The fix: every entry `queuePendingAbort` writes is tagged with an HMAC over
13
+ * its reference, computed with the ADMIN-scoped wallet under the
14
+ * `pending abort authority` namespace reserved in
15
+ * `core/services/vault/guard.ts`. `replayPendingAborts` re-derives and checks
16
+ * that tag before ever calling `abortAction`; an entry with no tag, or one
17
+ * that does not verify, is dropped -- never replayed. Exactly the pattern
18
+ * XR-027's `connection authority` tag already established for saved pairings
19
+ * (see `core/services/connectionAuthority.ts`) -- same reasoning applies here:
20
+ * a local attacker who can write this KV key does not have the admin wallet's
21
+ * key material, so they cannot mint a tag that verifies, however plausible
22
+ * the reference or originator string they forge.
23
+ */
24
+ import type { WalletInterface, WalletProtocol } from '@bsv/sdk'
25
+
26
+ export type PendingAbortTagWallet = Pick<WalletInterface, 'createHmac'>
27
+ export type PendingAbortVerifyWallet = Pick<WalletInterface, 'verifyHmac'>
28
+
29
+ /** Reserved identically to CONNECTION_AUTHORITY_PROTOCOL_NAMES in guard.ts --
30
+ * see that file's PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES for why a connected/
31
+ * paired origin (whose site-scoped WalletClient forwards createHmac/verifyHmac
32
+ * for any non-reserved namespace) must never be able to mint or verify this
33
+ * tag itself. */
34
+ export const PENDING_ABORT_AUTHORITY_PROTOCOL_ID: WalletProtocol = [2, 'pending abort authority']
35
+ const PENDING_ABORT_AUTHORITY_DOMAIN = 'bsv-wallet-pending-abort-authority-v1'
36
+
37
+ function messageBytes(reference: string): number[] {
38
+ return Array.from(new TextEncoder().encode(`${PENDING_ABORT_AUTHORITY_DOMAIN}|${reference}`))
39
+ }
40
+
41
+ /** Called by `queuePendingAbort` at the moment a reference is durably queued
42
+ * -- the only moment this codebase can honestly assert "a real decline or
43
+ * build failure just happened for this exact reference". `adminWallet` must
44
+ * be the guardVaultAccess(..., adminOriginator)-wrapped wallet, called with
45
+ * that same `adminOriginator`: that is what lets guard.ts's reservation
46
+ * recognize this as trusted rather than an external call. */
47
+ export async function computePendingAbortAuthorityTag(
48
+ adminWallet: PendingAbortTagWallet,
49
+ adminOriginator: string,
50
+ reference: string
51
+ ): Promise<string> {
52
+ const { hmac } = await adminWallet.createHmac(
53
+ {
54
+ protocolID: PENDING_ABORT_AUTHORITY_PROTOCOL_ID,
55
+ keyID: reference,
56
+ counterparty: 'self',
57
+ data: messageBytes(reference)
58
+ },
59
+ adminOriginator
60
+ )
61
+ return Buffer.from(hmac).toString('base64url')
62
+ }
63
+
64
+ /**
65
+ * Re-derives the tag over the CURRENT reference and compares it to the one on
66
+ * file. Never throws: a missing tag, a malformed tag, or any wallet-side
67
+ * failure (including `verifyHmac` REJECTING on an actual mismatch, per
68
+ * `@bsv/sdk`) are all folded into "not authentic" -- the only correct
69
+ * response to any of them is the same one, drop the entry, per
70
+ * `replayPendingAborts`.
71
+ */
72
+ export async function verifyPendingAbortAuthorityTag(
73
+ adminWallet: PendingAbortVerifyWallet,
74
+ adminOriginator: string,
75
+ reference: string,
76
+ tag: string | undefined
77
+ ): Promise<boolean> {
78
+ if (!tag) return false
79
+ try {
80
+ const hmac = Array.from(Buffer.from(tag, 'base64url'))
81
+ const { valid } = await adminWallet.verifyHmac(
82
+ {
83
+ protocolID: PENDING_ABORT_AUTHORITY_PROTOCOL_ID,
84
+ keyID: reference,
85
+ counterparty: 'self',
86
+ data: messageBytes(reference),
87
+ hmac
88
+ },
89
+ adminOriginator
90
+ )
91
+ return valid === true
92
+ } catch {
93
+ return false
94
+ }
95
+ }