@bsv/expo-wallet-toolbox 0.5.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.
Files changed (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -6,15 +6,12 @@
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 { CompletedProtoWallet } from '@bsv/sdk'
10
- import type {
11
- RequestSyncChunkArgs,
12
- SyncChunk
13
- } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
14
- import type { TableSettings } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
9
+ import { Hash, Utils, type CompletedProtoWallet } from '@bsv/sdk'
10
+ import type { TableSettings } from '@bsv/wallet-toolbox-mobile'
15
11
  import type { BackupClient, LogEntry } from './client'
16
- import { decodeChunk, emptyChunk } from './codec'
17
- import type { BackupChain } from './constants'
12
+ import { decodeEntry, emptyChunk, type AppDataSnapshot, type DecodedEntry } from './codec'
13
+ import { MAX_INDEX_ENTRIES, type BackupChain } from './constants'
14
+ import type { RequestSyncChunkArgs, SyncChunk } from '../toolboxTypes'
18
15
 
19
16
  export class BackupChainError extends Error {
20
17
  constructor (message: string) {
@@ -36,6 +33,13 @@ export class RemoteSyncReader {
36
33
  private entries: LogEntry[] | null = null
37
34
  private next = 0
38
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
39
43
 
40
44
  constructor (
41
45
  private readonly client: BackupClient,
@@ -53,20 +57,22 @@ export class RemoteSyncReader {
53
57
  }
54
58
 
55
59
  /**
56
- * Return the next chunk in sequence.
57
- *
58
- * `args` is ignored deliberately: a live reader would honour `since` and `offsets`, but a
59
- * log is an ordered recording of chunks that were already produced against those very
60
- * arguments. Replaying them in order reproduces the original stream exactly, and second
61
- * -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).
62
63
  */
63
- async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
64
+ private async ensureIndex (): Promise<LogEntry[]> {
64
65
  if (this.entries == null) {
65
66
  const entries: LogEntry[] = []
66
67
  let page = await this.client.index(this.deviceId, this.generation)
67
68
  for (;;) {
68
69
  const pageStart = entries.length
69
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
+ }
70
76
  this.verifyChain(entries, pageStart)
71
77
  const missingHead = this.expectedHeadSeq != null && entries.length < this.expectedHeadSeq
72
78
  if (page.length === 0) {
@@ -80,12 +86,11 @@ export class RemoteSyncReader {
80
86
  // let a retry skip verification or mistake a partial index for completion.
81
87
  this.entries = entries
82
88
  }
89
+ return this.entries
90
+ }
83
91
 
84
- if (this.next >= this.entries.length) {
85
- return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
86
- }
87
-
88
- 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
89
94
  let ciphertext: Uint8Array
90
95
  if (this.prefetched?.seq === entry.seq) {
91
96
  const pending = this.prefetched
@@ -96,13 +101,62 @@ export class RemoteSyncReader {
96
101
  } else {
97
102
  ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
98
103
  }
99
- const chunk = await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
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
100
153
  // Advance only after successful download AND decryption. Retrying this
101
154
  // reader after either fails must retry the same entry rather than lose it.
102
155
  this.next++
103
- const following = this.entries[this.next]
156
+ const following = entries[this.next]
104
157
  if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
105
- following.size > 0 && following.size <= PREFETCH_MAX_BYTES) {
158
+ following.size > 0 && following.size <= PREFETCH_MAX_BYTES &&
159
+ this.decodedCache?.seq !== following.seq) {
106
160
  this.prefetched = {
107
161
  seq: following.seq,
108
162
  // Store failures as values until consumed, so a stopped replay never
@@ -112,7 +166,8 @@ export class RemoteSyncReader {
112
166
  )
113
167
  }
114
168
  }
115
- return chunk
169
+
170
+ return decoded.chunk
116
171
  }
117
172
 
118
173
  /** Number of chunks in this generation, once the index has been read. */
@@ -120,6 +175,60 @@ export class RemoteSyncReader {
120
175
  return this.entries?.length ?? 0
121
176
  }
122
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
+
123
232
  /**
124
233
  * Reject a log with a gap or a fork before any of it is replayed.
125
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
+ }
@@ -30,7 +30,7 @@ import {
30
30
  type Limits,
31
31
  type LogEntry
32
32
  } from '@bsv/backup-cache-client'
33
- import type { BackupChain } from './constants'
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)
@@ -16,12 +16,12 @@
16
16
  */
17
17
  import type { CompletedProtoWallet } from '@bsv/sdk'
18
18
  import { Utils } from '@bsv/sdk'
19
- import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
20
19
  import {
21
20
  parseJsonRpc,
22
21
  stringifyJsonRpc
23
- } from '@bsv/wallet-toolbox-mobile/out/src/storage/remoting/BinaryJson'
22
+ } from '@bsv/wallet-toolbox-mobile'
24
23
  import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
24
+ import type { SyncChunk } from '../toolboxTypes'
25
25
 
26
26
  /**
27
27
  * Minimum length before a numeric array is worth packing as bytes.
@@ -99,6 +99,25 @@ export function estimateEncodedBytes (chunk: SyncChunk): number {
99
99
  return bytes
100
100
  }
101
101
 
102
+ /**
103
+ * Cheap lower bound on how many extra bytes an appData snapshot adds to an encoded chunk.
104
+ *
105
+ * Mirrors estimateEncodedBytes' own "must run before encoding" purpose: pushOnce's oversize
106
+ * gate checks the CHUNK alone today, but appData rides in the same envelope (see
107
+ * encodeChunk), so a large pending/outbox queue must count too or a doomed payload could
108
+ * still slip past the gate it exists to short-circuit. appData's strings are already
109
+ * serialised JSON (see backup/appData.ts), so — unlike packBytes' byte-array packing — there
110
+ * is no cheaper encoding to model here: this is a plain length sum, which is exact for
111
+ * strings and an underestimate only in the same way estimateEncodedBytes' own walk is (JSON
112
+ * quoting/escaping is ignored).
113
+ */
114
+ export function estimateAppDataBytes (appData: AppDataSnapshot | undefined): number {
115
+ if (appData == null) return 0
116
+ let bytes = (appData.localpayPending?.length ?? 0) + (appData.peerpayOutbox?.length ?? 0)
117
+ for (const d of appData.receiveIssuedDates ?? []) bytes += d.length
118
+ return bytes
119
+ }
120
+
102
121
  /** The table columns the toolbox types as Date. BinaryJson has no Date support:
103
122
  * encode writes them as ISO strings, so decode must revive them — the merge
104
123
  * entities call `.getTime()`/date arithmetic on them directly
@@ -123,7 +142,49 @@ function unpackBytes (value: unknown, key?: string): unknown {
123
142
  }
124
143
 
125
144
  /**
126
- * Serialise and encrypt a sync chunk.
145
+ * A seal's own payload: the generation it vouches for, and how many chunks made up that
146
+ * generation's initial snapshot — the count the reader needs to see before it can call the
147
+ * generation whole. Carried as an extra field on an ORDINARY chunk envelope (see
148
+ * encodeChunk), never as a separate log entry: an old build's decodeChunk ignores a field it
149
+ * has never heard of, so a chunk carrying a seal is byte-for-byte a chunk to any reader that
150
+ * predates sealing.
151
+ */
152
+ export interface BackupSeal {
153
+ generation: number
154
+ initialChunkCount: number
155
+ }
156
+
157
+ /**
158
+ * App-owned recovery-critical state carried alongside a chunk, additively, the same way
159
+ * `seal` is (see encodeChunk/decodeEntry below) — never a separate log entry, so an old
160
+ * reader that predates this field decodes the envelope exactly as it always has.
161
+ *
162
+ * This type is deliberately generic: it is just what the envelope carries. What populates
163
+ * and consumes it — reading/writing key_value_store, merging across devices — lives in
164
+ * backup/appData.ts, which is the only module that needs to know these rows exist (XR-011,
165
+ * XR-055). Every field is a plain string or string array — none of them needs `packBytes`'
166
+ * treatment, because a payment/outbox queue's own (de)serialisers (localpay/pending.ts,
167
+ * peerpay/outbox.ts) already write plain-JSON, byte-array-as-number[] text.
168
+ */
169
+ export interface AppDataSnapshot {
170
+ /** Verbatim value of key_value_store['localpay_pending'] at push time. */
171
+ localpayPending?: string
172
+ /** Verbatim value of key_value_store['peerpay_outbox'] at push time. */
173
+ peerpayOutbox?: string
174
+ /** Every YYYY-MM-DD a conventional-receive address has been issued for, deduplicated. */
175
+ receiveIssuedDates?: string[]
176
+ }
177
+
178
+ /**
179
+ * What a decrypted log entry turns out to be: always an ordinary chunk, optionally carrying
180
+ * a seal and/or an appData snapshot alongside it. There is no other entry shape any writer
181
+ * has ever appended — this type exists mainly so RemoteSyncReader can read `seal`/`appData`
182
+ * off an entry without re-decoding it a second time.
183
+ */
184
+ export type DecodedEntry = { kind: 'chunk', chunk: SyncChunk, seal?: BackupSeal, appData?: AppDataSnapshot }
185
+
186
+ /**
187
+ * Serialise and encrypt a sync chunk, optionally sealing a generation in the same envelope.
127
188
  *
128
189
  * `counterparty: 'self'` is the entire zero-knowledge property. With 'self' the symmetric
129
190
  * key comes from the wallet's own key material and nobody else can derive it; naming the
@@ -134,13 +195,28 @@ function unpackBytes (value: unknown, key?: string): unknown {
134
195
  * blob written on one network cannot decrypt on another at all. The plaintext also carries
135
196
  * a `chain` label, which decodeChunk asserts — belt and braces so that even a future
136
197
  * derivation mistake that collapsed the keys back together could not cross-restore.
198
+ *
199
+ * `seal` (and, likewise, `appData` — XR-011) is folded into the SAME `{chain, chunk}`
200
+ * envelope as an optional extra field, rather than appended as a separate log entry. A
201
+ * dedicated marker entry is unsafe for a reader that predates it: an all-empty chunk trips
202
+ * the toolbox's own done sentinel, and any OTHER shape crashes an old decodeChunk outright
203
+ * (see push.ts's own module docstring for the incident this replaced). `JSON.stringify`
204
+ * drops an `undefined` property, so a chunk with nothing new to carry in either field
205
+ * serialises to the exact old-format envelope, byte for byte. `appData` deliberately never
206
+ * rides on its own, entity-less chunk either: pushOnce only calls this once it already has a
207
+ * genuinely non-empty chunk to send, because the toolbox's own `processSyncChunk` treats
208
+ * EVERY entity array being empty as its completion sentinel regardless of position in the
209
+ * log (see push.ts's own docs) — an intentionally-empty-of-entities appended entry would
210
+ * make a live restore stop early and silently drop whatever was appended after it.
137
211
  */
138
212
  export async function encodeChunk (
139
213
  wallet: CompletedProtoWallet,
140
214
  chunk: SyncChunk,
141
- chain: BackupChain
215
+ chain: BackupChain,
216
+ seal?: BackupSeal,
217
+ appData?: AppDataSnapshot
142
218
  ): Promise<number[]> {
143
- const json = stringifyJsonRpc({ chain, chunk: packBytes(chunk) }, true)
219
+ const json = stringifyJsonRpc({ chain, chunk: packBytes(chunk), seal, appData }, true)
144
220
  const { ciphertext } = await wallet.encrypt({
145
221
  plaintext: Utils.toArray(json, 'utf8'),
146
222
  protocolID: BACKUP_PROTOCOL,
@@ -151,27 +227,89 @@ export async function encodeChunk (
151
227
  }
152
228
 
153
229
  /**
154
- * Decrypt and parse a sync chunk. Throws if the ciphertext was not written by this key,
155
- * or if the decrypted payload's chain label disagrees with the chain being restored.
230
+ * Decrypt a log entry, returning its chunk and — when present — the seal and/or appData
231
+ * riding alongside it. Throws if the ciphertext was not written by this key, if the
232
+ * decrypted payload's chain label disagrees with the chain being restored, or if a present
233
+ * `seal`/`appData` field is malformed.
234
+ *
235
+ * Old-format ciphertext — written before sealing/appData existed, with no such field at all
236
+ * — decodes unchanged: `envelope.seal`/`envelope.appData` is `undefined`, so each is omitted
237
+ * from the result exactly as it always was.
156
238
  */
157
- export async function decodeChunk (
239
+ export async function decodeEntry (
158
240
  wallet: CompletedProtoWallet,
159
241
  ciphertext: number[],
160
242
  chain: BackupChain
161
- ): Promise<SyncChunk> {
243
+ ): Promise<DecodedEntry> {
162
244
  const { plaintext } = await wallet.decrypt({
163
245
  ciphertext,
164
246
  protocolID: BACKUP_PROTOCOL,
165
247
  keyID: backupKeyId(chain),
166
248
  counterparty: 'self'
167
249
  })
168
- const envelope = parseJsonRpc(Utils.toUTF8(plaintext), true) as { chain?: unknown, chunk?: unknown }
250
+ const envelope = parseJsonRpc(Utils.toUTF8(plaintext), true) as {
251
+ chain?: unknown
252
+ chunk?: unknown
253
+ seal?: unknown
254
+ appData?: unknown
255
+ }
169
256
  if (envelope?.chain !== chain) {
170
257
  throw new Error(
171
258
  `backup blob is labeled for chain '${String(envelope?.chain)}' but '${chain}' was expected — refusing to restore across networks`
172
259
  )
173
260
  }
174
- return unpackBytes(envelope.chunk) as SyncChunk
261
+ let seal: BackupSeal | undefined
262
+ if (envelope.seal != null) {
263
+ const s = envelope.seal as { generation?: unknown, initialChunkCount?: unknown }
264
+ if (typeof s.generation !== 'number' || typeof s.initialChunkCount !== 'number') {
265
+ throw new Error('backup seal is malformed')
266
+ }
267
+ seal = { generation: s.generation, initialChunkCount: s.initialChunkCount }
268
+ }
269
+ const appData = decodeAppData(envelope.appData)
270
+ return { kind: 'chunk', chunk: unpackBytes(envelope.chunk) as SyncChunk, seal, appData }
271
+ }
272
+
273
+ /** Validates a decrypted envelope's `appData` field. Throws rather than silently dropping a
274
+ * malformed field: an app-owned recovery row that failed to decode as claimed must stop the
275
+ * restore, not quietly disappear (same failure posture as a malformed seal, above). */
276
+ function decodeAppData (raw: unknown): AppDataSnapshot | undefined {
277
+ if (raw == null) return undefined
278
+ const a = raw as { localpayPending?: unknown, peerpayOutbox?: unknown, receiveIssuedDates?: unknown }
279
+ if (a.localpayPending !== undefined && typeof a.localpayPending !== 'string') {
280
+ throw new Error('backup appData.localpayPending is malformed')
281
+ }
282
+ if (a.peerpayOutbox !== undefined && typeof a.peerpayOutbox !== 'string') {
283
+ throw new Error('backup appData.peerpayOutbox is malformed')
284
+ }
285
+ if (
286
+ a.receiveIssuedDates !== undefined &&
287
+ (!Array.isArray(a.receiveIssuedDates) || !a.receiveIssuedDates.every(d => typeof d === 'string'))
288
+ ) {
289
+ throw new Error('backup appData.receiveIssuedDates is malformed')
290
+ }
291
+ return {
292
+ localpayPending: a.localpayPending as string | undefined,
293
+ peerpayOutbox: a.peerpayOutbox as string | undefined,
294
+ receiveIssuedDates: a.receiveIssuedDates as string[] | undefined
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Decrypt and parse a sync chunk. Throws if the ciphertext was not written by this key, or
300
+ * if the decrypted payload's chain label disagrees with the chain being restored.
301
+ *
302
+ * Kept as a thin wrapper over decodeEntry — RemoteSyncReader now calls decodeEntry directly
303
+ * so it can also read a chunk's seal, but this stays exported with its original signature
304
+ * and behaviour so existing callers (and the codec round-trip tests) are unaffected.
305
+ */
306
+ export async function decodeChunk (
307
+ wallet: CompletedProtoWallet,
308
+ ciphertext: number[],
309
+ chain: BackupChain
310
+ ): Promise<SyncChunk> {
311
+ const decoded = await decodeEntry(wallet, ciphertext, chain)
312
+ return decoded.chunk
175
313
  }
176
314
 
177
315
  /** The twelve entity arrays a SyncChunk carries, in the protocol's dependency order. */
@@ -80,9 +80,38 @@ export const MIN_PUSH_INTERVAL_MS = 60_000
80
80
  */
81
81
  export const MAX_BLOB_BYTES = 1 << 20
82
82
 
83
+ /**
84
+ * Hard ceiling on a single restore-side HTTP response body, enforced against the
85
+ * Content-Length header before any transport call materializes it.
86
+ *
87
+ * Independent of the server's own advertised cap (`client.limits().maxBlobBytes`, up to
88
+ * 200 MiB) — this exists so a malicious or compromised backup host cannot exhaust mobile
89
+ * memory merely by declaring (and then sending) an oversized body. React Native's fetch has
90
+ * no incremental/streaming read mode (see client.ts's withBackupRequestTimeout), so the
91
+ * only point at which an oversized body can be bounded at all is before it is ever
92
+ * requested to be read — hence the check runs on the header, not the bytes.
93
+ */
94
+ export const MAX_RESTORE_RESPONSE_BYTES = 64 * 1024 * 1024
95
+
96
+ /**
97
+ * Hard ceiling on how many entries a single generation's index may accumulate across pages.
98
+ *
99
+ * `INDEX_PAGE_SIZE` (RemoteSyncReader.ts) is only a server-supplied paging hint — a
100
+ * malicious or compromised backup host could otherwise keep returning full pages forever,
101
+ * growing `entries[]` without bound. Far beyond any real wallet's expected chunk count:
102
+ * `GENERATION_CHUNK_THRESHOLD` rotates a generation long before this many chunks land.
103
+ */
104
+ export const MAX_INDEX_ENTRIES = 50_000
105
+
83
106
  /** AsyncStorage keys. */
84
107
  export const DEVICE_ID_KEY = 'backupDeviceId'
85
108
  // The chain is redundant with the pseudonym (which already differs per chain) but explicit:
86
109
  // a cursor must never be consulted for the wrong network's database.
110
+ //
111
+ // Exported separately from cursorKey so a caller that wants EVERY device's cursor for one
112
+ // identity — e.g. a Wallet Check that must not see a different (departed) wallet's leftover
113
+ // cursor on the same install — can scan by prefix without needing this device's own id.
114
+ export const cursorKeyPrefix = (chain: BackupChain, pseudonym: string): string =>
115
+ `backupCursor-${chain}-${pseudonym}-`
87
116
  export const cursorKey = (chain: BackupChain, pseudonym: string, deviceId: string): string =>
88
- `backupCursor-${chain}-${pseudonym}-${deviceId}`
117
+ `${cursorKeyPrefix(chain, pseudonym)}${deviceId}`