@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
@@ -1,6 +1,7 @@
1
1
  import { SymmetricKey } from '@bsv/sdk'
2
+ import type { AdmissionEntryWire } from '../mandala/types'
2
3
 
3
- export const FRAME_VERSION = 3
4
+ export const FRAME_VERSION = 5
4
5
 
5
6
  export class CodecError extends Error {
6
7
  constructor(message: string) {
@@ -17,7 +18,27 @@ export interface TokenPayment {
17
18
  overlayIdentityKey: string // 66-hex compressed pubkey
18
19
  certificates: Uint8Array[] // opaque serialized VerifiableCertificates
19
20
  linkage: Array<{ txid: string; payload: Uint8Array }> // per-txid MandalaLinkagePayload bytes, whole chain
20
- recipientLinkage: Uint8Array // JSON SpecificLinkage bytes, verifier = payee
21
+ /**
22
+ * σ_I evidence for the ancestors this frame's chain bottoms out at — the
23
+ * AdmissionBundle's `admissions` map, flattened (offline-settlement spec
24
+ * §1.1/§2.1). One entry per COVERED ancestor: the overlay's own signature
25
+ * over `(txid, outputsToAdmit)`, which the payee verifies against the
26
+ * session's `overlayIdentityKey` before crediting.
27
+ *
28
+ * REPLACES v3's `recipientLinkage`. A payee-decryptable linkage is
29
+ * impossible under D2 sender blinding without leaking the payer's real
30
+ * identity key (BRC-72 decryption by the named verifier requires
31
+ * `counterparty: prover`), and σ_I bound to the admitted output set is
32
+ * strictly stronger evidence at roughly a tenth the size: it is the
33
+ * OVERLAY's assertion, not the payer's assertion about their own honesty.
34
+ * Removed, not renamed — a v3 decoder cannot read a v4 frame at all.
35
+ *
36
+ * `linkage` and `admissions` are keyed by disjoint txid sets in a
37
+ * well-formed bundle: a txid with σ_I needs no linkage forwarded (nobody
38
+ * will submit it again); a txid without σ_I needs linkage (so whoever
39
+ * reconnects first can build its /submit body) and is walked further.
40
+ */
41
+ admissions: AdmissionEntryWire[]
21
42
  }
22
43
 
23
44
  export interface PaymentFrame {
@@ -46,6 +67,13 @@ export interface PaymentFrame {
46
67
  * submit the whole chain.
47
68
  */
48
69
  token?: TokenPayment
70
+ /**
71
+ * The sender's note, same app-specific extension as the message-box rail's
72
+ * `PaymentToken.note` (handle.ts). Empty and absent are wire-identical — an
73
+ * empty string round-trips as no `note` key at all — so there is exactly
74
+ * one way to say "no note".
75
+ */
76
+ note?: string
49
77
  /**
50
78
  * AtomicBEEF, on both transports. The design originally specified a bare
51
79
  * rawtx on the QR path to shrink the symbol, but ancestry is what lets the
@@ -153,8 +181,24 @@ export function encodeFrame(f: PaymentFrame): Uint8Array {
153
181
  for (const byte of hexToBytes(entry.txid.toLowerCase())) out.push(byte)
154
182
  putBytes(out, entry.payload)
155
183
  }
156
- putBytes(out, t.recipientLinkage)
184
+ putVarint(out, t.admissions.length)
185
+ for (const entry of t.admissions) {
186
+ if (entry.txid.length !== 64) throw new CodecError(`admission txid must be 64 hex chars, got ${entry.txid.length}`)
187
+ // Same shape check the overlay key already gets: a signerKey that is not
188
+ // a 33-byte compressed point can never verify, and one that is silently
189
+ // truncated on the wire would verify against a DIFFERENT key on the far
190
+ // side. Fail at encode, where there is still a payer to tell.
191
+ if (entry.signerKey.length !== 66) {
192
+ throw new CodecError(`admission signerKey must be 66 hex chars, got ${entry.signerKey.length}`)
193
+ }
194
+ for (const byte of hexToBytes(entry.txid.toLowerCase())) out.push(byte)
195
+ putVarint(out, entry.outputsToAdmit.length)
196
+ for (const vout of entry.outputsToAdmit) putVarint(out, vout)
197
+ putBytes(out, entry.signature)
198
+ for (const byte of hexToBytes(entry.signerKey.toLowerCase())) out.push(byte)
199
+ }
157
200
  }
201
+ putStr(out, f.note ?? '')
158
202
  putBytes(out, f.transaction)
159
203
  return new Uint8Array(out)
160
204
  }
@@ -190,14 +234,33 @@ export function decodeFrame(b: Uint8Array): PaymentFrame {
190
234
  pos.i += 32
191
235
  linkage.push({ txid, payload: getBytes(b, pos) })
192
236
  }
193
- const recipientLinkage = getBytes(b, pos)
194
- token = { assetId, overlayUrl, overlayIdentityKey, certificates, linkage, recipientLinkage }
237
+ const admissions: AdmissionEntryWire[] = []
238
+ const admissionCount = getVarint(b, pos)
239
+ for (let a = 0; a < admissionCount; a++) {
240
+ // Every field below consumes bytes and bounds-checks first, so a hostile
241
+ // count cannot make this loop spin: it throws the moment the buffer runs
242
+ // out, on the first entry that does not fit.
243
+ if (pos.i + 32 > b.length) throw new CodecError('truncated admission txid')
244
+ const txid = bytesToHex(b.slice(pos.i, pos.i + 32))
245
+ pos.i += 32
246
+ const voutCount = getVarint(b, pos)
247
+ const outputsToAdmit: number[] = []
248
+ for (let v = 0; v < voutCount; v++) outputsToAdmit.push(getVarint(b, pos))
249
+ const signature = getBytes(b, pos)
250
+ if (pos.i + 33 > b.length) throw new CodecError('truncated admission signerKey')
251
+ const signerKey = bytesToHex(b.slice(pos.i, pos.i + 33))
252
+ pos.i += 33
253
+ admissions.push({ txid, outputsToAdmit, signature, signerKey })
254
+ }
255
+ token = { assetId, overlayUrl, overlayIdentityKey, certificates, linkage, admissions }
195
256
  }
257
+ const note = getStr(b, pos)
196
258
  const transaction = getBytes(b, pos)
197
259
  if (pos.i !== b.length) throw new CodecError('trailing bytes after frame')
198
260
  return {
199
261
  version, kind, senderIdentityKey, outputIndex, derivationPrefix, derivationSuffix,
200
262
  ...(token === undefined ? {} : { token }),
263
+ ...(note ? { note } : {}),
201
264
  transaction,
202
265
  }
203
266
  }
@@ -1,6 +1,8 @@
1
1
  import { Beef } from '@bsv/sdk'
2
- import type { PaymentFrame } from './codec'
3
- import { abbreviateKey } from '../pay/counterparty'
2
+ import type { PaymentFrame, TokenPayment } from './codec'
3
+ import { MANDALA_ACTION_LABEL, MANDALA_BASKET } from '../mandala/bundle'
4
+ import type { AdmissionEntryWire } from '../mandala/types'
5
+ import { isRetriableInternalizeFailure } from '../mandala/drain'
4
6
 
5
7
  export const PENDING_KEY = 'localpay_pending'
6
8
  /**
@@ -72,16 +74,93 @@ export function getPendingCorruptNotice(): boolean {
72
74
  return pendingCorruptNotice
73
75
  }
74
76
 
77
+ /**
78
+ * Every byte field of a frame travels as a `number[]`: `JSON.stringify` turns a
79
+ * `Uint8Array` into an index-keyed object, and a token frame's linkage
80
+ * payloads, certificates and σ_I signatures came back that way for as long as
81
+ * only `transaction` was converted. `processPending` then handed the mangled
82
+ * frame to `onTokenHeld`, whose `putLinkage` bound a plain object — which
83
+ * expo-sqlite on Android stringifies into a TEXT row, unreadable by every later
84
+ * send that walked the received coin's ancestry (2026-09-16).
85
+ */
86
+ type WireBytes = number[]
87
+
88
+ interface WireToken extends Omit<TokenPayment, 'certificates' | 'linkage' | 'admissions'> {
89
+ certificates: WireBytes[]
90
+ linkage: Array<{ txid: string; payload: WireBytes }>
91
+ admissions: Array<Omit<AdmissionEntryWire, 'signature'> & { signature: WireBytes }>
92
+ }
93
+
75
94
  interface Serialised extends Omit<PendingPayment, 'frame'> {
76
- frame: Omit<PaymentFrame, 'transaction'> & { transaction: number[] }
95
+ frame: Omit<PaymentFrame, 'transaction' | 'token'> & { transaction: WireBytes; token?: WireToken }
96
+ }
97
+
98
+ /**
99
+ * Bytes as this queue wrote them (`number[]`), as it used to write them (the
100
+ * index-keyed object JSON makes of a `Uint8Array` — entries like that are still
101
+ * sitting in queues on devices), or already revived. Never throws: `readAll`
102
+ * quarantines the WHOLE queue on a throw, and one unreadable byte field must not
103
+ * cost every other payment in it. An unreadable field comes back EMPTY, which
104
+ * every consumer treats as "nothing held" (`putLinkage` refuses to store it).
105
+ */
106
+ function reviveBytes(value: unknown): Uint8Array {
107
+ if (value instanceof Uint8Array) return value
108
+ if (Array.isArray(value)) return Uint8Array.from(value as number[])
109
+ if (value !== null && typeof value === 'object') {
110
+ const entries = Object.entries(value as Record<string, unknown>)
111
+ const out = new Uint8Array(entries.length)
112
+ for (const [key, byte] of entries) {
113
+ const index = Number(key)
114
+ if (!Number.isInteger(index) || index < 0 || index >= out.length || typeof byte !== 'number') {
115
+ return new Uint8Array(0)
116
+ }
117
+ out[index] = byte
118
+ }
119
+ return out
120
+ }
121
+ return new Uint8Array(0)
77
122
  }
78
123
 
79
124
  function toWire(p: PendingPayment): Serialised {
80
- return { ...p, frame: { ...p.frame, transaction: Array.from(p.frame.transaction) } }
125
+ const { token, ...frame } = p.frame
126
+ return {
127
+ ...p,
128
+ frame: {
129
+ ...frame,
130
+ transaction: Array.from(p.frame.transaction),
131
+ ...(token
132
+ ? {
133
+ token: {
134
+ ...token,
135
+ certificates: token.certificates.map(c => Array.from(c)),
136
+ linkage: token.linkage.map(l => ({ txid: l.txid, payload: Array.from(l.payload) })),
137
+ admissions: token.admissions.map(a => ({ ...a, signature: Array.from(a.signature) }))
138
+ }
139
+ }
140
+ : {})
141
+ }
142
+ }
81
143
  }
82
144
 
83
145
  function fromWire(s: Serialised): PendingPayment {
84
- return { ...s, frame: { ...s.frame, transaction: new Uint8Array(s.frame.transaction) } }
146
+ const { token, ...frame } = s.frame
147
+ return {
148
+ ...s,
149
+ frame: {
150
+ ...frame,
151
+ transaction: reviveBytes(s.frame.transaction),
152
+ ...(token
153
+ ? {
154
+ token: {
155
+ ...token,
156
+ certificates: (token.certificates ?? []).map(reviveBytes),
157
+ linkage: (token.linkage ?? []).map(l => ({ txid: l.txid, payload: reviveBytes(l.payload) })),
158
+ admissions: (token.admissions ?? []).map(a => ({ ...a, signature: reviveBytes(a.signature) }))
159
+ }
160
+ }
161
+ : {})
162
+ }
163
+ }
85
164
  }
86
165
 
87
166
  // All read-modify-write sequences on the queue share one storage key, so they
@@ -263,7 +342,18 @@ export async function updateStatus(
263
342
  // Counted on failure only: 'processing' is set on the way in to
264
343
  // every attempt, so counting there would burn the ceiling without
265
344
  // anything having gone wrong.
266
- attempts: status === 'failed' ? (p.attempts ?? 0) + 1 : p.attempts
345
+ //
346
+ // FIX I. And not on EVERY failure either: a transient `Block header
347
+ // not found for height N` from a fresh-block BUMP this device has
348
+ // not caught up on is a header lag, not a bad frame — the money is
349
+ // real and the next tick credits it. Burning an attempt on it is
350
+ // how a good payment reached `MAX_PENDING_ATTEMPTS` and stopped
351
+ // being retried. A structurally bad BEEF is deliberately NOT
352
+ // matched by `isRetriableInternalizeFailure` and still counts.
353
+ attempts:
354
+ status === 'failed' && !isRetriableInternalizeFailure(failureReason)
355
+ ? (p.attempts ?? 0) + 1
356
+ : p.attempts
267
357
  }
268
358
  : p
269
359
  )
@@ -286,41 +376,165 @@ interface InternalizingWallet {
286
376
  */
287
377
  type AttributePayment = (txid: string, info: { senderIdentityKey: string; receivedVia?: string }) => Promise<void>
288
378
 
379
+ /**
380
+ * Called once a TOKEN frame has been credited, with the frame and the txid
381
+ * that was credited.
382
+ *
383
+ * This is the moment this device becomes responsible for submitting the chain
384
+ * (settlement rule 3), so it is where the `token_settlements` row and the
385
+ * evidence the frame carried — its admissions and linkage payloads — have to
386
+ * be persisted. Supplied by the caller rather than called directly from here,
387
+ * for the same reason `attribute` is: this module knows about the KV-backed
388
+ * queue and nothing else, and should stay that way.
389
+ *
390
+ * Optional, and its failure is never the payment's failure: the coin is
391
+ * already credited by the time it runs, and the drain re-reads its own tables
392
+ * on every online tick.
393
+ */
394
+ export type TokenCreditedHook = (frame: PaymentFrame, txid: string) => Promise<void>
395
+
396
+ /**
397
+ * The prefix every pre-internalize settlement-write failure carries.
398
+ *
399
+ * `isRetriableInternalizeFailure` matches it, so a local storage fault here
400
+ * never burns `MAX_PENDING_ATTEMPTS` (FIX I): the frame is durable, the money
401
+ * is real, and the next tick repeats the same write.
402
+ */
403
+ const SETTLEMENT_PREWRITE_FAILURE = 'could not record the settlement row before crediting'
404
+
405
+ /**
406
+ * The FT derivation protocol a received token coin was locked under. Same
407
+ * triple `verify.ts` checked the output against — written into
408
+ * `customInstructions` because the basket-insertion path forces every
409
+ * derivation field to undefined, and this is the only slot that survives to
410
+ * the day the coin is spent.
411
+ */
412
+ const FT_PROTOCOL_ID: [number, string] = [2, 'mandala token']
413
+
414
+ /** What `internalizeAction` is told about one frame's output. */
415
+ function internalizeOutput(frame: PaymentFrame): Record<string, unknown> {
416
+ if (frame.kind === 'token' && frame.token) {
417
+ // The toolbox never inspects a token script, credits no satoshis, and writes
418
+ // the output `spendable: true, change: false` immediately — which is exactly
419
+ // what makes a received-offline coin re-spendable before anyone has
420
+ // submitted anything (spec §1.6's chained offline hops).
421
+ return {
422
+ outputIndex: frame.outputIndex,
423
+ protocol: 'basket insertion',
424
+ insertionRemittance: {
425
+ basket: MANDALA_BASKET,
426
+ customInstructions: JSON.stringify({
427
+ protocolID: FT_PROTOCOL_ID,
428
+ keyID: `${frame.derivationPrefix} ${frame.derivationSuffix}`,
429
+ counterparty: frame.senderIdentityKey,
430
+ direction: 'received'
431
+ }),
432
+ tags: ['mandala', 'received', frame.token.assetId]
433
+ }
434
+ }
435
+ }
436
+ return {
437
+ outputIndex: frame.outputIndex,
438
+ protocol: 'wallet payment',
439
+ paymentRemittance: {
440
+ derivationPrefix: frame.derivationPrefix,
441
+ derivationSuffix: frame.derivationSuffix,
442
+ senderIdentityKey: frame.senderIdentityKey
443
+ }
444
+ }
445
+ }
446
+
289
447
  export async function processPending(
290
448
  wallet: InternalizingWallet,
291
449
  storage: KVStorage,
292
450
  originator: string,
293
- attribute?: AttributePayment
451
+ attribute?: AttributePayment,
452
+ onTokenCredited?: TokenCreditedHook,
453
+ /**
454
+ * TOKEN FRAMES ONLY, and it runs BEFORE `internalizeAction` — which is the
455
+ * entire point of it existing beside `onTokenCredited` (§4.2, §4.3 guard #2).
456
+ *
457
+ * `internalizeAction` forces a broadcast of its own through
458
+ * `shareReqsWithWorld` → `attemptToPostReqsToNetwork`, and the guard that
459
+ * stops an unadmitted token transaction going out there is a lookup of this
460
+ * txid in `token_settlements`. With the row written only afterwards — which
461
+ * is all `onTokenCredited` can do — the guard finds nothing on the FIRST
462
+ * internalize and falls straight through to a real, unmediated broadcast. The
463
+ * common shop case (payee has Wi-Fi, payer none) hits that path every time.
464
+ *
465
+ * So the row and the frame's evidence land first, and a failure here is a
466
+ * refusal to credit rather than an unguarded credit: the frame is already
467
+ * durable in `localpay_pending`, so the next tick retries the whole step and
468
+ * `isRetriableInternalizeFailure` keeps the ceiling from abandoning it.
469
+ */
470
+ onTokenHeld?: TokenCreditedHook
294
471
  ): Promise<{ id: string; success: boolean; error?: string }[]> {
295
472
  const results: { id: string; success: boolean; error?: string }[] = []
296
473
  for (const p of await getRetryable(storage)) {
297
474
  await updateStatus(storage, p.id, 'processing')
298
475
  try {
476
+ if (onTokenHeld && p.frame.kind === 'token') {
477
+ // Deliberately INSIDE the try: unlike every other settlement write in
478
+ // this file, this one gates the credit instead of following it.
479
+ let txid: string | undefined
480
+ try {
481
+ txid = Beef.fromBinary(p.frame.transaction).atomicTxid
482
+ } catch (e) {
483
+ // Unreadable bytes are not a settlement fault — let the internalize
484
+ // below reject them with its own, more precise message, which
485
+ // failure-matrix row 7 depends on being distinguishable.
486
+ console.warn('[localpay] token frame would not parse before the settlement write:', messageOf(e))
487
+ }
488
+ if (txid) {
489
+ try {
490
+ await onTokenHeld(p.frame, txid)
491
+ } catch (e) {
492
+ throw new Error(`${SETTLEMENT_PREWRITE_FAILURE}: ${messageOf(e)}`)
493
+ }
494
+ }
495
+ }
299
496
  await wallet.internalizeAction(
300
497
  {
301
498
  tx: Array.from(p.frame.transaction),
302
- outputs: [
303
- {
304
- outputIndex: p.frame.outputIndex,
305
- protocol: 'wallet payment',
306
- paymentRemittance: {
307
- derivationPrefix: p.frame.derivationPrefix,
308
- derivationSuffix: p.frame.derivationSuffix,
309
- senderIdentityKey: p.frame.senderIdentityKey
310
- }
311
- }
312
- ],
499
+ outputs: [internalizeOutput(p.frame)],
313
500
  // The activity list uses the description as the row title, so it
314
- // names the payer. The counterparty itself is recovered from
315
- // outputs.senderIdentityKey, which is why the label stays rail-only.
316
- description: abbreviateKey(p.frame.senderIdentityKey),
317
- labels: [PEERPAY_LABEL]
501
+ // says what happened — never who: a nearby transfer is blinded, so
502
+ // the payer's key it used to carry told the user nothing. The
503
+ // counterparty face is recovered from outputs.senderIdentityKey,
504
+ // which is why the rail label carries no key. A token frame ALSO
505
+ // carries the lib's own 'mandala' label: it is how the home screen
506
+ // recognises a token row, and without it a received stablecoin
507
+ // rendered as a BSV row over "+0 sats" (2026-09-16). A sender's note
508
+ // on the frame overrides this fixed wording, same as the message-box
509
+ // rail's PeerPay note.
510
+ description: (p.frame.note?.trim() || (p.frame.kind === 'token' ? 'Received token' : 'Received BSV')).padEnd(5),
511
+ labels: p.frame.kind === 'token' ? [PEERPAY_LABEL, MANDALA_ACTION_LABEL] : [PEERPAY_LABEL]
318
512
  },
319
513
  originator
320
514
  )
321
515
  await updateStatus(storage, p.id, 'completed')
322
516
  results.push({ id: p.id, success: true })
323
517
 
518
+ // The SECOND settlement write, and an idempotent re-derivation of the
519
+ // first: `onTokenHeld` already wrote the row before the internalize, and
520
+ // `upsertSettlement` never moves `state` on conflict, so this re-runs the
521
+ // same population harmlessly and is what still covers a caller that
522
+ // supplies only this hook. Isolated from the try/catch above for the same
523
+ // reason `attribute` is: the coin is credited by this point, so a failing
524
+ // write must not retroactively mark the payment 'failed' and
525
+ // re-internalize it.
526
+ if (onTokenCredited && p.frame.kind === 'token') {
527
+ try {
528
+ const txid = Beef.fromBinary(p.frame.transaction).atomicTxid
529
+ if (txid) await onTokenCredited(p.frame, txid)
530
+ } catch (e) {
531
+ // The drain owns the `token_settlements` row independently and
532
+ // re-reads its own tables on every online tick, so a lost write here
533
+ // costs a later reconciliation pass, not the payment.
534
+ console.warn('[localpay] token credited but settlement write failed:', e instanceof Error ? e.message : String(e))
535
+ }
536
+ }
537
+
324
538
  // Best-effort, and deliberately isolated from the try/catch above: by
325
539
  // this point the payment has already completed successfully, so a
326
540
  // failure here — a bad frame, a locked db — must not retroactively turn
@@ -356,6 +570,10 @@ export async function processPending(
356
570
  return results
357
571
  }
358
572
 
573
+ function messageOf(e: unknown): string {
574
+ return e instanceof Error ? e.message : String(e)
575
+ }
576
+
359
577
  export const SPENT_KEY = 'localpay_spent_sessions'
360
578
 
361
579
  function sessionKey(sessionId: Uint8Array): string {
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The settlement ack (offline-settlement spec §4.8, rule 5).
3
+ *
4
+ * When the recipient's drain gets σ_I for the tip, it tells the payer — so the
5
+ * payer's screen can say "settled" instead of "settling", and its own
6
+ * reconciliation pass can stop chasing a transaction that is already admitted.
7
+ *
8
+ * No new channel is introduced. The payload rides the string slot the existing
9
+ * confirm channel already has (`confirmFrame(accepted, reason)` →
10
+ * `Ack.error`), behind a prefix so it can never be mistaken for a
11
+ * `DeclineReason`; over the handle rail it rides the `'mandala-payments'`
12
+ * MessageBox instead. Same bytes either way.
13
+ *
14
+ * FIX H is the whole reason this module has a verification step at all. The
15
+ * payload is COUNTERPARTY-SUPPLIED: it arrives from the other device, which
16
+ * may be lying, broken, or replaying. So:
17
+ *
18
+ * · it is verified against THIS session's overlay key before it is allowed
19
+ * to mean anything;
20
+ * · a payload that fails verification is treated as ABSENT — never as a
21
+ * decline, never as proof. The drain then runs its own `postTokenStep` as
22
+ * if no ack had arrived, which is exactly what it would do for a payer
23
+ * whose counterparty said nothing at all.
24
+ *
25
+ * That asymmetry is deliberate: a forged ack can only ever cost the payer a
26
+ * redundant idempotent `/submit`, whereas treating a forged ack as a decline
27
+ * would let any counterparty unwind a payment it had already accepted.
28
+ */
29
+ import type { AdmissionEntryWire } from '../mandala/types'
30
+ import type { Ack } from './types'
31
+
32
+ /** Distinguishes a settlement payload from a `DeclineReason` in the same slot. */
33
+ export const SETTLEMENT_ACK_PREFIX = 'msa1:'
34
+
35
+ /** What the recipient tells the payer once the overlay has admitted the tip. */
36
+ export interface SettlementAck {
37
+ txid: string
38
+ /** Sorted ascending, exactly as the overlay signed them. */
39
+ outputsToAdmit: number[]
40
+ /** σ_I over `admissionDigestV2(txid, outputsToAdmit)`, DER hex. */
41
+ admissionSignature: string
42
+ }
43
+
44
+ /**
45
+ * Verifies one admission entry against the overlay that is supposed to have
46
+ * signed it. Injected: the σ_I digest is the overlay's own and lives in
47
+ * `@bsv/mandala`, so wallet and overlay cannot disagree about what is signed.
48
+ */
49
+ export type VerifyAdmissionFn = (
50
+ entry: AdmissionEntryWire,
51
+ overlayIdentityKey: string
52
+ ) => boolean | Promise<boolean>
53
+
54
+ export function encodeSettlementAck(ack: SettlementAck): string {
55
+ return SETTLEMENT_ACK_PREFIX + JSON.stringify(ack)
56
+ }
57
+
58
+ /**
59
+ * Reads a settlement payload out of the confirm channel's string slot.
60
+ *
61
+ * Returns undefined for anything that is not one — including a plain decline
62
+ * code, an empty string, and a payload whose shape is wrong. Never throws: this
63
+ * runs on bytes a counterparty chose, on a path where an exception would
64
+ * abort a screen that has already taken real money.
65
+ */
66
+ export function decodeSettlementAck(raw: unknown): SettlementAck | undefined {
67
+ if (typeof raw !== 'string' || !raw.startsWith(SETTLEMENT_ACK_PREFIX)) return undefined
68
+ let parsed: unknown
69
+ try {
70
+ parsed = JSON.parse(raw.slice(SETTLEMENT_ACK_PREFIX.length))
71
+ } catch {
72
+ return undefined
73
+ }
74
+ if (typeof parsed !== 'object' || parsed === null) return undefined
75
+ const { txid, outputsToAdmit, admissionSignature } = parsed as Record<string, unknown>
76
+ if (typeof txid !== 'string' || txid.length !== 64 || !/^[0-9a-f]+$/i.test(txid)) return undefined
77
+ if (typeof admissionSignature !== 'string' || admissionSignature.length === 0) return undefined
78
+ if (admissionSignature.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(admissionSignature)) return undefined
79
+ if (!Array.isArray(outputsToAdmit)) return undefined
80
+ const outs: number[] = []
81
+ for (const v of outputsToAdmit) {
82
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) return undefined
83
+ outs.push(v)
84
+ }
85
+ return { txid: txid.toLowerCase(), outputsToAdmit: outs, admissionSignature: admissionSignature.toLowerCase() }
86
+ }
87
+
88
+ function hexToBytes(hex: string): Uint8Array {
89
+ const out = new Uint8Array(hex.length / 2)
90
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
91
+ return out
92
+ }
93
+
94
+ /**
95
+ * The admission a positive ack carries, IF it carries one that verifies.
96
+ *
97
+ * Undefined means "no evidence arrived", for every reason there is: a decline,
98
+ * an ordinary positive ack with nothing on it, a malformed payload, a payload
99
+ * signed by somebody other than this session's overlay, a verifier that said
100
+ * no, or a verifier that threw. The caller's next move is the same in all of
101
+ * them — let the drain do its own submit — which is why they collapse to one
102
+ * value rather than a taxonomy nobody would branch on.
103
+ *
104
+ * `expectTxid` binds the payload to the transaction actually handed over: an
105
+ * ack naming a DIFFERENT txid is somebody else's admission, replayed. It
106
+ * verifies perfectly and proves nothing about this payment.
107
+ */
108
+ export async function readSettlementAck(
109
+ ack: Ack,
110
+ args: { overlayIdentityKey: string; expectTxid?: string; verify: VerifyAdmissionFn }
111
+ ): Promise<AdmissionEntryWire | undefined> {
112
+ if (!ack.ok) return undefined
113
+ const payload = decodeSettlementAck(ack.error)
114
+ if (!payload) return undefined
115
+ if (args.expectTxid !== undefined && payload.txid !== args.expectTxid.toLowerCase()) return undefined
116
+
117
+ const entry: AdmissionEntryWire = {
118
+ txid: payload.txid,
119
+ outputsToAdmit: payload.outputsToAdmit,
120
+ signature: hexToBytes(payload.admissionSignature),
121
+ signerKey: args.overlayIdentityKey
122
+ }
123
+ try {
124
+ return (await args.verify(entry, args.overlayIdentityKey)) ? entry : undefined
125
+ } catch {
126
+ return undefined
127
+ }
128
+ }
129
+
130
+ /**
131
+ * What the payer's success screen says after a token hand-over (spec §9 step 7).
132
+ *
133
+ * Only two states, because guard #1 means a token `finalizeDelivery` ALWAYS
134
+ * returns `broadcast: 'pending'` — there is no third, greener outcome it could
135
+ * report on its own. The difference is whether a verified σ_I for this
136
+ * transaction has come back yet:
137
+ *
138
+ * 'sent-settling' → "Sent. Settling with {{issuer}} — you'll see it confirm
139
+ * once you or {{payee}} reconnect."
140
+ * 'sent-settled' → "Sent · settled with {{issuer}}"
141
+ *
142
+ * Takes the already-VERIFIED admission, not a raw ack, so a screen cannot turn
143
+ * green on a payload nobody checked.
144
+ */
145
+ export type TokenSendState = 'sent-settling' | 'sent-settled'
146
+
147
+ export function tokenSendState(admission?: AdmissionEntryWire): TokenSendState {
148
+ return admission ? 'sent-settled' : 'sent-settling'
149
+ }
@@ -28,12 +28,25 @@ export type DeclineReason =
28
28
  | 'save_failed'
29
29
  /** The frame did not decode — version skew, truncation, trailing bytes. */
30
30
  | 'decode_failed'
31
+ /**
32
+ * Token frames only: the frame's admission evidence does not COVER its own
33
+ * ancestry (offline-settlement spec §1.2). Some token ancestor bottoms out
34
+ * at neither a σ_I this device can verify against the session's overlay key
35
+ * nor bytes it can walk further — so the coin being offered is one the
36
+ * issuer's overlay has never vouched for.
37
+ *
38
+ * Distinct from `session_mismatch` because it is not retryable and not the
39
+ * payer's mistake about WHICH request they are paying: the payer must get
40
+ * their own chain admitted before this payment can be accepted by anyone.
41
+ */
42
+ | 'not_covered'
31
43
 
32
44
  const DECLINE_REASONS: readonly string[] = [
33
45
  'session_mismatch',
34
46
  'already_paid',
35
47
  'save_failed',
36
- 'decode_failed'
48
+ 'decode_failed',
49
+ 'not_covered'
37
50
  ]
38
51
 
39
52
  export function isDeclineReason(value: string): value is DeclineReason {