@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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.
- package/CHANGELOG.md +1790 -0
- package/README.md +54 -1
- package/core/amountFormatHelpers.ts +20 -2
- package/core/backup/RemoteSyncReader.ts +131 -19
- package/core/backup/appData.ts +157 -0
- package/core/backup/client.ts +15 -1
- package/core/backup/codec.ts +147 -9
- package/core/backup/constants.ts +30 -1
- package/core/backup/cursor.ts +31 -2
- package/core/backup/push.ts +70 -4
- package/core/backup/restore.ts +104 -16
- package/core/backup/restoreOnImport.ts +94 -30
- package/core/backup/status.ts +13 -8
- package/core/constants.ts +14 -1
- package/core/context/ExchangeRateContext.tsx +34 -27
- package/core/context/LocalStorageProvider.tsx +43 -40
- package/core/context/UserContext.tsx +18 -7
- package/core/context/VaultContext.tsx +49 -2
- package/core/context/WalletConnectionContext.tsx +203 -11
- package/core/context/WalletContext.tsx +653 -175
- package/core/headers/OfflineFirstChaintracks.ts +48 -4
- package/core/headers/headerStore.ts +26 -4
- package/core/headers/headerSyncTriggers.ts +65 -0
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +1001 -25
- package/core/identity/handleRegistry/client.ts +31 -2
- package/core/identity/handleRegistry/keyPinStore.ts +70 -0
- package/core/identity/handleRegistry/resolver.ts +71 -3
- package/core/index.ts +33 -3
- package/core/localpay/build.ts +225 -24
- package/core/localpay/pending.ts +110 -7
- package/core/localpay/pendingAbortAuthority.ts +95 -0
- package/core/localpay/pendingAborts.ts +264 -28
- package/core/localpay/session.ts +42 -17
- package/core/localpay/settlementAck.ts +10 -1
- package/core/localpay/transport/socket.ts +52 -3
- package/core/localpay/types.ts +9 -1
- package/core/localpay/verify.ts +143 -16
- package/core/mandala/abortGuard.ts +96 -20
- package/core/mandala/createRuntime.ts +206 -33
- package/core/mandala/drain.ts +89 -11
- package/core/mandala/inboxPrehold.ts +186 -0
- package/core/mandala/permissionModule.ts +202 -20
- package/core/mandala/settlementStore.ts +24 -2
- package/core/mandala/types.ts +40 -5
- package/core/monitor/TaskBackupPush.ts +14 -0
- package/core/monitor/TaskDrainOutbox.ts +14 -0
- package/core/monitor/TaskSendOffline.ts +14 -0
- package/core/net/publicDestination.ts +91 -0
- package/core/net/validateArcUrl.ts +22 -0
- package/core/offline/cancelParked.ts +134 -13
- package/core/offline/payerHold.ts +100 -24
- package/core/offline/plan.ts +36 -7
- package/core/pay/beefRepair.ts +6 -2
- package/core/pay/damagedInbox.ts +24 -0
- package/core/pay/rails/address.ts +107 -12
- package/core/pay/rails/handle.ts +117 -22
- package/core/pay/rails/index.ts +45 -7
- package/core/pay/rails/nativeIntent.ts +61 -0
- package/core/pay/rails/nearby.ts +1 -0
- package/core/pay/receiveHistory.ts +93 -0
- package/core/pay/recordProof.ts +19 -1
- package/core/pay/refreshProofGuard.ts +42 -1
- package/core/pay/watchlist.ts +5 -2
- package/core/peerpay/control.ts +17 -18
- package/core/peerpay/handleResendRequests.ts +58 -4
- package/core/peerpay/outbox.ts +3 -1
- package/core/recovery/backupMaterial.ts +61 -0
- package/core/recovery/createWallet.ts +95 -0
- package/core/recovery/recoverWallet.ts +120 -0
- package/core/recovery/restoreWallet.ts +170 -0
- package/core/recovery/secret.ts +92 -0
- package/core/recovery/shareCollector.ts +71 -0
- package/core/recovery/shareParsing.ts +87 -0
- package/core/recovery/shares.ts +116 -0
- package/core/recovery/useRecoveryDeps.ts +70 -0
- package/core/services/arcTokenStorage.ts +52 -0
- package/core/services/arcadeBroadcastProvider.ts +232 -48
- package/core/services/autoApprovePolicy.ts +105 -0
- package/core/services/callbackToken.ts +19 -0
- package/core/services/capWalletArgs.ts +14 -2
- package/core/services/connectionAuthority.ts +98 -0
- package/core/services/exchangeRate.ts +35 -12
- package/core/services/externalOrigin.ts +11 -0
- package/core/services/secrets/kek.ts +126 -29
- package/core/services/secrets/migration.ts +16 -4
- package/core/services/secrets/store.ts +42 -14
- package/core/services/vault/VaultKeyService.ts +228 -45
- package/core/services/vault/chainRecovery.ts +483 -0
- package/core/services/vault/driver.ts +9 -1
- package/core/services/vault/enrolledSerialRegistry.ts +150 -0
- package/core/services/vault/guard.ts +218 -32
- package/core/services/vault/hardwareLease.ts +19 -0
- package/core/services/vault/metaAuthority.ts +210 -0
- package/core/services/vault/pivReset.ts +64 -23
- package/core/services/vault/r1comb.ts +139 -3
- package/core/services/vault/session.ts +25 -4
- package/core/services/vault/transfers.ts +866 -170
- package/core/services/vault/types.ts +19 -4
- package/core/services/vault/vaultStore.ts +256 -29
- package/core/services/walletArgLimits.ts +45 -2
- package/core/services/walletConnectionValidation.ts +76 -6
- package/core/services/walletServiceConfig.ts +10 -8
- package/core/storage/StorageExpoSQLite.ts +47 -13
- package/core/storage/methods/findSql.ts +21 -2
- package/core/storage/methods/offlineActions.ts +10 -1
- package/core/storage/methods/processOfflineActions.ts +116 -23
- package/core/storage/schema/createTables.ts +126 -2
- package/core/stores/ConnectionStore.ts +34 -0
- package/core/toolboxConfig.ts +45 -11
- package/core/walletDbRegistry.ts +63 -0
- package/core/walletMonitor.ts +17 -1
- package/core/walletRepair/releaseStuckReservations.ts +72 -0
- package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
- package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
- package/package.json +2 -2
- package/ui/backupShares.ts +26 -169
- package/ui/components/pay/AddressReceive.tsx +13 -6
- package/ui/components/pay/AssetPicker.tsx +30 -9
- package/ui/components/pay/MessageBoxConfig.tsx +16 -0
- package/ui/components/pay/NearbyFlow.tsx +511 -251
- package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
- package/ui/components/pay/UniversalSend.tsx +167 -73
- package/ui/components/ui/AlertCard.tsx +38 -5
- package/ui/components/ui/PermissionSheet.tsx +197 -66
- package/ui/components/vault/EnrollWizard.tsx +61 -13
- package/ui/components/vault/vaultErrorCopy.ts +3 -1
- package/ui/components/wallet/ActivityRow.tsx +5 -3
- package/ui/components/wallet/AmountInput.tsx +8 -2
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
- package/ui/components/wallet/Balance.tsx +42 -23
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
- package/ui/exportTransactions.ts +36 -4
- package/ui/hooks/useExportWalletData.ts +25 -2
- package/ui/importDatabases.ts +339 -24
- package/ui/index.ts +9 -3
- package/ui/isImageUrl.ts +6 -0
- package/ui/printRecoveryShares.ts +9 -10
- package/ui/recoveryPrompts.ts +91 -0
- package/ui/resolveIdentity.ts +31 -9
- package/ui/screens/ConnectionsScreen.tsx +86 -19
- package/ui/screens/IdentifierScreen.tsx +30 -8
- package/ui/screens/PairScreen.tsx +74 -2
- package/ui/screens/SettingsScreen.tsx +10 -4
- package/ui/screens/TrustScreen.tsx +99 -4
- package/ui/screens/VaultScreen.tsx +410 -61
- package/ui/screens/VaultTransferScreen.tsx +59 -7
- package/ui/screens/WalletCheckScreen.tsx +17 -6
- package/ui/screens/WalletConfigScreen.tsx +82 -28
- package/ui/screens/WalletHomeScreen.tsx +179 -88
- package/ui/screens/detailActionKeys.ts +55 -0
- package/ui/tokenFormat.ts +44 -4
- package/ui/txStatus.ts +5 -0
- package/core/storage/LocalStorageAdapter.ts +0 -58
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
* stands; the reference is retried on the next wallet build.
|
|
6
6
|
*/
|
|
7
7
|
import { ADMIN_ORIGINATOR, LEGACY_ADMIN_ORIGINATOR } from '../config'
|
|
8
|
+
import { VAULT_ABORT_REPLAY_MARKER } from '../services/vault/guard'
|
|
9
|
+
import {
|
|
10
|
+
computePendingAbortAuthorityTag,
|
|
11
|
+
verifyPendingAbortAuthorityTag,
|
|
12
|
+
type PendingAbortTagWallet,
|
|
13
|
+
type PendingAbortVerifyWallet
|
|
14
|
+
} from './pendingAbortAuthority'
|
|
8
15
|
|
|
9
16
|
interface StorageLike {
|
|
10
17
|
getKeyValue: (key: string) => Promise<string | undefined>
|
|
@@ -16,23 +23,232 @@ export const PENDING_ABORTS_KEY = 'pending_aborts'
|
|
|
16
23
|
export interface PendingAbort {
|
|
17
24
|
reference: string
|
|
18
25
|
originator: string
|
|
26
|
+
/** XR-102: HMAC over `reference`, computed by `queuePendingAbort` with the
|
|
27
|
+
* ADMIN-scoped wallet under the reserved `pending abort authority`
|
|
28
|
+
* namespace (see pendingAbortAuthority.ts). Absent on a legacy pre-XR-102
|
|
29
|
+
* entry or a forged one — `replayPendingAborts` drops either, never
|
|
30
|
+
* replays them. */
|
|
31
|
+
tag?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function messageOf(e: unknown): string {
|
|
35
|
+
return e instanceof Error && e.message ? e.message : String(e)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// XR-088: every read-modify-write sequence on PENDING_ABORTS_KEY shares one
|
|
39
|
+
// storage key, so they must not interleave — a concurrent write built from a
|
|
40
|
+
// stale read silently drops (or resurrects) an entry. `queuePendingAbort` and
|
|
41
|
+
// `replayPendingAborts` each used to be a bare load-then-setKeyValue with no
|
|
42
|
+
// lock between them; both now run through this chain. Same pattern as
|
|
43
|
+
// core/localpay/pending.ts's own withQueueLock, for the identical reason.
|
|
44
|
+
let pendingAbortsLock: Promise<unknown> = Promise.resolve()
|
|
45
|
+
|
|
46
|
+
function withPendingAbortsLock<T>(fn: () => Promise<T>): Promise<T> {
|
|
47
|
+
const run = pendingAbortsLock.then(fn, fn)
|
|
48
|
+
pendingAbortsLock = run.catch(() => undefined)
|
|
49
|
+
return run
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** XR-088 (SEC1-026's own second, separately-named defect): a sentinel that
|
|
53
|
+
* distinguishes "the key is genuinely absent/empty" from "the read or parse
|
|
54
|
+
* itself failed" — the two used to be collapsed into the same `[]`, which let
|
|
55
|
+
* `queuePendingAbort` treat a transient storage hiccup as an authoritative
|
|
56
|
+
* empty queue and overwrite every other durable, not-yet-replayed reference
|
|
57
|
+
* with just the one item it was trying to add. */
|
|
58
|
+
const READ_FAILED = Symbol('pending-aborts-read-failed')
|
|
59
|
+
|
|
60
|
+
function parsePendingAborts(parsed: unknown): PendingAbort[] | typeof READ_FAILED {
|
|
61
|
+
if (!Array.isArray(parsed)) return READ_FAILED
|
|
62
|
+
const out: PendingAbort[] = []
|
|
63
|
+
for (const item of parsed) {
|
|
64
|
+
if (!item || typeof item !== 'object') continue
|
|
65
|
+
const reference = (item as { reference?: unknown }).reference
|
|
66
|
+
const originator = (item as { originator?: unknown }).originator
|
|
67
|
+
const tag = (item as { tag?: unknown }).tag
|
|
68
|
+
if (typeof reference === 'string' && reference && typeof originator === 'string') {
|
|
69
|
+
out.push({
|
|
70
|
+
reference,
|
|
71
|
+
// An abort queued before the internal label moved into hostname space
|
|
72
|
+
// would otherwise fail originator validation on every replay, forever.
|
|
73
|
+
originator: originator === LEGACY_ADMIN_ORIGINATOR ? ADMIN_ORIGINATOR : originator,
|
|
74
|
+
...(typeof tag === 'string' && tag ? { tag } : {})
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function loadPendingAbortsOrFail(storage: StorageLike): Promise<PendingAbort[] | typeof READ_FAILED> {
|
|
82
|
+
let raw: string | undefined
|
|
83
|
+
try {
|
|
84
|
+
raw = await storage.getKeyValue(PENDING_ABORTS_KEY)
|
|
85
|
+
} catch (e) {
|
|
86
|
+
console.warn('[localpay] could not read the pending-abort queue:', messageOf(e))
|
|
87
|
+
return READ_FAILED
|
|
88
|
+
}
|
|
89
|
+
if (!raw) return []
|
|
90
|
+
let parsed: unknown
|
|
91
|
+
try {
|
|
92
|
+
parsed = JSON.parse(raw)
|
|
93
|
+
} catch (e) {
|
|
94
|
+
console.warn('[localpay] the pending-abort queue is not valid JSON:', messageOf(e))
|
|
95
|
+
return READ_FAILED
|
|
96
|
+
}
|
|
97
|
+
return parsePendingAborts(parsed)
|
|
19
98
|
}
|
|
20
99
|
|
|
21
100
|
export async function loadPendingAborts(storage: StorageLike): Promise<PendingAbort[]> {
|
|
101
|
+
const result = await loadPendingAbortsOrFail(storage)
|
|
102
|
+
return result === READ_FAILED ? [] : result
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function queuePendingAbort(
|
|
106
|
+
storage: StorageLike,
|
|
107
|
+
item: PendingAbort,
|
|
108
|
+
/** XR-102: the ADMIN-scoped wallet (and its originator) this entry's
|
|
109
|
+
* authenticity tag is computed with — every real call site already has
|
|
110
|
+
* one, since it is the same wallet `abortAction` itself is called on. */
|
|
111
|
+
authority: { wallet: PendingAbortTagWallet; originator: string }
|
|
112
|
+
): Promise<void> {
|
|
113
|
+
if (!item.reference) return
|
|
114
|
+
return withPendingAbortsLock(async () => {
|
|
115
|
+
const loaded = await loadPendingAbortsOrFail(storage)
|
|
116
|
+
if (loaded === READ_FAILED) {
|
|
117
|
+
// XR-088: never overwrite on a read/parse failure — fail this queue
|
|
118
|
+
// call instead. Every real call site already wraps queuePendingAbort in
|
|
119
|
+
// its own best-effort `.catch()`, so this costs exactly one reference
|
|
120
|
+
// not being queued THIS attempt (the same outcome a rejected write
|
|
121
|
+
// would have had); what it does NOT cost is every other, unrelated,
|
|
122
|
+
// already-durable abort reference silently erased underneath it.
|
|
123
|
+
throw new Error('pending_aborts: could not read the existing queue, refusing to overwrite it')
|
|
124
|
+
}
|
|
125
|
+
if (loaded.some(a => a.reference === item.reference)) return
|
|
126
|
+
let tag: string | undefined
|
|
127
|
+
try {
|
|
128
|
+
tag = await computePendingAbortAuthorityTag(authority.wallet, authority.originator, item.reference)
|
|
129
|
+
} catch (e) {
|
|
130
|
+
// An untagged entry can never pass replayPendingAborts's verification
|
|
131
|
+
// (below) and so can never auto-release — but it is still worth
|
|
132
|
+
// recording durably rather than losing the reference outright: it stays
|
|
133
|
+
// visible, and a stuck `nosend` row remains recoverable through
|
|
134
|
+
// WalletHomeScreen's manual per-row abort, which does not go through
|
|
135
|
+
// this queue or its authority check at all.
|
|
136
|
+
console.warn('[localpay] could not tag a pending abort for authenticated replay:', messageOf(e))
|
|
137
|
+
}
|
|
138
|
+
await storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify([...loaded, { ...item, ...(tag ? { tag } : {}) }]))
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface ReplayPendingAbortsResult {
|
|
143
|
+
/** XR-102: entries dropped because their authority tag was missing or did
|
|
144
|
+
* not verify — never replayed, never called abortAction. Surfaced so the
|
|
145
|
+
* UI can tell the user something was ignored, in case it corresponds to a
|
|
146
|
+
* payment that now looks stuck (still recoverable via WalletHomeScreen's
|
|
147
|
+
* per-row Cancel, which does not depend on this queue). */
|
|
148
|
+
droppedUntrusted: number
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function replayPendingAborts(args: {
|
|
152
|
+
wallet: {
|
|
153
|
+
abortAction: (
|
|
154
|
+
args: { reference: string; [VAULT_ABORT_REPLAY_MARKER]?: true },
|
|
155
|
+
originator?: string
|
|
156
|
+
) => Promise<{ aborted?: boolean } | void>
|
|
157
|
+
} & PendingAbortVerifyWallet
|
|
158
|
+
storage: StorageLike
|
|
159
|
+
}): Promise<ReplayPendingAbortsResult> {
|
|
160
|
+
return withPendingAbortsLock(async () => {
|
|
161
|
+
const pending = await loadPendingAborts(args.storage)
|
|
162
|
+
if (pending.length === 0) return { droppedUntrusted: 0 }
|
|
163
|
+
const kept: PendingAbort[] = []
|
|
164
|
+
let droppedUntrusted = 0
|
|
165
|
+
for (const item of pending) {
|
|
166
|
+
// XR-102 (non-Vault residual): the vault-inventory replay marker below
|
|
167
|
+
// only protects a Vault reference — an ordinary localpay/PeerPay
|
|
168
|
+
// reference has no settlement row and no vault-inventory entry, so
|
|
169
|
+
// nothing else stops a forged `pending_aborts` entry naming one from
|
|
170
|
+
// being replayed. Authenticate first: an entry this wallet did not
|
|
171
|
+
// itself tag at queue time (queuePendingAbort) is dropped, never
|
|
172
|
+
// replayed — fail closed, since the only thing a replay ever does is
|
|
173
|
+
// free a reservation, and a dropped reference stays recoverable through
|
|
174
|
+
// WalletHomeScreen's manual per-row abort.
|
|
175
|
+
const authentic = await verifyPendingAbortAuthorityTag(args.wallet, ADMIN_ORIGINATOR, item.reference, item.tag)
|
|
176
|
+
if (!authentic) {
|
|
177
|
+
droppedUntrusted++
|
|
178
|
+
continue
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
// XR-102: the persisted `originator` is never trusted here — this is a
|
|
182
|
+
// raw KV record, writable by anything with local storage access, and a
|
|
183
|
+
// forged admin-originator string used to replay straight past
|
|
184
|
+
// guardVaultAccess's inventory check. The ONLY originator ever used to
|
|
185
|
+
// replay is the real, imported constant every legitimate queued abort
|
|
186
|
+
// was already created under (see queuePendingAbort's call sites — all
|
|
187
|
+
// pass `adminOriginator`), never the field read back off disk.
|
|
188
|
+
//
|
|
189
|
+
// That alone is not enough: `assertPendingActionOriginator` requires
|
|
190
|
+
// this exact originator for a legitimate replay to succeed at all, and
|
|
191
|
+
// guardVaultAccess treats every admin-originator call as trusted. The
|
|
192
|
+
// marker opts this specific call OUT of that trust and into the same
|
|
193
|
+
// vault-inventory reference check a non-admin caller gets — so a
|
|
194
|
+
// reference an attacker injected that happens to name a Vault action is
|
|
195
|
+
// refused, while an ordinary (and authentically-tagged) localpay/
|
|
196
|
+
// PeerPay reference still replays.
|
|
197
|
+
const result = await args.wallet.abortAction(
|
|
198
|
+
{ reference: item.reference, [VAULT_ABORT_REPLAY_MARKER]: true },
|
|
199
|
+
ADMIN_ORIGINATOR
|
|
200
|
+
)
|
|
201
|
+
if (result && typeof result === 'object' && result.aborted === false) {
|
|
202
|
+
kept.push(item)
|
|
203
|
+
}
|
|
204
|
+
} catch {
|
|
205
|
+
kept.push(item)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
await args.storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify(kept))
|
|
209
|
+
return { droppedUntrusted }
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Durable watch list for a DECLINED payment (build.ts's `finalizeDelivery`)
|
|
215
|
+
* whose txid might, despite the decline, still reach the chain.
|
|
216
|
+
*
|
|
217
|
+
* A negative ack is the payee's own unverifiable claim that nothing was
|
|
218
|
+
* queued — this codebase's own abort-chain-protection only refuses an abort
|
|
219
|
+
* while a service is reachable AND the chain already knows the tx, so a
|
|
220
|
+
* decline made while offline (or a dishonest one) still releases the payer's
|
|
221
|
+
* inputs. Policy here is detect-and-warn, never block: the inputs are freed
|
|
222
|
+
* immediately either way, exactly as before this existed, and this list only
|
|
223
|
+
* exists so a later reappearance of that same txid on chain can be surfaced
|
|
224
|
+
* rather than silently missed — see `verifyDeclinedAborts`.
|
|
225
|
+
*/
|
|
226
|
+
export const DECLINED_ABORT_WATCH_KEY = 'declined_abort_watch'
|
|
227
|
+
|
|
228
|
+
export interface DeclinedAbortWatch {
|
|
229
|
+
txid: string
|
|
230
|
+
reference: string
|
|
231
|
+
/** Best-effort; presentational only, never used to key the watch itself. */
|
|
232
|
+
peerIdentityKey?: string
|
|
233
|
+
/** `Date.now()` when the decline was recorded, for the bounded-age drop. */
|
|
234
|
+
at: number
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** How long an unresolved watch entry is kept before it is dropped unsurfaced. */
|
|
238
|
+
export const DECLINED_ABORT_WATCH_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
|
239
|
+
|
|
240
|
+
export async function loadDeclinedAbortWatch(storage: StorageLike): Promise<DeclinedAbortWatch[]> {
|
|
22
241
|
try {
|
|
23
|
-
const raw = await storage.getKeyValue(
|
|
242
|
+
const raw = await storage.getKeyValue(DECLINED_ABORT_WATCH_KEY)
|
|
24
243
|
if (!raw) return []
|
|
25
244
|
const parsed = JSON.parse(raw) as unknown
|
|
26
245
|
if (!Array.isArray(parsed)) return []
|
|
27
|
-
const out:
|
|
246
|
+
const out: DeclinedAbortWatch[] = []
|
|
28
247
|
for (const item of parsed) {
|
|
29
248
|
if (!item || typeof item !== 'object') continue
|
|
30
|
-
const reference =
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
// An abort queued before the internal label moved into hostname space
|
|
34
|
-
// would otherwise fail originator validation on every replay, forever.
|
|
35
|
-
out.push({ reference, originator: originator === LEGACY_ADMIN_ORIGINATOR ? ADMIN_ORIGINATOR : originator })
|
|
249
|
+
const { txid, reference, peerIdentityKey, at } = item as Record<string, unknown>
|
|
250
|
+
if (typeof txid === 'string' && txid && typeof reference === 'string' && typeof at === 'number') {
|
|
251
|
+
out.push({ txid, reference, at, ...(typeof peerIdentityKey === 'string' ? { peerIdentityKey } : {}) })
|
|
36
252
|
}
|
|
37
253
|
}
|
|
38
254
|
return out
|
|
@@ -41,31 +257,51 @@ export async function loadPendingAborts(storage: StorageLike): Promise<PendingAb
|
|
|
41
257
|
}
|
|
42
258
|
}
|
|
43
259
|
|
|
44
|
-
export async function
|
|
45
|
-
if (!item.
|
|
46
|
-
const all = await
|
|
47
|
-
if (all.some(a => a.
|
|
48
|
-
await storage.setKeyValue(
|
|
260
|
+
export async function queueDeclinedAbortWatch(storage: StorageLike, item: DeclinedAbortWatch): Promise<void> {
|
|
261
|
+
if (!item.txid) return
|
|
262
|
+
const all = await loadDeclinedAbortWatch(storage)
|
|
263
|
+
if (all.some(a => a.txid === item.txid)) return
|
|
264
|
+
await storage.setKeyValue(DECLINED_ABORT_WATCH_KEY, JSON.stringify([...all, item]))
|
|
49
265
|
}
|
|
50
266
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Asks the network about every watched txid and returns the ones it now
|
|
269
|
+
* reports mined or known — a declined payment that went through anyway.
|
|
270
|
+
* Those are removed from the watch list (surfaced once, not repeatedly); an
|
|
271
|
+
* unresolved one is kept, up to `DECLINED_ABORT_WATCH_MAX_AGE_MS`, after which
|
|
272
|
+
* it is dropped unsurfaced rather than watched forever. An honest decline,
|
|
273
|
+
* where the network never reports the txid, never surfaces anything.
|
|
274
|
+
*
|
|
275
|
+
* `getStatusForTxids` is the exact call this codebase already makes for the
|
|
276
|
+
* same question elsewhere (core/storage/methods/processOfflineActions.ts's
|
|
277
|
+
* `networkAlreadyHas`) — injected here rather than imported so this stays
|
|
278
|
+
* unit-testable without a real storage/services object.
|
|
279
|
+
*/
|
|
280
|
+
export async function verifyDeclinedAborts(args: {
|
|
55
281
|
storage: StorageLike
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
282
|
+
getStatusForTxids: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
|
|
283
|
+
}): Promise<DeclinedAbortWatch[]> {
|
|
284
|
+
const watched = await loadDeclinedAbortWatch(args.storage)
|
|
285
|
+
if (watched.length === 0) return []
|
|
286
|
+
const now = Date.now()
|
|
287
|
+
const surfaced: DeclinedAbortWatch[] = []
|
|
288
|
+
const kept: DeclinedAbortWatch[] = []
|
|
289
|
+
for (const item of watched) {
|
|
290
|
+
let status: string | undefined
|
|
61
291
|
try {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
kept.push(item)
|
|
65
|
-
}
|
|
292
|
+
const r = await args.getStatusForTxids([item.txid])
|
|
293
|
+
status = r.results?.find(x => x.txid === item.txid)?.status
|
|
66
294
|
} catch {
|
|
67
|
-
|
|
295
|
+
// Treat a failed probe as still-unknown, not as a negative result —
|
|
296
|
+
// the next reconnect tries again.
|
|
297
|
+
status = undefined
|
|
298
|
+
}
|
|
299
|
+
if (status === 'mined' || status === 'known') {
|
|
300
|
+
surfaced.push(item)
|
|
301
|
+
continue
|
|
68
302
|
}
|
|
303
|
+
if (now - item.at < DECLINED_ABORT_WATCH_MAX_AGE_MS) kept.push(item)
|
|
69
304
|
}
|
|
70
|
-
await args.storage.setKeyValue(
|
|
305
|
+
await args.storage.setKeyValue(DECLINED_ABORT_WATCH_KEY, JSON.stringify(kept))
|
|
306
|
+
return surfaced
|
|
71
307
|
}
|
package/core/localpay/session.ts
CHANGED
|
@@ -44,6 +44,16 @@ export const RUNG_MASK = 0x00ff
|
|
|
44
44
|
|
|
45
45
|
export type SessionOs = 'ios' | 'android'
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Bound on `SessionAsset.decimals` (XR-043), mirrored at every other boundary
|
|
49
|
+
* that ever reads a token's decimals — `ui/tokenFormat.ts`'s formatters and
|
|
50
|
+
* `core/mandala/createRuntime.ts`'s asset-metadata resolution. Nothing
|
|
51
|
+
* token-shaped this wallet knows of uses more than a handful; an unbounded
|
|
52
|
+
* value here is how an extreme decimals figure from a session QR reaches
|
|
53
|
+
* `String(...).padStart` deep in the confirmation UI and blows up the render.
|
|
54
|
+
*/
|
|
55
|
+
export const MAX_TOKEN_DECIMALS = 18
|
|
56
|
+
|
|
47
57
|
/**
|
|
48
58
|
* The asset a token request names. When present on a Session, `amount` is
|
|
49
59
|
* BASE UNITS of this asset, not satoshis, and remains a binding term.
|
|
@@ -121,6 +131,16 @@ export function mintSession(args: {
|
|
|
121
131
|
if (args.asset !== undefined && args.asset.overlayIdentityKey.length !== 66) {
|
|
122
132
|
throw new CodecError('bad asset overlayIdentityKey')
|
|
123
133
|
}
|
|
134
|
+
// XR-043: same bound `decodeSession` enforces below, checked here too for
|
|
135
|
+
// the same reason `amount` is — an out-of-range figure minted on THIS
|
|
136
|
+
// device would render (and crash) on its own screen before any decoder
|
|
137
|
+
// ever saw it.
|
|
138
|
+
if (
|
|
139
|
+
args.asset?.decimals !== undefined &&
|
|
140
|
+
(!Number.isInteger(args.asset.decimals) || args.asset.decimals < 0 || args.asset.decimals > MAX_TOKEN_DECIMALS)
|
|
141
|
+
) {
|
|
142
|
+
throw new CodecError('bad asset decimals')
|
|
143
|
+
}
|
|
124
144
|
return {
|
|
125
145
|
version: SESSION_VERSION,
|
|
126
146
|
caps:
|
|
@@ -136,7 +156,7 @@ export function mintSession(args: {
|
|
|
136
156
|
...(args.asset === undefined ? {} : { asset: args.asset }),
|
|
137
157
|
derivationPrefix: args.derivationPrefix,
|
|
138
158
|
derivationSuffix: args.derivationSuffix,
|
|
139
|
-
...(args.os === undefined ? {} : { os: args.os })
|
|
159
|
+
...(args.os === undefined ? {} : { os: args.os })
|
|
140
160
|
}
|
|
141
161
|
}
|
|
142
162
|
|
|
@@ -176,18 +196,20 @@ export function encodeSession(s: Session): string {
|
|
|
176
196
|
i: s.identityKey,
|
|
177
197
|
...(s.os === undefined ? {} : { o: s.os === 'ios' ? 'i' : 'a' }),
|
|
178
198
|
...(s.amount === undefined ? {} : { a: s.amount }),
|
|
179
|
-
...(s.asset === undefined
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
199
|
+
...(s.asset === undefined
|
|
200
|
+
? {}
|
|
201
|
+
: {
|
|
202
|
+
t: {
|
|
203
|
+
i: s.asset.id,
|
|
204
|
+
...(s.asset.label === undefined ? {} : { n: s.asset.label }),
|
|
205
|
+
...(s.asset.ticker === undefined ? {} : { s: s.asset.ticker }),
|
|
206
|
+
...(s.asset.decimals === undefined ? {} : { d: s.asset.decimals }),
|
|
207
|
+
u: s.asset.overlayUrl,
|
|
208
|
+
k: s.asset.overlayIdentityKey
|
|
209
|
+
}
|
|
210
|
+
}),
|
|
189
211
|
p: s.derivationPrefix,
|
|
190
|
-
x: s.derivationSuffix
|
|
212
|
+
x: s.derivationSuffix
|
|
191
213
|
})
|
|
192
214
|
return 'bsvpay1:' + toB64url(new TextEncoder().encode(body))
|
|
193
215
|
}
|
|
@@ -235,17 +257,20 @@ export function decodeSession(text: string): Session {
|
|
|
235
257
|
if (typeof ok !== 'string' || ok.length !== 66) throw new CodecError('bad overlayIdentityKey')
|
|
236
258
|
if (n !== undefined && typeof n !== 'string') throw new CodecError('bad asset label')
|
|
237
259
|
if (tick !== undefined && typeof tick !== 'string') throw new CodecError('bad asset ticker')
|
|
238
|
-
if (d !== undefined && (typeof d !== 'number' || !Number.isSafeInteger(d) || d < 0
|
|
260
|
+
if (d !== undefined && (typeof d !== 'number' || !Number.isSafeInteger(d) || d < 0 || d > MAX_TOKEN_DECIMALS))
|
|
261
|
+
throw new CodecError('bad asset decimals')
|
|
239
262
|
asset = {
|
|
240
|
-
id: ai,
|
|
263
|
+
id: ai,
|
|
264
|
+
overlayUrl: u,
|
|
265
|
+
overlayIdentityKey: ok,
|
|
241
266
|
...(n === undefined ? {} : { label: n }),
|
|
242
267
|
...(tick === undefined ? {} : { ticker: tick }),
|
|
243
|
-
...(d === undefined ? {} : { decimals: d })
|
|
268
|
+
...(d === undefined ? {} : { decimals: d })
|
|
244
269
|
}
|
|
245
270
|
}
|
|
246
271
|
return {
|
|
247
272
|
version: v as number,
|
|
248
|
-
caps:
|
|
273
|
+
caps: typeof c === 'number' ? c : 0,
|
|
249
274
|
sessionId,
|
|
250
275
|
psk,
|
|
251
276
|
identityKey: i,
|
|
@@ -253,7 +278,7 @@ export function decodeSession(text: string): Session {
|
|
|
253
278
|
...(asset === undefined ? {} : { asset }),
|
|
254
279
|
derivationPrefix: p,
|
|
255
280
|
derivationSuffix: x,
|
|
256
|
-
...(os === undefined ? {} : { os })
|
|
281
|
+
...(os === undefined ? {} : { os })
|
|
257
282
|
}
|
|
258
283
|
}
|
|
259
284
|
|
|
@@ -104,15 +104,24 @@ function hexToBytes(hex: string): Uint8Array {
|
|
|
104
104
|
* `expectTxid` binds the payload to the transaction actually handed over: an
|
|
105
105
|
* ack naming a DIFFERENT txid is somebody else's admission, replayed. It
|
|
106
106
|
* verifies perfectly and proves nothing about this payment.
|
|
107
|
+
*
|
|
108
|
+
* `expectVout` binds it further, to the payee's OWN output on that
|
|
109
|
+
* transaction (XR-093): the overlay signs `outputsToAdmit` as a set, so a
|
|
110
|
+
* genuine admission of a sibling output on the same tip — the payer's own
|
|
111
|
+
* token change, say — verifies just as well as one that actually covers the
|
|
112
|
+
* payee's output. Without this check the two are indistinguishable and the
|
|
113
|
+
* payer's screen could claim 'sent-settled' for a payment the overlay never
|
|
114
|
+
* admitted.
|
|
107
115
|
*/
|
|
108
116
|
export async function readSettlementAck(
|
|
109
117
|
ack: Ack,
|
|
110
|
-
args: { overlayIdentityKey: string; expectTxid?: string; verify: VerifyAdmissionFn }
|
|
118
|
+
args: { overlayIdentityKey: string; expectTxid?: string; expectVout: number; verify: VerifyAdmissionFn }
|
|
111
119
|
): Promise<AdmissionEntryWire | undefined> {
|
|
112
120
|
if (!ack.ok) return undefined
|
|
113
121
|
const payload = decodeSettlementAck(ack.error)
|
|
114
122
|
if (!payload) return undefined
|
|
115
123
|
if (args.expectTxid !== undefined && payload.txid !== args.expectTxid.toLowerCase()) return undefined
|
|
124
|
+
if (!payload.outputsToAdmit.includes(args.expectVout)) return undefined
|
|
116
125
|
|
|
117
126
|
const entry: AdmissionEntryWire = {
|
|
118
127
|
txid: payload.txid,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { LocalPayTransport } from '@bsv/react-native-localpay-transport'
|
|
2
|
+
import { MAX_MESSAGE_BYTES } from '@bsv/air-gap'
|
|
2
3
|
import { sealFrame, unsealFrame, type PaymentFrame } from '../codec'
|
|
3
4
|
import { instanceName, type Session } from '../session'
|
|
4
5
|
import {
|
|
@@ -10,6 +11,27 @@ import {
|
|
|
10
11
|
type ReceivedFrame
|
|
11
12
|
} from '../types'
|
|
12
13
|
|
|
14
|
+
/**
|
|
15
|
+
* XR-090. The ceiling every sealed frame this device would ever SEND already
|
|
16
|
+
* respects — `@bsv/air-gap`'s own limit, shared with the QR/fountain encoder
|
|
17
|
+
* (see codec.ts's FRAME_QR_PREFIX docs) — reused here as the ceiling on what
|
|
18
|
+
* this device will DECODE from a counterparty. Without it, an oversized
|
|
19
|
+
* radio payload reached `atob()` -> AES-GCM decrypt -> JSON.parse in full
|
|
20
|
+
* before anything refused it: unbounded memory/CPU per received message, on
|
|
21
|
+
* every transport that shares this decode layer (AWDL, Nearby JS, and BLE's
|
|
22
|
+
* onFrame all call `fromBase64` before anything else looks at the bytes).
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_INBOUND_FRAME_BYTES = MAX_MESSAGE_BYTES
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* An ack is `{ ok: boolean, error?: string }`, and `error` is one of a
|
|
28
|
+
* handful of short machine codes (see `DeclineReason`) or, at most, an
|
|
29
|
+
* echoed message — never anything close to a frame's size. Generous headroom
|
|
30
|
+
* over any real reason string, nowhere near large enough to matter for
|
|
31
|
+
* memory/CPU even if a counterparty sends nothing but padding.
|
|
32
|
+
*/
|
|
33
|
+
export const MAX_INBOUND_ACK_BYTES = 4096
|
|
34
|
+
|
|
13
35
|
/**
|
|
14
36
|
* Whole-exchange budget: connect + transfer + the payee's save + ack. Shared
|
|
15
37
|
* by every socketed rung — only the connect-phase budget is radio-specific,
|
|
@@ -44,8 +66,35 @@ export function toBase64(b: Uint8Array): string {
|
|
|
44
66
|
return globalThis.btoa(s)
|
|
45
67
|
}
|
|
46
68
|
|
|
47
|
-
|
|
48
|
-
|
|
69
|
+
/**
|
|
70
|
+
* The largest base64 STRING whose decode cannot exceed `maxBytes` — checked
|
|
71
|
+
* before `atob()` runs, not after. Base64 expands 3 bytes to 4 characters, so
|
|
72
|
+
* this is the same bound `atob()` would enforce itself if it refused rather
|
|
73
|
+
* than happily decoding a payload of any size handed to it.
|
|
74
|
+
*/
|
|
75
|
+
function maxBase64Length(maxBytes: number): number {
|
|
76
|
+
return Math.ceil(maxBytes / 3) * 4
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* XR-090: `maxBytes` defaults to a full frame's ceiling since that is this
|
|
81
|
+
* function's most common and most sensitive caller; `parseAck` below passes
|
|
82
|
+
* the much smaller ack ceiling explicitly. Rejects by encoded length before
|
|
83
|
+
* `atob()` ever runs, so an oversized payload never reaches decode at all.
|
|
84
|
+
*/
|
|
85
|
+
export function fromBase64(s: string, maxBytes: number = MAX_INBOUND_FRAME_BYTES): Uint8Array {
|
|
86
|
+
if (s.length > maxBase64Length(maxBytes)) {
|
|
87
|
+
throw new Error(`base64 payload of ${s.length} chars exceeds the ${maxBytes}-byte ceiling`)
|
|
88
|
+
}
|
|
89
|
+
const bytes = Uint8Array.from(globalThis.atob(s), c => c.charCodeAt(0))
|
|
90
|
+
// The length check above is a cheap, coarse circuit-breaker on the ENCODED
|
|
91
|
+
// string (base64 groups 3 bytes into 4 characters, so it can only bound the
|
|
92
|
+
// decode to within a couple of bytes of `maxBytes`). This is the precise
|
|
93
|
+
// one, on the actual decoded length.
|
|
94
|
+
if (bytes.length > maxBytes) {
|
|
95
|
+
throw new Error(`base64 payload decodes to ${bytes.length} bytes, exceeding the ${maxBytes}-byte ceiling`)
|
|
96
|
+
}
|
|
97
|
+
return bytes
|
|
49
98
|
}
|
|
50
99
|
|
|
51
100
|
/**
|
|
@@ -56,7 +105,7 @@ export function fromBase64(s: string): Uint8Array {
|
|
|
56
105
|
export function parseAck(ackBase64: string): Ack {
|
|
57
106
|
let parsed: unknown
|
|
58
107
|
try {
|
|
59
|
-
parsed = JSON.parse(new TextDecoder().decode(fromBase64(ackBase64)))
|
|
108
|
+
parsed = JSON.parse(new TextDecoder().decode(fromBase64(ackBase64, MAX_INBOUND_ACK_BYTES)))
|
|
60
109
|
} catch {
|
|
61
110
|
throw new AckError('malformed ack: invalid base64 or JSON')
|
|
62
111
|
}
|
package/core/localpay/types.ts
CHANGED
|
@@ -40,13 +40,21 @@ export type DeclineReason =
|
|
|
40
40
|
* their own chain admitted before this payment can be accepted by anyone.
|
|
41
41
|
*/
|
|
42
42
|
| 'not_covered'
|
|
43
|
+
/**
|
|
44
|
+
* The transaction's ancestry ends at a block whose merkle root this device
|
|
45
|
+
* could not confirm — usually an offline payee whose header window does not
|
|
46
|
+
* reach that block yet. Retryable once the PAYEE has been online long enough
|
|
47
|
+
* to sync headers. A payer on an older build shows this code verbatim.
|
|
48
|
+
*/
|
|
49
|
+
| 'root_unverified'
|
|
43
50
|
|
|
44
51
|
const DECLINE_REASONS: readonly string[] = [
|
|
45
52
|
'session_mismatch',
|
|
46
53
|
'already_paid',
|
|
47
54
|
'save_failed',
|
|
48
55
|
'decode_failed',
|
|
49
|
-
'not_covered'
|
|
56
|
+
'not_covered',
|
|
57
|
+
'root_unverified'
|
|
50
58
|
]
|
|
51
59
|
|
|
52
60
|
export function isDeclineReason(value: string): value is DeclineReason {
|