@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -1,754 +0,0 @@
1
- /**
2
- * The wallet half of Mandala offline settlement: cache the evidence a frame
3
- * carried, then submit-before-broadcast.
4
- *
5
- * Two independent halves live here because they are two halves of one rule —
6
- * *the overlay is the only authority on a final refusal* (FIX D):
7
- *
8
- * · `populateEvidenceFromFrame` / `reconcileSettlements` (FIX G). Every row of
9
- * the four settlement tables is re-derivable, offline and idempotently, from
10
- * frame bytes already durable in `localpay_pending` (receiver) or
11
- * `offline_actions.framePayload` (payer). So these writes are never on the
12
- * critical path between "frame received" and "ack sent": they run
13
- * best-effort at hold time and again at the start of every drain pass, in
14
- * any order, over any subset already done. A crash between "frame persisted"
15
- * and "evidence written" self-heals on the next tick with no recovery code.
16
- * · `postTokenStep` (§4.3). One step of the release plan for a transaction
17
- * that has a `token_settlements` row: COVER, submit every unadmitted
18
- * ancestor parents-first, and only then broadcast the tip exactly as a BSV
19
- * transaction. A cover hole, a liftable policy refusal and a 503 all come
20
- * back as `serviceError` — the row stays non-terminal and the whole prefix
21
- * is retried next pass, which is safe because `/submit` is idempotent
22
- * (FIX C). Only the overlay's own final verdict burns a row.
23
- *
24
- * Everything the drain cannot do offline is injected (`cover`, `submit`,
25
- * `broadcast`), so this module has no network and no `StorageExpoSQLite`
26
- * dependency and is unit-testable against an in-memory SQLite.
27
- */
28
- import { Beef, Utils } from '@bsv/sdk'
29
- import { MandalaToken } from './token'
30
- import { payloadHash, tokenTopicOrEmpty } from '@bsv/mandala'
31
- import type { PostOutcome } from '../offline/plan'
32
- import { devLog } from '../logging'
33
- import {
34
- STUCK_AFTER_MS,
35
- type AdmissionEntryWire,
36
- type AdmissionVerifier,
37
- type CoverFn,
38
- type EvidenceFrame,
39
- type EvidenceTokenBlock,
40
- type SettlementStore,
41
- type SubmitFn,
42
- type TokenAdmissionEdge,
43
- type TokenAdmissionRow,
44
- type TokenSettlementRole,
45
- type TokenSettlementRow,
46
- type TokenSettlementState
47
- } from './types'
48
-
49
- /**
50
- * Re-exported so every existing importer of these two keeps its import site.
51
- * They live in `./types` now because the payer's hold and the receiver's queue
52
- * need them too, and neither may depend on this module's runtime.
53
- */
54
- export type { EvidenceFrame, EvidenceTokenBlock }
55
-
56
- // ─────────────────────────────── states ───────────────────────────────
57
-
58
- /** Nothing leaves these. Mirrors spec §5's "terminal states never revert". */
59
- export const TERMINAL_SETTLEMENT_STATES: readonly TokenSettlementState[] = ['broadcast', 'refused', 'orphaned']
60
-
61
- /** Everything else. FIX M's "stuck" query and the drain's cascade both use it. */
62
- export const NON_TERMINAL_SETTLEMENT_STATES: readonly TokenSettlementState[] = [
63
- 'built',
64
- 'parked',
65
- 'handed_over',
66
- 'held',
67
- 'submitting',
68
- 'admitted'
69
- ]
70
-
71
- /**
72
- * The only states a drain pass may claim.
73
- *
74
- * `built` and `parked` are the USER's states, never the drain's: a parked
75
- * payment is one the payer walked away from, and pulling it into a submit set
76
- * would send money the payer deliberately withheld (spec §5, FIX F). `admitted`
77
- * is admitted only because a re-submit of already-admitted bytes is the
78
- * idempotent no-op — it is how a device whose admission cache was cleared
79
- * recovers without a special path.
80
- */
81
- const SUBMITTABLE_STATES: TokenSettlementState[] = ['handed_over', 'held', 'submitting', 'admitted']
82
-
83
- /** What a proven admission may advance directly, without a submit of its own. */
84
- const PRE_ADMIT_STATES: TokenSettlementState[] = ['handed_over', 'held', 'submitting']
85
-
86
- // ───────────────────────────── evidence (FIX G) ─────────────────────────────
87
-
88
- /**
89
- * Every `(child, parent, vout)` token edge in a frame's AtomicBEEF.
90
- *
91
- * FIX K: only inputs whose SOURCE OUTPUT decodes as a `MandalaToken` of this
92
- * frame's `assetId` are edges. A fresh unconfirmed BSV change output funding
93
- * the fee is not a token ancestor — the release engine already broadcasts such
94
- * a parent in dependency order, and treating it as a coverage hole would refuse
95
- * the ordinary case of a payer spending their own change.
96
- *
97
- * The whole beef is walked, not just the tip, because COVER has to recurse into
98
- * ancestors the payer forwarded but never submitted (spec §1.6's 1-hop and
99
- * 3-hop examples). Unreadable bytes yield no edges rather than throwing: a
100
- * frame the drain cannot parse is a frame it will simply never cover, and that
101
- * is a retry, not a refusal.
102
- */
103
- export function deriveTokenEdges(transaction: Uint8Array, assetId: string): TokenAdmissionEdge[] {
104
- let beef: Beef
105
- try {
106
- beef = Beef.fromBinary(transaction)
107
- } catch {
108
- return []
109
- }
110
- const edges: TokenAdmissionEdge[] = []
111
- for (const bt of beef.txs) {
112
- const tx = bt.tx
113
- if (!tx) continue
114
- for (const input of tx.inputs) {
115
- const parentVout = input.sourceOutputIndex
116
- const parentTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex')
117
- if (!parentTxid || typeof parentVout !== 'number') continue
118
- const source = input.sourceTransaction ?? beef.findTxid(parentTxid)?.tx
119
- const output = source?.outputs?.[parentVout]
120
- if (!output?.lockingScript) continue
121
- try {
122
- if (MandalaToken.decode(output.lockingScript).assetId !== assetId) continue
123
- } catch {
124
- continue // not a token output at all
125
- }
126
- edges.push({ childTxid: bt.txid, parentTxid, parentVout })
127
- }
128
- }
129
- return edges
130
- }
131
-
132
- export interface EvidencePopulated {
133
- admissions: number
134
- linkage: number
135
- edges: number
136
- /**
137
- * Counterparty-supplied `admissions[]` entries that were NOT cached, because
138
- * they were signed by some key other than this wallet's configured overlay,
139
- * failed σ_I verification, or arrived with no verifier to check them (FIX H).
140
- * Not an error: an unverifiable σ_I is treated as ABSENT, and the ancestor is
141
- * simply walked and submitted like any other.
142
- */
143
- admissionsDropped: number
144
- /** Non-fatal: this is a cache-population step, so failures are reported, never thrown. */
145
- errors: string[]
146
- }
147
-
148
- /** How `populateEvidenceFromFrame` is told what a σ_I has to be to be believed. */
149
- export interface EvidenceTrustAnchor {
150
- /**
151
- * THIS WALLET's configured overlay identity key — never `frame.token
152
- * .overlayIdentityKey` and never `settlement.overlayIdentityKey`, both of
153
- * which are counterparty-supplied data (wire contract §9.10).
154
- */
155
- overlayIdentityKey?: string
156
- /** FIX H: the cryptographic check. Absent → nothing is cached. */
157
- verifyAdmission?: AdmissionVerifier
158
- }
159
-
160
- /**
161
- * `INSERT OR IGNORE` a frame's `admissions[]`, `linkage[]` and derived edges
162
- * into the three cache tables.
163
- *
164
- * **Every admission is verified before it is cached (FIX H).** The cache is not
165
- * a transcript of what a counterparty said — `admissionStandsIn` lets a cached
166
- * entry SKIP a `/submit`, and `assembleBundle` forwards cached entries onward
167
- * as this device's own claim about the chain, so a forged entry landing here
168
- * would strand a payment that was never admitted and propagate the lie to the
169
- * next hop. An entry signed by anything but the configured overlay key, or
170
- * whose σ_I does not verify, is dropped and counted; with no verifier supplied,
171
- * every entry is dropped, because "no verifier" is "no evidence".
172
- *
173
- * Linkage payloads are NOT filtered: they are opaque bytes destined for the
174
- * overlay's own verifier, prove nothing on their own, and a wrong one can only
175
- * ever cost a refused `/submit` that the drain records as a refusal for exactly
176
- * that payload hash.
177
- *
178
- * Never throws. A caller reaching this is either holding a payment it has
179
- * already promised (so a throw would turn a completed credit into a decline —
180
- * the exact hazard FIX G makes structurally impossible) or is a drain pass that
181
- * must reach the rest of the queue regardless.
182
- */
183
- export async function populateEvidenceFromFrame(
184
- store: SettlementStore,
185
- frame: EvidenceFrame,
186
- opts: EvidenceTrustAnchor & {
187
- now?: () => Date
188
- /** How this device came by the admissions: forwarded to it, or minted by it. */
189
- admissionSource?: TokenAdmissionRow['source']
190
- linkageSource?: 'minted' | 'forwarded'
191
- } = {}
192
- ): Promise<EvidencePopulated> {
193
- const result: EvidencePopulated = { admissions: 0, linkage: 0, edges: 0, admissionsDropped: 0, errors: [] }
194
- const token = frame.token
195
- if (!token) return result
196
- const at = (opts.now?.() ?? new Date()).toISOString()
197
-
198
- for (const entry of token.admissions ?? []) {
199
- // BRC-162: σI v3 binds the token topic; the frame's asset names it.
200
- if (!(await entryIsTrustworthy({ ...entry, topic: entry.topic ?? tokenTopicOrEmpty(token.assetId) }, opts))) {
201
- result.admissionsDropped++
202
- continue
203
- }
204
- try {
205
- await store.putAdmission({
206
- txid: entry.txid,
207
- outputsToAdmit: [...entry.outputsToAdmit],
208
- signatureHex: Utils.toHex(Array.from(entry.signature)),
209
- signerKey: entry.signerKey,
210
- source: opts.admissionSource ?? 'bundle',
211
- obtainedAt: at
212
- })
213
- result.admissions++
214
- } catch (e) {
215
- result.errors.push(`admission ${entry.txid}: ${messageOf(e)}`)
216
- }
217
- }
218
-
219
- for (const entry of token.linkage ?? []) {
220
- try {
221
- await store.putLinkage({
222
- txid: entry.txid,
223
- payloadBytes: entry.payload,
224
- overlayUrl: token.overlayUrl,
225
- overlayIdentityKey: token.overlayIdentityKey,
226
- source: opts.linkageSource ?? 'forwarded',
227
- createdAt: at
228
- })
229
- result.linkage++
230
- } catch (e) {
231
- result.errors.push(`linkage ${entry.txid}: ${messageOf(e)}`)
232
- }
233
- }
234
-
235
- try {
236
- const edges = deriveTokenEdges(frame.transaction, token.assetId)
237
- await store.putEdges(edges)
238
- result.edges = edges.length
239
- } catch (e) {
240
- result.errors.push(`edges: ${messageOf(e)}`)
241
- }
242
-
243
- return result
244
- }
245
-
246
- /**
247
- * One durable frame, paired with the txid and role its settlement row needs.
248
- *
249
- * The caller supplies these because only it can read them: the receiver's
250
- * frames are already decoded in `localpay_pending`, while the payer's
251
- * `offline_actions.framePayload` is the SEALED `bsvpayf1:` string and needs the
252
- * session pre-shared key to open — which the drain does not, and should not,
253
- * hold. A payer-side source is therefore contributed by whoever still has the
254
- * session; a receiver-side one needs nothing.
255
- */
256
- export interface TokenFrameSource {
257
- txid: string
258
- role: TokenSettlementRole
259
- frame: EvidenceFrame
260
- counterpartyKey?: string
261
- amountBaseUnits?: number
262
- /** Only used when no row exists yet. Defaults per role: sent → handed_over, received → held. */
263
- state?: TokenSettlementState
264
- }
265
-
266
- /**
267
- * FIX I / FIX G, run at the start of every drain pass.
268
- *
269
- * Re-derives a `token_settlements` row for any durable token frame that has
270
- * lost one (or never got one), and re-populates the evidence cache. This is why
271
- * `MAX_PENDING_ATTEMPTS` cannot abandon a token payment: the pending queue's
272
- * retry ceiling governs its own BSV-shaped bookkeeping, while the row that
273
- * actually decides whether this money settles is re-established here on every
274
- * tick and is abandoned only by an explicit `refused`/`orphaned` verdict.
275
- *
276
- * `upsertSettlement` never writes `state` on conflict, so a later pass can
277
- * never drag an `admitted` row back to `held`.
278
- */
279
- export async function reconcileSettlements(
280
- args: EvidenceTrustAnchor & {
281
- store: SettlementStore
282
- sources: readonly TokenFrameSource[]
283
- now?: () => Date
284
- }
285
- ): Promise<{ derived: number; populated: number; dropped: number; errors: string[] }> {
286
- const { store, sources } = args
287
- const out = { derived: 0, populated: 0, dropped: 0, errors: [] as string[] }
288
- for (const source of sources) {
289
- const token = source.frame.token
290
- if (!token) continue
291
- try {
292
- const evidence = await populateEvidenceFromFrame(store, source.frame, {
293
- now: args.now,
294
- overlayIdentityKey: args.overlayIdentityKey,
295
- verifyAdmission: args.verifyAdmission
296
- })
297
- out.errors.push(...evidence.errors)
298
- out.dropped += evidence.admissionsDropped
299
- out.populated++
300
-
301
- const existing = await store.getSettlement(source.txid)
302
- await store.upsertSettlement({
303
- txid: source.txid,
304
- role: source.role,
305
- assetId: token.assetId,
306
- state: existing?.state ?? source.state ?? (source.role === 'sent' ? 'handed_over' : 'held'),
307
- counterpartyKey: source.counterpartyKey,
308
- amountBaseUnits: source.amountBaseUnits,
309
- overlayUrl: token.overlayUrl,
310
- overlayIdentityKey: token.overlayIdentityKey,
311
- createdAt: existing?.createdAt
312
- })
313
- if (!existing) out.derived++
314
- } catch (e) {
315
- out.errors.push(`settlement ${source.txid}: ${messageOf(e)}`)
316
- }
317
- }
318
- return out
319
- }
320
-
321
- // ───────────────────────────── the drain (§4.3) ─────────────────────────────
322
-
323
- export interface TokenStepDeps extends EvidenceTrustAnchor {
324
- store: SettlementStore
325
- /** The pure COVER walk over local evidence (spec §1.2). */
326
- cover: CoverFn
327
- /** POST /submit for one txid; beef + linkage resolved from the local tables. */
328
- submit: SubmitFn
329
- /**
330
- * Broadcast the tip EXACTLY as a BSV transaction. Injected so this is
331
- * literally the release engine's own `postOwned`/`postForeign` — a token tip
332
- * gets no special broadcast path, only a gate in front of it.
333
- */
334
- broadcast: (txid: string) => Promise<PostOutcome>
335
- /**
336
- * Clear `@bsv/mandala`'s own tx-journal entry for a txid this drain has now
337
- * really broadcast (the lib's `journalRemove`, over the storage adapter
338
- * `configureMandala` was given).
339
- *
340
- * Injected rather than imported so this module keeps no lib-pipeline
341
- * dependency — and because the entry it clears is written by a pipeline this
342
- * module never runs.
343
- *
344
- * WHY IT IS HERE AT ALL. The lib's `submitAndBroadcast` journals `'accepted'`
345
- * and then broadcasts through `createAction({ sendWith })`. In this wallet
346
- * that broadcast is HELD (guard #2) — the drain owns it — so the lib's own
347
- * clear either fired on a broadcast that never happened (the 2026-09-15 bug)
348
- * or, once the lib stops clearing it, never fires at all and leaves the entry
349
- * for `reconcileWallet` to rebroadcast forever behind the drain's back. The
350
- * honest clear is this one: the moment the tip actually reaches the network,
351
- * from the only code that knows it did.
352
- *
353
- * Best-effort in the strongest sense — the money is already on chain when
354
- * this runs, and a stale journal entry costs an idempotent re-broadcast
355
- * attempt, never a payment.
356
- */
357
- journalRemove?: (txid: string) => Promise<void>
358
- now?: () => Date
359
- }
360
-
361
- /**
362
- * Whether a cached admission may stand in for a submit.
363
- *
364
- * **Three halves are required, and none is optional.** The structural half —
365
- * a non-empty admitted set, signed by the wallet's CONFIGURED overlay identity
366
- * key — only says the entry is addressed to the right overlay. It says nothing
367
- * about whether that overlay actually signed it, and this entry may have
368
- * arrived on a frame a counterparty composed. Skipping a `/submit` on a forged
369
- * entry is how a transaction the overlay has never seen reaches a real
370
- * broadcast: the drain would mark the ancestor `admitted` from the lie, walk
371
- * past it, and put an unadmitted chain on chain.
372
- *
373
- * So `deps.verifyAdmission` — σ_I checked against the configured key — gates
374
- * every skip, and its ABSENCE means "never skip": the ancestor is submitted,
375
- * which is free (`/submit` is idempotent, FIX C) and always correct. The
376
- * configured key comes from `deps`, never from `settlement.overlayIdentityKey`:
377
- * that column is re-derived from counterparty frame bytes by
378
- * `reconcileSettlements`, so anchoring trust in it would let the frame name its
379
- * own signer (wire contract §9.10).
380
- *
381
- * **The third half (XR-038): `requiredVouts` scoping.** A genuine σ_I over
382
- * `(txid, outputsToAdmit)` proves the overlay admitted THOSE outputs of
383
- * `txid` — nothing says the output THIS walk actually needs (the tip's own
384
- * held/payee vout, or an ancestor edge's `parentVout`) is one of them. A payer
385
- * who obtains a real admission for one output of a multi-output token tx
386
- * (their own change, say) must not get the WHOLE transaction — including an
387
- * output the issuer never admitted — treated as admitted. `requiredVouts`
388
- * empty means "not proven which vout matters", never "no vout matters", so it
389
- * is refused exactly like an absent row.
390
- */
391
- async function admissionStandsIn(
392
- row: TokenAdmissionRow | undefined,
393
- anchor: EvidenceTrustAnchor,
394
- requiredVouts: readonly number[],
395
- assetId?: string
396
- ): Promise<boolean> {
397
- if (row === undefined) return false
398
- if (row.signatureHex.length === 0 || row.outputsToAdmit.length === 0) return false
399
- if (requiredVouts.length === 0 || !requiredVouts.every(v => row.outputsToAdmit.includes(v))) return false
400
- return await entryIsTrustworthy(
401
- {
402
- txid: row.txid,
403
- ...(assetId !== undefined ? { topic: tokenTopicOrEmpty(assetId) } : {}),
404
- outputsToAdmit: row.outputsToAdmit,
405
- signature: hexToBytes(row.signatureHex),
406
- signerKey: row.signerKey
407
- },
408
- anchor
409
- )
410
- }
411
-
412
- /**
413
- * Which vout(s) of `parentTxid` THIS walk actually needs it admitted for —
414
- * from every `token_admission_edges` row already recorded (FIX K: derived
415
- * once from the beef itself, never from a counterparty's say-so) for a
416
- * transaction still in `mustSubmit` that spends `parentTxid`.
417
- *
418
- * Empty means "not proven", not "nothing needed": no cached edge names
419
- * `parentTxid` as a parent of anything still being walked — most likely
420
- * because evidence population has not run or lost a race — so the caller
421
- * (`admissionStandsIn`) must refuse to skip rather than guess.
422
- */
423
- async function requiredVoutsOfAncestor(
424
- store: SettlementStore,
425
- parentTxid: string,
426
- mustSubmit: readonly string[]
427
- ): Promise<number[]> {
428
- const vouts = new Set<number>()
429
- for (const childTxid of mustSubmit) {
430
- if (childTxid === parentTxid) continue
431
- for (const edge of await store.parentsOf(childTxid)) {
432
- if (edge.parentTxid === parentTxid) vouts.add(edge.parentVout)
433
- }
434
- }
435
- return [...vouts]
436
- }
437
-
438
- /**
439
- * FIX H in one predicate: is this σ_I the configured overlay's own?
440
- *
441
- * False for every way the answer can be "not proven" — a foreign signer key, a
442
- * missing verifier, a missing configured key, a signature that does not verify,
443
- * or a verifier that threw. The caller's move is identical in all of them
444
- * (treat the entry as absent and submit), which is why they collapse to one
445
- * boolean rather than a taxonomy nobody branches on.
446
- */
447
- async function entryIsTrustworthy(entry: AdmissionEntryWire, anchor: EvidenceTrustAnchor): Promise<boolean> {
448
- const configured = anchor.overlayIdentityKey
449
- if (!configured || !anchor.verifyAdmission) return false
450
- if (entry.signerKey.toLowerCase() !== configured.toLowerCase()) return false
451
- try {
452
- return (await anchor.verifyAdmission(entry)) === true
453
- } catch {
454
- return false
455
- }
456
- }
457
-
458
- function hexToBytes(hex: string): Uint8Array {
459
- const clean = hex.length % 2 === 0 ? hex : ''
460
- const out = new Uint8Array(clean.length / 2)
461
- for (let i = 0; i < out.length; i++) {
462
- const byte = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16)
463
- out[i] = Number.isNaN(byte) ? 0 : byte
464
- }
465
- return out
466
- }
467
-
468
- /**
469
- * One plan step for a transaction that has a `token_settlements` row.
470
- *
471
- * Reached ONLY from `processOfflineActions`'s own per-step loop, which itself
472
- * runs only from the drain — never from `finalizeDelivery`, never from
473
- * `internalizeAction`'s forced-broadcast path. That, plus the token guard in
474
- * `StorageExpoSQLite.attemptToPostReqsToNetwork`, is what makes an unadmitted
475
- * token broadcast unreachable rather than merely discouraged.
476
- *
477
- * Returns the unchanged `PostOutcome` shape, so the existing `applyOutcome`
478
- * cascade and requeue logic need no token-specific branch of their own.
479
- */
480
- export async function postTokenStep(
481
- deps: TokenStepDeps,
482
- settlement: TokenSettlementRow,
483
- step: { txid: string; owned: boolean }
484
- ): Promise<PostOutcome> {
485
- const { store } = deps
486
- const now = deps.now ?? (() => new Date())
487
- const tip = step.txid
488
- // The wallet-relevant output of the TIP itself — see `TokenSettlementRow
489
- // .relevantVout`. Nothing locally spends the tip, so this is the one vout
490
- // an admission for `tip` has to cover, on both the fast path just below and
491
- // the ordinary walk's own pass over the tip (it is always `mustSubmit`'s
492
- // last entry).
493
- const tipRequiredVouts = [settlement.relevantVout ?? 0]
494
-
495
- // The overlay's own σ_I over the tip is its ruling on the tip's ENTIRE
496
- // ancestry — nothing in the local evidence can outrank it, so there is
497
- // nothing left to submit and no walk to do. Without this, a hole COVER
498
- // cannot close locally (an ancestor admission never cached, a parent whose
499
- // bytes this device does not hold) left an already-admitted tip at
500
- // `admitted` on every tick, never broadcast (2026-09-16).
501
- const tipAdmission = await store.getAdmission(tip)
502
- if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts, settlement.assetId)) {
503
- await store.advanceSettlement(tip, PRE_ADMIT_STATES, 'admitted', {
504
- admissionOutputs: tipAdmission?.outputsToAdmit,
505
- admissionSignatureHex: tipAdmission?.signatureHex
506
- })
507
- return await broadcastAdmittedTip(deps, tip)
508
- }
509
-
510
- const cover = await deps.cover(tip)
511
- if (!cover.ok) {
512
- // An ancestor is still missing. Never a local refusal — the overlay is the
513
- // only authority on a final verdict (FIX D) — so the row stays exactly
514
- // where it was and the next pass tries again. Said out loud: a silent
515
- // stall here is what hid the 2026-09-15 fee-parent hole for four minutes.
516
- devLog(`[mandala] cover of ${tip} incomplete (${cover.reason}); its settlement step is deferred`)
517
- return 'serviceError'
518
- }
519
-
520
- for (const ancestorTxid of cover.mustSubmit) {
521
- const before = await store.getSettlement(ancestorTxid)
522
-
523
- // A row the USER owns must never be submitted by a drain pass, and an
524
- // anomaly that puts one in a submit set must not be worked around
525
- // silently — stall the whole step so the next pass (or a human) sees it
526
- // still waiting rather than a payment the payer deliberately withheld
527
- // going out (FIX F, spec §5's ownership column).
528
- if (before && (before.state === 'built' || before.state === 'parked')) return 'serviceError'
529
-
530
- // An ancestor this device has already seen a final verdict for can never
531
- // become valid: re-submitting would only fetch the same persisted verdict
532
- // back ("verdict wins", wire contract §2). Poison the tip from local
533
- // knowledge instead of over the network.
534
- if (before && (before.state === 'refused' || before.state === 'orphaned')) {
535
- if (ancestorTxid !== tip) {
536
- await store.advanceSettlement(tip, [...NON_TERMINAL_SETTLEMENT_STATES], 'orphaned', {
537
- poisonedByTxid: ancestorTxid
538
- })
539
- }
540
- return before.state === 'orphaned' ? 'doubleSpend' : 'invalidTx'
541
- }
542
-
543
- const cached = await store.getAdmission(ancestorTxid)
544
- // The tip's own required vout(s) when the walk reaches it (mustSubmit's
545
- // last entry) — nothing spends the tip locally, so an edge lookup would
546
- // find nothing. Every other entry is a true ancestor, scoped to whichever
547
- // vout(s) of it something still in this walk actually spends.
548
- const requiredVouts =
549
- ancestorTxid === tip ? tipRequiredVouts : await requiredVoutsOfAncestor(store, ancestorTxid, cover.mustSubmit)
550
- if (await admissionStandsIn(cached, deps, requiredVouts, settlement.assetId)) {
551
- await store.advanceSettlement(ancestorTxid, PRE_ADMIT_STATES, 'admitted', {
552
- admissionOutputs: cached?.outputsToAdmit,
553
- admissionSignatureHex: cached?.signatureHex
554
- })
555
- continue
556
- }
557
-
558
- await store.advanceSettlement(ancestorTxid, SUBMITTABLE_STATES, 'submitting')
559
- const verdict = await deps.submit(ancestorTxid)
560
-
561
- if (verdict.kind === 'admitted') {
562
- // Belt and braces: `submit` already refused an unsigned or unverifiable
563
- // answer, but when this drain has its own anchor (the runtime always
564
- // injects one), nothing may advance a row to `admitted` on a σ_I that
565
- // anchor cannot verify (2026-09-15 review). Without an anchor the
566
- // verdict is `submit`'s to have checked.
567
- if (
568
- deps.verifyAdmission !== undefined &&
569
- !(await entryIsTrustworthy(
570
- {
571
- txid: ancestorTxid,
572
- outputsToAdmit: verdict.outputsToAdmit,
573
- signature: hexToBytes(verdict.signatureHex),
574
- signerKey: verdict.signerKey
575
- },
576
- deps
577
- ))
578
- ) {
579
- devLog(
580
- `[mandala] /submit of ${ancestorTxid} answered admitted without a verifiable σ_I; treated as unavailable`
581
- )
582
- if (before && SUBMITTABLE_STATES.includes(before.state)) {
583
- await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
584
- }
585
- return 'serviceError'
586
- }
587
- await store.putAdmission({
588
- txid: ancestorTxid,
589
- outputsToAdmit: verdict.outputsToAdmit,
590
- signatureHex: verdict.signatureHex,
591
- signerKey: verdict.signerKey,
592
- source: 'submitted',
593
- obtainedAt: now().toISOString()
594
- })
595
- await store.advanceSettlement(ancestorTxid, SUBMITTABLE_STATES, 'admitted', {
596
- admissionOutputs: verdict.outputsToAdmit,
597
- admissionSignatureHex: verdict.signatureHex
598
- })
599
- continue
600
- }
601
-
602
- if (verdict.kind === 'unavailable') {
603
- devLog(`[mandala] /submit of ${ancestorTxid} unavailable (${verdict.code}); the step is retried next pass`)
604
- // Liftable policy refusal or infra fault. Put the row back where it was
605
- // and stall the WHOLE step — never partially advance a chain past a
606
- // liftable stall; the whole prefix is retried next pass, idempotently.
607
- if (before && SUBMITTABLE_STATES.includes(before.state)) {
608
- await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
609
- }
610
- return 'serviceError'
611
- }
612
-
613
- // XR-042: `deps.submit`'s negative verdicts, unlike its 'admitted' branch
614
- // (checked above against `deps.verifyAdmission`), carry no signature at
615
- // all. A row this device already holds a σ_I-VERIFIED admission for —
616
- // `admissionSignatureHex`/`admissionOutputs`, only ever written after a
617
- // verified admission (`admissionStandsIn`'s own callers, and
618
- // `fetchAdmission`/`receiveFromInbox` upstream) — must not be unwound by a
619
- // LATER unsigned negative for the same txid: that positive is
620
- // cryptographic and this negative is not, so the positive stands. Put the
621
- // row back where it was and stall, exactly like an 'unavailable' verdict,
622
- // rather than treat "the overlay said no, unsigned" as final.
623
- if (before?.admissionSignatureHex && before.admissionOutputs && before.admissionOutputs.length > 0) {
624
- devLog(
625
- `[mandala] /submit of ${ancestorTxid} answered ${verdict.kind} without a signature, but this device ` +
626
- 'already holds a verified admission for it; treated as unavailable'
627
- )
628
- if (SUBMITTABLE_STATES.includes(before.state)) {
629
- await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
630
- }
631
- return 'serviceError'
632
- }
633
-
634
- // A final verdict for THIS txid. Evicted means it was admitted and then
635
- // undone (inputs restored overlay-side); refused means it never was.
636
- const to: TokenSettlementState = verdict.kind === 'evicted' ? 'orphaned' : 'refused'
637
- // Amendment §9.1/§9.3: a persisted refusal is keyed by (txid, payloadHash),
638
- // not by txid alone, so the row records which payload it was refused
639
- // FOR — the same bytes `deps.submit` read from this ancestor's own linkage
640
- // row — alongside the code, so the UI can say "refused for this payload"
641
- // rather than implying the txid itself is universally dead. Best-effort:
642
- // a lookup fault must never block recording the refusal itself.
643
- let refusedPayloadHash: string | undefined
644
- if (verdict.kind === 'refused') {
645
- try {
646
- const linkage = await store.getLinkage(ancestorTxid)
647
- if (linkage) refusedPayloadHash = payloadHash(linkage.payloadBytes)
648
- } catch {
649
- // Best-effort hint only; the refusal itself is recorded regardless.
650
- }
651
- }
652
- await store.advanceSettlement(ancestorTxid, [...NON_TERMINAL_SETTLEMENT_STATES], to, {
653
- refusedCode: verdict.kind === 'refused' ? verdict.code : undefined,
654
- refusedPayloadHash,
655
- poisonedByTxid: verdict.kind === 'evicted' ? ancestorTxid : undefined
656
- })
657
- if (ancestorTxid !== tip) {
658
- // The tip spends the dead ancestor, so it can never be valid. The broad
659
- // children-first cascade over every local spender is the caller's
660
- // unchanged `applyOutcome`; this mirrors the verdict onto the one row
661
- // that owns the token payment's state.
662
- await store.advanceSettlement(tip, [...NON_TERMINAL_SETTLEMENT_STATES], 'orphaned', {
663
- poisonedByTxid: ancestorTxid
664
- })
665
- }
666
- return verdict.kind === 'evicted' ? 'doubleSpend' : 'invalidTx'
667
- }
668
-
669
- // Every ancestor in mustSubmit is admitted. Only now is a broadcast honest.
670
- return await broadcastAdmittedTip(deps, tip)
671
- }
672
-
673
- async function broadcastAdmittedTip(deps: TokenStepDeps, tip: string): Promise<PostOutcome> {
674
- const { store } = deps
675
- const outcome = await deps.broadcast(tip)
676
- if (outcome === 'success') {
677
- await store.advanceSettlement(tip, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
678
- // This is the one moment anything in this wallet may honestly say the tip
679
- // was broadcast, so it is the one place the lib's journal entry for it may
680
- // be cleared. Guarded rather than awaited-and-trusted: the row is already
681
- // `broadcast` and the transaction is already out, and no journal fault may
682
- // turn that into anything other than `'success'`.
683
- try {
684
- await deps.journalRemove?.(tip)
685
- } catch (e) {
686
- // The entry stays; `reconcileWallet` finds the tx already broadcast and
687
- // clears it then. Never a reason to report a delivered payment as failed.
688
- console.warn(`[mandala] broadcast ${tip} but could not clear its journal entry:`, messageOf(e))
689
- }
690
- }
691
- return outcome
692
- }
693
-
694
- // ─────────────────────────── FIX I / FIX M helpers ───────────────────────────
695
-
696
- /**
697
- * Failures that must never be allowed to abandon a token payment (FIX I).
698
- *
699
- * `MAX_PENDING_ATTEMPTS` burns an attempt on ANY `internalizeAction` failure,
700
- * including a transient `Block header not found for height N` from a
701
- * fresh-block BUMP this device has not caught up on yet. That is a header lag,
702
- * not a bad frame: the money is real and the next tick will credit it. A
703
- * structurally bad BEEF is the opposite, and is deliberately NOT matched here —
704
- * failure-matrix row 7's "ask the sender to send it again" is for exactly that
705
- * case and nothing else.
706
- */
707
- const RETRIABLE_INTERNALIZE_PATTERNS: readonly RegExp[] = [
708
- /header not found/i,
709
- /no header/i,
710
- /chain ?tracker/i,
711
- /network request failed/i,
712
- /timed? ?out/i,
713
- /econnreset|econnrefused|enotfound|fetch failed/i,
714
- // internalizeAction posts an unproven payment itself (wallet-toolbox-mobile
715
- // 2.14.7+); when no broadcaster answered, `failedPostReason` says so.
716
- /no broadcaster could be reached/i,
717
- // `processPending`'s own pre-internalize settlement write (§4.2/§4.3 guard
718
- // #2). A failure there is a local storage fault, not a bad frame: the money
719
- // is real, the frame is durable, and the next tick tries the same write
720
- // again. Burning the ceiling on it would abandon a good payment for the
721
- // exact reason FIX I exists — see `SETTLEMENT_PREWRITE_FAILURE`.
722
- /settlement row before crediting/i
723
- ]
724
-
725
- export function isRetriableInternalizeFailure(reason: string | undefined): boolean {
726
- if (!reason) return false
727
- return RETRIABLE_INTERNALIZE_PATTERNS.some(p => p.test(reason))
728
- }
729
-
730
- /**
731
- * FIX M: rows that have been waiting past the bound, for the UI to name.
732
- *
733
- * Non-terminal by `state` and old by `createdAt` — the user-facing claim is
734
- * "this payment has been waiting to settle for over three days", which is about
735
- * the payment's age, not about when the drain last touched it. Every
736
- * non-terminal state is included; a caller that wants only the drain-owned ones
737
- * can narrow with `SUBMITTABLE_STATES`' public sibling,
738
- * `NON_TERMINAL_SETTLEMENT_STATES`, which is exported beside it.
739
- */
740
- export async function listStuckSettlements(
741
- store: SettlementStore,
742
- now: number = Date.now(),
743
- olderThanMs: number = STUCK_AFTER_MS
744
- ): Promise<TokenSettlementRow[]> {
745
- const rows = await store.listSettlements({ state: [...NON_TERMINAL_SETTLEMENT_STATES] })
746
- return rows.filter(r => {
747
- const at = Date.parse(r.createdAt)
748
- return Number.isFinite(at) && now - at >= olderThanMs
749
- })
750
- }
751
-
752
- function messageOf(e: unknown): string {
753
- return e instanceof Error ? e.message : String(e)
754
- }