@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,670 @@
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 '@bsv/templates'
30
+ import { payloadHash } 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
+ if (!(await entryIsTrustworthy(entry, opts))) {
200
+ result.admissionsDropped++
201
+ continue
202
+ }
203
+ try {
204
+ await store.putAdmission({
205
+ txid: entry.txid,
206
+ outputsToAdmit: [...entry.outputsToAdmit],
207
+ signatureHex: Utils.toHex(Array.from(entry.signature)),
208
+ signerKey: entry.signerKey,
209
+ source: opts.admissionSource ?? 'bundle',
210
+ obtainedAt: at
211
+ })
212
+ result.admissions++
213
+ } catch (e) {
214
+ result.errors.push(`admission ${entry.txid}: ${messageOf(e)}`)
215
+ }
216
+ }
217
+
218
+ for (const entry of token.linkage ?? []) {
219
+ try {
220
+ await store.putLinkage({
221
+ txid: entry.txid,
222
+ payloadBytes: entry.payload,
223
+ overlayUrl: token.overlayUrl,
224
+ overlayIdentityKey: token.overlayIdentityKey,
225
+ source: opts.linkageSource ?? 'forwarded',
226
+ createdAt: at
227
+ })
228
+ result.linkage++
229
+ } catch (e) {
230
+ result.errors.push(`linkage ${entry.txid}: ${messageOf(e)}`)
231
+ }
232
+ }
233
+
234
+ try {
235
+ const edges = deriveTokenEdges(frame.transaction, token.assetId)
236
+ await store.putEdges(edges)
237
+ result.edges = edges.length
238
+ } catch (e) {
239
+ result.errors.push(`edges: ${messageOf(e)}`)
240
+ }
241
+
242
+ return result
243
+ }
244
+
245
+ /**
246
+ * One durable frame, paired with the txid and role its settlement row needs.
247
+ *
248
+ * The caller supplies these because only it can read them: the receiver's
249
+ * frames are already decoded in `localpay_pending`, while the payer's
250
+ * `offline_actions.framePayload` is the SEALED `bsvpayf1:` string and needs the
251
+ * session pre-shared key to open — which the drain does not, and should not,
252
+ * hold. A payer-side source is therefore contributed by whoever still has the
253
+ * session; a receiver-side one needs nothing.
254
+ */
255
+ export interface TokenFrameSource {
256
+ txid: string
257
+ role: TokenSettlementRole
258
+ frame: EvidenceFrame
259
+ counterpartyKey?: string
260
+ amountBaseUnits?: number
261
+ /** Only used when no row exists yet. Defaults per role: sent → handed_over, received → held. */
262
+ state?: TokenSettlementState
263
+ }
264
+
265
+ /**
266
+ * FIX I / FIX G, run at the start of every drain pass.
267
+ *
268
+ * Re-derives a `token_settlements` row for any durable token frame that has
269
+ * lost one (or never got one), and re-populates the evidence cache. This is why
270
+ * `MAX_PENDING_ATTEMPTS` cannot abandon a token payment: the pending queue's
271
+ * retry ceiling governs its own BSV-shaped bookkeeping, while the row that
272
+ * actually decides whether this money settles is re-established here on every
273
+ * tick and is abandoned only by an explicit `refused`/`orphaned` verdict.
274
+ *
275
+ * `upsertSettlement` never writes `state` on conflict, so a later pass can
276
+ * never drag an `admitted` row back to `held`.
277
+ */
278
+ export async function reconcileSettlements(
279
+ args: EvidenceTrustAnchor & {
280
+ store: SettlementStore
281
+ sources: readonly TokenFrameSource[]
282
+ now?: () => Date
283
+ }
284
+ ): Promise<{ derived: number; populated: number; dropped: number; errors: string[] }> {
285
+ const { store, sources } = args
286
+ const out = { derived: 0, populated: 0, dropped: 0, errors: [] as string[] }
287
+ for (const source of sources) {
288
+ const token = source.frame.token
289
+ if (!token) continue
290
+ try {
291
+ const evidence = await populateEvidenceFromFrame(store, source.frame, {
292
+ now: args.now,
293
+ overlayIdentityKey: args.overlayIdentityKey,
294
+ verifyAdmission: args.verifyAdmission
295
+ })
296
+ out.errors.push(...evidence.errors)
297
+ out.dropped += evidence.admissionsDropped
298
+ out.populated++
299
+
300
+ const existing = await store.getSettlement(source.txid)
301
+ await store.upsertSettlement({
302
+ txid: source.txid,
303
+ role: source.role,
304
+ assetId: token.assetId,
305
+ state: existing?.state ?? source.state ?? (source.role === 'sent' ? 'handed_over' : 'held'),
306
+ counterpartyKey: source.counterpartyKey,
307
+ amountBaseUnits: source.amountBaseUnits,
308
+ overlayUrl: token.overlayUrl,
309
+ overlayIdentityKey: token.overlayIdentityKey,
310
+ createdAt: existing?.createdAt
311
+ })
312
+ if (!existing) out.derived++
313
+ } catch (e) {
314
+ out.errors.push(`settlement ${source.txid}: ${messageOf(e)}`)
315
+ }
316
+ }
317
+ return out
318
+ }
319
+
320
+ // ───────────────────────────── the drain (§4.3) ─────────────────────────────
321
+
322
+ export interface TokenStepDeps extends EvidenceTrustAnchor {
323
+ store: SettlementStore
324
+ /** The pure COVER walk over local evidence (spec §1.2). */
325
+ cover: CoverFn
326
+ /** POST /submit for one txid; beef + linkage resolved from the local tables. */
327
+ submit: SubmitFn
328
+ /**
329
+ * Broadcast the tip EXACTLY as a BSV transaction. Injected so this is
330
+ * literally the release engine's own `postOwned`/`postForeign` — a token tip
331
+ * gets no special broadcast path, only a gate in front of it.
332
+ */
333
+ broadcast: (txid: string) => Promise<PostOutcome>
334
+ /**
335
+ * Clear `@bsv/mandala`'s own tx-journal entry for a txid this drain has now
336
+ * really broadcast (the lib's `journalRemove`, over the storage adapter
337
+ * `configureMandala` was given).
338
+ *
339
+ * Injected rather than imported so this module keeps no lib-pipeline
340
+ * dependency — and because the entry it clears is written by a pipeline this
341
+ * module never runs.
342
+ *
343
+ * WHY IT IS HERE AT ALL. The lib's `submitAndBroadcast` journals `'accepted'`
344
+ * and then broadcasts through `createAction({ sendWith })`. In this wallet
345
+ * that broadcast is HELD (guard #2) — the drain owns it — so the lib's own
346
+ * clear either fired on a broadcast that never happened (the 2026-09-15 bug)
347
+ * or, once the lib stops clearing it, never fires at all and leaves the entry
348
+ * for `reconcileWallet` to rebroadcast forever behind the drain's back. The
349
+ * honest clear is this one: the moment the tip actually reaches the network,
350
+ * from the only code that knows it did.
351
+ *
352
+ * Best-effort in the strongest sense — the money is already on chain when
353
+ * this runs, and a stale journal entry costs an idempotent re-broadcast
354
+ * attempt, never a payment.
355
+ */
356
+ journalRemove?: (txid: string) => Promise<void>
357
+ now?: () => Date
358
+ }
359
+
360
+ /**
361
+ * Whether a cached admission may stand in for a submit.
362
+ *
363
+ * **Both halves are required, and the cryptographic one is not optional.** The
364
+ * structural half — a non-empty admitted set, signed by the wallet's CONFIGURED
365
+ * overlay identity key — only says the entry is addressed to the right overlay.
366
+ * It says nothing about whether that overlay actually signed it, and this entry
367
+ * may have arrived on a frame a counterparty composed. Skipping a `/submit` on
368
+ * a forged entry is how a transaction the overlay has never seen reaches a real
369
+ * broadcast: the drain would mark the ancestor `admitted` from the lie, walk
370
+ * past it, and put an unadmitted chain on chain.
371
+ *
372
+ * So `deps.verifyAdmission` — σ_I checked against the configured key — gates
373
+ * every skip, and its ABSENCE means "never skip": the ancestor is submitted,
374
+ * which is free (`/submit` is idempotent, FIX C) and always correct. The
375
+ * configured key comes from `deps`, never from `settlement.overlayIdentityKey`:
376
+ * that column is re-derived from counterparty frame bytes by
377
+ * `reconcileSettlements`, so anchoring trust in it would let the frame name its
378
+ * own signer (wire contract §9.10).
379
+ */
380
+ async function admissionStandsIn(
381
+ row: TokenAdmissionRow | undefined,
382
+ anchor: EvidenceTrustAnchor
383
+ ): Promise<boolean> {
384
+ if (row === undefined) return false
385
+ if (row.signatureHex.length === 0 || row.outputsToAdmit.length === 0) return false
386
+ return await entryIsTrustworthy(
387
+ {
388
+ txid: row.txid,
389
+ outputsToAdmit: row.outputsToAdmit,
390
+ signature: hexToBytes(row.signatureHex),
391
+ signerKey: row.signerKey
392
+ },
393
+ anchor
394
+ )
395
+ }
396
+
397
+ /**
398
+ * FIX H in one predicate: is this σ_I the configured overlay's own?
399
+ *
400
+ * False for every way the answer can be "not proven" — a foreign signer key, a
401
+ * missing verifier, a missing configured key, a signature that does not verify,
402
+ * or a verifier that threw. The caller's move is identical in all of them
403
+ * (treat the entry as absent and submit), which is why they collapse to one
404
+ * boolean rather than a taxonomy nobody branches on.
405
+ */
406
+ async function entryIsTrustworthy(entry: AdmissionEntryWire, anchor: EvidenceTrustAnchor): Promise<boolean> {
407
+ const configured = anchor.overlayIdentityKey
408
+ if (!configured || !anchor.verifyAdmission) return false
409
+ if (entry.signerKey.toLowerCase() !== configured.toLowerCase()) return false
410
+ try {
411
+ return (await anchor.verifyAdmission(entry)) === true
412
+ } catch {
413
+ return false
414
+ }
415
+ }
416
+
417
+ function hexToBytes(hex: string): Uint8Array {
418
+ const clean = hex.length % 2 === 0 ? hex : ''
419
+ const out = new Uint8Array(clean.length / 2)
420
+ for (let i = 0; i < out.length; i++) {
421
+ const byte = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16)
422
+ out[i] = Number.isNaN(byte) ? 0 : byte
423
+ }
424
+ return out
425
+ }
426
+
427
+ /**
428
+ * One plan step for a transaction that has a `token_settlements` row.
429
+ *
430
+ * Reached ONLY from `processOfflineActions`'s own per-step loop, which itself
431
+ * runs only from the drain — never from `finalizeDelivery`, never from
432
+ * `internalizeAction`'s forced-broadcast path. That, plus the token guard in
433
+ * `StorageExpoSQLite.attemptToPostReqsToNetwork`, is what makes an unadmitted
434
+ * token broadcast unreachable rather than merely discouraged.
435
+ *
436
+ * Returns the unchanged `PostOutcome` shape, so the existing `applyOutcome`
437
+ * cascade and requeue logic need no token-specific branch of their own.
438
+ */
439
+ export async function postTokenStep(
440
+ deps: TokenStepDeps,
441
+ settlement: TokenSettlementRow,
442
+ step: { txid: string; owned: boolean }
443
+ ): Promise<PostOutcome> {
444
+ const { store } = deps
445
+ const now = deps.now ?? (() => new Date())
446
+ const tip = step.txid
447
+
448
+ // The overlay's own σ_I over the tip is its ruling on the tip's ENTIRE
449
+ // ancestry — nothing in the local evidence can outrank it, so there is
450
+ // nothing left to submit and no walk to do. Without this, a hole COVER
451
+ // cannot close locally (an ancestor admission never cached, a parent whose
452
+ // bytes this device does not hold) left an already-admitted tip at
453
+ // `admitted` on every tick, never broadcast (2026-09-16).
454
+ const tipAdmission = await store.getAdmission(tip)
455
+ if (await admissionStandsIn(tipAdmission, deps)) {
456
+ await store.advanceSettlement(tip, PRE_ADMIT_STATES, 'admitted', {
457
+ admissionOutputs: tipAdmission?.outputsToAdmit,
458
+ admissionSignatureHex: tipAdmission?.signatureHex
459
+ })
460
+ return await broadcastAdmittedTip(deps, tip)
461
+ }
462
+
463
+ const cover = await deps.cover(tip)
464
+ if (!cover.ok) {
465
+ // An ancestor is still missing. Never a local refusal — the overlay is the
466
+ // only authority on a final verdict (FIX D) — so the row stays exactly
467
+ // where it was and the next pass tries again. Said out loud: a silent
468
+ // stall here is what hid the 2026-09-15 fee-parent hole for four minutes.
469
+ devLog(`[mandala] cover of ${tip} incomplete (${cover.reason}); its settlement step is deferred`)
470
+ return 'serviceError'
471
+ }
472
+
473
+ for (const ancestorTxid of cover.mustSubmit) {
474
+ const before = await store.getSettlement(ancestorTxid)
475
+
476
+ // A row the USER owns must never be submitted by a drain pass, and an
477
+ // anomaly that puts one in a submit set must not be worked around
478
+ // silently — stall the whole step so the next pass (or a human) sees it
479
+ // still waiting rather than a payment the payer deliberately withheld
480
+ // going out (FIX F, spec §5's ownership column).
481
+ if (before && (before.state === 'built' || before.state === 'parked')) return 'serviceError'
482
+
483
+ // An ancestor this device has already seen a final verdict for can never
484
+ // become valid: re-submitting would only fetch the same persisted verdict
485
+ // back ("verdict wins", wire contract §2). Poison the tip from local
486
+ // knowledge instead of over the network.
487
+ if (before && (before.state === 'refused' || before.state === 'orphaned')) {
488
+ if (ancestorTxid !== tip) {
489
+ await store.advanceSettlement(tip, [...NON_TERMINAL_SETTLEMENT_STATES], 'orphaned', {
490
+ poisonedByTxid: ancestorTxid
491
+ })
492
+ }
493
+ return before.state === 'orphaned' ? 'doubleSpend' : 'invalidTx'
494
+ }
495
+
496
+ const cached = await store.getAdmission(ancestorTxid)
497
+ if (await admissionStandsIn(cached, deps)) {
498
+ await store.advanceSettlement(ancestorTxid, PRE_ADMIT_STATES, 'admitted', {
499
+ admissionOutputs: cached?.outputsToAdmit,
500
+ admissionSignatureHex: cached?.signatureHex
501
+ })
502
+ continue
503
+ }
504
+
505
+ await store.advanceSettlement(ancestorTxid, SUBMITTABLE_STATES, 'submitting')
506
+ const verdict = await deps.submit(ancestorTxid)
507
+
508
+ if (verdict.kind === 'admitted') {
509
+ // Belt and braces: `submit` already refused an unsigned or unverifiable
510
+ // answer, but when this drain has its own anchor (the runtime always
511
+ // injects one), nothing may advance a row to `admitted` on a σ_I that
512
+ // anchor cannot verify (2026-09-15 review). Without an anchor the
513
+ // verdict is `submit`'s to have checked.
514
+ if (
515
+ deps.verifyAdmission !== undefined &&
516
+ !(await entryIsTrustworthy(
517
+ { txid: ancestorTxid, outputsToAdmit: verdict.outputsToAdmit, signature: hexToBytes(verdict.signatureHex), signerKey: verdict.signerKey },
518
+ deps
519
+ ))
520
+ ) {
521
+ devLog(`[mandala] /submit of ${ancestorTxid} answered admitted without a verifiable σ_I; treated as unavailable`)
522
+ if (before && SUBMITTABLE_STATES.includes(before.state)) {
523
+ await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
524
+ }
525
+ return 'serviceError'
526
+ }
527
+ await store.putAdmission({
528
+ txid: ancestorTxid,
529
+ outputsToAdmit: verdict.outputsToAdmit,
530
+ signatureHex: verdict.signatureHex,
531
+ signerKey: verdict.signerKey,
532
+ source: 'submitted',
533
+ obtainedAt: now().toISOString()
534
+ })
535
+ await store.advanceSettlement(ancestorTxid, SUBMITTABLE_STATES, 'admitted', {
536
+ admissionOutputs: verdict.outputsToAdmit,
537
+ admissionSignatureHex: verdict.signatureHex
538
+ })
539
+ continue
540
+ }
541
+
542
+ if (verdict.kind === 'unavailable') {
543
+ devLog(`[mandala] /submit of ${ancestorTxid} unavailable (${verdict.code}); the step is retried next pass`)
544
+ // Liftable policy refusal or infra fault. Put the row back where it was
545
+ // and stall the WHOLE step — never partially advance a chain past a
546
+ // liftable stall; the whole prefix is retried next pass, idempotently.
547
+ if (before && SUBMITTABLE_STATES.includes(before.state)) {
548
+ await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
549
+ }
550
+ return 'serviceError'
551
+ }
552
+
553
+ // A final verdict for THIS txid. Evicted means it was admitted and then
554
+ // undone (inputs restored overlay-side); refused means it never was.
555
+ const to: TokenSettlementState = verdict.kind === 'evicted' ? 'orphaned' : 'refused'
556
+ // Amendment §9.1/§9.3: a persisted refusal is keyed by (txid, payloadHash),
557
+ // not by txid alone, so the row records which payload it was refused
558
+ // FOR — the same bytes `deps.submit` read from this ancestor's own linkage
559
+ // row — alongside the code, so the UI can say "refused for this payload"
560
+ // rather than implying the txid itself is universally dead. Best-effort:
561
+ // a lookup fault must never block recording the refusal itself.
562
+ let refusedPayloadHash: string | undefined
563
+ if (verdict.kind === 'refused') {
564
+ try {
565
+ const linkage = await store.getLinkage(ancestorTxid)
566
+ if (linkage) refusedPayloadHash = payloadHash(linkage.payloadBytes)
567
+ } catch {
568
+ // Best-effort hint only; the refusal itself is recorded regardless.
569
+ }
570
+ }
571
+ await store.advanceSettlement(ancestorTxid, [...NON_TERMINAL_SETTLEMENT_STATES], to, {
572
+ refusedCode: verdict.kind === 'refused' ? verdict.code : undefined,
573
+ refusedPayloadHash,
574
+ poisonedByTxid: verdict.kind === 'evicted' ? ancestorTxid : undefined
575
+ })
576
+ if (ancestorTxid !== tip) {
577
+ // The tip spends the dead ancestor, so it can never be valid. The broad
578
+ // children-first cascade over every local spender is the caller's
579
+ // unchanged `applyOutcome`; this mirrors the verdict onto the one row
580
+ // that owns the token payment's state.
581
+ await store.advanceSettlement(tip, [...NON_TERMINAL_SETTLEMENT_STATES], 'orphaned', {
582
+ poisonedByTxid: ancestorTxid
583
+ })
584
+ }
585
+ return verdict.kind === 'evicted' ? 'doubleSpend' : 'invalidTx'
586
+ }
587
+
588
+ // Every ancestor in mustSubmit is admitted. Only now is a broadcast honest.
589
+ return await broadcastAdmittedTip(deps, tip)
590
+ }
591
+
592
+ async function broadcastAdmittedTip(deps: TokenStepDeps, tip: string): Promise<PostOutcome> {
593
+ const { store } = deps
594
+ const outcome = await deps.broadcast(tip)
595
+ if (outcome === 'success') {
596
+ await store.advanceSettlement(tip, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
597
+ // This is the one moment anything in this wallet may honestly say the tip
598
+ // was broadcast, so it is the one place the lib's journal entry for it may
599
+ // be cleared. Guarded rather than awaited-and-trusted: the row is already
600
+ // `broadcast` and the transaction is already out, and no journal fault may
601
+ // turn that into anything other than `'success'`.
602
+ try {
603
+ await deps.journalRemove?.(tip)
604
+ } catch (e) {
605
+ // The entry stays; `reconcileWallet` finds the tx already broadcast and
606
+ // clears it then. Never a reason to report a delivered payment as failed.
607
+ console.warn(`[mandala] broadcast ${tip} but could not clear its journal entry:`, messageOf(e))
608
+ }
609
+ }
610
+ return outcome
611
+ }
612
+
613
+ // ─────────────────────────── FIX I / FIX M helpers ───────────────────────────
614
+
615
+ /**
616
+ * Failures that must never be allowed to abandon a token payment (FIX I).
617
+ *
618
+ * `MAX_PENDING_ATTEMPTS` burns an attempt on ANY `internalizeAction` failure,
619
+ * including a transient `Block header not found for height N` from a
620
+ * fresh-block BUMP this device has not caught up on yet. That is a header lag,
621
+ * not a bad frame: the money is real and the next tick will credit it. A
622
+ * structurally bad BEEF is the opposite, and is deliberately NOT matched here —
623
+ * failure-matrix row 7's "ask the sender to send it again" is for exactly that
624
+ * case and nothing else.
625
+ */
626
+ const RETRIABLE_INTERNALIZE_PATTERNS: readonly RegExp[] = [
627
+ /header not found/i,
628
+ /no header/i,
629
+ /chain ?tracker/i,
630
+ /network request failed/i,
631
+ /timed? ?out/i,
632
+ /econnreset|econnrefused|enotfound|fetch failed/i,
633
+ // `processPending`'s own pre-internalize settlement write (§4.2/§4.3 guard
634
+ // #2). A failure there is a local storage fault, not a bad frame: the money
635
+ // is real, the frame is durable, and the next tick tries the same write
636
+ // again. Burning the ceiling on it would abandon a good payment for the
637
+ // exact reason FIX I exists — see `SETTLEMENT_PREWRITE_FAILURE`.
638
+ /settlement row before crediting/i
639
+ ]
640
+
641
+ export function isRetriableInternalizeFailure(reason: string | undefined): boolean {
642
+ if (!reason) return false
643
+ return RETRIABLE_INTERNALIZE_PATTERNS.some(p => p.test(reason))
644
+ }
645
+
646
+ /**
647
+ * FIX M: rows that have been waiting past the bound, for the UI to name.
648
+ *
649
+ * Non-terminal by `state` and old by `createdAt` — the user-facing claim is
650
+ * "this payment has been waiting to settle for over three days", which is about
651
+ * the payment's age, not about when the drain last touched it. Every
652
+ * non-terminal state is included; a caller that wants only the drain-owned ones
653
+ * can narrow with `SUBMITTABLE_STATES`' public sibling,
654
+ * `NON_TERMINAL_SETTLEMENT_STATES`, which is exported beside it.
655
+ */
656
+ export async function listStuckSettlements(
657
+ store: SettlementStore,
658
+ now: number = Date.now(),
659
+ olderThanMs: number = STUCK_AFTER_MS
660
+ ): Promise<TokenSettlementRow[]> {
661
+ const rows = await store.listSettlements({ state: [...NON_TERMINAL_SETTLEMENT_STATES] })
662
+ return rows.filter(r => {
663
+ const at = Date.parse(r.createdAt)
664
+ return Number.isFinite(at) && now - at >= olderThanMs
665
+ })
666
+ }
667
+
668
+ function messageOf(e: unknown): string {
669
+ return e instanceof Error ? e.message : String(e)
670
+ }