@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/core/backup/codec.ts
CHANGED
|
@@ -140,16 +140,23 @@ function unpackBytes(value: unknown, key?: string): unknown {
|
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
* encodeChunk), never as a separate log entry: an old build's decodeChunk ignores a field it
|
|
147
|
-
* has never heard of, so a chunk carrying a seal is byte-for-byte a chunk to any reader that
|
|
148
|
-
* predates sealing.
|
|
143
|
+
* The initial snapshot's ordered ciphertext head and count. V2 readers verify
|
|
144
|
+
* both against a fully position-authenticated generation. Legacy count-only
|
|
145
|
+
* seals remain decodable but cannot establish completeness.
|
|
149
146
|
*/
|
|
150
147
|
export interface BackupSeal {
|
|
151
148
|
generation: number
|
|
152
149
|
initialChunkCount: number
|
|
150
|
+
/** V2: digest of the final ciphertext in the ordered initial snapshot. */
|
|
151
|
+
initialHeadSha256?: string
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Position authenticated inside the encrypted v2 envelope, never by the server index. */
|
|
155
|
+
export interface BackupLogPosition {
|
|
156
|
+
deviceId: string
|
|
157
|
+
generation: number
|
|
158
|
+
seq: number
|
|
159
|
+
prevSha256?: string
|
|
153
160
|
}
|
|
154
161
|
|
|
155
162
|
/**
|
|
@@ -181,10 +188,19 @@ export interface AppDataSnapshot {
|
|
|
181
188
|
* has ever appended — this type exists mainly so RemoteSyncReader can read `seal`/`appData`
|
|
182
189
|
* off an entry without re-decoding it a second time.
|
|
183
190
|
*/
|
|
184
|
-
export type DecodedEntry = {
|
|
191
|
+
export type DecodedEntry = {
|
|
192
|
+
kind: 'chunk'
|
|
193
|
+
chunk: SyncChunk
|
|
194
|
+
seal?: BackupSeal
|
|
195
|
+
appData?: AppDataSnapshot
|
|
196
|
+
position?: BackupLogPosition
|
|
197
|
+
}
|
|
185
198
|
|
|
186
199
|
/**
|
|
187
|
-
* Serialise and encrypt a sync chunk
|
|
200
|
+
* Serialise and encrypt a sync chunk. Production writers supply `position`,
|
|
201
|
+
* selecting v2 and binding the device, generation, sequence and predecessor
|
|
202
|
+
* digest inside the AEAD envelope. Omitting it retains legacy codec support;
|
|
203
|
+
* legacy entries can recover entities but cannot authenticate recovery snapshots.
|
|
188
204
|
*
|
|
189
205
|
* `counterparty: 'self'` is the entire zero-knowledge property. With 'self' the symmetric
|
|
190
206
|
* key comes from the wallet's own key material and nobody else can derive it; naming the
|
|
@@ -214,9 +230,13 @@ export async function encodeChunk(
|
|
|
214
230
|
chunk: SyncChunk,
|
|
215
231
|
chain: BackupChain,
|
|
216
232
|
seal?: BackupSeal,
|
|
217
|
-
appData?: AppDataSnapshot
|
|
233
|
+
appData?: AppDataSnapshot,
|
|
234
|
+
position?: BackupLogPosition
|
|
218
235
|
): Promise<number[]> {
|
|
219
|
-
const json = stringifyJsonRpc(
|
|
236
|
+
const json = stringifyJsonRpc(
|
|
237
|
+
{ version: position ? 2 : undefined, chain, chunk: packBytes(chunk), seal, appData, position },
|
|
238
|
+
true
|
|
239
|
+
)
|
|
220
240
|
const { ciphertext } = await wallet.encrypt({
|
|
221
241
|
plaintext: Utils.toArray(json, 'utf8'),
|
|
222
242
|
protocolID: BACKUP_PROTOCOL,
|
|
@@ -248,6 +268,8 @@ export async function decodeEntry(
|
|
|
248
268
|
counterparty: 'self'
|
|
249
269
|
})
|
|
250
270
|
const envelope = parseJsonRpc(Utils.toUTF8(plaintext), true) as {
|
|
271
|
+
version?: unknown
|
|
272
|
+
position?: unknown
|
|
251
273
|
chain?: unknown
|
|
252
274
|
chunk?: unknown
|
|
253
275
|
seal?: unknown
|
|
@@ -258,16 +280,59 @@ export async function decodeEntry(
|
|
|
258
280
|
`backup blob is labeled for chain '${String(envelope?.chain)}' but '${chain}' was expected — refusing to restore across networks`
|
|
259
281
|
)
|
|
260
282
|
}
|
|
283
|
+
if (envelope.version !== undefined && envelope.version !== 2) throw new Error('unsupported backup envelope version')
|
|
284
|
+
const position = envelope.version === 2 ? decodePosition(envelope.position) : undefined
|
|
261
285
|
let seal: BackupSeal | undefined
|
|
262
286
|
if (envelope.seal != null) {
|
|
263
|
-
const s = envelope.seal as { generation?: unknown; initialChunkCount?: unknown }
|
|
287
|
+
const s = envelope.seal as { generation?: unknown; initialChunkCount?: unknown; initialHeadSha256?: unknown }
|
|
264
288
|
if (typeof s.generation !== 'number' || typeof s.initialChunkCount !== 'number') {
|
|
265
289
|
throw new Error('backup seal is malformed')
|
|
266
290
|
}
|
|
267
|
-
|
|
291
|
+
if (
|
|
292
|
+
position &&
|
|
293
|
+
(!Number.isSafeInteger(s.initialChunkCount) ||
|
|
294
|
+
s.initialChunkCount < 1 ||
|
|
295
|
+
!isDigest(s.initialHeadSha256) ||
|
|
296
|
+
s.generation !== position.generation ||
|
|
297
|
+
s.initialChunkCount >= position.seq)
|
|
298
|
+
) {
|
|
299
|
+
throw new Error('authenticated backup seal is malformed')
|
|
300
|
+
}
|
|
301
|
+
seal = {
|
|
302
|
+
generation: s.generation,
|
|
303
|
+
initialChunkCount: s.initialChunkCount,
|
|
304
|
+
...(position ? { initialHeadSha256: s.initialHeadSha256 as string } : {})
|
|
305
|
+
}
|
|
268
306
|
}
|
|
269
307
|
const appData = decodeAppData(envelope.appData)
|
|
270
|
-
return {
|
|
308
|
+
return {
|
|
309
|
+
kind: 'chunk',
|
|
310
|
+
chunk: unpackBytes(envelope.chunk) as SyncChunk,
|
|
311
|
+
seal,
|
|
312
|
+
appData,
|
|
313
|
+
...(position ? { position } : {})
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function isDigest(value: unknown): value is string {
|
|
318
|
+
return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function decodePosition(raw: unknown): BackupLogPosition {
|
|
322
|
+
const p = raw as Partial<BackupLogPosition> | null
|
|
323
|
+
if (
|
|
324
|
+
!p ||
|
|
325
|
+
typeof p.deviceId !== 'string' ||
|
|
326
|
+
!/^[0-9a-f]{32}$/.test(p.deviceId) ||
|
|
327
|
+
!Number.isSafeInteger(p.generation) ||
|
|
328
|
+
p.generation! < 1 ||
|
|
329
|
+
!Number.isSafeInteger(p.seq) ||
|
|
330
|
+
p.seq! < 1 ||
|
|
331
|
+
(p.seq === 1 ? p.prevSha256 !== undefined : !isDigest(p.prevSha256))
|
|
332
|
+
) {
|
|
333
|
+
throw new Error('authenticated backup position is malformed')
|
|
334
|
+
}
|
|
335
|
+
return { deviceId: p.deviceId, generation: p.generation!, seq: p.seq!, prevSha256: p.prevSha256 }
|
|
271
336
|
}
|
|
272
337
|
|
|
273
338
|
/** Validates a decrypted envelope's `appData` field. Throws rather than silently dropping a
|
package/core/backup/constants.ts
CHANGED
|
@@ -82,15 +82,9 @@ export const MIN_PUSH_INTERVAL_MS = 60_000
|
|
|
82
82
|
export const MAX_BLOB_BYTES = 1 << 20
|
|
83
83
|
|
|
84
84
|
/**
|
|
85
|
-
* Hard ceiling on
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
* Independent of the server's own advertised cap (`client.limits().maxBlobBytes`, up to
|
|
89
|
-
* 200 MiB) — this exists so a malicious or compromised backup host cannot exhaust mobile
|
|
90
|
-
* memory merely by declaring (and then sending) an oversized body. React Native's fetch has
|
|
91
|
-
* no incremental/streaming read mode (see client.ts's withBackupRequestTimeout), so the
|
|
92
|
-
* only point at which an oversized body can be bounded at all is before it is ever
|
|
93
|
-
* requested to be read — hence the check runs on the header, not the bytes.
|
|
85
|
+
* Hard ceiling on decoded bytes in any backup HTTP response, enforced inside
|
|
86
|
+
* the native receiver before accumulation, base64 conversion or JSON parsing.
|
|
87
|
+
* The server's advertised blob cap does not override this device memory bound.
|
|
94
88
|
*/
|
|
95
89
|
export const MAX_RESTORE_RESPONSE_BYTES = 64 * 1024 * 1024
|
|
96
90
|
|
package/core/backup/cursor.ts
CHANGED
|
@@ -51,6 +51,10 @@ export const ENTITY_TO_CHUNK_ARRAY: Record<EntityName, string> = {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
export interface PushCursor {
|
|
54
|
+
/** Undefined on legacy logs, which must rotate before writing authenticated positions. */
|
|
55
|
+
formatVersion?: 2
|
|
56
|
+
/** Authenticated initial snapshot commitment, fixed when the first window closes. */
|
|
57
|
+
initialHeadSha256?: string
|
|
54
58
|
/** ISO timestamp; only records updated at or after this are considered. */
|
|
55
59
|
since?: string
|
|
56
60
|
/** Per-entity consumed counts within the current `since` window. */
|
|
@@ -88,6 +92,8 @@ export interface PushCursor {
|
|
|
88
92
|
|
|
89
93
|
export function freshCursor(generation = 1): PushCursor {
|
|
90
94
|
return {
|
|
95
|
+
formatVersion: 2,
|
|
96
|
+
initialHeadSha256: undefined,
|
|
91
97
|
since: undefined,
|
|
92
98
|
offsets: zeroOffsets(),
|
|
93
99
|
maxUpdatedAt: undefined,
|
|
@@ -119,6 +125,8 @@ export async function loadCursor(chain: BackupChain, pseudonym: string, deviceId
|
|
|
119
125
|
try {
|
|
120
126
|
const parsed = JSON.parse(raw) as Partial<PushCursor>
|
|
121
127
|
return {
|
|
128
|
+
formatVersion: parsed.formatVersion,
|
|
129
|
+
initialHeadSha256: parsed.initialHeadSha256,
|
|
122
130
|
since: parsed.since,
|
|
123
131
|
// Merge over a zeroed base so a cursor written by an older build, before a new
|
|
124
132
|
// entity existed, does not produce an undefined offset.
|
package/core/backup/push.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* are `since`-based and replay is idempotent, so a torn read corrects itself on the next
|
|
16
16
|
* pass.
|
|
17
17
|
*/
|
|
18
|
+
import { Hash, Utils } from '@bsv/sdk'
|
|
18
19
|
import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
|
|
19
20
|
import { captureAppDataSnapshot, isEmptyAppData } from './appData'
|
|
20
21
|
import { captureContacts } from './contactsBackup'
|
|
@@ -98,6 +99,15 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
|
|
|
98
99
|
const deviceId = deps.deviceId ?? (await getDeviceId())
|
|
99
100
|
|
|
100
101
|
let cursor = await loadCursor(deps.chain, pseudonym, deviceId)
|
|
102
|
+
// Old ciphertext has no authenticated position. A new snapshot is required;
|
|
103
|
+
// claiming an existing unbound generation is now authenticated is unsafe.
|
|
104
|
+
if (
|
|
105
|
+
cursor.formatVersion !== 2 ||
|
|
106
|
+
(cursor.seq > 0 && !/^[0-9a-f]{64}$/.test(cursor.prevSha256 ?? '')) ||
|
|
107
|
+
(cursor.initialChunkCount != null && !/^[0-9a-f]{64}$/.test(cursor.initialHeadSha256 ?? ''))
|
|
108
|
+
) {
|
|
109
|
+
cursor = rotate(cursor)
|
|
110
|
+
}
|
|
101
111
|
|
|
102
112
|
// Clock-regression guard: `since` only ever advances forward via nextInstant, and the
|
|
103
113
|
// column comparison is `>=`, so a record stamped BELOW a window this cursor already
|
|
@@ -118,16 +128,6 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
|
|
|
118
128
|
cursor.maxObservedWallClock != null && cursor.maxObservedWallClock > nowIso ? cursor.maxObservedWallClock : nowIso
|
|
119
129
|
}
|
|
120
130
|
|
|
121
|
-
// Back-fill: this cursor's window closed at least once (since is set) with real chunks
|
|
122
|
-
// pushed (chunksInGeneration > 0), but under an older build that predates sealing —
|
|
123
|
-
// initialChunkCount was never set. Set it now, purely locally: the log through the
|
|
124
|
-
// current seq is already a coherent complete state, so nothing needs re-uploading. No
|
|
125
|
-
// network round trip and no new entry — the NEXT real chunk this device appends (whenever
|
|
126
|
-
// that is) carries the seal referencing this count, same as any other sealed generation.
|
|
127
|
-
if (cursor.since != null && cursor.initialChunkCount === undefined && cursor.chunksInGeneration > 0) {
|
|
128
|
-
cursor = { ...cursor, initialChunkCount: cursor.chunksInGeneration }
|
|
129
|
-
}
|
|
130
|
-
|
|
131
131
|
const chunk = await deps.storage.getSyncChunk({
|
|
132
132
|
identityKey: deps.identityKey,
|
|
133
133
|
fromStorageIdentityKey: deps.identityKey,
|
|
@@ -164,7 +164,8 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
|
|
|
164
164
|
// the seal always references the original initial snapshot, which is what lets
|
|
165
165
|
// verifiedComplete stay true as further deltas land (see RemoteSyncReader).
|
|
166
166
|
initialChunkCount:
|
|
167
|
-
cursor.initialChunkCount ?? (cursor.chunksInGeneration > 0 ? cursor.chunksInGeneration : undefined)
|
|
167
|
+
cursor.initialChunkCount ?? (cursor.chunksInGeneration > 0 ? cursor.chunksInGeneration : undefined),
|
|
168
|
+
initialHeadSha256: cursor.initialHeadSha256 ?? (cursor.chunksInGeneration > 0 ? cursor.prevSha256 : undefined)
|
|
168
169
|
}
|
|
169
170
|
|
|
170
171
|
const rotated = shouldRotate(advanced)
|
|
@@ -227,15 +228,24 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
|
|
|
227
228
|
// module's own docstring on why a dedicated marker is unsafe for an old reader).
|
|
228
229
|
const seal: BackupSeal | undefined =
|
|
229
230
|
cursor.initialChunkCount != null
|
|
230
|
-
? {
|
|
231
|
+
? {
|
|
232
|
+
generation: cursor.generation,
|
|
233
|
+
initialChunkCount: cursor.initialChunkCount,
|
|
234
|
+
initialHeadSha256: cursor.initialHeadSha256
|
|
235
|
+
}
|
|
231
236
|
: undefined
|
|
232
|
-
const ciphertext = await encodeChunk(wallet, chunk, deps.chain, seal, appDataToSend)
|
|
233
|
-
|
|
234
237
|
const seq = cursor.seq + 1
|
|
238
|
+
const ciphertext = await encodeChunk(wallet, chunk, deps.chain, seal, appDataToSend, {
|
|
239
|
+
deviceId,
|
|
240
|
+
generation: cursor.generation,
|
|
241
|
+
seq,
|
|
242
|
+
prevSha256: cursor.prevSha256
|
|
243
|
+
})
|
|
235
244
|
let sha: string
|
|
236
245
|
try {
|
|
237
|
-
|
|
238
|
-
|
|
246
|
+
await client.append(deviceId, cursor.generation, seq, cursor.prevSha256, ciphertext)
|
|
247
|
+
// The server's append response is not an authenticated commitment.
|
|
248
|
+
sha = Utils.toHex(Hash.sha256(ciphertext))
|
|
239
249
|
} catch (e) {
|
|
240
250
|
if (e instanceof BackupHttpError && e.code === ERR_SEQ_CONFLICT) {
|
|
241
251
|
// The server and the cursor disagree about the head. Resynchronise from the server's
|
package/core/backup/restore.ts
CHANGED
|
@@ -39,8 +39,9 @@ export interface RestoreDeps {
|
|
|
39
39
|
onProgress?: (chunks: number, total: number) => void
|
|
40
40
|
/**
|
|
41
41
|
* Called whenever the restore finishes a step that is not a chunk: ranking a candidate
|
|
42
|
-
* generation, and each page of the post-replay proof
|
|
43
|
-
* only says the restore is still working,
|
|
42
|
+
* generation, authenticating each entry, and each page of the post-replay proof
|
|
43
|
+
* reconciliation. Carries nothing; it only says the restore is still working,
|
|
44
|
+
* so a caller waiting on it can tell a slow
|
|
44
45
|
* restore from a stuck one.
|
|
45
46
|
*/
|
|
46
47
|
onActivity?: () => void
|
|
@@ -51,8 +52,8 @@ export interface RestoreResult {
|
|
|
51
52
|
deviceId: string
|
|
52
53
|
generation: number
|
|
53
54
|
/**
|
|
54
|
-
* True when
|
|
55
|
-
*
|
|
55
|
+
* True when every v2 position and the newest seal's ordered snapshot head
|
|
56
|
+
* commitment verify — see codec.ts's DecodedEntry and
|
|
56
57
|
* push.ts's pushOnce. False means either an explicit device/generation override was
|
|
57
58
|
* chosen with no seal, or no candidate anywhere in the manifest was sealed and today's
|
|
58
59
|
* newest-only fallback was used instead. See P1-backup-incomplete-generation.
|
|
@@ -260,7 +261,7 @@ export async function pickTarget(
|
|
|
260
261
|
}
|
|
261
262
|
|
|
262
263
|
const readerFor = (d: DeviceSummary): RemoteSyncReader =>
|
|
263
|
-
new RemoteSyncReader(client, wallet, chain, d.deviceId, d.generation, settings, d.headSeq)
|
|
264
|
+
new RemoteSyncReader(client, wallet, chain, d.deviceId, d.generation, settings, d.headSeq, onActivity)
|
|
264
265
|
|
|
265
266
|
if (generation != null) {
|
|
266
267
|
const exact = candidates.find(d => d.generation === generation)
|
package/core/bridge/inbox.ts
CHANGED
|
@@ -17,7 +17,13 @@ import type { Dispatcher, Outcome } from './dispatcher'
|
|
|
17
17
|
import { connectionError, isConnectionError, type ConnectionError } from './protocol/connectionError'
|
|
18
18
|
import { isUuidV4, type InboxCloseEvent, type InboxRecord, type InboxResult } from './protocol/envelopes'
|
|
19
19
|
import { parseStrictJson } from './protocol/json'
|
|
20
|
-
import {
|
|
20
|
+
import {
|
|
21
|
+
INBOX_CLOCK_SKEW_MS,
|
|
22
|
+
INBOX_MAX_VALIDITY_MS,
|
|
23
|
+
MAX_BRIDGE_REQUEST_BYTES,
|
|
24
|
+
MAX_IN_FLIGHT_BYTES,
|
|
25
|
+
MAX_IN_FLIGHT_TOTAL
|
|
26
|
+
} from './protocol/limits'
|
|
21
27
|
import type { Attestation } from './protocol/origin'
|
|
22
28
|
import type { BridgeSnapshot } from './runtime'
|
|
23
29
|
|
|
@@ -69,6 +75,7 @@ export interface InboxStore {
|
|
|
69
75
|
*/
|
|
70
76
|
readEventsAfter(seq: number): Promise<{ events: InboxCloseEvent[]; gap: boolean }>
|
|
71
77
|
bootId(): string
|
|
78
|
+
/** Pending ids are oldest first by the record createdAt, stable for equal timestamps. */
|
|
72
79
|
list(state: InboxState): Promise<string[]>
|
|
73
80
|
}
|
|
74
81
|
|
|
@@ -156,7 +163,7 @@ export interface InboxProcessorDeps {
|
|
|
156
163
|
export interface InboxProcessor {
|
|
157
164
|
/**
|
|
158
165
|
* Recovers after a restart (once), expires stale pending records, then accepts every pending
|
|
159
|
-
* record in `createdAt` order
|
|
166
|
+
* record in `createdAt` order within the byte/count budget, starting independent work concurrently. Resolves when
|
|
160
167
|
* everything it started has settled; a record parked behind a sheet keeps it open, so callers
|
|
161
168
|
* that must not wait run `sweepExpired` on their timer instead.
|
|
162
169
|
*/
|
|
@@ -208,6 +215,21 @@ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
|
|
|
208
215
|
return (require('./runtime') as typeof import('./runtime')).onBindingClosed(fn)
|
|
209
216
|
})
|
|
210
217
|
let recovered: Promise<void> | undefined
|
|
218
|
+
let draining: Promise<void> | undefined
|
|
219
|
+
let wakeDrain: (() => void) | undefined
|
|
220
|
+
let drainRequested = false
|
|
221
|
+
let disposed = false
|
|
222
|
+
const resultRetries = new Set<() => void>()
|
|
223
|
+
const finishing = new Map<string, Promise<void>>()
|
|
224
|
+
let executionTurn: Promise<void> = Promise.resolve()
|
|
225
|
+
|
|
226
|
+
async function reserveExecution(): Promise<() => void> {
|
|
227
|
+
const previous = executionTurn
|
|
228
|
+
let release!: () => void
|
|
229
|
+
executionTurn = new Promise<void>(resolve => { release = resolve })
|
|
230
|
+
await previous
|
|
231
|
+
return release
|
|
232
|
+
}
|
|
211
233
|
|
|
212
234
|
// Every close of one of this transport's bindings goes to the events outbox, in close order
|
|
213
235
|
// (6.7). The writes are chained, and `handle` waits for the chain before it admits anything, so
|
|
@@ -247,12 +269,45 @@ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
|
|
|
247
269
|
}
|
|
248
270
|
}
|
|
249
271
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
272
|
+
function finish(id: string, bytes: Uint8Array): Promise<void> {
|
|
273
|
+
const existing = finishing.get(id)
|
|
274
|
+
if (existing) return existing
|
|
275
|
+
const task = (async () => {
|
|
276
|
+
let oversized = false
|
|
277
|
+
while (!disposed) {
|
|
278
|
+
try {
|
|
279
|
+
await store.writeResult(id, bytes)
|
|
280
|
+
return
|
|
281
|
+
} catch (e) {
|
|
282
|
+
const code = isObj(e) ? e.code : undefined
|
|
283
|
+
if (code === 'ERR_RESULT_TOO_LARGE' && !oversized) {
|
|
284
|
+
oversized = true
|
|
285
|
+
bytes = errorResult(id, connectionError('RESOURCE_LIMIT', 'Response too large', 'unknown'))
|
|
286
|
+
continue
|
|
287
|
+
}
|
|
288
|
+
if (code !== 'ERR_RESOURCE_LIMIT') {
|
|
289
|
+
console.warn('[bridge] inbox result write failed', e)
|
|
290
|
+
return
|
|
291
|
+
}
|
|
292
|
+
// Keep the exact outcome and its drain slot until storage is reclaimed. Native
|
|
293
|
+
// Wallet execution stays serialized through finish, retaining at most one 5 MiB
|
|
294
|
+
// response plus small probe/admission errors. JS objects add representation overhead.
|
|
295
|
+
// Duplicate expiry sweeps share this task; no claimed call is dispatched again.
|
|
296
|
+
await new Promise<void>(resolve => {
|
|
297
|
+
const done = () => {
|
|
298
|
+
clearTimeout(timer)
|
|
299
|
+
resultRetries.delete(done)
|
|
300
|
+
resolve()
|
|
301
|
+
}
|
|
302
|
+
const timer = setTimeout(done, 1000)
|
|
303
|
+
resultRetries.add(done)
|
|
304
|
+
if (disposed) done()
|
|
305
|
+
})
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
})().finally(() => finishing.delete(id))
|
|
309
|
+
finishing.set(id, task)
|
|
310
|
+
return task
|
|
256
311
|
}
|
|
257
312
|
|
|
258
313
|
async function recoverOnce() {
|
|
@@ -323,6 +378,7 @@ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
|
|
|
323
378
|
// Closes that happened while this record waited are in the outbox before it is admitted.
|
|
324
379
|
await eventWrites
|
|
325
380
|
if (snap !== undefined) snap = await readySnapshot()
|
|
381
|
+
if (disposed) return
|
|
326
382
|
if (snap === undefined) {
|
|
327
383
|
await finish(
|
|
328
384
|
id,
|
|
@@ -372,47 +428,63 @@ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
|
|
|
372
428
|
return
|
|
373
429
|
}
|
|
374
430
|
let claimed = false
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
431
|
+
let dispatchSettled = false
|
|
432
|
+
let releaseExecution = () => {}
|
|
433
|
+
try {
|
|
434
|
+
const outcome = await deps
|
|
435
|
+
.dispatch({
|
|
436
|
+
transport: transport.id,
|
|
437
|
+
request: {
|
|
438
|
+
epoch: record.epoch,
|
|
439
|
+
instanceId: record.instanceId,
|
|
440
|
+
continuityKey: record.continuityKey,
|
|
441
|
+
origin: record.origin,
|
|
442
|
+
accountContext: record.accountContext,
|
|
443
|
+
method: record.method as string,
|
|
444
|
+
args: record.args,
|
|
445
|
+
sizeBytes: size,
|
|
446
|
+
beforeCall: async () => {
|
|
447
|
+
// Approval/readiness waits remain concurrent; only execution and result persistence
|
|
448
|
+
// serialize. A dispatcher may stop waiting on this promise when its binding closes.
|
|
449
|
+
const release = await reserveExecution()
|
|
450
|
+
if (disposed || dispatchSettled) {
|
|
451
|
+
release()
|
|
452
|
+
throw connectionError('CONNECTION_CLOSED', 'The bridge stopped waiting', 'not-sent')
|
|
453
|
+
}
|
|
454
|
+
releaseExecution = release
|
|
455
|
+
const c = await store.claim(id, inboxDigest(bytes))
|
|
456
|
+
if (c === 'claimed') {
|
|
457
|
+
claimed = true
|
|
458
|
+
return
|
|
459
|
+
}
|
|
460
|
+
throw connectionError(
|
|
461
|
+
'PROTOCOL_ERROR',
|
|
462
|
+
c === 'digest-mismatch' ? 'The record changed after it was read' : 'The record is no longer waiting',
|
|
463
|
+
'not-sent',
|
|
464
|
+
{ epoch: record.epoch }
|
|
465
|
+
)
|
|
392
466
|
}
|
|
393
|
-
throw connectionError(
|
|
394
|
-
'PROTOCOL_ERROR',
|
|
395
|
-
c === 'digest-mismatch' ? 'The record changed after it was read' : 'The record is no longer waiting',
|
|
396
|
-
'not-sent',
|
|
397
|
-
{ epoch: record.epoch }
|
|
398
|
-
)
|
|
399
467
|
}
|
|
400
|
-
}
|
|
401
|
-
})
|
|
402
|
-
.catch(
|
|
403
|
-
(e): Outcome => ({
|
|
404
|
-
ok: false,
|
|
405
|
-
connectionError: connectionError(
|
|
406
|
-
'CONFIGURATION_ERROR',
|
|
407
|
-
'The wallet bridge failed',
|
|
408
|
-
claimed ? 'unknown' : 'not-sent',
|
|
409
|
-
{
|
|
410
|
-
epoch: record.epoch
|
|
411
|
-
}
|
|
412
|
-
)
|
|
413
468
|
})
|
|
414
|
-
|
|
415
|
-
|
|
469
|
+
.catch(
|
|
470
|
+
(e): Outcome => ({
|
|
471
|
+
ok: false,
|
|
472
|
+
connectionError: connectionError(
|
|
473
|
+
'CONFIGURATION_ERROR',
|
|
474
|
+
'The wallet bridge failed',
|
|
475
|
+
claimed ? 'unknown' : 'not-sent',
|
|
476
|
+
{
|
|
477
|
+
epoch: record.epoch
|
|
478
|
+
}
|
|
479
|
+
)
|
|
480
|
+
})
|
|
481
|
+
)
|
|
482
|
+
dispatchSettled = true
|
|
483
|
+
await finish(id, outcomeResult(id, outcome))
|
|
484
|
+
} finally {
|
|
485
|
+
dispatchSettled = true
|
|
486
|
+
releaseExecution()
|
|
487
|
+
}
|
|
416
488
|
}
|
|
417
489
|
|
|
418
490
|
async function sweepExpired() {
|
|
@@ -437,28 +509,61 @@ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
|
|
|
437
509
|
flushEvents: () => eventWrites,
|
|
438
510
|
|
|
439
511
|
dispose() {
|
|
512
|
+
disposed = true
|
|
513
|
+
for (const done of resultRetries) done()
|
|
440
514
|
unsubscribeClosed()
|
|
441
515
|
},
|
|
442
516
|
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
517
|
+
processPending() {
|
|
518
|
+
if (disposed) return Promise.resolve()
|
|
519
|
+
// One budget across nudges; new arrivals can still join while an earlier approval waits.
|
|
520
|
+
if (draining) {
|
|
521
|
+
drainRequested = true
|
|
522
|
+
wakeDrain?.()
|
|
523
|
+
return draining
|
|
449
524
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
525
|
+
draining = (async () => {
|
|
526
|
+
try {
|
|
527
|
+
await this.recover()
|
|
528
|
+
const running = new Set<Promise<void>>()
|
|
529
|
+
let loadedBytes = 0
|
|
530
|
+
for (;;) {
|
|
531
|
+
drainRequested = false
|
|
532
|
+
const nudged = new Promise<void>(resolve => { wakeDrain = resolve })
|
|
533
|
+
for (const id of await store.list('pending')) {
|
|
534
|
+
if (disposed) break
|
|
535
|
+
const stat = await store.stat(id)
|
|
536
|
+
if (!stat || stat.state !== 'pending') continue
|
|
537
|
+
const size = Math.max(0, stat.size)
|
|
538
|
+
while (running.size > 0 && (running.size >= MAX_IN_FLIGHT_TOTAL || loadedBytes + size > MAX_IN_FLIGHT_BYTES)) {
|
|
539
|
+
await Promise.race(running)
|
|
540
|
+
}
|
|
541
|
+
const loaded = await load(id)
|
|
542
|
+
if (!loaded || !(await admissible(loaded.record)) || disposed || !(await store.accept(id))) continue
|
|
543
|
+
loadedBytes += loaded.size
|
|
544
|
+
const task = handle(id, loaded.record, loaded.bytes, loaded.size)
|
|
545
|
+
.catch(e => {
|
|
546
|
+
console.warn('[bridge] inbox record failed', e)
|
|
547
|
+
})
|
|
548
|
+
.finally(() => {
|
|
549
|
+
loadedBytes -= loaded.size
|
|
550
|
+
running.delete(task)
|
|
551
|
+
})
|
|
552
|
+
running.add(task)
|
|
553
|
+
}
|
|
554
|
+
if (running.size === 0) {
|
|
555
|
+
if (drainRequested) continue
|
|
556
|
+
break
|
|
557
|
+
}
|
|
558
|
+
await Promise.race([nudged, ...running])
|
|
559
|
+
}
|
|
560
|
+
} finally {
|
|
561
|
+
draining = undefined
|
|
562
|
+
wakeDrain = undefined
|
|
563
|
+
drainRequested = false
|
|
564
|
+
}
|
|
565
|
+
})()
|
|
566
|
+
return draining
|
|
462
567
|
}
|
|
463
568
|
}
|
|
464
569
|
}
|
|
@@ -25,6 +25,7 @@ interface Entry {
|
|
|
25
25
|
state: InboxState
|
|
26
26
|
size: number
|
|
27
27
|
createdAt: number
|
|
28
|
+
recordCreatedAt: number
|
|
28
29
|
sealedRecord?: Uint8Array
|
|
29
30
|
sealedResult?: Uint8Array
|
|
30
31
|
resultAt?: number
|
|
@@ -111,10 +112,16 @@ function open(
|
|
|
111
112
|
async create(id, bytes) {
|
|
112
113
|
sweep()
|
|
113
114
|
if (shared.entries.has(id)) return false
|
|
115
|
+
let recordCreatedAt = now()
|
|
116
|
+
try {
|
|
117
|
+
const value = JSON.parse(Utils.toUTF8(Array.from(bytes)))?.createdAt
|
|
118
|
+
if (typeof value === 'number' && Number.isFinite(value)) recordCreatedAt = value
|
|
119
|
+
} catch { /* malformed records are refused by the processor */ }
|
|
114
120
|
shared.entries.set(id, {
|
|
115
121
|
state: 'pending',
|
|
116
122
|
size: bytes.byteLength,
|
|
117
123
|
createdAt: now(),
|
|
124
|
+
recordCreatedAt,
|
|
118
125
|
sealedRecord: seal(bytes)
|
|
119
126
|
})
|
|
120
127
|
return true
|
|
@@ -204,7 +211,9 @@ function open(
|
|
|
204
211
|
|
|
205
212
|
async list(state) {
|
|
206
213
|
sweep()
|
|
207
|
-
|
|
214
|
+
const entries = [...shared.entries].filter(([, e]) => e.state === state)
|
|
215
|
+
if (state === 'pending') entries.sort((a, b) => a[1].recordCreatedAt - b[1].recordCreatedAt)
|
|
216
|
+
return entries.map(([id]) => id)
|
|
208
217
|
},
|
|
209
218
|
|
|
210
219
|
rawBytes() {
|
package/core/constants.ts
CHANGED
|
@@ -52,20 +52,16 @@ export interface KnownArcUrl {
|
|
|
52
52
|
* Known ARC endpoint presets, per network. Each list names only endpoints that
|
|
53
53
|
* serve that network: picking a mainnet ARC on a test chain posts its
|
|
54
54
|
* transactions to a network that will reject them (or, worse, accept a replay).
|
|
55
|
-
*
|
|
55
|
+
* Test, tera and scaling test networks have one BSV Broadcaster each, so they offer no
|
|
56
56
|
* presets beyond their default.
|
|
57
57
|
*/
|
|
58
58
|
export const KNOWN_ARC_URLS: Record<AppChain, readonly KnownArcUrl[]> = {
|
|
59
59
|
main: [
|
|
60
|
-
{ label: '
|
|
61
|
-
{ label: '
|
|
62
|
-
{ label: '
|
|
63
|
-
{ label: 'GorillaPool', url: 'https://arc.gorillapool.io', requiresToken: false }
|
|
60
|
+
{ label: 'BSV Broadcaster (default)', url: NETWORKS.main.arcadeUrl, requiresToken: false },
|
|
61
|
+
{ label: 'BSV Broadcaster US', url: 'https://arcade-us-1.bsvblockchain.tech', requiresToken: false },
|
|
62
|
+
{ label: 'BSV Broadcaster EU', url: 'https://arcade-eu-1.bsvblockchain.tech', requiresToken: false }
|
|
64
63
|
],
|
|
65
|
-
test: [
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
],
|
|
69
|
-
teratest: [{ label: 'Arcade v2 (default)', url: NETWORKS.teratest.arcadeUrl, requiresToken: false }],
|
|
70
|
-
scaletest: [{ label: 'Arcade (default)', url: NETWORKS.scaletest.arcadeUrl, requiresToken: false }]
|
|
64
|
+
test: [{ label: 'BSV Broadcaster (default)', url: NETWORKS.test.arcadeUrl, requiresToken: false }],
|
|
65
|
+
teratest: [{ label: 'BSV Broadcaster (default)', url: NETWORKS.teratest.arcadeUrl, requiresToken: false }],
|
|
66
|
+
scaletest: [{ label: 'BSV Broadcaster (default)', url: NETWORKS.scaletest.arcadeUrl, requiresToken: false }]
|
|
71
67
|
}
|