@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,246 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.24.0
6
+
7
+ BSV Broadcaster as the broadcast path (#97), sweep of external keys (#93), the
8
+ security review fixes (#72 to #92) and an end-to-end harness mode (#67). Hosts
9
+ must rebuild their native apps: the package now ships a native module.
10
+
11
+ ### Breaking / host action
12
+
13
+ - **The package ships a native Expo module, `BsvBoundedFetch` (#72, #79).**
14
+ `android/`, `ios/` and `expo-module.config.json` are now published, and
15
+ `expo-modules-core` ~57.0.0 is a new peer. Expo autolinking picks the module
16
+ up; hosts must rebuild the native apps (a JS-only update is not enough).
17
+ Backup, handle registry and trust-list requests go through it so that the
18
+ response size is capped in native code before JS sees a byte. There is no
19
+ fallback to the global `fetch`: without the module those requests throw.
20
+ Redirects are returned as 3xx and are not followed.
21
+ - **Taal is removed** (#97): `taalArcUrl`, `taalApiKey` and
22
+ `createTaalBroadcastService`. See Removed.
23
+ - **Wallet guard** (#77): `revealCounterpartyKeyLinkage` is refused for every
24
+ originator but the admin, and the wallet database export protocol is a
25
+ reserved namespace that only the admin may use.
26
+ - **Vault deposits need a hardware key** (#83). Before a new vault output is
27
+ funded, one enrolled key must sign a challenge bound to that output
28
+ (`requireVaultOutputKeyPossession`). A deposit with no key present fails
29
+ with `VaultError` `not-enrolled` or `wrong-key`.
30
+ - **Imported databases hold their outgoing PeerPay payments** (#92).
31
+ `importDatabases` quarantines the imported outbox; nothing is sent again
32
+ until the user approves each payment in `UniversalSend`
33
+ (`ImportedOutboxApproval`). Approval is bound to the signed recipient output.
34
+ - **Legacy secret migration refuses to overwrite an existing wallet** (#84).
35
+ The result can now be `{ outcome: 'failed', stage: 'existing-identity' }`,
36
+ `retryable: true` when the store could not be read and `false` when an
37
+ envelope identity or KEK is already there.
38
+
39
+ ### Security
40
+
41
+ - **Backup** (#72, #73): response bytes are capped in the native receiver.
42
+ Writers now produce v2 envelopes that authenticate the log position (device,
43
+ generation, sequence, predecessor digest) and the snapshot head inside the
44
+ AEAD. Legacy entries still decode, but they cannot prove that a recovery
45
+ snapshot is complete.
46
+ - **Headers** (#81, #85): linked headers are checked for difficulty
47
+ transitions and accumulated work, an interrupted branch replacement is
48
+ recovered, and a remote payment root is accepted only when its header is an
49
+ anchored member of the validated chain.
50
+ - **Wallet connections** (#78, #80, #87, #88): the replay floor survives
51
+ pairing a topic again; revocation cancels pairing attempts that are still in
52
+ progress (`usePairingAttempt`); in-flight wallet requests are revoked when
53
+ the relay socket closes; and the session response must match the approved
54
+ topic, backend identity key and protocol at the claimed HTTPS origin.
55
+ `parseRelayResponse(raw, expected?)` takes the expected tuple.
56
+ - **Database import** (#82): every `sqlite_master` object is compared with the
57
+ reference schema. Names that start with `sqlite` are no longer exempt.
58
+ - **Secrets** (#86): a biometric upgrade reads the new key back through its
59
+ access control before the session unlocks.
60
+ - **Vault** (#91): metadata mutations (rename, key removal, recovery) are
61
+ bound to the authenticated snapshot.
62
+ - **Safari bridge inbox** (#74): queue limits are enforced in the native
63
+ store, results are kept under queue pressure and pending calls are closed on
64
+ disposal.
65
+ - **Nearby payments** (#76): a received description is cut at a complete
66
+ UTF-8 boundary, so it stays within its byte limit.
67
+
68
+ ### Added: end-to-end harness mode (#67)
69
+
70
+ - `configureToolbox({ e2e: { broadcasterUrl } })`, for test builds only. It
71
+ locks the wallet off mainnet, stores keys without a biometric prompt and
72
+ points Pay at a mock broadcaster on a loopback or private address.
73
+ `configureToolbox` throws when an E2E config also has a backup URL, the
74
+ vault, a push adapter or mainnet services. Never set it in a build that can
75
+ hold funds.
76
+ - Exports `isE2eBuild`, `getE2eBroadcasterUrl` and `e2eSafeChain`. Pay and
77
+ Home controls gained `testID`s for Maestro.
78
+
79
+ ### Changed
80
+
81
+ - BSV Broadcaster (`broadcast.bsvblockchain.tech`) is now the primary
82
+ broadcast, SSE and chaintracks endpoint on all 4 networks (main, test,
83
+ teratest, scaletest).
84
+ - Broadcast provider order: BSV Broadcaster, GorillaPool, WhatsOnChain,
85
+ Bitails. Each is registered only where the network table says it serves
86
+ that network.
87
+ - Each provider gets a flat 30 s budget (`postBeefUntilSuccessSoftTimeoutMs`
88
+ 30000, per-KB 0, max 30000). The walk inside a provider ends 2 s earlier
89
+ (28 s), so its results arrive before the soft timeout; a post does not
90
+ start with less than 1 s left. Transactions not reached get retryable
91
+ errors.
92
+ - Every unconfirmed transaction of a BEEF is posted as EF, parents first.
93
+ An ancestor that cannot be built as EF gets a retryable error, as do its
94
+ descendants.
95
+ - Only BSV Broadcaster validator answers HTTP 400 with the posted txid and
96
+ ARC code 461 or 464 (number or string) are final rejections. Every other
97
+ non-success answer is retryable.
98
+
99
+ ### Removed
100
+
101
+ - Taal: `taalArcUrl`, `taalApiKey` and `createTaalBroadcastService`. Hosts
102
+ that pass `taalApiKey` must drop it.
103
+
104
+ ### Added: sweep external keys (`core/pay/rails/sweep.ts`)
105
+
106
+ Move coins that an external key controls into this wallet. Each sweep has a
107
+ preview step (WhatsOnChain reads only) and an execute step.
108
+
109
+ - **WIF:** `parseWif` / `isWif` (mainnet and testnet, compressed and
110
+ uncompressed), `planWifSweep` (preview), `sweepWif` (execute).
111
+ - **Recovery phrase:** `scanMnemonic` (preview: gap-limit scan of each path's
112
+ receive chain; the change chain only when the receive chain shows use),
113
+ `sweepMnemonic` (execute, with per-path totals). The path list
114
+ (`paths`, default `DEFAULT_SWEEP_PATHS`, a placeholder) and the gap limit
115
+ (`gapLimit`, default 20) are parameters.
116
+ - **Import decision:** `decideMnemonicImport` returns `restore` (backup cache
117
+ hit), `sweep` (no backup, coins found) or `empty` (restore as this wallet's
118
+ root). A failed cache lookup throws; it never falls through to a sweep.
119
+ - The spend is the wallet's own `createAction` with the external outpoints as
120
+ inputs and no outputs, then `signAction` with locally signed inputs. The
121
+ wallet sets the fee, adds change to the default basket and broadcasts.
122
+ Batches of at most `maxInputsPerTx` (default 100) inputs per transaction.
123
+ - Never spent: 1-sat outputs (`token`), outputs below their own input fee
124
+ (`dust`), outputs whose real script is not plain P2PKH (`nonstandard`). All
125
+ are reported in `skipped`. A batch is aborted when the wallet adds an input
126
+ of its own or the fee rate exceeds `maxFeeRate` (default 1000 sat/kB).
127
+ - `wocFetch` in `pay/rails/address.ts` is now exported.
128
+
129
+ ### Fixed
130
+
131
+ - **The ARC and WhatsOnChain broadcasters now post every transaction in a multi-transaction BEEF.** They previously
132
+ converted the BEEF to a single transaction (`Transaction.fromBEEF` returns the last one) and returned one result, so in
133
+ a `sendWith` batch of chained transactions only the last was posted, and the earlier ones reached the network only if
134
+ a later provider in the chain posted the whole BEEF. Each requested
135
+ txid is now posted on its own, parents first (`Beef.sortTxs`), with one result per txid in the caller's order. A
136
+ child whose parent was not accepted is not posted and is reported as a retryable service error.
137
+
138
+ ## 0.23.0
139
+
140
+ Peer floors raised to the latest `@bsv` releases, the browser wallet bridge
141
+ (BRC-185 core, Android loopback and iOS Safari seams: #57, #58, #59) and
142
+ encrypted wallet database export/import (#60).
143
+
144
+ ### Peers
145
+
146
+ - **Raised floors** to the latest published releases: `@bsv/sdk` ^4.0.1,
147
+ `@bsv/wallet-toolbox-mobile` ^2.15.1, `@bsv/btms-permission-module` ^1.2.4,
148
+ `@bsv/message-box-client` ^2.7.0, `@bsv/webrtpay` ^0.2.3. Hosts copy
149
+ `patches/@bsv+wallet-toolbox-mobile+2.15.1.patch` in place of the 2.15.0 patch
150
+ (same changes, ported onto the 2.15.1 signing guard).
151
+ - `@bsv/backup-cache-client` 0.1.0 still peers `@bsv/sdk` ^2.4.1 (and its
152
+ `@bsv/auth` 0.1.3 peers ^2.1.6). Hosts keep an `overrides` entry for
153
+ `@bsv/sdk` until upstream widens these ranges.
154
+
155
+ ### Fixed (review of the Android bridge overlay)
156
+
157
+ - `Sheet`: the open-spring completion no longer re-applies the open position once the sheet has been closed, and a
158
+ non-dismissible sheet hides its backdrop from screen readers.
159
+ - `PermissionSheet`: no longer closes a queue's modal flag itself; the queue does it when it empties, so a request
160
+ enqueued just before an answer cannot be left behind a closed flag.
161
+
162
+ ### Browser bridge core
163
+
164
+ - **Transport-agnostic BRC-185 bridge engine** (`core/bridge`): origin rule, site consent with
165
+ reconnect tokens and a fresh grant tag per approval, a separate permissions manager for
166
+ unverified origins, bindings, the 28-method dispatcher, a durable inbox contract and host
167
+ wiring through `BrowserBridgeProvider`. No transport ships yet.
168
+ - **Conformance report.** `buildConformanceReport()` returns a versioned JSON listing the 28
169
+ methods, the bridge's refusals and the recorded deviations from BRC-185 / BRC-219; a snapshot
170
+ test keeps it deliberate.
171
+
172
+ ### Browser bridge: seams for the Android loopback kit
173
+
174
+ - **`ContextRelay`** (`ui/bridgeSheet`). `ContextRelayPublisher` (first root, inside the providers) copies the
175
+ contexts `PermissionSheet` reads (`RELAYED_CONTEXTS`: theme, wallet, exchange rate, user) into a module store, and
176
+ `ContextRelaySubscriber` re-provides them on a second React root, rendering nothing until every entry is published.
177
+ A theme change reaches the second root without remounting it. Language is the i18n singleton and is not relayed;
178
+ safe-area insets are per native root and the second root mounts its own provider. A scan test fails when the
179
+ sheet's import closure reads a context that is not listed.
180
+ - **`Sheet` re-applies its open position on mount and on a host signal.** `signalSheetResumed()`
181
+ (`ui/components/ui/sheetResumeSignal`) nudges every open `Sheet`, for a host window that resumes without an
182
+ `AppState` change the sheet can see (the Android bridge's second root). The open spring also re-applies once it settles.
183
+ - **`PermissionSheet backdropDismisses={false}`, `Sheet dismissible={false}`.** `PermissionSheet` treats a backdrop tap
184
+ or a swipe down as a rejection; a host window where an outside tap must do nothing (the Android bridge's overlay root)
185
+ passes `false` on its own instance. A swipe then springs back to the open position instead of leaving the sheet off
186
+ screen. The default is unchanged, and the setting is per instance, not process-wide.
187
+ - **A second request queued behind an answered one is shown.** `PermissionSheet` closed the queue's modal flag after
188
+ every grant or deny, even with another request of the same kind still queued, and the queue only opens that flag when
189
+ it goes from empty to non-empty, so the next request (another site's, or the same site's) stayed hidden and its call
190
+ hung. The flag is now closed only when nothing else is queued behind the answered request.
191
+
192
+ - **`BridgeSnapshot.hostAttached`.** True once a host is attached and the runtime has loaded, false at start and
193
+ after detach. Every change goes through `onSnapshotChange`, so a transport hears attach and detach even when
194
+ readiness stays `none` (a cold start with no wallet).
195
+ - **`assertAdvertisesResponder(descriptor, responder)`** (protocol/descriptor): throws `ProofError` unless a
196
+ `http-json` endpoint of the descriptor has the same scheme, host and port as the responder that answered.
197
+ - **Loopback HTTP router** (`core/bridge/loopback/`): the pure BRC-185 4.1 HTTP semantics for a native loopback
198
+ transport. Router (describe, connect, RPC, disconnect, outcome mapping), Host check, endpoint list, CORS, status table
199
+ and the launch proof MACs (hello, describe ack, launch, ack, binding) with their JCS payloads. Platform code supplies
200
+ requests and receives responses; nothing here opens a socket.
201
+ - **Testing helpers** (`core/bridge/testing`): the `PageClient` contract types and the transport-independent
202
+ conformance cases (all 28 methods, error codec, request and response caps) a transport runs against its executor.
203
+ - **Stable test ids on the connection and permission sheet.** `bridge-connect-origin` (the full origin),
204
+ `bridge-approve` and `bridge-deny` for every prompt kind, for UI automation; no visual change.
205
+ - **Android copy.** `bridge_notifications_off`, `bridge_ports_exhausted` and `bridge_not_ready_android` in all
206
+ 12 locales.
207
+
208
+ ### Browser bridge: seams for a native transport (iOS Safari kit)
209
+
210
+ - **Exports.** The transport API (inbox processor, store contract, origin constants) is exported for
211
+ a native transport to import, the contract suite `__tests__/bridge/inboxContract` runs against any
212
+ store, and the origin and permission-policy constants moved into a pure module so
213
+ an extension bundle can import them without the app's config.
214
+ - **Events gap and retention.** The inbox event log keeps at most 1024 events and 24 hours; a reader
215
+ that asks after a trimmed cursor gets an explicit gap instead of silence. `flushEvents()` writes
216
+ pending events before a transport reads them. The store contract's raw-bytes hook is owned by the
217
+ harness, not the adapter.
218
+ - **`onPromptRaised`** transport hook: fires when a wallet prompt is raised for a binding, so a
219
+ transport can tell a call needed approval.
220
+ - **Merged Connect sheet.** One sheet lists the site's manifest groups (no toggles) and Connect mints
221
+ every listed item at once; the later group check raises no second sheet. "Don't connect" mints and
222
+ records nothing and starts a 30 second backoff (`RESOURCE_LIMIT`, "This site was just declined").
223
+ Unattested origins keep the plain sheet. New copy in all 12 locales (`bridge_*` keys).
224
+ - **`usePermissionSheetBusy()`** (from `PermissionSheet`): true while a permission sheet is open or
225
+ queued, so a done screen never covers one.
226
+
227
+ ### Wallet data export
228
+
229
+ - **Encrypted export.** `exportAllWalletDatabases(storage, { encrypt: true, wallet, originator })`
230
+ writes `wallet-…-<ts>.db.enc`: a random file key wrapped by `wallet.encrypt` (counterparty
231
+ `self`, protocol `[2, 'wallet db export']`), body in 1 MiB AES-256-GCM chunks (STREAM nonces,
232
+ so reordered, dropped or truncated chunks fail). The snapshot comes from `VACUUM INTO` and is
233
+ encrypted a chunk at a time in native AES (`globalThis.__bsvNativeCrypto`), never held whole
234
+ in JS memory. Without `encrypt` the plain `.db` export is unchanged.
235
+ - **Encrypted import.** `importWalletDatabase(storage, { wallet, originator })` accepts `.db.enc`
236
+ up to 2 GiB, decrypting chunk by chunk to a temp file that SQLite opens from disk, then the same
237
+ identity/schema checks as before. Another wallet's file or a damaged one is refused as
238
+ untrusted; the picked copy and decrypted temp file are deleted either way.
239
+ - **UI.** Settings and Vault "Export Wallet Data" now export encrypted; dev builds get an extra
240
+ "Export Wallet Data (unencrypted)" row. `useExportWalletData().exportData({ encrypt })`
241
+ defaults to `true`.
242
+ - New core exports: `encryptDbImage`, `decryptDbImage`, `isEncryptedDbImage`, `EncryptedDbError`.
243
+
3
244
  ## 0.22.0
4
245
 
5
246
  1Color / BRC-207 tokens through `@bsv/color-permission-module`. There is no
package/README.md CHANGED
@@ -57,14 +57,14 @@ Expo SDK line.
57
57
 
58
58
  | Package | Version |
59
59
  | ------------------------------ | ------- |
60
- | `@bsv/sdk` | ^4.0.0 |
61
- | `@bsv/wallet-toolbox-mobile` | ^2.15.0 |
62
- | `@bsv/btms-permission-module` | ^1.2.1 |
60
+ | `@bsv/sdk` | ^4.0.1 |
61
+ | `@bsv/wallet-toolbox-mobile` | ^2.15.1 |
62
+ | `@bsv/btms-permission-module` | ^1.2.4 |
63
63
  | `@bsv/color-permission-module` | ^0.2.0 |
64
64
  | `@bsv/mandala` | ^0.5.0 |
65
65
  | `@bsv/air-gap` | ^0.1.3 |
66
66
  | `@bsv/backup-cache-client` | ^0.1.0 |
67
- | `@bsv/message-box-client` | ^2.5.3 |
67
+ | `@bsv/message-box-client` | ^2.7.0 |
68
68
  | `@bsv/templates` | ^2.2.0 |
69
69
  | `@noble/curves` | ^2.3.0 |
70
70
  | `qrcode` | ^1.5.4 |
@@ -76,10 +76,14 @@ React Native app must alias to `@bsv/wallet-toolbox-mobile` (see
76
76
  [`metro.config.js`](#metroconfigjs) and [Jest configuration](#jest-configuration)).
77
77
  The module also declares `@bsv/wallet-toolbox-client` as a peer; satisfy it
78
78
  with an npm alias of the mobile toolbox, e.g.
79
- `"@bsv/wallet-toolbox-client": "npm:@bsv/wallet-toolbox-mobile@^2.15.0"`, so no
79
+ `"@bsv/wallet-toolbox-client": "npm:@bsv/wallet-toolbox-mobile@^2.15.1"`, so no
80
80
  second toolbox is installed. That copy is never loaded (the bundler and Jest
81
81
  map the name to `-mobile`), so `patch-package` patches only `-mobile`.
82
82
 
83
+ The files under this repo's `patches/` are in pnpm format: paths are relative
84
+ to the package root. For `patch-package`, prefix each path with
85
+ `node_modules/<package name>/`.
86
+
83
87
  ### Expo native modules (required — each needs its own autolinking/config)
84
88
 
85
89
  | Package | Version |
@@ -183,10 +187,7 @@ configureToolbox({
183
187
  arcUrl: process.env.EXPO_PUBLIC_ARC_URL,
184
188
  arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
185
189
  chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
186
- whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY,
187
- // A distinct key: TAAL and WhatsOnChain are different origins, and this
188
- // one is never used as a fallback for the other.
189
- taalApiKey: process.env.EXPO_PUBLIC_TAAL_API_KEY
190
+ whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
190
191
  }
191
192
  }
192
193
  })
@@ -0,0 +1,15 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'org.bsv'
7
+ version = '0.0.0'
8
+
9
+ android {
10
+ namespace 'org.bsv.boundedfetch'
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName '0.0.0'
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ </manifest>
@@ -0,0 +1,19 @@
1
+ package org.bsv.boundedfetch;
2
+
3
+ import java.io.ByteArrayOutputStream;
4
+ import java.io.IOException;
5
+
6
+ /** Counts decoded response bytes before they enter the accumulated body. */
7
+ public final class BoundedBody {
8
+ private final int limit;
9
+ private final ByteArrayOutputStream body = new ByteArrayOutputStream();
10
+
11
+ public BoundedBody(int limit) { this.limit = limit; }
12
+
13
+ public void append(byte[] chunk, int count) throws IOException {
14
+ if (count > limit - body.size()) throw new IOException("ERR_RESPONSE_TOO_LARGE");
15
+ body.write(chunk, 0, count);
16
+ }
17
+
18
+ public byte[] bytes() { return body.toByteArray(); }
19
+ }
@@ -0,0 +1,28 @@
1
+ package org.bsv.boundedfetch;
2
+
3
+ import java.io.IOException;
4
+ import java.net.HttpURLConnection;
5
+ import java.util.concurrent.atomic.AtomicBoolean;
6
+
7
+ /** Cancellation remains effective even before HttpURLConnection is connected. */
8
+ public final class BoundedConnection {
9
+ private final HttpURLConnection connection;
10
+ private final AtomicBoolean cancelled = new AtomicBoolean();
11
+
12
+ public BoundedConnection(HttpURLConnection connection) { this.connection = connection; }
13
+
14
+ public void cancel() {
15
+ cancelled.set(true);
16
+ connection.disconnect();
17
+ }
18
+
19
+ public void checkActive() throws IOException {
20
+ if (cancelled.get()) throw new IOException("Bounded request aborted");
21
+ }
22
+
23
+ public void connect() throws IOException {
24
+ checkActive();
25
+ connection.connect();
26
+ checkActive();
27
+ }
28
+ }
@@ -0,0 +1,114 @@
1
+ package org.bsv.boundedfetch
2
+
3
+ import android.util.Base64
4
+ import expo.modules.kotlin.Promise
5
+ import expo.modules.kotlin.modules.Module
6
+ import expo.modules.kotlin.modules.ModuleDefinition
7
+ import expo.modules.kotlin.records.Field
8
+ import expo.modules.kotlin.records.Record
9
+ import java.net.HttpURLConnection
10
+ import java.net.URL
11
+ import java.util.concurrent.ConcurrentHashMap
12
+ import java.util.concurrent.Executors
13
+ import java.util.zip.GZIPInputStream
14
+
15
+ class BoundedRequestOptions : Record {
16
+ @Field var id: String = ""
17
+ @Field var url: String = ""
18
+ @Field var method: String = "GET"
19
+ @Field var headers: List<List<String>> = emptyList()
20
+ @Field var body: String? = null
21
+ @Field var maxBytes: Int = -1
22
+ }
23
+
24
+ class BsvBoundedFetchModule : Module() {
25
+ private val requests = ConcurrentHashMap<String, BoundedConnection>()
26
+ private val workers = Executors.newCachedThreadPool()
27
+
28
+ override fun definition() = ModuleDefinition {
29
+ Name("BsvBoundedFetch")
30
+
31
+ // Register synchronously on the module queue before scheduling network I/O.
32
+ // The subsequent cancel call uses the same queue and sees the receiver.
33
+ AsyncFunction("request") { options: BoundedRequestOptions, promise: Promise ->
34
+ try {
35
+ val url = URL(options.url)
36
+ require(url.protocol == "https" && options.maxBytes in 0..67108864) { "Invalid bounded HTTPS request" }
37
+ val connection = url.openConnection() as HttpURLConnection
38
+ connection.instanceFollowRedirects = false
39
+ connection.useCaches = false
40
+ connection.connectTimeout = 30000
41
+ connection.readTimeout = 30000
42
+ connection.requestMethod = options.method
43
+ options.headers.forEach { header ->
44
+ require(header.size == 2) { "Invalid header" }
45
+ connection.setRequestProperty(header[0], header[1])
46
+ }
47
+ // Explicit encoding disables Android's implicit decompression; count the
48
+ // decoded stream below, including when the server ignores identity.
49
+ connection.setRequestProperty("Accept-Encoding", "identity")
50
+ val receiver = BoundedConnection(connection)
51
+ requests[options.id] = receiver
52
+ workers.execute {
53
+ try {
54
+ receiver.checkActive()
55
+ val upload = options.body?.let { Base64.decode(it, Base64.DEFAULT) }
56
+ if (upload != null) {
57
+ connection.doOutput = true
58
+ connection.setFixedLengthStreamingMode(upload.size)
59
+ }
60
+ receiver.connect()
61
+ if (upload != null) {
62
+ receiver.checkActive()
63
+ connection.outputStream.use { it.write(upload) }
64
+ }
65
+ receiver.checkActive()
66
+ val status = connection.responseCode
67
+ val declaredLength = connection.getHeaderField("Content-Length")?.toLongOrNull()
68
+ if (declaredLength != null && declaredLength > options.maxBytes) {
69
+ throw java.io.IOException("ERR_RESPONSE_TOO_LARGE")
70
+ }
71
+ val body = BoundedBody(options.maxBytes)
72
+ val raw = if (status >= 400) connection.errorStream else connection.inputStream
73
+ raw?.use {
74
+ val stream = when (connection.contentEncoding?.lowercase()) {
75
+ null, "identity" -> it
76
+ "gzip" -> GZIPInputStream(it)
77
+ else -> throw java.io.IOException("Unsupported response encoding")
78
+ }
79
+ stream.use { decoded ->
80
+ val chunk = ByteArray(8192)
81
+ while (true) {
82
+ receiver.checkActive()
83
+ val count = decoded.read(chunk)
84
+ if (count < 0) break
85
+ // Reject BEFORE appending, with no native-to-JS chunk queue.
86
+ body.append(chunk, count)
87
+ }
88
+ }
89
+ }
90
+ val headers = connection.headerFields.entries.filter { it.key != null }
91
+ .flatMap { entry -> entry.value.map { listOf(entry.key, it) } }
92
+ promise.resolve(mapOf("status" to status, "headers" to headers,
93
+ "body" to Base64.encodeToString(body.bytes(), Base64.NO_WRAP)))
94
+ } catch (error: Exception) {
95
+ promise.reject("ERR_BOUNDED_FETCH", error.message ?: "Bounded request failed", error)
96
+ } finally {
97
+ requests.remove(options.id)
98
+ connection.disconnect()
99
+ }
100
+ }
101
+ } catch (error: Exception) {
102
+ promise.reject("ERR_BOUNDED_FETCH", error.message ?: "Invalid bounded request", error)
103
+ }
104
+ }
105
+
106
+ AsyncFunction("cancel") { id: String -> requests[id]?.cancel(); Unit }
107
+
108
+ OnDestroy {
109
+ requests.values.forEach { it.cancel() }
110
+ requests.clear()
111
+ workers.shutdownNow()
112
+ }
113
+ }
114
+ }
@@ -33,10 +33,11 @@ export class RemoteSyncReader {
33
33
  private entries: LogEntry[] | null = null
34
34
  private next = 0
35
35
  private prefetched: { seq: number; result: Promise<BlobResult> } | null = null
36
- /** Decoded once, keyed by seq, so verifiedComplete's own look-ahead at the newest entry
37
- * never re-fetches or re-decrypts it when replay later reaches that same entry. */
36
+ /** One decoded entry retained across authentication and replay, bounded independently of log size. */
38
37
  private decodedCache: { seq: number; decoded: DecodedEntry } | null = null
39
38
  private verifiedCompletePromise: Promise<boolean> | null = null
39
+ private authenticationPromise: Promise<boolean> | null = null
40
+ private authenticatedLog = false
40
41
  /** The most recent (i.e. furthest along in replay order) appData snapshot seen on any
41
42
  * entry so far — see the `appData` getter below. */
42
43
  private lastAppData: AppDataSnapshot | undefined
@@ -48,7 +49,8 @@ export class RemoteSyncReader {
48
49
  private readonly deviceId: string,
49
50
  private readonly generation: number,
50
51
  private readonly settings: TableSettings,
51
- private readonly expectedHeadSeq?: number
52
+ private readonly expectedHeadSeq?: number,
53
+ private readonly onActivity?: () => void
52
54
  ) {}
53
55
 
54
56
  /** Settings for the storage being restored into. */
@@ -57,9 +59,8 @@ export class RemoteSyncReader {
57
59
  }
58
60
 
59
61
  /**
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
+ * Fetch and check server-index consistency, once. Authenticated membership is
63
+ * checked separately against the encrypted positions before replay.
63
64
  */
64
65
  private async ensureIndex(): Promise<LogEntry[]> {
65
66
  if (this.entries == null) {
@@ -101,15 +102,8 @@ export class RemoteSyncReader {
101
102
  } else {
102
103
  ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
103
104
  }
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.
105
+ // These checks detect corrupted transport bytes. The encrypted v2 position
106
+ // below is the authority for log membership, not this server-owned index.
113
107
  if (ciphertext.length !== entry.size) {
114
108
  throw new BackupChainError(
115
109
  `backup blob at sequence ${entry.seq} is ${ciphertext.length} bytes but the index recorded ${entry.size}`
@@ -119,7 +113,18 @@ export class RemoteSyncReader {
119
113
  if (digest !== entry.sha256) {
120
114
  throw new BackupChainError(`backup blob at sequence ${entry.seq} does not match the index's recorded digest`)
121
115
  }
122
- return await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
116
+ const decoded = await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
117
+ const position = decoded.position
118
+ if (
119
+ position &&
120
+ (position.deviceId !== this.deviceId ||
121
+ position.generation !== this.generation ||
122
+ position.seq !== entry.seq ||
123
+ position.prevSha256 !== (entry.prevSha256 ?? undefined))
124
+ ) {
125
+ throw new BackupChainError(`authenticated backup position does not match sequence ${entry.seq}`)
126
+ }
127
+ return decoded
123
128
  }
124
129
 
125
130
  /**
@@ -134,7 +139,7 @@ export class RemoteSyncReader {
134
139
  * rides alongside a chunk rather than replacing it, so nothing here needs to be swallowed.
135
140
  */
136
141
  async getSyncChunk(_args: RequestSyncChunkArgs): Promise<SyncChunk> {
137
- await this.ensureIndex()
142
+ await this.authenticateLog()
138
143
  const entries = this.entries!
139
144
 
140
145
  if (this.next >= entries.length) {
@@ -149,7 +154,9 @@ export class RemoteSyncReader {
149
154
  // own log (unlike restoreOnImport's cross-device merge). An entry that predates this
150
155
  // feature, or one written while there was genuinely nothing app-owned to add, carries no
151
156
  // `appData` at all and must not erase a still-current snapshot from an earlier entry.
152
- if (decoded.appData !== undefined) this.lastAppData = decoded.appData
157
+ // Legacy snapshots are reorderable by the service and must not overwrite
158
+ // live pending payments, outbox entries, contacts or issued dates.
159
+ if (this.authenticatedLog && decoded.appData !== undefined) this.lastAppData = decoded.appData
153
160
  // Advance only after successful download AND decryption. Retrying this
154
161
  // reader after either fails must retry the same entry rather than lose it.
155
162
  this.next++
@@ -192,21 +199,9 @@ export class RemoteSyncReader {
192
199
  }
193
200
 
194
201
  /**
195
- * Whether this generation's log, as it stands right now, is provably complete — i.e. this
196
- * device itself once confirmed the generation's initial snapshot was whole, independent of
197
- * anything the server's index metadata alone reports (see codec.ts's DecodedEntry and
198
- * push.ts's own seal docs).
199
- *
200
- * True only when the NEWEST entry carries a seal for THIS generation whose
201
- * `initialChunkCount` is no greater than the number of entries in the log — i.e. every
202
- * chunk of the initial snapshot the seal refers to is present. Cheap by design: only that
203
- * one entry is decrypted here, never the whole log — replay (getSyncChunk) still decodes
204
- * every entry as it goes and is what actually enforces the chain end to end.
205
- *
206
- * Because every chunk appended after the initial window closes carries the SAME seal (see
207
- * push.ts's pushOnce), this stays true as further deltas land, rather than flipping back to
208
- * false the moment a new chunk becomes the newest entry — a generation is not "un-verified"
209
- * by continuing to receive backups.
202
+ * True only after all v2 positions and the ordered initial-snapshot head
203
+ * commitment verify. A complete authentic old log can still be replayed by a
204
+ * server: freshness requires an independent trusted head anchor.
210
205
  */
211
206
  async verifiedComplete(): Promise<boolean> {
212
207
  if (this.verifiedCompletePromise == null) {
@@ -216,23 +211,53 @@ export class RemoteSyncReader {
216
211
  }
217
212
 
218
213
  private async computeVerifiedComplete(): Promise<boolean> {
219
- const entries = await this.ensureIndex()
220
- if (entries.length === 0) return false
221
-
222
- const last = entries[entries.length - 1]
223
- let decoded: DecodedEntry
224
214
  try {
225
- decoded = await this.fetchAndDecode(last)
215
+ if (!(await this.authenticateLog())) return false
216
+ return this.decodedCache?.decoded.seal != null
226
217
  } catch {
227
- // A last entry that fails to download or decrypt cannot be trusted as sealed —
228
- // treat the generation as unverified rather than throwing out of a check that
229
- // pickTarget uses purely to rank candidates.
218
+ // Ranking may skip a corrupt candidate. Its cached authentication failure
219
+ // is still rethrown before replay if the legacy fallback selects it.
230
220
  return false
231
221
  }
232
- this.decodedCache = { seq: last.seq, decoded }
233
- const seal = decoded.seal
234
- if (seal == null) return false
235
- return seal.generation === this.generation && seal.initialChunkCount <= entries.length
222
+ }
223
+
224
+ private authenticateLog(): Promise<boolean> {
225
+ if (this.authenticationPromise == null) {
226
+ this.authenticationPromise = this.checkAuthenticatedLog().catch(error => {
227
+ // Transient download failures must remain retryable at the same position.
228
+ this.authenticationPromise = null
229
+ throw error
230
+ })
231
+ }
232
+ return this.authenticationPromise
233
+ }
234
+
235
+ private async checkAuthenticatedLog(): Promise<boolean> {
236
+ const entries = await this.ensureIndex()
237
+ if (entries.length === 0) return false
238
+ const first = entries[0]
239
+ const decoded = await this.fetchAndDecode(first)
240
+ this.decodedCache = { seq: first.seq, decoded }
241
+ // Keep legacy entity recovery available, explicitly unverified. Its count-
242
+ // only seals prove neither ordered membership nor snapshot completeness.
243
+ if (!decoded.position) return false
244
+
245
+ // Preflight every authenticated position before returning ANY recovery
246
+ // state. Keep only one decoded entry cached so large backups stay bounded.
247
+ for (const entry of entries) {
248
+ const current = await this.fetchAndDecode(entry)
249
+ if (!current.position) throw new BackupChainError('backup generation mixes legacy and authenticated positions')
250
+ if (entry.seq === entries.length) this.decodedCache = { seq: entry.seq, decoded: current }
251
+ const seal = current.seal
252
+ if (seal && entries[seal.initialChunkCount - 1]?.sha256 !== seal.initialHeadSha256) {
253
+ throw new BackupChainError('authenticated initial snapshot head does not match the backup log')
254
+ }
255
+ // Authentication can take longer than the rebuild's inactivity deadline.
256
+ // Report work without exposing any recovery data before the whole log verifies.
257
+ this.onActivity?.()
258
+ }
259
+ this.authenticatedLog = true
260
+ return true
236
261
  }
237
262
 
238
263
  /**