@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
@@ -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,9 +16,9 @@
16
16
  * pass.
17
17
  */
18
18
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
19
- import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
19
+ import { captureAppDataSnapshot, isEmptyAppData } from './appData'
20
20
  import { BackupClient, BackupHttpError, ERR_SEQ_CONFLICT } from './client'
21
- import { encodeChunk, estimateEncodedBytes, isEmptyChunk } from './codec'
21
+ import { encodeChunk, estimateAppDataBytes, estimateEncodedBytes, isEmptyChunk, type BackupSeal } from './codec'
22
22
  import { GENERATION_CHUNK_THRESHOLD, MAX_ITEMS, MAX_ROUGH_SIZE, type BackupChain } from './constants'
23
23
  import {
24
24
  ENTITY_NAMES,
@@ -33,6 +33,7 @@ import {
33
33
  import { backupPseudonym, deriveBackupWallet } from './derive'
34
34
  import { getDeviceId } from './deviceId'
35
35
  import { isBackupPushEnabled } from './preference'
36
+ import type { SyncChunk } from '../toolboxTypes'
36
37
 
37
38
  export interface PushDeps {
38
39
  storage: StorageExpoSQLite
@@ -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 {
@@ -13,21 +13,33 @@
13
13
  * device id, and `restoreFromBackup`'s default target is the most recently updated
14
14
  * device in the manifest. Let the monitor push once and the newest entry becomes this
15
15
  * device's own near-empty log — restore would then replay nothing and report success.
16
- * Belt and braces: this module resolves the target itself and passes it explicitly, so
17
- * the default is never consulted even if the ordering slips.
16
+ * Belt and braces: this module resolves every target itself and passes each one
17
+ * through explicitly, so the default is never consulted even if the ordering slips.
18
18
  * 2. **Into a fresh database.** `restoreFromBackup` documents its storage argument as a
19
19
  * fresh, migrated provider. Replay merges by record identity, so re-running it after a
20
20
  * failed attempt converges rather than duplicating — but it is not a repair tool for a
21
21
  * wallet that has already been transacting.
22
22
  *
23
+ * Every DEVICE in the manifest is replayed into the same storage, not only the single
24
+ * highest-ranked one (see XR-015): each device's own log is an independent, non-overlapping
25
+ * history — a change/receipt record unique to one device is never duplicated into another's
26
+ * — so restoring only the "best" candidate would silently drop the rest. This is safe
27
+ * because it merges by record identity exactly as ordinary live multi-device sync already
28
+ * does; the highest-ranked device (by `restore.ts`'s own verified-first-then-newest rule)
29
+ * still decides the `deviceId`/`generation`/`verified` this module reports, so a
30
+ * single-device manifest — the overwhelming common case — behaves exactly as before.
31
+ *
23
32
  * Errors propagate. A partial or forked log must stop the import: a wallet that looks
24
33
  * healthy while missing the outputs it needs to spend is worse than one that plainly
25
34
  * failed to restore.
26
35
  */
27
36
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
28
- import { BackupClient, type DeviceSummary } from './client'
37
+ import { applyAppData, mergeAppData } from './appData'
38
+ import { BackupClient } from './client'
39
+ import type { AppDataSnapshot } from './codec'
29
40
  import type { BackupChain } from './constants'
30
- import { listBackups, restoreFromBackup } from './restore'
41
+ import { deriveBackupWallet } from './derive'
42
+ import { listBackups, pickTarget, restoreFromBackup } from './restore'
31
43
 
32
44
  export interface RestoreOnImportDeps {
33
45
  /** A fresh, migrated storage provider to replay into. */
@@ -42,7 +54,11 @@ export interface RestoreOnImportDeps {
42
54
  baseUrl?: string
43
55
  /** Injected transport, for tests. Takes precedence over `baseUrl`. */
44
56
  client?: BackupClient
45
- /** Chunks replayed so far, and how many this generation holds. */
57
+ /**
58
+ * Chunks replayed so far, and how many this generation holds. Scoped to whichever
59
+ * device is currently replaying — with more than one device in the manifest this fires
60
+ * once per device, each restarting from its own generation's own total.
61
+ */
46
62
  onProgress?: (chunks: number, total: number) => void
47
63
  /**
48
64
  * After a successful replay, check that restored coins are still spendable.
@@ -54,11 +70,20 @@ export interface RestoreOnImportDeps {
54
70
 
55
71
  export interface RestoreOnImportResult {
56
72
  restored: boolean
73
+ /** Total chunks replayed across every device in the manifest, not only the primary one. */
57
74
  chunks: number
75
+ /** The highest-ranked (primary) device replayed — see this module's own docstring. */
58
76
  deviceId?: string
77
+ /** The primary device's own replayed generation. */
59
78
  generation?: number
60
79
  /** Why nothing was replayed. Absent when `restored` is true. */
61
80
  reason?: 'not-configured' | 'no-backup'
81
+ /**
82
+ * True only when EVERY device replayed had a newest entry carrying a seal proving it
83
+ * complete — see restore.ts's RestoreResult and P1-backup-incomplete-generation. False if
84
+ * any one of them could not be verified. Absent when nothing was replayed.
85
+ */
86
+ verified?: boolean
62
87
  }
63
88
 
64
89
  export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<RestoreOnImportResult> {
@@ -68,53 +93,92 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
68
93
  }
69
94
 
70
95
  const devices = await listBackups({ primaryKey: deps.primaryKey, chain: deps.chain, client })
71
- const target = newestTarget(devices)
72
- if (target == null) {
96
+ if (devices.length === 0) {
73
97
  // Nothing was ever pushed under this seed. An ordinary outcome — a phrase from a
74
98
  // wallet that predates backups, or one that never went online — so the import
75
99
  // continues with an empty history rather than failing.
76
100
  return { restored: false, chunks: 0, reason: 'no-backup' }
77
101
  }
78
102
 
79
- const result = await restoreFromBackup({
103
+ // Resolved HERE, via the same verified-first ranking restore.ts's pickTarget applies, and
104
+ // passed through explicitly below — never left to restoreFromBackup's own default, which
105
+ // this device's own first push would win as soon as the monitor starts (see this
106
+ // module's docstring). Mirrors restore.ts's pickTarget deliberately: an older but sealed
107
+ // generation is preferred over a newer one still mid-rotation. This PRIMARY target is
108
+ // still what deviceId/generation on the result below describe, so a single-device
109
+ // manifest — the overwhelming common case — restores exactly as before.
110
+ const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
111
+ const settings = await deps.storage.makeAvailable()
112
+ const primary = await pickTarget(devices, client, wallet, deps.chain, settings)
113
+
114
+ const primaryResult = await restoreFromBackup({
80
115
  storage: deps.storage,
81
116
  primaryKey: deps.primaryKey,
82
117
  chain: deps.chain,
83
118
  identityKey: deps.identityKey,
84
119
  client,
85
120
  manifest: devices,
86
- deviceId: target.deviceId,
87
- generation: target.generation,
121
+ deviceId: primary.deviceId,
122
+ generation: primary.generation,
88
123
  onProgress: deps.onProgress
89
124
  })
90
125
 
126
+ let chunks = primaryResult.chunks
127
+ let verified = primaryResult.verified
128
+ // Folded together across every device before the single write below (XR-011) — never
129
+ // applied per-device: each restoreFromBackup call only RETURNS its own appData rather than
130
+ // writing it, precisely so one device's snapshot can never clobber another's (see
131
+ // mergeAppData's own docs on why this is a union, not last-write-wins).
132
+ let appData: AppDataSnapshot | undefined = primaryResult.appData
133
+
134
+ // Every OTHER device in the manifest is an independent, non-overlapping backup history
135
+ // (see XR-015) — a device's own change/receipt records exist ONLY in its own log, never
136
+ // duplicated into another device's. Restoring only the single highest-ranked device would
137
+ // silently drop anything unique to the rest. Replay each remaining device's own best
138
+ // generation into the SAME storage: safe because it merges by record identity exactly as
139
+ // ordinary live multi-device sync already does (see restoreFromBackup/processSyncChunk),
140
+ // and each device gets its own pickTarget ranking (verified-first, same rule as above)
141
+ // rather than blindly taking its newest generation.
142
+ const otherDeviceIds = [...new Set(devices.map(d => d.deviceId))].filter(id => id !== primary.deviceId)
143
+ for (const deviceId of otherDeviceIds) {
144
+ const target = await pickTarget(devices, client, wallet, deps.chain, settings, deviceId)
145
+ const result = await restoreFromBackup({
146
+ storage: deps.storage,
147
+ primaryKey: deps.primaryKey,
148
+ chain: deps.chain,
149
+ identityKey: deps.identityKey,
150
+ client,
151
+ manifest: devices,
152
+ deviceId: target.deviceId,
153
+ generation: target.generation,
154
+ onProgress: deps.onProgress
155
+ })
156
+ chunks += result.chunks
157
+ verified = verified && result.verified
158
+ appData = mergeAppData(appData, result.appData)
159
+ }
160
+
161
+ // Written once, here, BEFORE validateRestoredCoins/reviewSpendableOutputs and well before
162
+ // the caller marks the wallet built (WalletContext.tsx) — the existing background
163
+ // pending-queue effect and the outbox's own consumers pick these rows up on their own next
164
+ // tick, through their own existing guards, exactly as if this device had written them
165
+ // itself. No new hook, and nothing here ever internalizes, broadcasts or releases anything
166
+ // (see appData.ts's applyAppData docs).
167
+ if (appData !== undefined) {
168
+ await applyAppData(deps.storage, appData)
169
+ }
170
+
91
171
  if (deps.validateRestoredCoins) {
92
172
  await deps.validateRestoredCoins()
93
173
  }
94
174
 
95
175
  return {
96
176
  restored: true,
97
- chunks: result.chunks,
98
- deviceId: result.deviceId,
99
- generation: result.generation
177
+ chunks,
178
+ deviceId: primary.deviceId,
179
+ generation: primary.generation,
180
+ verified
100
181
  }
101
182
  }
102
183
 
103
184
  const hasUrl = (u?: string): boolean => u != null && u !== ''
104
-
105
- /**
106
- * The most recently written device, then that device's highest generation.
107
- *
108
- * A generation is a full snapshot, so the newest one alone is sufficient and is also the
109
- * shortest replay. Mirrors `restoreFromBackup`'s own default deliberately: this exists to
110
- * make the choice explicit at a point where only the other device's logs can be in the
111
- * manifest, not to choose differently.
112
- */
113
- function newestTarget (devices: DeviceSummary[]): { deviceId: string, generation: number } | null {
114
- if (devices.length === 0) return null
115
- const newest = devices.reduce((best, d) => (d.updatedAt > best.updatedAt ? d : best))
116
- const generation = devices
117
- .filter(d => d.deviceId === newest.deviceId)
118
- .reduce((best, d) => (d.generation > best.generation ? d : best)).generation
119
- return { deviceId: newest.deviceId, generation }
120
- }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Has this device actually put a backup on the server?
2
+ * Has THIS wallet actually put a backup on the server?
3
3
  *
4
4
  * Read from the push cursor rather than by asking the server: the cursor is
5
5
  * written only after chunks are appended, so a non-zero `seq` is this device's
@@ -7,26 +7,31 @@
7
7
  * "we could not reach the server" is not the same as "you have no backup", and
8
8
  * the troubleshooting list must not conflate them.
9
9
  *
10
- * Scanning the key prefix avoids needing the primary key (the pseudonym is
11
- * derived from it) up in the UI, where it has no business being.
10
+ * Scoped to `chain`+`pseudonym` (the caller's own identity), not merely the bare
11
+ * `backupCursor-` prefix: `cursorKey`'s deviceId component never changes across a
12
+ * logout/re-import on the same install (see deviceId.ts), so an unscoped scan can read a
13
+ * DIFFERENT, departed wallet's leftover cursor and report a brand-new wallet as backed up
14
+ * before it has ever pushed anything (XR-009). The pseudonym is derived from the primary
15
+ * key but is not itself secret — it is exactly what the backup server sees as this
16
+ * wallet's account — so passing it here still keeps the primary key itself out of the UI.
12
17
  */
13
18
  import AsyncStorage from '@react-native-async-storage/async-storage'
19
+ import { cursorKeyPrefix, type BackupChain } from './constants'
14
20
  import { isBackupPushEnabled } from './preference'
15
21
 
16
- const CURSOR_PREFIX = 'backupCursor-'
17
-
18
22
  export type BackupUploadState = {
19
23
  /** The user has not opted out. */
20
24
  enabled: boolean
21
- /** At least one chunk has been appended for some generation on this device. */
25
+ /** At least one chunk has been appended for some generation, under this identity. */
22
26
  uploaded: boolean
23
27
  }
24
28
 
25
- export async function getBackupUploadState(): Promise<BackupUploadState> {
29
+ export async function getBackupUploadState(chain: BackupChain, pseudonym: string): Promise<BackupUploadState> {
26
30
  const enabled = await isBackupPushEnabled()
27
31
  let uploaded = false
28
32
  try {
29
- const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(CURSOR_PREFIX))
33
+ const prefix = cursorKeyPrefix(chain, pseudonym)
34
+ const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(prefix))
30
35
  if (keys.length > 0) {
31
36
  const entries = await AsyncStorage.multiGet(keys)
32
37
  uploaded = entries.some(([, raw]) => {
package/core/config.tsx CHANGED
@@ -42,9 +42,16 @@ export const DEFAULT_CHAIN: AppChain = 'main'
42
42
  /**
43
43
  * Internal authority label passed only by the wallet shell.
44
44
  *
45
- * Keep this deliberately outside the hostname namespace. The permissions
46
- * manager grants this originator administrative access, so using an ordinary
47
- * DNS name would let whoever controls that host acquire the same authority
48
- * through a paired connection.
45
+ * The permissions manager grants this originator administrative access, so it
46
+ * must be a name no external caller can present. It used to sit outside the
47
+ * hostname namespace altogether (`urn:bsv-wallet:internal-admin`), but
48
+ * @bsv/sdk 2.8 accepts only canonical hostnames as originators. It now lives
49
+ * in the RFC 6761 `.invalid` TLD, which never resolves, so no host can be
50
+ * served from it, and `parseExternalOrigin` refuses that whole TLD at the
51
+ * external trust boundary. An ordinary DNS name would let whoever controls
52
+ * that host acquire the same authority through a paired connection.
49
53
  */
50
- export const ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
54
+ export const ADMIN_ORIGINATOR = 'internal-admin.bsv-wallet.invalid'
55
+
56
+ /** The label before @bsv/sdk 2.8, still found in data persisted by older builds. */
57
+ export const LEGACY_ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
package/core/constants.ts CHANGED
@@ -1,9 +1,22 @@
1
1
  /** Auto-approve transactions below this satoshi amount without showing the spend modal */
2
2
  export const DEFAULT_AUTO_APPROVE_THRESHOLD = 100_000
3
- /** Minimum milliseconds between auto-approved transactions (global, origin-agnostic) */
3
+ /** Minimum milliseconds between two auto-approved transactions from the SAME originator */
4
4
  export const AUTO_APPROVE_COOLDOWN_MS = 10_000
5
5
  /** AsyncStorage key for persisted auto-approve threshold */
6
6
  export const AUTO_APPROVE_STORAGE_KEY = 'autoApproveThreshold'
7
+ /**
8
+ * Global rolling 24h cumulative cap (satoshis) on auto-approved spending,
9
+ * across every originator combined — closes the gap where a single origin
10
+ * (or several) could otherwise auto-approve an unbounded total by staying
11
+ * under the per-request threshold and cooldown forever (misc-p2-04).
12
+ *
13
+ * PROVISIONAL: 10x the default per-request threshold, chosen only so the cap
14
+ * cannot bind in ordinary single-payment use. Pending product sign-off on
15
+ * the real number.
16
+ */
17
+ export const AUTO_APPROVE_DAILY_CAP_SATS = 10 * DEFAULT_AUTO_APPROVE_THRESHOLD
18
+ /** AsyncStorage key for the persisted rolling auto-approve ledger (best-effort; survives app restart) */
19
+ export const AUTO_APPROVE_LEDGER_STORAGE_KEY = 'auto_approve_ledger'
7
20
 
8
21
  /**
9
22
  * AsyncStorage key for whether Settings' Advanced group is expanded.