@bsv/expo-wallet-toolbox 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1745 -0
- package/README.md +47 -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 +631 -162
- package/core/headers/OfflineFirstChaintracks.ts +48 -4
- package/core/headers/headerStore.ts +26 -4
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +953 -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/verify.ts +100 -10
- 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/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 +480 -243
- 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
package/README.md
CHANGED
|
@@ -171,7 +171,9 @@ configureToolbox({
|
|
|
171
171
|
arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
|
|
172
172
|
chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
|
|
173
173
|
whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY,
|
|
174
|
-
|
|
174
|
+
// A distinct key: TAAL and WhatsOnChain are different origins, and this
|
|
175
|
+
// one is never used as a fallback for the other.
|
|
176
|
+
taalApiKey: process.env.EXPO_PUBLIC_TAAL_API_KEY
|
|
175
177
|
}
|
|
176
178
|
}
|
|
177
179
|
})
|
|
@@ -560,6 +562,50 @@ are required — both hard-won during this package's extraction:
|
|
|
560
562
|
|
|
561
563
|
## Breaking changes
|
|
562
564
|
|
|
565
|
+
**0.9.0:** `useWallet().logout` now returns `Promise<boolean>` (it was
|
|
566
|
+
`() => void`). It resolves once teardown has finished, and resolves to
|
|
567
|
+
`false` when the secrets layer could not confirm erasure. Await it before
|
|
568
|
+
treating sign-out or Delete Wallet as complete. The
|
|
569
|
+
`@bsv/wallet-toolbox-mobile` peer range moves to ^2.14.3, and hosts must copy
|
|
570
|
+
`patches/@bsv+wallet-toolbox-mobile+2.14.3.patch` in place of the 2.14.0
|
|
571
|
+
patch. 0.8.0 was never published, so hosts upgrading from 0.7.0 get its
|
|
572
|
+
breaking changes below as well.
|
|
573
|
+
|
|
574
|
+
**0.8.0:** three API points break. `DerivingWallet` (the interface
|
|
575
|
+
`core/localpay/verify.ts`'s `verifyFramePayment` accepts) gains a required
|
|
576
|
+
`getServices(): { getChainTracker(): Promise<ChainTracker> | ChainTracker }`
|
|
577
|
+
— a host that built its own object against the old, narrower shape (just
|
|
578
|
+
`getPublicKey`) must add it before its build will typecheck.
|
|
579
|
+
`RestoreWalletDeps` gains a required `hasStoredIdentity(): Promise<boolean>`
|
|
580
|
+
and `RestorePrompts` gains a required `confirmReplace(): Promise<'replace' |
|
|
581
|
+
'keep'>` — a host supplying its own `RestoreWalletDeps`, or building its own
|
|
582
|
+
`RestorePrompts` instead of using `ui/recoveryPrompts.ts`'s
|
|
583
|
+
`restorePrompts(t)`, must implement both. `core/storage/LocalStorageAdapter.ts`
|
|
584
|
+
and its exports (`initializeLocalStorage`, `isLocalStorage`,
|
|
585
|
+
`getStorageDisplayName`, `LocalStorageConfig`) are removed — dead code with
|
|
586
|
+
no real caller in this app, but a host that imported these names directly
|
|
587
|
+
gets a build error.
|
|
588
|
+
|
|
589
|
+
`restoreWallet`/`recoverWallet` also change host-visible behaviour for
|
|
590
|
+
anything that goes through them (the app's own mnemonic and scan-shares
|
|
591
|
+
screens, and any host reusing the `core/recovery/` module directly):
|
|
592
|
+
recovering or importing over an already-built wallet now rebuilds instead of
|
|
593
|
+
silently no-op'ing, storing one secret kind now deletes the other (exactly
|
|
594
|
+
one secret survives a restore), a failed backup replay's "skip" now also
|
|
595
|
+
works for hex/WIF imports, an attestation failure after a successful build
|
|
596
|
+
is reported non-fatally instead of failing the whole attempt, and
|
|
597
|
+
`recoverWallet` now asks the new `confirmReplace` prompt before overwriting
|
|
598
|
+
a secret already on the device — declining cancels before anything is
|
|
599
|
+
written. An external pairing deep link no longer auto-connects from
|
|
600
|
+
Connections; it now lands on `/pair` and requires the same explicit
|
|
601
|
+
Approve/Reject tap a scanned QR gets. `validateShareCompatibility` is
|
|
602
|
+
deprecated (still works, returns English prose) in favour of
|
|
603
|
+
`checkShareCompatibility`, which returns a code for the caller to translate.
|
|
604
|
+
See the CHANGELOG's 0.8.0 entry for the full list, including the additive
|
|
605
|
+
review-fix changes (Nearby/QR payment verification, offline-drain and
|
|
606
|
+
declined-payment handling, auto-approve bounds, exchange-rate/header/backup
|
|
607
|
+
fixes, and more) that ship alongside these three breaking points.
|
|
608
|
+
|
|
563
609
|
**0.4.0:** the package no longer reads `process.env` at all. `DEFAULT_BACKUP_URL`
|
|
564
610
|
is removed, and the `EXPO_PUBLIC_*` service reads in `walletServiceConfig` are
|
|
565
611
|
gone. The host supplies these through `configureToolbox({ backupUrl, services })`
|
|
@@ -428,10 +428,26 @@ export const formatAmountInInputUnit = (
|
|
|
428
428
|
return formatSatoshisLocale(Math.abs(Math.round(n)))
|
|
429
429
|
}
|
|
430
430
|
|
|
431
|
+
/**
|
|
432
|
+
* The character the active locale uses for a decimal point (e.g. ',' for
|
|
433
|
+
* de-DE), read off a real formatted number rather than hardcoded — a
|
|
434
|
+
* comma-decimal locale typing '3,50' must not have it silently truncated at
|
|
435
|
+
* the comma by `parseFloat`, which only ever recognizes '.'.
|
|
436
|
+
*/
|
|
437
|
+
export const decimalSeparator = (): string => {
|
|
438
|
+
try {
|
|
439
|
+
const part = new Intl.NumberFormat(locale()).formatToParts(1.1).find(p => p.type === 'decimal')
|
|
440
|
+
return part?.value ?? '.'
|
|
441
|
+
} catch {
|
|
442
|
+
return '.'
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
431
446
|
/**
|
|
432
447
|
* Convert a user-entered display value back to integer satoshis.
|
|
433
448
|
* - BSV mode: input is satoshi integers, passthrough
|
|
434
|
-
* - fiat mode: input is a decimal amount in that currency
|
|
449
|
+
* - fiat mode: input is a decimal amount in that currency, typed with the
|
|
450
|
+
* active locale's own decimal separator
|
|
435
451
|
*/
|
|
436
452
|
export const parseDisplayToSatoshis = (
|
|
437
453
|
displayValue: string,
|
|
@@ -443,7 +459,9 @@ export const parseDisplayToSatoshis = (
|
|
|
443
459
|
if (!cleaned) return 0
|
|
444
460
|
|
|
445
461
|
if (isFiatCurrency(currency)) {
|
|
446
|
-
const
|
|
462
|
+
const sep = decimalSeparator()
|
|
463
|
+
const normalized = sep === '.' ? cleaned : cleaned.replace(sep, '.')
|
|
464
|
+
const amount = parseFloat(normalized)
|
|
447
465
|
if (isNaN(amount)) return 0
|
|
448
466
|
const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
|
|
449
467
|
if (!(per > 0)) return 0
|
|
@@ -6,11 +6,11 @@
|
|
|
6
6
|
* toolbox at all. `WalletStorageManager.syncFromReader` drives this exactly as it would
|
|
7
7
|
* drive a live remote storage provider.
|
|
8
8
|
*/
|
|
9
|
-
import type
|
|
9
|
+
import { Hash, Utils, type CompletedProtoWallet } from '@bsv/sdk'
|
|
10
10
|
import type { TableSettings } from '@bsv/wallet-toolbox-mobile'
|
|
11
11
|
import type { BackupClient, LogEntry } from './client'
|
|
12
|
-
import {
|
|
13
|
-
import type
|
|
12
|
+
import { decodeEntry, emptyChunk, type AppDataSnapshot, type DecodedEntry } from './codec'
|
|
13
|
+
import { MAX_INDEX_ENTRIES, type BackupChain } from './constants'
|
|
14
14
|
import type { RequestSyncChunkArgs, SyncChunk } from '../toolboxTypes'
|
|
15
15
|
|
|
16
16
|
export class BackupChainError extends Error {
|
|
@@ -33,6 +33,13 @@ export class RemoteSyncReader {
|
|
|
33
33
|
private entries: LogEntry[] | null = null
|
|
34
34
|
private next = 0
|
|
35
35
|
private prefetched: { seq: number, result: Promise<BlobResult> } | null = null
|
|
36
|
+
/** Decoded once, keyed by seq, so verifiedComplete's own look-ahead at the newest entry
|
|
37
|
+
* never re-fetches or re-decrypts it when replay later reaches that same entry. */
|
|
38
|
+
private decodedCache: { seq: number, decoded: DecodedEntry } | null = null
|
|
39
|
+
private verifiedCompletePromise: Promise<boolean> | null = null
|
|
40
|
+
/** The most recent (i.e. furthest along in replay order) appData snapshot seen on any
|
|
41
|
+
* entry so far — see the `appData` getter below. */
|
|
42
|
+
private lastAppData: AppDataSnapshot | undefined
|
|
36
43
|
|
|
37
44
|
constructor (
|
|
38
45
|
private readonly client: BackupClient,
|
|
@@ -50,20 +57,22 @@ export class RemoteSyncReader {
|
|
|
50
57
|
}
|
|
51
58
|
|
|
52
59
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
* log is an ordered recording of chunks that were already produced against those very
|
|
57
|
-
* arguments. Replaying them in order reproduces the original stream exactly, and second
|
|
58
|
-
* -guessing it would risk skipping records.
|
|
60
|
+
* Fetch and verify the index, once. Shared by getSyncChunk (which needs every entry to
|
|
61
|
+
* replay) and verifiedComplete (which only needs to know how many entries exist and what
|
|
62
|
+
* the last one is).
|
|
59
63
|
*/
|
|
60
|
-
async
|
|
64
|
+
private async ensureIndex (): Promise<LogEntry[]> {
|
|
61
65
|
if (this.entries == null) {
|
|
62
66
|
const entries: LogEntry[] = []
|
|
63
67
|
let page = await this.client.index(this.deviceId, this.generation)
|
|
64
68
|
for (;;) {
|
|
65
69
|
const pageStart = entries.length
|
|
66
70
|
entries.push(...page)
|
|
71
|
+
// A malicious/compromised backup host could otherwise keep paging forever — nothing
|
|
72
|
+
// else in this loop depends on the server ever running out of entries to offer.
|
|
73
|
+
if (entries.length > MAX_INDEX_ENTRIES) {
|
|
74
|
+
throw new BackupChainError(`backup index has grown past ${MAX_INDEX_ENTRIES} entries without completing`)
|
|
75
|
+
}
|
|
67
76
|
this.verifyChain(entries, pageStart)
|
|
68
77
|
const missingHead = this.expectedHeadSeq != null && entries.length < this.expectedHeadSeq
|
|
69
78
|
if (page.length === 0) {
|
|
@@ -77,12 +86,11 @@ export class RemoteSyncReader {
|
|
|
77
86
|
// let a retry skip verification or mistake a partial index for completion.
|
|
78
87
|
this.entries = entries
|
|
79
88
|
}
|
|
89
|
+
return this.entries
|
|
90
|
+
}
|
|
80
91
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const entry = this.entries[this.next]
|
|
92
|
+
private async fetchAndDecode (entry: LogEntry): Promise<DecodedEntry> {
|
|
93
|
+
if (this.decodedCache?.seq === entry.seq) return this.decodedCache.decoded
|
|
86
94
|
let ciphertext: Uint8Array
|
|
87
95
|
if (this.prefetched?.seq === entry.seq) {
|
|
88
96
|
const pending = this.prefetched
|
|
@@ -93,13 +101,62 @@ export class RemoteSyncReader {
|
|
|
93
101
|
} else {
|
|
94
102
|
ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
|
|
95
103
|
}
|
|
96
|
-
|
|
104
|
+
// The index is itself server-supplied, but it is fetched from a separate endpoint than
|
|
105
|
+
// the blob body — a malicious or compromised service can serve the wrong (though still
|
|
106
|
+
// authentic, same-wallet) ciphertext at a given sequence while its own index entry for
|
|
107
|
+
// that sequence still carries the digest/size of what that sequence actually holds.
|
|
108
|
+
// Decryption alone cannot catch this: the AEAD envelope authenticates only
|
|
109
|
+
// {chain, chunk, seal} (see codec.ts), never the position a chunk was appended at.
|
|
110
|
+
// Checking the downloaded bytes against the index's own claim for THIS entry, before
|
|
111
|
+
// ever decrypting them, rejects a substituted or reordered blob outright instead of
|
|
112
|
+
// silently replaying it mislabeled.
|
|
113
|
+
if (ciphertext.length !== entry.size) {
|
|
114
|
+
throw new BackupChainError(
|
|
115
|
+
`backup blob at sequence ${entry.seq} is ${ciphertext.length} bytes but the index recorded ${entry.size}`
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
const digest = Utils.toHex(Hash.sha256(Array.from(ciphertext)))
|
|
119
|
+
if (digest !== entry.sha256) {
|
|
120
|
+
throw new BackupChainError(`backup blob at sequence ${entry.seq} does not match the index's recorded digest`)
|
|
121
|
+
}
|
|
122
|
+
return await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Return the next chunk in sequence.
|
|
127
|
+
*
|
|
128
|
+
* `args` is ignored deliberately: a live reader would honour `since` and `offsets`, but a
|
|
129
|
+
* log is an ordered recording of chunks that were already produced against those very
|
|
130
|
+
* arguments. Replaying them in order reproduces the original stream exactly, and second
|
|
131
|
+
* -guessing it would risk skipping records.
|
|
132
|
+
*
|
|
133
|
+
* Every entry is an ordinary chunk (see codec.ts's DecodedEntry) — a seal, when present,
|
|
134
|
+
* rides alongside a chunk rather than replacing it, so nothing here needs to be swallowed.
|
|
135
|
+
*/
|
|
136
|
+
async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
|
|
137
|
+
await this.ensureIndex()
|
|
138
|
+
const entries = this.entries!
|
|
139
|
+
|
|
140
|
+
if (this.next >= entries.length) {
|
|
141
|
+
return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const entry = entries[this.next]
|
|
145
|
+
const decoded = await this.fetchAndDecode(entry)
|
|
146
|
+
// Every appData-carrying chunk is a full snapshot as of its own push (see
|
|
147
|
+
// backup/appData.ts's captureAppDataSnapshot), so the LAST one seen while replaying in
|
|
148
|
+
// order is authoritative — never merged with an earlier one within this same device's
|
|
149
|
+
// own log (unlike restoreOnImport's cross-device merge). An entry that predates this
|
|
150
|
+
// feature, or one written while there was genuinely nothing app-owned to add, carries no
|
|
151
|
+
// `appData` at all and must not erase a still-current snapshot from an earlier entry.
|
|
152
|
+
if (decoded.appData !== undefined) this.lastAppData = decoded.appData
|
|
97
153
|
// Advance only after successful download AND decryption. Retrying this
|
|
98
154
|
// reader after either fails must retry the same entry rather than lose it.
|
|
99
155
|
this.next++
|
|
100
|
-
const following =
|
|
156
|
+
const following = entries[this.next]
|
|
101
157
|
if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
|
|
102
|
-
following.size > 0 && following.size <= PREFETCH_MAX_BYTES
|
|
158
|
+
following.size > 0 && following.size <= PREFETCH_MAX_BYTES &&
|
|
159
|
+
this.decodedCache?.seq !== following.seq) {
|
|
103
160
|
this.prefetched = {
|
|
104
161
|
seq: following.seq,
|
|
105
162
|
// Store failures as values until consumed, so a stopped replay never
|
|
@@ -109,7 +166,8 @@ export class RemoteSyncReader {
|
|
|
109
166
|
)
|
|
110
167
|
}
|
|
111
168
|
}
|
|
112
|
-
|
|
169
|
+
|
|
170
|
+
return decoded.chunk
|
|
113
171
|
}
|
|
114
172
|
|
|
115
173
|
/** Number of chunks in this generation, once the index has been read. */
|
|
@@ -117,6 +175,60 @@ export class RemoteSyncReader {
|
|
|
117
175
|
return this.entries?.length ?? 0
|
|
118
176
|
}
|
|
119
177
|
|
|
178
|
+
/**
|
|
179
|
+
* The most recent appData snapshot seen across every entry replayed through getSyncChunk
|
|
180
|
+
* so far (XR-011). Read by restore.ts once this device's log is fully drained, so it
|
|
181
|
+
* reflects the newest chunk that carried the field — undefined for a log written entirely
|
|
182
|
+
* before this feature shipped, or one with genuinely nothing app-owned to carry.
|
|
183
|
+
*/
|
|
184
|
+
get appData (): AppDataSnapshot | undefined {
|
|
185
|
+
return this.lastAppData
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether this generation's log, as it stands right now, is provably complete — i.e. this
|
|
190
|
+
* device itself once confirmed the generation's initial snapshot was whole, independent of
|
|
191
|
+
* anything the server's index metadata alone reports (see codec.ts's DecodedEntry and
|
|
192
|
+
* push.ts's own seal docs).
|
|
193
|
+
*
|
|
194
|
+
* True only when the NEWEST entry carries a seal for THIS generation whose
|
|
195
|
+
* `initialChunkCount` is no greater than the number of entries in the log — i.e. every
|
|
196
|
+
* chunk of the initial snapshot the seal refers to is present. Cheap by design: only that
|
|
197
|
+
* one entry is decrypted here, never the whole log — replay (getSyncChunk) still decodes
|
|
198
|
+
* every entry as it goes and is what actually enforces the chain end to end.
|
|
199
|
+
*
|
|
200
|
+
* Because every chunk appended after the initial window closes carries the SAME seal (see
|
|
201
|
+
* push.ts's pushOnce), this stays true as further deltas land, rather than flipping back to
|
|
202
|
+
* false the moment a new chunk becomes the newest entry — a generation is not "un-verified"
|
|
203
|
+
* by continuing to receive backups.
|
|
204
|
+
*/
|
|
205
|
+
async verifiedComplete (): Promise<boolean> {
|
|
206
|
+
if (this.verifiedCompletePromise == null) {
|
|
207
|
+
this.verifiedCompletePromise = this.computeVerifiedComplete()
|
|
208
|
+
}
|
|
209
|
+
return await this.verifiedCompletePromise
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private async computeVerifiedComplete (): Promise<boolean> {
|
|
213
|
+
const entries = await this.ensureIndex()
|
|
214
|
+
if (entries.length === 0) return false
|
|
215
|
+
|
|
216
|
+
const last = entries[entries.length - 1]
|
|
217
|
+
let decoded: DecodedEntry
|
|
218
|
+
try {
|
|
219
|
+
decoded = await this.fetchAndDecode(last)
|
|
220
|
+
} catch {
|
|
221
|
+
// A last entry that fails to download or decrypt cannot be trusted as sealed —
|
|
222
|
+
// treat the generation as unverified rather than throwing out of a check that
|
|
223
|
+
// pickTarget uses purely to rank candidates.
|
|
224
|
+
return false
|
|
225
|
+
}
|
|
226
|
+
this.decodedCache = { seq: last.seq, decoded }
|
|
227
|
+
const seal = decoded.seal
|
|
228
|
+
if (seal == null) return false
|
|
229
|
+
return seal.generation === this.generation && seal.initialChunkCount <= entries.length
|
|
230
|
+
}
|
|
231
|
+
|
|
120
232
|
/**
|
|
121
233
|
* Reject a log with a gap or a fork before any of it is replayed.
|
|
122
234
|
*
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app-owned recovery-critical rows that ride alongside a pushed sync chunk, as the
|
|
3
|
+
* additive `appData` envelope field (see codec.ts's encodeChunk/decodeEntry).
|
|
4
|
+
*
|
|
5
|
+
* XR-011: `codec.ts`'s twelve CHUNK_ENTITIES are all toolbox-owned tables — nothing here ever
|
|
6
|
+
* touches key_value_store, so a receiver's acknowledged-but-not-yet-internalized Nearby/QR
|
|
7
|
+
* PaymentFrame (localpay_pending) and an outbound PeerPay token's delivery checkpoint
|
|
8
|
+
* (peerpay_outbox) were never backed up at all: a device loss before internalize/delivery
|
|
9
|
+
* completed stranded them permanently, even with a perfect seed+backup restore of everything
|
|
10
|
+
* else. XR-055 adds a third row, the durable issued-conventional-receive-date history
|
|
11
|
+
* (pay/receiveHistory.ts), for the same reason: it also lives only in key_value_store.
|
|
12
|
+
*
|
|
13
|
+
* This module is the ONLY place these rows cross from local storage into the backup log and
|
|
14
|
+
* back. It deliberately knows nothing about how to internalize a payment, retry a delivery,
|
|
15
|
+
* or sweep an address — `applyAppData` does exactly one thing, write rows back to
|
|
16
|
+
* key_value_store, so a replayed row is picked up by the SAME existing consumers (the
|
|
17
|
+
* background pending-queue effect, the outbox's own retry UI, the recovery sweep) through
|
|
18
|
+
* their own existing guards, exactly as if this device had written the row itself while
|
|
19
|
+
* briefly offline. Nothing here ever calls internalizeAction, broadcasts, or releases an
|
|
20
|
+
* input.
|
|
21
|
+
*
|
|
22
|
+
* Deferred out of this pass (see XR-011's ledger row): `offline_actions` and
|
|
23
|
+
* `token_linkage_payloads` are real SQL tables, not key_value_store blobs — replaying them
|
|
24
|
+
* needs a userId remap (their FK is device-local) and, for offline_actions, a decision on
|
|
25
|
+
* how a restored row's local `seq` should interleave with whatever this fresh device's own
|
|
26
|
+
* autoincrement has already assigned. Both are tractable but are a separate, larger change
|
|
27
|
+
* from the three KV rows here, which is why they are not included yet.
|
|
28
|
+
*
|
|
29
|
+
* KNOWN, STILL-OPEN GAP (see XR-011's reviewer follow-up): a row written here is only ever
|
|
30
|
+
* actually PERSISTED to the backup log on a push whose CHUNK already carries a real toolbox-
|
|
31
|
+
* entity change — see push.ts's own comment at its `captureAppDataSnapshot` call and
|
|
32
|
+
* codec.ts's encodeChunk docs for why (an appData-only entry, with every entity array empty,
|
|
33
|
+
* would trip the toolbox's own processSyncChunk completion sentinel for a downstream reader
|
|
34
|
+
* that doesn't yet understand this field). That means the row's own headline scenario — an
|
|
35
|
+
* acknowledged Nearby/QR payment, a PeerPay delivery checkpoint, or an issued receive date,
|
|
36
|
+
* with NOTHING ELSE touching an entity table in that same window — is NOT covered: the row
|
|
37
|
+
* stays local-only until some unrelated entity-bearing push happens to close a later window,
|
|
38
|
+
* which may never occur before the device is lost. This is pinned end-to-end (not merely at
|
|
39
|
+
* the pushOnce-unit level) by
|
|
40
|
+
* __tests__/backup/appDataIsolatedActivity.test.ts. Closing it for real needs either a
|
|
41
|
+
* dedicated appData-only log-entry shape — safe only once every device in the fleet is known
|
|
42
|
+
* to run a build that understands it — or a separate backup-server channel outside the
|
|
43
|
+
* per-device chunk log; both are wire/server changes shared with other devices, not a
|
|
44
|
+
* same-device code fix, so they are recorded here as an open design delta rather than
|
|
45
|
+
* attempted.
|
|
46
|
+
*/
|
|
47
|
+
import { OUTBOX_KEY } from '../peerpay/outbox'
|
|
48
|
+
import { PENDING_KEY } from '../localpay/pending'
|
|
49
|
+
import { getIssuedDates, setIssuedDates } from '../pay/receiveHistory'
|
|
50
|
+
import type { AppDataSnapshot } from './codec'
|
|
51
|
+
|
|
52
|
+
export interface KVStorage {
|
|
53
|
+
getKeyValue (k: string): Promise<string | undefined>
|
|
54
|
+
setKeyValue (k: string, v: string): Promise<void>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** True for `undefined` or a snapshot carrying nothing at all — the common "nothing queued,
|
|
58
|
+
* nothing to add" case, which must produce no `appData` field at all (see codec.ts's
|
|
59
|
+
* encodeChunk docs on why an unsealed/appData-less chunk must serialise byte-for-byte as the
|
|
60
|
+
* old-format envelope). */
|
|
61
|
+
export function isEmptyAppData (appData: AppDataSnapshot | undefined): boolean {
|
|
62
|
+
return (
|
|
63
|
+
appData == null ||
|
|
64
|
+
(appData.localpayPending === undefined &&
|
|
65
|
+
appData.peerpayOutbox === undefined &&
|
|
66
|
+
(appData.receiveIssuedDates?.length ?? 0) === 0)
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Read the current value of every app-owned recovery-critical row, straight off local
|
|
72
|
+
* storage, for pushOnce to fold into the same envelope as whatever chunk it is about to
|
|
73
|
+
* send. Never called on its own cadence — see codec.ts's encodeChunk docs on why appData
|
|
74
|
+
* only ever rides an already-non-empty chunk.
|
|
75
|
+
*/
|
|
76
|
+
export async function captureAppDataSnapshot (storage: KVStorage): Promise<AppDataSnapshot> {
|
|
77
|
+
const [localpayPending, peerpayOutbox, receiveIssuedDates] = await Promise.all([
|
|
78
|
+
storage.getKeyValue(PENDING_KEY),
|
|
79
|
+
storage.getKeyValue(OUTBOX_KEY),
|
|
80
|
+
getIssuedDates(storage)
|
|
81
|
+
])
|
|
82
|
+
const snapshot: AppDataSnapshot = {}
|
|
83
|
+
if (localpayPending !== undefined) snapshot.localpayPending = localpayPending
|
|
84
|
+
if (peerpayOutbox !== undefined) snapshot.peerpayOutbox = peerpayOutbox
|
|
85
|
+
if (receiveIssuedDates.length > 0) snapshot.receiveIssuedDates = receiveIssuedDates
|
|
86
|
+
return snapshot
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Apply a decoded snapshot to local storage. The ONLY effect of a restore replaying appData
|
|
91
|
+
* — three plain key_value_store writes, nothing else. Skips a field the snapshot did not
|
|
92
|
+
* carry (rather than overwriting with nothing), so replaying an OLDER chunk's appData after
|
|
93
|
+
* a newer one already landed (e.g. re-running an interrupted restore) can never regress a
|
|
94
|
+
* row that a later chunk already updated in this same pass.
|
|
95
|
+
*/
|
|
96
|
+
export async function applyAppData (storage: KVStorage, snapshot: AppDataSnapshot): Promise<void> {
|
|
97
|
+
if (snapshot.localpayPending !== undefined) await storage.setKeyValue(PENDING_KEY, snapshot.localpayPending)
|
|
98
|
+
if (snapshot.peerpayOutbox !== undefined) await storage.setKeyValue(OUTBOX_KEY, snapshot.peerpayOutbox)
|
|
99
|
+
if (snapshot.receiveIssuedDates !== undefined && snapshot.receiveIssuedDates.length > 0) {
|
|
100
|
+
await setIssuedDates(storage, snapshot.receiveIssuedDates)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Parses a KV row's raw JSON text into an array of plain objects, never throwing — a
|
|
105
|
+
* corrupt or missing blob merges as if it were empty rather than failing the whole restore. */
|
|
106
|
+
function parseJsonArray (raw: string | undefined): Array<Record<string, unknown>> { // eslint-disable-line @typescript-eslint/array-type
|
|
107
|
+
if (raw === undefined) return []
|
|
108
|
+
try {
|
|
109
|
+
const parsed = JSON.parse(raw) as unknown
|
|
110
|
+
return Array.isArray(parsed) ? (parsed as Array<Record<string, unknown>>) : [] // eslint-disable-line @typescript-eslint/array-type
|
|
111
|
+
} catch {
|
|
112
|
+
return []
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Union two same-shaped `id`-keyed JSON-array KV blobs (localpay_pending / peerpay_outbox),
|
|
118
|
+
* keeping every distinct entry from both sides. Used only when restoring more than one
|
|
119
|
+
* device's own backup log into the same storage (XR-015): each device's own queue is an
|
|
120
|
+
* independent, non-overlapping history exactly like the toolbox's own entity tables are —
|
|
121
|
+
* restoring only the highest-ranked device's snapshot would silently drop whatever a second
|
|
122
|
+
* device alone was still holding (e.g. a Nearby payment received on a phone that was never
|
|
123
|
+
* the "primary" device in the manifest).
|
|
124
|
+
*
|
|
125
|
+
* On an id collision the FIRST side's entry wins, matching restoreOnImport's own device
|
|
126
|
+
* iteration order (primary device folded in first) — irrelevant in practice, since two
|
|
127
|
+
* devices sharing a seed cannot mint the same PaymentPending/OutboxEntry id (both are
|
|
128
|
+
* `${timestamp}_${keyPrefix}`-derived per device), but keeps the merge total rather than
|
|
129
|
+
* throwing on a theoretical collision.
|
|
130
|
+
*/
|
|
131
|
+
function mergeJsonArrayById (a: string | undefined, b: string | undefined): string | undefined {
|
|
132
|
+
if (a === undefined) return b
|
|
133
|
+
if (b === undefined) return a
|
|
134
|
+
const merged = new Map<string, Record<string, unknown>>()
|
|
135
|
+
for (const item of [...parseJsonArray(a), ...parseJsonArray(b)]) {
|
|
136
|
+
const id = typeof item.id === 'string' ? item.id : JSON.stringify(item)
|
|
137
|
+
if (!merged.has(id)) merged.set(id, item)
|
|
138
|
+
}
|
|
139
|
+
return JSON.stringify([...merged.values()])
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Merge two snapshots — see mergeJsonArrayById for why this is a union rather than a
|
|
144
|
+
* last-write-wins overwrite. `restoreOnImport` folds every device's own final appData
|
|
145
|
+
* together this way before the single `applyAppData` call that actually reaches storage, so
|
|
146
|
+
* no one device's snapshot can clobber another's.
|
|
147
|
+
*/
|
|
148
|
+
export function mergeAppData (a: AppDataSnapshot | undefined, b: AppDataSnapshot | undefined): AppDataSnapshot {
|
|
149
|
+
return {
|
|
150
|
+
localpayPending: mergeJsonArrayById(a?.localpayPending, b?.localpayPending),
|
|
151
|
+
peerpayOutbox: mergeJsonArrayById(a?.peerpayOutbox, b?.peerpayOutbox),
|
|
152
|
+
receiveIssuedDates:
|
|
153
|
+
a?.receiveIssuedDates === undefined && b?.receiveIssuedDates === undefined
|
|
154
|
+
? undefined
|
|
155
|
+
: [...new Set([...(a?.receiveIssuedDates ?? []), ...(b?.receiveIssuedDates ?? [])])].sort()
|
|
156
|
+
}
|
|
157
|
+
}
|
package/core/backup/client.ts
CHANGED
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
type Limits,
|
|
31
31
|
type LogEntry
|
|
32
32
|
} from '@bsv/backup-cache-client'
|
|
33
|
-
import type
|
|
33
|
+
import { MAX_RESTORE_RESPONSE_BYTES, type BackupChain } from './constants'
|
|
34
34
|
import { deriveBackupWallet } from './derive'
|
|
35
35
|
|
|
36
36
|
export { BackupHttpError, ERR_BLOB_TOO_LARGE, ERR_SEQ_CONFLICT }
|
|
@@ -135,6 +135,20 @@ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch
|
|
|
135
135
|
}
|
|
136
136
|
|
|
137
137
|
const response = await bounded(() => transport(input, { ...init, signal: controller.signal }))
|
|
138
|
+
// Refuse before EITHER reader is ever wrapped, let alone called: on this platform fetch
|
|
139
|
+
// has no incremental/streaming read mode (see this function's own docstring), so a
|
|
140
|
+
// declared-oversized body can only be bounded here, never partway through reading it.
|
|
141
|
+
// A response that omits Content-Length entirely passes through unchanged — a documented
|
|
142
|
+
// residual gap (see MAX_RESTORE_RESPONSE_BYTES), not a false rejection of ordinary
|
|
143
|
+
// traffic that happens not to declare a length.
|
|
144
|
+
const declaredLength = Number(response.headers.get('content-length'))
|
|
145
|
+
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_RESPONSE_BYTES) {
|
|
146
|
+
throw new BackupHttpError(
|
|
147
|
+
response.status,
|
|
148
|
+
'ERR_RESPONSE_TOO_LARGE',
|
|
149
|
+
`response declared ${declaredLength} bytes, over the ${MAX_RESTORE_RESPONSE_BYTES}-byte restore cap`
|
|
150
|
+
)
|
|
151
|
+
}
|
|
138
152
|
const readJson = response.json.bind(response)
|
|
139
153
|
const readArrayBuffer = response.arrayBuffer.bind(response)
|
|
140
154
|
response.json = () => bounded(readJson)
|