@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.
Files changed (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  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/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -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}`
@@ -65,6 +65,25 @@ export interface PushCursor {
65
65
  prevSha256?: string
66
66
  /** Chunks appended in this generation, used to decide when to rotate. */
67
67
  chunksInGeneration: number
68
+ /**
69
+ * How many chunks made up this generation's initial snapshot, set the moment that first
70
+ * window closes (the isEmptyChunk branch in pushOnce that advances `since`) to
71
+ * `chunksInGeneration` as it stands at that instant.
72
+ *
73
+ * Undefined for a generation still mid-way through its first window — there is nothing
74
+ * coherent to seal yet. Reset to undefined on rotation, same as every other per-generation
75
+ * field. Every chunk appended once this is defined carries a seal referencing it (see
76
+ * push.ts), so later deltas keep the generation provably complete rather than only its
77
+ * first snapshot.
78
+ */
79
+ initialChunkCount?: number
80
+ /**
81
+ * The highest wall-clock value this device has ever observed at the start of a push
82
+ * pass, independent of `since`/`maxUpdatedAt` — see pushOnce's own clock-regression guard.
83
+ * Undefined for a cursor written before this field existed; pushOnce treats that as "no
84
+ * known ceiling yet" rather than as evidence of a rollback.
85
+ */
86
+ maxObservedWallClock?: string
68
87
  }
69
88
 
70
89
  export function freshCursor (generation = 1): PushCursor {
@@ -75,7 +94,9 @@ export function freshCursor (generation = 1): PushCursor {
75
94
  generation,
76
95
  seq: 0,
77
96
  prevSha256: undefined,
78
- chunksInGeneration: 0
97
+ chunksInGeneration: 0,
98
+ initialChunkCount: undefined,
99
+ maxObservedWallClock: undefined
79
100
  }
80
101
  }
81
102
 
@@ -106,7 +127,15 @@ export async function loadCursor (chain: BackupChain, pseudonym: string, deviceI
106
127
  generation: parsed.generation ?? 1,
107
128
  seq: parsed.seq ?? 0,
108
129
  prevSha256: parsed.prevSha256,
109
- chunksInGeneration: parsed.chunksInGeneration ?? 0
130
+ chunksInGeneration: parsed.chunksInGeneration ?? 0,
131
+ // Absent on every cursor written before sealing existed — that is exactly the
132
+ // back-fill case push.ts's pushOnce checks for, so it must default to undefined,
133
+ // never to chunksInGeneration here (the back-fill only happens once `since` is
134
+ // known to be set too, which pushOnce itself checks).
135
+ initialChunkCount: parsed.initialChunkCount,
136
+ // Absent on every cursor written before the clock-regression guard existed — treated
137
+ // as "no known ceiling yet" by pushOnce, never as evidence of a rollback.
138
+ maxObservedWallClock: parsed.maxObservedWallClock
110
139
  }
111
140
  } catch {
112
141
  // A corrupt cursor must not wedge backups forever. Starting a fresh generation costs
@@ -16,8 +16,9 @@
16
16
  * pass.
17
17
  */
18
18
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
19
+ import { captureAppDataSnapshot, isEmptyAppData } from './appData'
19
20
  import { BackupClient, BackupHttpError, ERR_SEQ_CONFLICT } from './client'
20
- import { encodeChunk, estimateEncodedBytes, isEmptyChunk } from './codec'
21
+ import { encodeChunk, estimateAppDataBytes, estimateEncodedBytes, isEmptyChunk, type BackupSeal } from './codec'
21
22
  import { GENERATION_CHUNK_THRESHOLD, MAX_ITEMS, MAX_ROUGH_SIZE, type BackupChain } from './constants'
22
23
  import {
23
24
  ENTITY_NAMES,
@@ -89,6 +90,37 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
89
90
 
90
91
  let cursor = await loadCursor(deps.chain, pseudonym, deviceId)
91
92
 
93
+ // Clock-regression guard: `since` only ever advances forward via nextInstant, and the
94
+ // column comparison is `>=`, so a record stamped BELOW a window this cursor already
95
+ // closed can never be selected by any future incremental pass — the exact scenario a
96
+ // backward-moving device clock creates (see nextInstant's own docs). `maxObservedWallClock`
97
+ // tracks the highest wall-clock value ever seen at push time, independent of `since` (which
98
+ // only moves when a window happens to close), so a clock that is now BEHIND it is
99
+ // detected here regardless of what `since` currently holds. Treated as a fresh generation
100
+ // rather than merely resetting `since`: a full snapshot sees every record regardless of
101
+ // its timestamp, so this is the only reset that is actually safe to trust.
102
+ const nowIso = new Date().toISOString()
103
+ if (cursor.maxObservedWallClock != null && nowIso < cursor.maxObservedWallClock) {
104
+ cursor = rotate(cursor)
105
+ }
106
+ cursor = {
107
+ ...cursor,
108
+ maxObservedWallClock:
109
+ cursor.maxObservedWallClock != null && cursor.maxObservedWallClock > nowIso
110
+ ? cursor.maxObservedWallClock
111
+ : nowIso
112
+ }
113
+
114
+ // Back-fill: this cursor's window closed at least once (since is set) with real chunks
115
+ // pushed (chunksInGeneration > 0), but under an older build that predates sealing —
116
+ // initialChunkCount was never set. Set it now, purely locally: the log through the
117
+ // current seq is already a coherent complete state, so nothing needs re-uploading. No
118
+ // network round trip and no new entry — the NEXT real chunk this device appends (whenever
119
+ // that is) carries the seal referencing this count, same as any other sealed generation.
120
+ if (cursor.since != null && cursor.initialChunkCount === undefined && cursor.chunksInGeneration > 0) {
121
+ cursor = { ...cursor, initialChunkCount: cursor.chunksInGeneration }
122
+ }
123
+
92
124
  const chunk = await deps.storage.getSyncChunk({
93
125
  identityKey: deps.identityKey,
94
126
  fromStorageIdentityKey: deps.identityKey,
@@ -100,6 +132,17 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
100
132
  })
101
133
 
102
134
  if (isEmptyChunk(chunk)) {
135
+ // KNOWN, STILL-OPEN GAP (XR-011/XR-055): this branch returns before captureAppDataSnapshot
136
+ // is ever called below, on purpose (see that call's own comment and codec.ts's encodeChunk
137
+ // docs for why an appData-only entry is unsafe to append) — but the practical consequence
138
+ // is that ANY appData queued right now (a just-acknowledged localpay_pending frame, a
139
+ // peerpay_outbox delivery checkpoint, a just-recorded receiveIssuedDates entry) is not
140
+ // merely delayed, it never reaches THIS push at all: the window closes with nothing sent,
141
+ // and the row stays local-only until some unrelated entity change happens to close a
142
+ // later window. See appData.ts's module docstring for the design delta this needs, and
143
+ // __tests__/backup/appDataIsolatedActivity.test.ts, which pins this exact scenario
144
+ // end-to-end (push → restore) rather than only at this function's own unit level.
145
+ //
103
146
  // Window exhausted. Advance `since` past everything seen and reset the offsets, as
104
147
  // EntitySyncState does when its merge reports done — except that we advance PAST the
105
148
  // high-water mark rather than onto it. See nextInstant.
@@ -107,7 +150,14 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
107
150
  ...cursor,
108
151
  since: nextInstant(cursor.maxUpdatedAt) ?? cursor.since,
109
152
  maxUpdatedAt: undefined,
110
- offsets: zeroOffsets()
153
+ offsets: zeroOffsets(),
154
+ // The window that just closed becomes the generation's initial snapshot — but only
155
+ // the FIRST time this fires for a generation (initialChunkCount still undefined). A
156
+ // later window closing mid-generation (pure delta continuation) must not move it:
157
+ // the seal always references the original initial snapshot, which is what lets
158
+ // verifiedComplete stay true as further deltas land (see RemoteSyncReader).
159
+ initialChunkCount:
160
+ cursor.initialChunkCount ?? (cursor.chunksInGeneration > 0 ? cursor.chunksInGeneration : undefined)
111
161
  }
112
162
 
113
163
  const rotated = shouldRotate(advanced)
@@ -116,6 +166,15 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
116
166
  return { pushed: 0, bytes: 0, windowClosed: true, rotated }
117
167
  }
118
168
 
169
+ // Read alongside the chunk, before the size gate below, so a large pending/outbox queue
170
+ // (XR-011) or a long issued-date history (XR-055) counts toward the oversize check exactly
171
+ // like the chunk's own records do — appData rides in the SAME encrypted envelope (see
172
+ // codec.ts's encodeChunk), so it costs real bytes against the same server cap. `undefined`
173
+ // when there is nothing app-owned to add, so a chunk with an empty queue serialises
174
+ // byte-for-byte as the pre-appData envelope (see encodeChunk's own docs).
175
+ const appData = await captureAppDataSnapshot(deps.storage)
176
+ const appDataToSend = isEmptyAppData(appData) ? undefined : appData
177
+
119
178
  // Bail BEFORE the expensive part when the chunk cannot possibly be accepted.
120
179
  //
121
180
  // maxRoughSize bounds what the toolbox accumulates across records; it cannot bound ONE
@@ -127,7 +186,7 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
127
186
  // Ordering is still the point. Encrypting and signing a doomed payload is synchronous
128
187
  // CPU work that blocked the JS thread for ~50s per attempt on device; checking here
129
188
  // makes a doomed pass nearly free instead of nearly a minute.
130
- const estimate = estimateEncodedBytes(chunk)
189
+ const estimate = estimateEncodedBytes(chunk) + estimateAppDataBytes(appDataToSend)
131
190
  const { maxBlobBytes } = await client.limits()
132
191
  if (estimate > maxBlobBytes) {
133
192
  // Interpolated, not printf-style: React Native's console does not substitute %d, so a
@@ -144,7 +203,14 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
144
203
  }
145
204
 
146
205
  const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
147
- const ciphertext = await encodeChunk(wallet, chunk, deps.chain)
206
+ // Every chunk appended once the generation's initial window has closed carries the seal
207
+ // referencing it — never a separate entry (see codec.ts's encodeChunk docs and this
208
+ // module's own docstring on why a dedicated marker is unsafe for an old reader).
209
+ const seal: BackupSeal | undefined =
210
+ cursor.initialChunkCount != null
211
+ ? { generation: cursor.generation, initialChunkCount: cursor.initialChunkCount }
212
+ : undefined
213
+ const ciphertext = await encodeChunk(wallet, chunk, deps.chain, seal, appDataToSend)
148
214
 
149
215
  const seq = cursor.seq + 1
150
216
  let sha: string
@@ -4,7 +4,10 @@
4
4
  * Given nothing but a recovered seed (or the primary key from printed shares), rebuild the
5
5
  * wallet database from the encrypted log.
6
6
  */
7
+ import type { CompletedProtoWallet } from '@bsv/sdk'
8
+ import type { TableSettings } from '@bsv/wallet-toolbox-mobile'
7
9
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
10
+ import type { AppDataSnapshot } from './codec'
8
11
  import { BackupClient, type DeviceSummary } from './client'
9
12
  import type { BackupChain } from './constants'
10
13
  import { deriveBackupWallet } from './derive'
@@ -40,6 +43,22 @@ export interface RestoreResult {
40
43
  chunks: number
41
44
  deviceId: string
42
45
  generation: number
46
+ /**
47
+ * True when the replayed generation's newest entry carries a seal proving, to this
48
+ * device, that its initial snapshot is fully present — see codec.ts's DecodedEntry and
49
+ * push.ts's pushOnce. False means either an explicit device/generation override was
50
+ * chosen with no seal, or no candidate anywhere in the manifest was sealed and today's
51
+ * newest-only fallback was used instead. See P1-backup-incomplete-generation.
52
+ */
53
+ verified: boolean
54
+ /**
55
+ * This device's own most recent app-owned recovery-critical snapshot (XR-011), if its log
56
+ * carried one — see RemoteSyncReader.appData. Returned rather than applied here: with more
57
+ * than one device in the manifest (XR-015), restoreOnImport merges every device's own
58
+ * result before the SINGLE write that actually reaches key_value_store, so one device's
59
+ * snapshot can never silently clobber another's.
60
+ */
61
+ appData?: AppDataSnapshot
43
62
  }
44
63
 
45
64
  /** What the user can choose between when more than one device has a backup. */
@@ -53,10 +72,15 @@ export async function listBackups (deps: {
53
72
  }
54
73
 
55
74
  /**
56
- * Replay the newest complete generation into `storage`.
75
+ * Replay the best generation the manifest reports for the chosen device.
57
76
  *
58
- * Picks the newest generation rather than the oldest because a generation is a full
59
- * snapshot: the newest one alone is sufficient, and it is the shortest replay.
77
+ * A generation is intended by the writer (see push.ts rotate/shouldRotate) to be a
78
+ * coherent, self-contained snapshot, so the newest one alone should be sufficient and is
79
+ * the shortest replay — but the manifest's own metadata carries no notion of "complete", so
80
+ * pickTarget prefers whichever candidate is proven complete by its own seal (see
81
+ * RemoteSyncReader.verifiedComplete) over blindly trusting recency. `verified` on the
82
+ * result says which way this restore was chosen; the chunk-count check below still runs
83
+ * either way as the last line of defence.
60
84
  */
61
85
  export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResult> {
62
86
  const client = resolveClient(deps)
@@ -67,9 +91,8 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
67
91
  throw new Error('No backup found for this wallet')
68
92
  }
69
93
 
70
- const chosen = pickTarget(devices, deps.deviceId, deps.generation)
71
-
72
94
  const settings = await deps.storage.makeAvailable()
95
+ const chosen = await pickTarget(devices, client, wallet, deps.chain, settings, deps.deviceId, deps.generation)
73
96
 
74
97
  // processSyncChunk's preconditions, which a fresh, just-migrated database does
75
98
  // not meet: it does verifyTruthy(findUserByIdentityKey(identityKey)) and then
@@ -85,8 +108,10 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
85
108
  'backup-restore'
86
109
  )
87
110
 
88
- const headSeq = devices.find(d => d.deviceId === chosen.deviceId && d.generation === chosen.generation)?.headSeq
89
- const reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings, headSeq)
111
+ // Reuses the exact reader pickTarget already probed (it may already have read this
112
+ // generation's index and decoded its newest entry while ranking candidates), rather than
113
+ // re-fetching the same index a second time.
114
+ const reader = chosen.reader
90
115
 
91
116
  let chunks = 0
92
117
  for (;;) {
@@ -120,7 +145,13 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
120
145
  }
121
146
 
122
147
  await reconcileRestoredProofs(deps.storage)
123
- return { chunks, deviceId: chosen.deviceId, generation: chosen.generation }
148
+ return {
149
+ chunks,
150
+ deviceId: chosen.deviceId,
151
+ generation: chosen.generation,
152
+ verified: chosen.verified,
153
+ appData: reader.appData
154
+ }
124
155
  }
125
156
 
126
157
  /**
@@ -166,31 +197,88 @@ async function reconcileRestoredProofs (storage: StorageExpoSQLite): Promise<voi
166
197
  }
167
198
  }
168
199
 
169
- function pickTarget (
200
+ /** What pickTarget resolves to: the chosen device/generation, whether it is verified
201
+ * complete, and the reader that already probed it — reused by restoreFromBackup for the
202
+ * actual replay rather than re-reading the same index a second time. */
203
+ export interface PickedTarget {
204
+ deviceId: string
205
+ generation: number
206
+ verified: boolean
207
+ reader: RemoteSyncReader
208
+ }
209
+
210
+ /**
211
+ * Choose which device/generation to replay.
212
+ *
213
+ * With an explicit `generation`, this is a forced selection — no ranking, exactly the
214
+ * generation asked for — but `verified` still reports whether IT happens to be sealed.
215
+ *
216
+ * Otherwise: every (device, generation) candidate is ranked newest-updatedAt first, and the
217
+ * first one whose own log proves itself complete (RemoteSyncReader.verifiedComplete) wins —
218
+ * an older but SEALED generation is safer to restore than a newer one still mid-rotation,
219
+ * which is the whole point of P1-backup-incomplete-generation's fix. Only when NONE of the
220
+ * manifest's candidates are sealed (a fully legacy manifest, written entirely before this
221
+ * fix shipped) does this fall back to today's plain "most recently written device, then its
222
+ * newest generation" heuristic, with `verified: false` so the caller can warn rather than
223
+ * silently claim a verified restore.
224
+ */
225
+ export async function pickTarget (
170
226
  devices: DeviceSummary[],
227
+ client: BackupClient,
228
+ wallet: CompletedProtoWallet,
229
+ chain: BackupChain,
230
+ settings: TableSettings,
171
231
  deviceId?: string,
172
232
  generation?: number
173
- ): { deviceId: string, generation: number } {
233
+ ): Promise<PickedTarget> {
174
234
  const candidates = deviceId != null ? devices.filter(d => d.deviceId === deviceId) : devices
175
235
  if (candidates.length === 0) {
176
236
  throw new Error(`No backup found for device ${String(deviceId)}`)
177
237
  }
178
238
 
239
+ const readerFor = (d: DeviceSummary): RemoteSyncReader =>
240
+ new RemoteSyncReader(client, wallet, chain, d.deviceId, d.generation, settings, d.headSeq)
241
+
179
242
  if (generation != null) {
180
243
  const exact = candidates.find(d => d.generation === generation)
181
244
  if (exact == null) throw new Error(`No backup found for generation ${generation}`)
182
- return { deviceId: exact.deviceId, generation: exact.generation }
245
+ const reader = readerFor(exact)
246
+ const verified = await reader.verifiedComplete()
247
+ return { deviceId: exact.deviceId, generation: exact.generation, verified, reader }
183
248
  }
184
249
 
185
- // Most recently written device, then its newest generation.
186
- const newest = candidates.reduce((best, d) =>
187
- d.updatedAt > best.updatedAt ? d : best
188
- )
250
+ // Newest updatedAt first, across every device in the candidate set — not scoped to the
251
+ // most recently written device alone, because the point is to prefer a sealed generation
252
+ // even if it belongs to a slightly less recently updated device.
253
+ const sorted = [...candidates].sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0))
254
+
255
+ for (const candidate of sorted) {
256
+ const reader = readerFor(candidate)
257
+ let verified: boolean
258
+ try {
259
+ verified = await reader.verifiedComplete()
260
+ } catch {
261
+ // Ranking must not abort the whole restore over a candidate that turns out unreadable
262
+ // and was never going to be chosen anyway — it is simply not verified.
263
+ verified = false
264
+ }
265
+ if (verified) return { deviceId: candidate.deviceId, generation: candidate.generation, verified: true, reader }
266
+ }
267
+
268
+ // Nothing in the manifest is marked complete: fall back to today's heuristic (most
269
+ // recently written device, then its newest generation) so a fully legacy manifest still
270
+ // restores exactly as before — just now saying honestly that it could not be verified.
271
+ const newest = candidates.reduce((best, d) => (d.updatedAt > best.updatedAt ? d : best))
189
272
  const newestGeneration = candidates
190
273
  .filter(d => d.deviceId === newest.deviceId)
191
274
  .reduce((best, d) => (d.generation > best.generation ? d : best))
192
275
 
193
- return { deviceId: newestGeneration.deviceId, generation: newestGeneration.generation }
276
+ return {
277
+ deviceId: newestGeneration.deviceId,
278
+ generation: newestGeneration.generation,
279
+ verified: false,
280
+ reader: readerFor(newestGeneration)
281
+ }
194
282
  }
195
283
 
196
284
  function resolveClient (deps: { primaryKey: number[], chain: BackupChain, baseUrl?: string, client?: BackupClient }): BackupClient {