@bsv/expo-wallet-toolbox 0.23.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.
- package/CHANGELOG.md +133 -0
- package/README.md +1 -4
- package/android/build.gradle +15 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
- package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
- package/core/backup/RemoteSyncReader.ts +71 -46
- package/core/backup/client.ts +6 -15
- package/core/backup/codec.ts +78 -13
- package/core/backup/constants.ts +3 -9
- package/core/backup/cursor.ts +8 -0
- package/core/backup/push.ts +26 -16
- package/core/backup/restore.ts +6 -5
- package/core/bridge/inbox.ts +169 -64
- package/core/bridge/memoryInboxStore.ts +10 -1
- package/core/constants.ts +7 -11
- package/core/context/WalletConnectionContext.tsx +85 -48
- package/core/context/WalletContext.tsx +30 -32
- package/core/context/usePairingAttempt.ts +31 -0
- package/core/e2e/broadcaster.ts +25 -0
- package/core/e2e/consentFixture.ts +46 -0
- package/core/e2e/mode.ts +42 -0
- package/core/headers/OfflineFirstChaintracks.ts +57 -107
- package/core/headers/headerConsensus.ts +230 -0
- package/core/headers/headerStore.ts +344 -122
- package/core/headers/prewarm.ts +4 -7
- package/core/headers/syncHeaders.ts +82 -12
- package/core/i18n/translations.tsx +47 -12
- package/core/identity/handleRegistry/client.ts +4 -2
- package/core/identity/handleRegistry/resolver.ts +7 -11
- package/core/index.ts +2 -0
- package/core/localpay/pending.ts +39 -4
- package/core/network/boundedFetch.ts +101 -0
- package/core/networks.ts +11 -13
- package/core/pay/rails/address.ts +5 -4
- package/core/pay/rails/handle.ts +3 -1
- package/core/pay/rails/sweep.ts +791 -0
- package/core/peerpay/brc29.ts +4 -0
- package/core/peerpay/handleResendRequests.ts +15 -2
- package/core/peerpay/outbox.ts +115 -2
- package/core/profiles/assertProfileEmpty.ts +2 -2
- package/core/profiles/profileStore.ts +3 -2
- package/core/services/arcadeBroadcastProvider.ts +260 -114
- package/core/services/secrets/kek.ts +5 -0
- package/core/services/secrets/migration.ts +27 -2
- package/core/services/secrets/policy.ts +6 -0
- package/core/services/vault/VaultKeyService.ts +5 -2
- package/core/services/vault/ceremony.ts +2 -2
- package/core/services/vault/ceremonyHost.ts +1 -1
- package/core/services/vault/guard.ts +10 -0
- package/core/services/vault/outputAuthority.ts +76 -0
- package/core/services/vault/transfers.ts +52 -28
- package/core/services/vault/vaultStore.ts +60 -14
- package/core/services/walletConnectionValidation.ts +13 -1
- package/core/services/walletServiceConfig.ts +8 -7
- package/core/stores/ConnectionStore.ts +17 -0
- package/core/toolboxConfig.ts +60 -1
- package/expo-module.config.json +5 -0
- package/ios/BoundedBody.swift +15 -0
- package/ios/BsvBoundedFetch.podspec +17 -0
- package/ios/BsvBoundedFetchModule.swift +121 -0
- package/package.json +7 -3
- package/ui/components/pay/AddressReceive.tsx +6 -2
- package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
- package/ui/components/pay/PayCellRow.tsx +3 -1
- package/ui/components/pay/PayForm.tsx +12 -2
- package/ui/components/pay/RecipientField.tsx +1 -0
- package/ui/components/pay/RequestHub.tsx +1 -0
- package/ui/components/pay/UniversalSend.tsx +110 -42
- package/ui/components/ui/ListRow.tsx +10 -2
- package/ui/components/vault/KeyChooser.tsx +1 -1
- package/ui/components/wallet/AmountInput.tsx +4 -1
- package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
- package/ui/components/wallet/ProfileButton.tsx +1 -0
- package/ui/importDatabases.ts +31 -6
- package/ui/screens/ConnectionsScreen.tsx +12 -3
- package/ui/screens/PairScreen.tsx +10 -3
- package/ui/screens/PayScreen.tsx +1 -0
- package/ui/screens/TrustScreen.tsx +6 -3
- package/ui/screens/VaultScreen.tsx +13 -3
- package/ui/screens/VaultTransferScreen.tsx +6 -3
- package/ui/screens/WalletConfigScreen.tsx +17 -2
- package/ui/screens/WalletHomeScreen.tsx +7 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,139 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
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
|
+
|
|
5
138
|
## 0.23.0
|
|
6
139
|
|
|
7
140
|
Peer floors raised to the latest `@bsv` releases, the browser wallet bridge
|
package/README.md
CHANGED
|
@@ -187,10 +187,7 @@ configureToolbox({
|
|
|
187
187
|
arcUrl: process.env.EXPO_PUBLIC_ARC_URL,
|
|
188
188
|
arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
|
|
189
189
|
chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
|
|
190
|
-
whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
|
|
191
|
-
// A distinct key: TAAL and WhatsOnChain are different origins, and this
|
|
192
|
-
// one is never used as a fallback for the other.
|
|
193
|
-
taalApiKey: process.env.EXPO_PUBLIC_TAAL_API_KEY
|
|
190
|
+
whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
|
|
194
191
|
}
|
|
195
192
|
}
|
|
196
193
|
})
|
|
@@ -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
|
-
/**
|
|
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
|
|
61
|
-
*
|
|
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
|
-
//
|
|
105
|
-
//
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
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
|
-
|
|
215
|
+
if (!(await this.authenticateLog())) return false
|
|
216
|
+
return this.decodedCache?.decoded.seal != null
|
|
226
217
|
} catch {
|
|
227
|
-
//
|
|
228
|
-
//
|
|
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
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
/**
|
package/core/backup/client.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
} from '@bsv/backup-cache-client'
|
|
33
33
|
import { MAX_RESTORE_RESPONSE_BYTES, type BackupChain } from './constants'
|
|
34
34
|
import { deriveBackupWallet } from './derive'
|
|
35
|
+
import { createBoundedNativeFetch } from '../network/boundedFetch'
|
|
35
36
|
|
|
36
37
|
export { BackupHttpError, ERR_BLOB_TOO_LARGE, ERR_SEQ_CONFLICT }
|
|
37
38
|
export type { DeviceSummary, Limits, LogEntry }
|
|
@@ -53,13 +54,13 @@ export class BackupClient extends BackupCacheClient {
|
|
|
53
54
|
* @param primaryKey the wallet's m/0'/0' key, from which the pseudonym is derived.
|
|
54
55
|
* @param chain the network this client serves. Each chain derives a different
|
|
55
56
|
* pseudonym, so each network's log lives in its own server account.
|
|
56
|
-
* @param fetchImpl injectable transport for tests;
|
|
57
|
+
* @param fetchImpl trusted injectable transport for tests; production uses the native receive cap.
|
|
57
58
|
*/
|
|
58
59
|
constructor(baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
|
|
59
60
|
super({
|
|
60
61
|
baseUrl,
|
|
61
62
|
wallet: deriveBackupWallet(primaryKey, chain),
|
|
62
|
-
fetch: withBackupRequestTimeout(fetchImpl ?? (
|
|
63
|
+
fetch: withBackupRequestTimeout(fetchImpl ?? createBoundedNativeFetch(MAX_RESTORE_RESPONSE_BYTES))
|
|
63
64
|
})
|
|
64
65
|
}
|
|
65
66
|
|
|
@@ -80,13 +81,9 @@ export class BackupClient extends BackupCacheClient {
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* before any body bytes arrive. Neither phase may strand the monitor.
|
|
87
|
-
*
|
|
88
|
-
* Wrap the existing readers instead of rebuilding/cloning the Response: a
|
|
89
|
-
* large backup still allocates only the buffer the package itself requests.
|
|
84
|
+
* Apply one deadline to transport and body decoding. The production transport
|
|
85
|
+
* bounds actual received bytes natively before this wrapper receives a Response;
|
|
86
|
+
* Content-Length here is only an advisory early rejection for injected transports.
|
|
90
87
|
*/
|
|
91
88
|
export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch {
|
|
92
89
|
return async (input, init) => {
|
|
@@ -135,12 +132,6 @@ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch
|
|
|
135
132
|
}
|
|
136
133
|
|
|
137
134
|
const response = await bounded(() => transport(input, { ...init, signal: controller.signal }))
|
|
138
|
-
// Refuse before EITHER reader is ever wrapped, let alone called: on this platform fetch
|
|
139
|
-
// has no incremental/streaming read mode (see this function's own docstring), so a
|
|
140
|
-
// declared-oversized body can only be bounded here, never partway through reading it.
|
|
141
|
-
// A response that omits Content-Length entirely passes through unchanged — a documented
|
|
142
|
-
// residual gap (see MAX_RESTORE_RESPONSE_BYTES), not a false rejection of ordinary
|
|
143
|
-
// traffic that happens not to declare a length.
|
|
144
135
|
const declaredLength = Number(response.headers.get('content-length'))
|
|
145
136
|
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_RESPONSE_BYTES) {
|
|
146
137
|
throw new BackupHttpError(
|