@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
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The handle rail's inbox pre-hold pass (offline-settlement spec §4.2/§4.3
3
+ * guard #2; codebase-review mandala-handle-P1-4).
4
+ *
5
+ * `@bsv/mandala`'s own `receiveTokens` (`dist/receive.js` `acceptOne`) calls
6
+ * `wallet.internalizeAction` BEFORE it calls the `settle` hook that finally
7
+ * writes a `token_settlements` row — and `internalizeAction` forces a
8
+ * broadcast attempt of its own via `shareReqsWithWorld`. The only thing
9
+ * standing between that and a real, unmediated broadcast of an unadmitted
10
+ * token transaction is `StorageExpoSQLite.attemptToPostReqsToNetwork`'s
11
+ * lookup of exactly that row. On the FIRST credit of a v2 hand-over message
12
+ * the row does not exist yet, so the guard finds nothing and lets the
13
+ * broadcast through before the issuer's overlay ever got to admit or refuse
14
+ * the transfer. `core/localpay/pending.ts`'s `processPending` closed the same
15
+ * hole for the nearby rail by moving the settlement write ahead of the
16
+ * credit; this file is the handle rail's equivalent, run once per inbox
17
+ * drain, before `createRuntime.ts`'s `receiveFromInbox` ever calls
18
+ * `receiveTokens`.
19
+ *
20
+ * This does NOT reimplement the library's trust logic. The only piece ported
21
+ * here is the mechanical shape of `acceptOne`'s `coverHandover` — parse the
22
+ * AtomicBEEF, merge it into a `Beef`, and hand the linkage/admissions arrays
23
+ * off to `cover` — because `coverHandover` itself is not exported. The
24
+ * verdict is entirely `cover`'s (the same pure, exported COVER walk the real
25
+ * `receiveTokens` runs), and the row it lets through is written by the
26
+ * caller's own `settle` hook, the SAME one `createRuntime.ts` wires as
27
+ * `settleThroughDrain` for the real `receiveTokens` call that follows. Two
28
+ * calls into the same idempotent hook for the same mustSubmit id are exactly
29
+ * the FIX G re-derivation `settlementStore.ts`'s `advanceSettlement` (a CAS)
30
+ * and `upsertSettlement` (never drags `state` backward on conflict) are built
31
+ * to tolerate.
32
+ *
33
+ * A message that will not decode on this side (bad bytes, not a handover, a
34
+ * COVER refusal) is simply left alone: `receiveTokens`'s own `acceptOne` runs
35
+ * the identical pure walk over the identical bytes moments later and, for a
36
+ * hand-over body, reaches `coverHandover` — and therefore any refusal —
37
+ * BEFORE it ever calls `internalizeAction`, so skipping it here costs
38
+ * nothing. Only a message whose evidence WOULD have credited safely, but
39
+ * whose settlement write failed, is dangerous to hand to `receiveTokens`
40
+ * unfiltered — that message is excluded from this pass via the same
41
+ * `processed` dedup set `receiveTokens` already accepts as a message filter
42
+ * (`ReceiveParams.processed`), so it is retried whole on the next drain tick
43
+ * rather than credited on a bare table.
44
+ *
45
+ * One inherent gap: this lists the inbox once, `receiveTokens` lists it
46
+ * again a moment later. A message that arrives in that narrow window is not
47
+ * covered by this pass — it is credited by `receiveTokens` with the
48
+ * library's original ordering, exactly as before this file existed. Closing
49
+ * that would require intercepting inside `acceptOne` itself, which is what
50
+ * the review's alternative (a pre-internalize hook upstream in
51
+ * `@bsv/mandala`) is for.
52
+ */
53
+ import { Beef, Transaction } from '@bsv/sdk'
54
+ import { MESSAGEBOX } from '@bsv/mandala/constants'
55
+ import type { MessageBoxLike, SettleFn } from '@bsv/mandala'
56
+ import type { CoverResult } from './types'
57
+ import { devLog } from '../logging'
58
+
59
+ /** The v2 hand-over body fields this pass reads (wire contract v2 §8). Untyped past this: everything else is the caller's / the library's concern. */
60
+ interface RawHandoverBody {
61
+ v?: unknown
62
+ kind?: unknown
63
+ assetId?: unknown
64
+ transaction?: unknown
65
+ linkage?: unknown
66
+ admissions?: unknown
67
+ }
68
+
69
+ interface RawInboxMessage {
70
+ messageId: string
71
+ body?: RawHandoverBody
72
+ }
73
+
74
+ /** What one decoded hand-over needs from `settle` — the exact shape `SettleArgs` wants. */
75
+ interface DecodedHandover {
76
+ tip: Transaction
77
+ mustSubmit: string[]
78
+ bytesFor: (txid: string) => { beef: number[]; offChainValues: number[] } | undefined
79
+ }
80
+
81
+ /** The bundle shape this pass's injected `cover` reads — mirrors `libCoverArgs`'s own bundle parameter in `createRuntime.ts`. */
82
+ export interface PreHoldCoverBundle {
83
+ assetId: string
84
+ beef: Map<string, Transaction>
85
+ linkage: Map<string, number[]>
86
+ admissions: Map<string, { outputsToAdmit: number[]; signature: string; signerKey: string }>
87
+ }
88
+
89
+ /**
90
+ * The pure COVER walk, already crossing the app/lib `@bsv/sdk` duplication
91
+ * seam (see `createRuntime.ts`'s `libCoverArgs` — this pass is handed a
92
+ * closure built from that same helper, never the raw library `cover`, so
93
+ * this file needs no cast of its own).
94
+ */
95
+ export type PreHoldCoverFn = (tip: Transaction, bundle: PreHoldCoverBundle) => CoverResult
96
+
97
+ export interface PreHoldInboxDeps {
98
+ messageBoxClient: MessageBoxLike
99
+ cover: PreHoldCoverFn
100
+ /** The SAME hook `receiveFromInbox` passes to `receiveTokens` as `settle` — `settleThroughDrain`. */
101
+ settle: SettleFn
102
+ }
103
+
104
+ /** Parses one v2 hand-over body into what `settle` needs, or `undefined` if COVER refuses it. Throws on bytes that will not even parse — the caller classifies that as "leave it to the library". */
105
+ function decodeHandover(body: RawHandoverBody, cover: PreHoldCoverFn): DecodedHandover | undefined {
106
+ if (typeof body.assetId !== 'string' || body.assetId === '') return undefined
107
+ if (!Array.isArray(body.transaction)) return undefined
108
+ const tip = Transaction.fromAtomicBEEF(body.transaction as number[])
109
+
110
+ const beef = new Beef()
111
+ beef.mergeTransaction(tip)
112
+ const txs = new Map<string, Transaction>()
113
+ for (const entry of beef.txs) if (entry.tx) txs.set(entry.txid, entry.tx)
114
+
115
+ const linkage = new Map<string, number[]>()
116
+ for (const l of Array.isArray(body.linkage) ? body.linkage : []) {
117
+ if (typeof l?.txid === 'string' && Array.isArray(l.payload)) linkage.set(l.txid, l.payload)
118
+ }
119
+ const admissions = new Map<string, { outputsToAdmit: number[]; signature: string; signerKey: string }>()
120
+ for (const a of Array.isArray(body.admissions) ? body.admissions : []) {
121
+ if (typeof a?.txid === 'string') {
122
+ admissions.set(a.txid, { outputsToAdmit: a.outputsToAdmit, signature: a.signature, signerKey: a.signerKey })
123
+ }
124
+ }
125
+
126
+ const result = cover(tip, { assetId: body.assetId, beef: txs, linkage, admissions })
127
+ if (!result.ok) return undefined
128
+
129
+ return {
130
+ tip,
131
+ mustSubmit: result.mustSubmit,
132
+ bytesFor: (id: string) => {
133
+ const found = beef.findAtomicTransaction(id)
134
+ if (found == null) return undefined
135
+ return { beef: found.toAtomicBEEF(true), offChainValues: linkage.get(id) ?? [] }
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Runs the pre-hold pass. Returns the ids of messages whose settlement write
142
+ * failed this pass — the caller must keep those out of the `receiveTokens`
143
+ * call that follows (e.g. by adding them to its `processed` set for the
144
+ * duration of that one call, then removing them so the next drain retries).
145
+ *
146
+ * Deliberately best-effort PER MESSAGE and fail-closed PER MESSAGE: one bad
147
+ * or unwritable message never blocks the rest of the inbox, but a message
148
+ * this pass could have safely pre-held is never handed to `receiveTokens`
149
+ * with that write missing.
150
+ */
151
+ export async function preHoldInboxSettlements(deps: PreHoldInboxDeps): Promise<Set<string>> {
152
+ const exclude = new Set<string>()
153
+ const messages = (await deps.messageBoxClient.listMessages({
154
+ messageBox: MESSAGEBOX,
155
+ acceptPayments: false
156
+ })) as RawInboxMessage[]
157
+
158
+ for (const raw of messages) {
159
+ const body = raw.body
160
+ // v2 + kind:'handover' is the whole version discriminator (receive.js).
161
+ // A v1 body's `covering` is always undefined in `acceptOne`, so its
162
+ // `settle` never runs at all — there is nothing here to pre-hold.
163
+ if (body == null || body.v !== 2 || body.kind !== 'handover') continue
164
+
165
+ let decoded: DecodedHandover | undefined
166
+ try {
167
+ decoded = decodeHandover(body, deps.cover)
168
+ } catch (e) {
169
+ devLog(`[mandala] inbox pre-hold could not decode message ${raw.messageId}; leaving it to the library:`, e)
170
+ continue
171
+ }
172
+ if (!decoded) continue // COVER refused it — acceptOne will reach the same refusal before internalizing
173
+
174
+ try {
175
+ await deps.settle({ txid: decoded.tip.id('hex'), mustSubmit: decoded.mustSubmit, bytesFor: decoded.bytesFor })
176
+ } catch (e) {
177
+ devLog(
178
+ `[mandala] inbox pre-hold could not write the settlement row for message ${raw.messageId}; holding it back this pass:`,
179
+ e
180
+ )
181
+ exclude.add(raw.messageId)
182
+ }
183
+ }
184
+
185
+ return exclude
186
+ }
@@ -36,6 +36,81 @@ import { MANDALA_BASKET } from './types'
36
36
  const SESSION_TIMEOUT_MS = 60_000
37
37
  const SESSION_CLEANUP_INTERVAL_MS = 30_000
38
38
 
39
+ /**
40
+ * Normalises an outpoint the same way the SDK's own `Number(...)` coercion
41
+ * of a vout would (mirrors `services/vault/guard.ts`'s own
42
+ * `canonicalOutpoint`, kept as a separate small copy rather than a shared
43
+ * import so Mandala's permission gate does not depend on Vault's module).
44
+ *
45
+ * XR-039: `listMandalaTokenOutpoints`'s Set and an input's own `outpoint`
46
+ * string have to agree on ONE spelling of the same outpoint, or an alternate
47
+ * spelling ("00", "0e0", a differently-cased txid) lets a real token input
48
+ * slip past the `.has()` check unmatched. `undefined` for anything that is
49
+ * not a well-formed `<64-hex-txid>.<vout>` — callers then never match it
50
+ * against anything, which is the safe default.
51
+ */
52
+ export function canonicalOutpoint(value: string | undefined): string | undefined {
53
+ if (typeof value !== 'string') return undefined
54
+ const parts = value.split('.')
55
+ if (parts.length !== 2 || !/^[0-9a-fA-F]{64}$/.test(parts[0])) return undefined
56
+ const vout = Number(parts[1])
57
+ if (!Number.isSafeInteger(vout) || vout < 0) return undefined
58
+ return `${parts[0].toLowerCase()}.${vout}`
59
+ }
60
+
61
+ /** One `listOutputs`-shaped page, as `listAllOutpoints` needs to see it. */
62
+ export interface OutpointListPage {
63
+ outputs: { outpoint: string }[]
64
+ totalOutputs?: number
65
+ }
66
+
67
+ /**
68
+ * Every outpoint a paged listing reports, to completion, canonicalized.
69
+ *
70
+ * XR-039: `listMandalaTokenOutpoints` (WalletContext.tsx) used to read a
71
+ * single capped page and call that the whole basket — a spend of an input
72
+ * past that page read as "not a token input" to every caller of the Set this
73
+ * builds, exactly the same balance-truncation bug `core/localpay/build.ts`'s
74
+ * `listTokenBasket` and `core/mandala/createRuntime.ts`'s `listTokenOutputs`
75
+ * were already fixed for. Same paging discipline here: the wallet's own
76
+ * `totalOutputs` ends the loop when it reports one, a short/empty page ends
77
+ * it otherwise, and `maxPages` is the hard stop against a wallet that ignores
78
+ * `offset` or reports a total it never actually serves.
79
+ *
80
+ * A pure function over an injected `list` rather than a method on the wallet
81
+ * itself so this loop — the actual security-relevant logic, not just glue —
82
+ * is unit-testable without a real wallet/storage stack.
83
+ */
84
+ export async function listAllOutpoints(
85
+ list: (limit: number, offset: number) => Promise<OutpointListPage>,
86
+ pageSize = 1000,
87
+ maxPages = 1000
88
+ ): Promise<Set<string>> {
89
+ const outpoints = new Set<string>()
90
+ let offset = 0
91
+ for (let page = 0; page < maxPages; page++) {
92
+ const { outputs, totalOutputs } = await list(pageSize, offset)
93
+ for (const o of outputs) {
94
+ const canonical = canonicalOutpoint(o.outpoint)
95
+ if (canonical !== undefined) outpoints.add(canonical)
96
+ }
97
+ // An empty page always ends it — that, plus the page ceiling, is what
98
+ // keeps a wallet that ignores `offset` from looping forever.
99
+ if (outputs.length === 0) break
100
+ offset += outputs.length
101
+ if (typeof totalOutputs === 'number') {
102
+ // The wallet's own count is authoritative when it reports one. A SHORT
103
+ // page must not end the loop here: a wallet may cap `limit` below what
104
+ // was asked for, and treating that cap as "end of basket" would
105
+ // re-introduce the truncation this loop exists to remove.
106
+ if (offset >= totalOutputs) break
107
+ } else if (outputs.length < pageSize) {
108
+ break
109
+ }
110
+ }
111
+ return outpoints
112
+ }
113
+
39
114
  export interface MandalaAssetMetadata {
40
115
  label?: string
41
116
  ticker?: string
@@ -67,6 +142,16 @@ export interface MandalaTokenModuleDeps {
67
142
  * not toward "silently allow".
68
143
  */
69
144
  listTokenOutpoints: () => Promise<Set<string>>
145
+ /**
146
+ * XR-041: resolves ONE currently-held `MANDALA_BASKET` outpoint to its
147
+ * decoded `{assetId, amount}`, via the admin-originator wallet's own
148
+ * listing — never from anything a caller claims. `null` for an outpoint
149
+ * this device does not currently hold as a Mandala coin (already spent,
150
+ * never was one, or an unresolvable/malformed one) — `promptForRelinquish`
151
+ * fails CLOSED on `null` rather than falling back to unlabeled copy: an
152
+ * app must not be able to get an unnamed holding removed.
153
+ */
154
+ resolveMandalaOutput: (outpoint: string) => Promise<DecodedMandalaOutput | null>
70
155
  }
71
156
 
72
157
  /** The slice of `CreateActionOutput` this module reads. Structural, not the
@@ -75,6 +160,11 @@ interface MandalaCreateActionOutputLike {
75
160
  lockingScript?: string
76
161
  basket?: string
77
162
  }
163
+ /** The slice of `RelinquishOutputArgs` this module reads. */
164
+ interface MandalaRelinquishOutputArgsLike {
165
+ basket?: string
166
+ output?: string
167
+ }
78
168
  /** The slice of `CreateActionInput` this module reads. */
79
169
  interface MandalaCreateActionInputLike {
80
170
  outpoint?: string
@@ -103,7 +193,7 @@ interface MandalaListOutputsArgsLike {
103
193
  [key: string]: unknown
104
194
  }
105
195
 
106
- interface DecodedMandalaOutput {
196
+ export interface DecodedMandalaOutput {
107
197
  assetId: string
108
198
  amount: number
109
199
  }
@@ -135,7 +225,7 @@ export interface MandalaCreditLine {
135
225
  * shape, and every caller here treats "not a Mandala output" the same way
136
226
  * whether the script is empty, foreign, or simply malformed.
137
227
  */
138
- function tryDecodeMandalaOutput(lockingScriptHex: string | undefined): DecodedMandalaOutput | null {
228
+ export function tryDecodeMandalaOutput(lockingScriptHex: string | undefined): DecodedMandalaOutput | null {
139
229
  if (!lockingScriptHex) return null
140
230
  try {
141
231
  const script = LockingScript.fromHex(lockingScriptHex)
@@ -146,6 +236,57 @@ function tryDecodeMandalaOutput(lockingScriptHex: string | undefined): DecodedMa
146
236
  }
147
237
  }
148
238
 
239
+ /** One `listOutputs`-shaped page carrying locking scripts, as `resolveMandalaOutput` needs them. */
240
+ export interface ScriptedOutputPage {
241
+ outputs: { outpoint: string; lockingScript?: string }[]
242
+ totalOutputs?: number
243
+ }
244
+
245
+ /**
246
+ * Finds ONE currently-held outpoint in a paged listing, to completion, and
247
+ * decodes its Mandala token script.
248
+ *
249
+ * XR-041: `promptForRelinquish` used to authorize removing a holding with no
250
+ * more than the bare action name — "wants to remove a Mandala token holding
251
+ * from your wallet" — never which one. This is what lets it name the target:
252
+ * `assetId`/`amount` resolved from the wallet's OWN current listing, never
253
+ * from anything the caller claims. `null` — not found (already spent, never
254
+ * held, or `target` malformed), or the page ceiling was hit without a match —
255
+ * is the caller's signal to fail closed rather than approve an unlabeled
256
+ * removal; same truncation discipline as `listAllOutpoints` (XR-039), because
257
+ * a holding on page two must be just as nameable as one on page one.
258
+ */
259
+ export async function resolveMandalaOutput(
260
+ list: (limit: number, offset: number) => Promise<ScriptedOutputPage>,
261
+ target: string,
262
+ pageSize = 1000,
263
+ maxPages = 1000
264
+ ): Promise<DecodedMandalaOutput | null> {
265
+ const canonicalTarget = canonicalOutpoint(target)
266
+ if (canonicalTarget === undefined) return null
267
+ let offset = 0
268
+ for (let page = 0; page < maxPages; page++) {
269
+ const { outputs, totalOutputs } = await list(pageSize, offset)
270
+ for (const o of outputs) {
271
+ if (canonicalOutpoint(o.outpoint) === canonicalTarget) return tryDecodeMandalaOutput(o.lockingScript)
272
+ }
273
+ // An empty page always ends it — that, plus the page ceiling, is what
274
+ // keeps a wallet that ignores `offset` from looping forever.
275
+ if (outputs.length === 0) break
276
+ offset += outputs.length
277
+ if (typeof totalOutputs === 'number') {
278
+ // The wallet's own count is authoritative when it reports one. A SHORT
279
+ // page must not end the loop here: a wallet may cap `limit` below what
280
+ // was asked for, and treating that cap as "end of basket" would
281
+ // re-introduce the truncation this loop exists to remove.
282
+ if (offset >= totalOutputs) break
283
+ } else if (outputs.length < pageSize) {
284
+ break
285
+ }
286
+ }
287
+ return null
288
+ }
289
+
149
290
  /** A short, human-scannable form of a long `'<64-hex>.<vout>'` assetId. */
150
291
  function shortAssetId(assetId: string): string {
151
292
  if (!assetId || assetId.length <= 16) return assetId
@@ -280,7 +421,7 @@ export class MandalaTokenModule implements PermissionsModule {
280
421
  await this.promptOnceForAccess(originator, 'listActions')
281
422
  break
282
423
  case 'relinquishOutput':
283
- await this.promptForRelinquish(originator)
424
+ await this.promptForRelinquish(args as MandalaRelinquishOutputArgsLike, originator)
284
425
  break
285
426
  case 'createAction':
286
427
  await this.promptForSpend(args as MandalaCreateActionArgsLike, originator)
@@ -327,9 +468,37 @@ export class MandalaTokenModule implements PermissionsModule {
327
468
  * a holding from the wallet is consequential enough that every call must
328
469
  * show its own prompt, and approving it must not silently unlock
329
470
  * listOutputs/listActions for the rest of the session window.
471
+ *
472
+ * XR-041: the prompt used to say only "wants to remove a Mandala token
473
+ * holding from your wallet" — never which one, or how much. `args.output`
474
+ * is resolved against this device's OWN current listing (never trusted
475
+ * from the caller) into `{assetId, amount}` before anything is shown, and
476
+ * an unresolved target fails the whole call closed — a consequential,
477
+ * irreversible-feeling removal must never be approved uninformed.
330
478
  */
331
- private async promptForRelinquish(originator: string): Promise<void> {
332
- const message = JSON.stringify({ type: 'mandala_access', action: 'relinquishOutput' })
479
+ private async promptForRelinquish(args: MandalaRelinquishOutputArgsLike, originator: string): Promise<void> {
480
+ const outpoint = typeof args?.output === 'string' ? args.output : undefined
481
+ let resolved: DecodedMandalaOutput | null = null
482
+ if (outpoint) {
483
+ try {
484
+ resolved = await this.deps.resolveMandalaOutput(outpoint)
485
+ } catch {
486
+ resolved = null
487
+ }
488
+ }
489
+ if (!resolved) {
490
+ throw new Error('Could not identify the Mandala holding to be removed')
491
+ }
492
+ const { tokenName, decimals } = await this.resolveAssetDisplay(resolved.assetId)
493
+ const message = JSON.stringify({
494
+ type: 'mandala_access',
495
+ action: 'relinquishOutput',
496
+ assetId: resolved.assetId,
497
+ tokenName,
498
+ amount: resolved.amount,
499
+ display: formatTokenAmount(resolved.amount, decimals, tokenName, resolved.assetId),
500
+ outpoint
501
+ })
333
502
  const approved = await this.deps.requestTokenAccess(originator, message)
334
503
  if (!approved) {
335
504
  throw new Error('User denied permission to access Mandala tokens')
@@ -499,7 +668,10 @@ export class MandalaTokenModule implements PermissionsModule {
499
668
  } catch {
500
669
  return false
501
670
  }
502
- return inputs.some(input => !!input?.outpoint && tokenOutpoints.has(input.outpoint))
671
+ return inputs.some(input => {
672
+ const outpoint = canonicalOutpoint(input?.outpoint)
673
+ return outpoint !== undefined && tokenOutpoints.has(outpoint)
674
+ })
503
675
  }
504
676
 
505
677
  private async buildSpendLines(
@@ -596,17 +768,17 @@ export class MandalaTokenModule implements PermissionsModule {
596
768
  * (a test double, a future second entry point) that skips this wrapper
597
769
  * reopens exactly the gap described above.
598
770
  */
599
- export function wrapCreateActionForTokenInputs<T extends { createAction: (args: any, originator: string) => Promise<unknown> }>(
600
- manager: T,
601
- listTokenOutpoints: () => Promise<Set<string>>,
602
- adminOriginator?: string
603
- ): T {
771
+ export function wrapCreateActionForTokenInputs<
772
+ T extends { createAction: (args: any, originator: string) => Promise<unknown> }
773
+ >(manager: T, listTokenOutpoints: () => Promise<Set<string>>, adminOriginator?: string): T {
604
774
  return new Proxy(manager, {
605
775
  get(target, prop, receiver) {
606
776
  if (prop === 'createAction') {
607
777
  return async (args: MandalaCreateActionArgsLike & { labels?: string[] }, originator: string) => {
608
778
  const routedArgs =
609
- originator === adminOriginator ? args : await injectMandalaLabelIfTokenInputsPresent(args, listTokenOutpoints)
779
+ originator === adminOriginator
780
+ ? args
781
+ : await injectMandalaLabelIfTokenInputsPresent(args, listTokenOutpoints)
610
782
  return target.createAction(routedArgs, originator)
611
783
  }
612
784
  }
@@ -623,20 +795,30 @@ async function injectMandalaLabelIfTokenInputsPresent(
623
795
  const inputs = args?.inputs
624
796
  if (!Array.isArray(inputs) || inputs.length === 0) return args
625
797
 
798
+ const labels = Array.isArray(args.labels) ? args.labels : []
799
+ if (labels.includes(MANDALA_ACTION_LABEL)) return args
800
+
626
801
  let tokenOutpoints: Set<string>
627
802
  try {
628
803
  tokenOutpoints = await listTokenOutpoints()
629
804
  } catch {
630
- // Never block a createAction call on a listing fault — the module's own
631
- // input check (if routing happens to fire some other way) and the
632
- // output-side gate remain the backstop.
633
- return args
805
+ // XR-039: forwarding `args` UNCHANGED here is how a full-balance (no
806
+ // basketed change) Mandala spend hit by a transient listing fault used to
807
+ // reach the manager's generic, no-token-amount-awareness review instead
808
+ // of this module's own. `MANDALA_ACTION_LABEL` is the ONLY thing that
809
+ // routes an input-only Mandala spend to `MandalaTokenModule.onRequest` at
810
+ // all — with no reliable read on whether these inputs spend a token coin,
811
+ // fail closed and force it, same as a confirmed match below. Worst case
812
+ // (a plain, non-Mandala action) still resolves to `promptForSpend`'s own
813
+ // generic fallback, which is a real, interactive approval — never a
814
+ // silent one.
815
+ return { ...args, labels: [...labels, MANDALA_ACTION_LABEL] }
634
816
  }
635
817
 
636
- const spendsTokenInput = inputs.some(input => !!input?.outpoint && tokenOutpoints.has(input.outpoint))
818
+ const spendsTokenInput = inputs.some(input => {
819
+ const outpoint = canonicalOutpoint(input?.outpoint)
820
+ return outpoint !== undefined && tokenOutpoints.has(outpoint)
821
+ })
637
822
  if (!spendsTokenInput) return args
638
-
639
- const labels = Array.isArray(args.labels) ? args.labels : []
640
- if (labels.includes(MANDALA_ACTION_LABEL)) return args
641
823
  return { ...args, labels: [...labels, MANDALA_ACTION_LABEL] }
642
824
  }
@@ -69,6 +69,7 @@ interface SettlementDbRow {
69
69
  overlayIdentityKey: string
70
70
  admissionOutputsJson: string | null
71
71
  admissionSignatureHex: string | null
72
+ relevantVout: number | null
72
73
  refusedCode: string | null
73
74
  refusedPayloadHash: string | null
74
75
  poisonedByTxid: string | null
@@ -101,6 +102,7 @@ function toSettlement(row: SettlementDbRow): TokenSettlementRow {
101
102
  overlayIdentityKey: row.overlayIdentityKey,
102
103
  admissionOutputs: readNumberArray(row.admissionOutputsJson),
103
104
  admissionSignatureHex: row.admissionSignatureHex ?? undefined,
105
+ relevantVout: row.relevantVout ?? undefined,
104
106
  refusedCode: row.refusedCode ?? undefined,
105
107
  refusedPayloadHash: row.refusedPayloadHash ?? undefined,
106
108
  poisonedByTxid: row.poisonedByTxid ?? undefined,
@@ -196,6 +198,24 @@ export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
196
198
  return row ? toSettlement(row) : undefined
197
199
  },
198
200
 
201
+ /**
202
+ * XR-033: the coarse fallback `getSettlementByReference` cannot offer for
203
+ * a row with no reference at all. `state` names the same set
204
+ * `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES` does — duplicated
205
+ * rather than imported, in keeping with this file's own rule that it is
206
+ * statements only, with no cross-module logic.
207
+ */
208
+ async hasUnresolvedLegacyBlockedRows(): Promise<boolean> {
209
+ const row = (await db.getFirstAsync(
210
+ `SELECT 1 FROM token_settlements
211
+ WHERE reference IS NULL
212
+ AND state IN ('held','handed_over','submitting','admitted','broadcast')
213
+ LIMIT 1`,
214
+ []
215
+ )) as unknown
216
+ return row != null
217
+ },
218
+
199
219
  async listSettlements(filter = {}): Promise<TokenSettlementRow[]> {
200
220
  const where: string[] = []
201
221
  const params: SettlementBindValue[] = []
@@ -225,9 +245,9 @@ export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
225
245
  await db.runAsync(
226
246
  `INSERT INTO token_settlements
227
247
  (txid, role, assetId, state, counterpartyKey, amountBaseUnits, overlayUrl, overlayIdentityKey,
228
- admissionOutputsJson, admissionSignatureHex, refusedCode, refusedPayloadHash, poisonedByTxid,
248
+ admissionOutputsJson, admissionSignatureHex, relevantVout, refusedCode, refusedPayloadHash, poisonedByTxid,
229
249
  reference, createdAt, updatedAt)
230
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
250
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
231
251
  ON CONFLICT(txid) DO UPDATE SET
232
252
  assetId = excluded.assetId,
233
253
  counterpartyKey = COALESCE(excluded.counterpartyKey, token_settlements.counterpartyKey),
@@ -236,6 +256,7 @@ export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
236
256
  overlayIdentityKey = excluded.overlayIdentityKey,
237
257
  admissionOutputsJson = COALESCE(excluded.admissionOutputsJson, token_settlements.admissionOutputsJson),
238
258
  admissionSignatureHex = COALESCE(excluded.admissionSignatureHex, token_settlements.admissionSignatureHex),
259
+ relevantVout = COALESCE(excluded.relevantVout, token_settlements.relevantVout),
239
260
  reference = COALESCE(excluded.reference, token_settlements.reference),
240
261
  updatedAt = excluded.updatedAt`,
241
262
  [
@@ -249,6 +270,7 @@ export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
249
270
  row.overlayIdentityKey,
250
271
  row.admissionOutputs ? JSON.stringify(row.admissionOutputs) : null,
251
272
  row.admissionSignatureHex ?? null,
273
+ row.relevantVout ?? null,
252
274
  row.refusedCode ?? null,
253
275
  row.refusedPayloadHash ?? null,
254
276
  row.poisonedByTxid ?? null,
@@ -35,6 +35,20 @@ export interface TokenSettlementRow {
35
35
  admissionOutputs?: number[]
36
36
  /** σ_I over THIS txid once known (DER hex). */
37
37
  admissionSignatureHex?: string
38
+ /**
39
+ * Which output of THIS txid the wallet's own stake in the payment is — the
40
+ * payee's output, for both a `received` row and a `sent` row (frame
41
+ * convention: output 0 is always the payee's, never the payer's own change
42
+ * — see `onTokenHandedOver`). Read as 0 when absent, mirroring
43
+ * `EvidenceFrame.outputIndex`'s own "absent reads as 0" convention.
44
+ *
45
+ * The one thing `admissionStandsIn` (drain.ts) requires present in a cached
46
+ * admission's `outputsToAdmit` before that admission may stand in for a real
47
+ * `/submit` of THIS txid (XR-038): a genuine σ_I for some OTHER output of
48
+ * the same txid — the payer's own change, say — must never be read as
49
+ * covering this one.
50
+ */
51
+ relevantVout?: number
38
52
  refusedCode?: string
39
53
  /**
40
54
  * `payloadHash` of the off-chain linkage bytes this device submitted when
@@ -99,9 +113,9 @@ export interface TokenLinkageRow {
99
113
  /** Wire-contract v2 §2: what the overlay answered for one /submit. */
100
114
  export type OverlayVerdict =
101
115
  | { kind: 'admitted'; outputsToAdmit: number[]; signatureHex: string; signerKey: string }
102
- | { kind: 'refused'; code: string; spendTxid?: string } // final (400) — terminal
103
- | { kind: 'evicted' } // 410 — terminal, inputs restored
104
- | { kind: 'unavailable'; code: string; retryable: true } // 409 liftable or 503 — retry
116
+ | { kind: 'refused'; code: string; spendTxid?: string } // final (400) — terminal
117
+ | { kind: 'evicted' } // 410 — terminal, inputs restored
118
+ | { kind: 'unavailable'; code: string; retryable: true } // 409 liftable or 503 — retry
105
119
 
106
120
  /** An AdmissionEntry as carried on the wire (frame v4 `admissions[]`). */
107
121
  export interface AdmissionEntryWire {
@@ -132,10 +146,31 @@ export interface SettlementStore {
132
146
  * row at all — so it is one indexed statement rather than a scan.
133
147
  */
134
148
  getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined>
135
- listSettlements(filter?: { state?: TokenSettlementState[]; role?: TokenSettlementRole }): Promise<TokenSettlementRow[]>
149
+ /**
150
+ * XR-033: whether any row is stuck in a blocked state (see
151
+ * `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES`) with no `reference`
152
+ * to match an `abortAction` against — a pre-migration row the one-time
153
+ * backfill (`createTables.ts`'s `ensureTokenSettlementColumns`) could not
154
+ * resolve, most likely because its transaction row is gone. Such a row is
155
+ * invisible to `getSettlementByReference` no matter what reference is
156
+ * asked for, so the abort guard's second, coarser layer asks this instead:
157
+ * true refuses EVERY abort until the row is reconciled, which trades an
158
+ * occasional over-refusal of an unrelated action for never silently
159
+ * releasing inputs a legacy row still has a claim on.
160
+ */
161
+ hasUnresolvedLegacyBlockedRows(): Promise<boolean>
162
+ listSettlements(filter?: {
163
+ state?: TokenSettlementState[]
164
+ role?: TokenSettlementRole
165
+ }): Promise<TokenSettlementRow[]>
136
166
  upsertSettlement(row: Omit<TokenSettlementRow, 'createdAt' | 'updatedAt'> & { createdAt?: string }): Promise<void>
137
167
  /** Single-statement state advance; returns false if the row was not in one of `from`. */
138
- advanceSettlement(txid: string, from: TokenSettlementState[], to: TokenSettlementState, patch?: Partial<TokenSettlementRow>): Promise<boolean>
168
+ advanceSettlement(
169
+ txid: string,
170
+ from: TokenSettlementState[],
171
+ to: TokenSettlementState,
172
+ patch?: Partial<TokenSettlementRow>
173
+ ): Promise<boolean>
139
174
  // token_admissions
140
175
  getAdmission(txid: string): Promise<TokenAdmissionRow | undefined>
141
176
  putAdmission(row: TokenAdmissionRow): Promise<void>
@@ -50,6 +50,11 @@ export class TaskBackupPush extends WalletMonitorTask {
50
50
  static lastError: string | undefined
51
51
  /** Time of the last successful pass, for the backup-health display. */
52
52
  static lastSuccessAt: number | undefined
53
+ /** A push pass is in flight. Guards against MonitorSupervisor's watchdog
54
+ * restart overlapping an old generation's still-running runOnce() with a
55
+ * new generation's — without this, both could concurrently push the same
56
+ * backup log (XR-105; same pattern as TaskDrainOutbox.running). */
57
+ static running = false
53
58
 
54
59
  static noteConnectivity (online: boolean): void {
55
60
  TaskBackupPush.onlineNow = online
@@ -95,6 +100,7 @@ export class TaskBackupPush extends WalletMonitorTask {
95
100
  TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
96
101
  TaskBackupPush.lastError = undefined
97
102
  TaskBackupPush.lastSuccessAt = undefined
103
+ TaskBackupPush.running = false
98
104
  }
99
105
 
100
106
  constructor (
@@ -115,6 +121,12 @@ export class TaskBackupPush extends WalletMonitorTask {
115
121
  }
116
122
 
117
123
  async runTask (): Promise<string> {
124
+ // A watchdog restart can spawn a new generation's runOnce() while an old
125
+ // generation's own runOnce() is still executing (it is not cancelled,
126
+ // only stopped from looping again). Without this guard both could
127
+ // concurrently push the same backup log (XR-105).
128
+ if (TaskBackupPush.running) return ''
129
+ TaskBackupPush.running = true
118
130
  TaskBackupPush.checkNow = false
119
131
  const startedAt = Date.now()
120
132
 
@@ -163,6 +175,8 @@ export class TaskBackupPush extends WalletMonitorTask {
163
175
  TaskBackupPush.lastError = message
164
176
  TaskBackupPush.noteFailure(startedAt)
165
177
  return `backup: push failed, retrying after ${TaskBackupPush.backoffMs}ms: ${message}`
178
+ } finally {
179
+ TaskBackupPush.running = false
166
180
  }
167
181
  }
168
182
  }