@bsv/expo-wallet-toolbox 0.1.2 → 0.2.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/README.md CHANGED
@@ -413,7 +413,7 @@ are required — both hard-won during this package's extraction:
413
413
 
414
414
  ```
415
415
  transformIgnorePatterns: [
416
- "node_modules/(?!((jest-)?react-native|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@sentry/react-native|native-base|react-native-svg|react-native-reanimated|react-native-gesture-handler|react-native-worklets|expo-modules-core|@noble/secp256k1|@noble/curves|@noble/hashes|@bsv/backup-cache-client|@bsv/auth|@bsv/expo-wallet-toolbox)/)",
416
+ "node_modules/(?!((jest-)?react-native|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@sentry/react-native|native-base|react-native-svg|react-native-reanimated|react-native-gesture-handler|react-native-worklets|expo-modules-core|@noble/secp256k1|@noble/curves|@noble/hashes|@bsv/backup-cache-client|@bsv/auth|@bsv/expo-wallet-toolbox|@bsv/react-native-localpay-transport)/)",
417
417
  "/node_modules/react-native-reanimated/plugin/"
418
418
  ]
419
419
  ```
@@ -424,8 +424,10 @@ are required — both hard-won during this package's extraction:
424
424
  because `react-native-reanimated` is a required peer dependency.
425
425
  You don't need every name in that big alternation — most come from
426
426
  the `jest-expo` preset's own defaults or other-app concerns — but
427
- `@bsv/expo-wallet-toolbox` itself and `@bsv/backup-cache-client` (see
428
- below) must be in whatever pattern you end up with.
427
+ `@bsv/expo-wallet-toolbox`, `@bsv/react-native-localpay-transport`
428
+ (also raw TypeScript — `core/localpay/transport/select.ts` imports it
429
+ directly), and `@bsv/backup-cache-client` (see below) must be in
430
+ whatever pattern you end up with.
429
431
 
430
432
  2. **Native-module and ESM-only-package mocks** — anything the package
431
433
  touches that has no pure-JS Jest-safe implementation, or that ships
@@ -470,6 +472,17 @@ are required — both hard-won during this package's extraction:
470
472
  other Expo native modules — start from that preset before adding the
471
473
  overrides above.
472
474
 
475
+ ## Breaking changes
476
+
477
+ **0.1.1:** `react-native-localpay-transport` (unscoped, private, hand-synced
478
+ out of this repo) became `@bsv/react-native-localpay-transport` (published
479
+ independently). This is a native-module identity change, not just an npm
480
+ rename: the pod name (`LocalPayTransport`) and Nitro hybrid object
481
+ registrations are unchanged, so a consumer that still has its own local
482
+ copy of the old module installed alongside the new package will get a
483
+ duplicate pod and duplicate native registration. Delete any local copy
484
+ before installing the new package — do not run both at once.
485
+
473
486
  ## Publishing notes
474
487
 
475
488
  This package deliberately ships **no `exports` map** in `package.json`.
@@ -23,9 +23,19 @@ export class BackupChainError extends Error {
23
23
  }
24
24
  }
25
25
 
26
+ // The server caps each index page at 500 entries. Reading only its first page
27
+ // can otherwise look like a successful restore of a truncated wallet.
28
+ const INDEX_PAGE_SIZE = 500
29
+ // At most one small ciphertext is fetched ahead while SQLite replays the
30
+ // current chunk. Large chunks remain sequential to bound mobile memory use.
31
+ const PREFETCH_MAX_BYTES = 1024 * 1024
32
+
33
+ type BlobResult = { bytes: Uint8Array, error?: never } | { bytes?: never, error: unknown }
34
+
26
35
  export class RemoteSyncReader {
27
36
  private entries: LogEntry[] | null = null
28
37
  private next = 0
38
+ private prefetched: { seq: number, result: Promise<BlobResult> } | null = null
29
39
 
30
40
  constructor (
31
41
  private readonly client: BackupClient,
@@ -33,7 +43,8 @@ export class RemoteSyncReader {
33
43
  private readonly chain: BackupChain,
34
44
  private readonly deviceId: string,
35
45
  private readonly generation: number,
36
- private readonly settings: TableSettings
46
+ private readonly settings: TableSettings,
47
+ private readonly expectedHeadSeq?: number
37
48
  ) {}
38
49
 
39
50
  /** Settings for the storage being restored into. */
@@ -51,18 +62,57 @@ export class RemoteSyncReader {
51
62
  */
52
63
  async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
53
64
  if (this.entries == null) {
54
- this.entries = await this.client.index(this.deviceId, this.generation)
55
- this.verifyChain(this.entries)
65
+ const entries: LogEntry[] = []
66
+ let page = await this.client.index(this.deviceId, this.generation)
67
+ for (;;) {
68
+ const pageStart = entries.length
69
+ entries.push(...page)
70
+ this.verifyChain(entries, pageStart)
71
+ const missingHead = this.expectedHeadSeq != null && entries.length < this.expectedHeadSeq
72
+ if (page.length === 0) {
73
+ if (missingHead) throw new BackupChainError('backup index ended before its advertised head')
74
+ break
75
+ }
76
+ if (page.length < INDEX_PAGE_SIZE && !missingHead) break
77
+ page = await this.client.index(this.deviceId, this.generation, entries.length + 1)
78
+ }
79
+ // Publish only a fully verified index. A failed read/validation must not
80
+ // let a retry skip verification or mistake a partial index for completion.
81
+ this.entries = entries
56
82
  }
57
83
 
58
84
  if (this.next >= this.entries.length) {
59
- // All twelve arrays present and empty: the completion sentinel.
60
85
  return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
61
86
  }
62
87
 
63
- const entry = this.entries[this.next++]
64
- const ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
65
- return await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
88
+ const entry = this.entries[this.next]
89
+ let ciphertext: Uint8Array
90
+ if (this.prefetched?.seq === entry.seq) {
91
+ const pending = this.prefetched
92
+ this.prefetched = null
93
+ const result = await pending.result
94
+ if ('error' in result) throw result.error
95
+ ciphertext = result.bytes
96
+ } else {
97
+ ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
98
+ }
99
+ const chunk = await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
100
+ // Advance only after successful download AND decryption. Retrying this
101
+ // reader after either fails must retry the same entry rather than lose it.
102
+ this.next++
103
+ const following = this.entries[this.next]
104
+ if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
105
+ following.size > 0 && following.size <= PREFETCH_MAX_BYTES) {
106
+ this.prefetched = {
107
+ seq: following.seq,
108
+ // Store failures as values until consumed, so a stopped replay never
109
+ // leaves an unhandled rejection from a speculative download.
110
+ result: this.client.blob(this.deviceId, this.generation, following.seq).then(
111
+ bytes => ({ bytes }), error => ({ error })
112
+ )
113
+ }
114
+ }
115
+ return chunk
66
116
  }
67
117
 
68
118
  /** Number of chunks in this generation, once the index has been read. */
@@ -76,8 +126,8 @@ export class RemoteSyncReader {
76
126
  * A restore that silently stops halfway is worse than one that fails: the wallet would
77
127
  * look healthy while missing the outputs it needs to spend.
78
128
  */
79
- private verifyChain (entries: LogEntry[]): void {
80
- for (let i = 0; i < entries.length; i++) {
129
+ private verifyChain (entries: LogEntry[], start = 0): void {
130
+ for (let i = start; i < entries.length; i++) {
81
131
  const expectedSeq = i + 1
82
132
  if (entries[i].seq !== expectedSeq) {
83
133
  throw new BackupChainError(
@@ -55,11 +55,11 @@ export class BackupClient extends BackupCacheClient {
55
55
  * pseudonym, so each network's log lives in its own server account.
56
56
  * @param fetchImpl injectable transport for tests; defaults to global fetch.
57
57
  */
58
- constructor (baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
58
+ constructor(baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
59
59
  super({
60
60
  baseUrl,
61
61
  wallet: deriveBackupWallet(primaryKey, chain),
62
- fetch: withTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
62
+ fetch: withBackupRequestTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
63
63
  })
64
64
  }
65
65
 
@@ -67,45 +67,78 @@ export class BackupClient extends BackupCacheClient {
67
67
  * Append a chunk. Accepts the codec's `number[]` ciphertext alongside the
68
68
  * package's own body shapes, so encodeChunk's output flows straight through.
69
69
  */
70
- override async append (
70
+ override async append(
71
71
  deviceId: string,
72
72
  generation: number,
73
73
  seq: number,
74
74
  prevSha256: string | undefined,
75
75
  body: Uint8Array | Blob | number[]
76
- ): Promise<{ seq: number, sha256: string, size: number }> {
76
+ ): Promise<{ seq: number; sha256: string; size: number }> {
77
77
  const bytes = Array.isArray(body) ? new Uint8Array(body) : body
78
78
  return await super.append(deviceId, generation, seq, prevSha256, bytes)
79
79
  }
80
80
  }
81
81
 
82
82
  /**
83
- * Bound every request the client makes.
83
+ * Bound the request and the body readers used by BackupCacheClient with one
84
+ * deadline. React Native's XHR fetch resolves after the download, but its
85
+ * Blob/FileReader conversion is still asynchronous; browser fetch can resolve
86
+ * before any body bytes arrive. Neither phase may strand the monitor.
84
87
  *
85
- * A race rather than an AbortController, kept from the previous client: losing
86
- * the race abandons the in-flight promise, which is acceptable because the
87
- * caller retries the whole pass and nothing downstream depends on the
88
- * abandoned result.
88
+ * Wrap the existing readers instead of rebuilding/cloning the Response: a
89
+ * large backup still allocates only the buffer the package itself requests.
89
90
  */
90
- function withTimeout (transport: typeof fetch): typeof fetch {
91
+ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch {
91
92
  return async (input, init) => {
92
- let timer: ReturnType<typeof setTimeout> | undefined
93
- try {
94
- return await Promise.race([
95
- transport(input, init),
96
- new Promise<never>((_resolve, reject) => {
97
- timer = setTimeout(
98
- () =>
99
- reject(
100
- new Error(`Backup request timed out after ${BACKUP_REQUEST_TIMEOUT_MS}ms: ${String(input)}`)
101
- ),
102
- BACKUP_REQUEST_TIMEOUT_MS
103
- )
104
- ;(timer as { unref?: () => void }).unref?.()
105
- })
106
- ])
107
- } finally {
108
- if (timer != null) clearTimeout(timer)
93
+ const controller = new AbortController()
94
+ const callerSignal =
95
+ init?.signal ?? (typeof Request !== 'undefined' && input instanceof Request ? input.signal : null)
96
+ const deadline = Date.now() + BACKUP_REQUEST_TIMEOUT_MS
97
+
98
+ async function bounded<T>(operation: () => Promise<T>): Promise<T> {
99
+ let timer: ReturnType<typeof setTimeout> | undefined
100
+ let rejectStopped!: (reason: unknown) => void
101
+ const stopped = new Promise<never>((_resolve, reject) => {
102
+ rejectStopped = reject
103
+ })
104
+ const cancel = (reason: unknown) => {
105
+ // Reject before aborting: a transport's synchronous AbortError must not
106
+ // mask the more useful timeout or caller-supplied cancellation reason.
107
+ rejectStopped(reason)
108
+ controller.abort(reason)
109
+ }
110
+ const onAbort = () => {
111
+ const error = new Error('Backup request aborted')
112
+ error.name = 'AbortError'
113
+ cancel(callerSignal?.reason ?? error)
114
+ }
115
+ try {
116
+ const remaining = deadline - Date.now()
117
+ if (callerSignal?.aborted) {
118
+ onAbort()
119
+ return await stopped
120
+ }
121
+ callerSignal?.addEventListener('abort', onAbort)
122
+ const onTimeout = () =>
123
+ cancel(new Error(`Backup request timed out after ${BACKUP_REQUEST_TIMEOUT_MS}ms: ${String(input)}`))
124
+ if (remaining <= 0) {
125
+ onTimeout()
126
+ return await stopped
127
+ }
128
+ timer = setTimeout(onTimeout, remaining)
129
+ ;(timer as { unref?: () => void }).unref?.()
130
+ return await Promise.race([operation(), stopped])
131
+ } finally {
132
+ if (timer != null) clearTimeout(timer)
133
+ callerSignal?.removeEventListener('abort', onAbort)
134
+ }
109
135
  }
136
+
137
+ const response = await bounded(() => transport(input, { ...init, signal: controller.signal }))
138
+ const readJson = response.json.bind(response)
139
+ const readArrayBuffer = response.arrayBuffer.bind(response)
140
+ response.json = () => bounded(readJson)
141
+ response.arrayBuffer = () => bounded(readArrayBuffer)
142
+ return response
110
143
  }
111
144
  }
@@ -24,6 +24,8 @@ export interface RestoreDeps {
24
24
  client?: BackupClient
25
25
  /** Defaults to the most recently updated device in the manifest. */
26
26
  deviceId?: string
27
+ /** A manifest already read by the import flow; avoids a duplicate request. */
28
+ manifest?: DeviceSummary[]
27
29
  /** Defaults to the newest generation for that device. */
28
30
  generation?: number
29
31
  /**
@@ -60,7 +62,7 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
60
62
  const client = resolveClient(deps)
61
63
  const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
62
64
 
63
- const devices = await client.manifest()
65
+ const devices = deps.manifest ?? await client.manifest()
64
66
  if (devices.length === 0) {
65
67
  throw new Error('No backup found for this wallet')
66
68
  }
@@ -83,7 +85,8 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
83
85
  'backup-restore'
84
86
  )
85
87
 
86
- const reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings)
88
+ const headSeq = devices.find(d => d.deviceId === chosen.deviceId && d.generation === chosen.generation)?.headSeq
89
+ const reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings, headSeq)
87
90
 
88
91
  let chunks = 0
89
92
  for (;;) {
@@ -105,17 +108,64 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
105
108
  offsets: []
106
109
  }, chunk)
107
110
 
108
- if (result.done) break
111
+ if (result.done) {
112
+ if (chunks < reader.length) throw new Error('Backup replay completed before all indexed chunks were applied')
113
+ break
114
+ }
109
115
  chunks++
110
116
  deps.onProgress?.(chunks, reader.length)
111
117
 
112
118
  // The reader is finite; this guards against a processSyncChunk that never reports done.
113
- if (chunks > reader.length) break
119
+ if (chunks > reader.length) throw new Error('Backup replay did not acknowledge completion')
114
120
  }
115
121
 
122
+ await reconcileRestoredProofs(deps.storage)
116
123
  return { chunks, deviceId: chosen.deviceId, generation: chosen.generation }
117
124
  }
118
125
 
126
+ /**
127
+ * Toolbox sync merges transaction status but only history/notify for an
128
+ * existing proof request. An unsent request followed by its completed version
129
+ * can therefore replay beside a completed transaction and keep rebroadcasting
130
+ * it. Reuse proofs already in storage through the normal completion method,
131
+ * which also reconciles notification IDs and preserves completed transactions.
132
+ * Run only after the entire log lands, before the wallet/monitor is published.
133
+ */
134
+ async function reconcileRestoredProofs (storage: StorageExpoSQLite): Promise<void> {
135
+ const limit = 1
136
+ for (let offset = 0; ; offset += limit) {
137
+ // Page over every status so completing a request cannot shift the next
138
+ // page's offsets. A request may contain a large expanded inputBEEF, so
139
+ // retain only one request at a time while completion reloads its proof.
140
+ const requests = await storage.findProvenTxReqs({ partial: {}, paged: { limit, offset } })
141
+ for (const req of requests) {
142
+ if (req.status === 'completed' && req.notified && (req.provenTxId ?? 0) > 0) continue
143
+ const proofs = await storage.findProvenTxs({ partial: { txid: req.txid } })
144
+ if (proofs.length === 0) continue
145
+ if (proofs.length !== 1) throw new Error('Restored transaction has conflicting stored proofs')
146
+ const proof = proofs[0]
147
+ const result = await storage.updateProvenTxReqWithNewProvenTx({
148
+ provenTxReqId: req.provenTxReqId,
149
+ txid: req.txid,
150
+ status: req.status,
151
+ attempts: req.attempts,
152
+ history: req.history,
153
+ height: proof.height,
154
+ index: proof.index,
155
+ blockHash: proof.blockHash,
156
+ merkleRoot: proof.merkleRoot,
157
+ merklePath: proof.merklePath
158
+ })
159
+ // The toolbox can report incomplete notification after a failed row
160
+ // update. Do not advertise a completed restore in that case.
161
+ if (result.status !== 'completed' || result.provenTxId !== proof.provenTxId || result.notified === false) {
162
+ throw new Error('Restored transaction proof reconciliation did not complete')
163
+ }
164
+ }
165
+ if (requests.length < limit) break
166
+ }
167
+ }
168
+
119
169
  function pickTarget (
120
170
  devices: DeviceSummary[],
121
171
  deviceId?: string,
@@ -82,6 +82,7 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
82
82
  chain: deps.chain,
83
83
  identityKey: deps.identityKey,
84
84
  client,
85
+ manifest: devices,
85
86
  deviceId: target.deviceId,
86
87
  generation: target.generation,
87
88
  onProgress: deps.onProgress
@@ -554,6 +554,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
554
554
  */
555
555
  const walletBuiltRef = useRef<boolean>(false)
556
556
  const walletBuildingRef = useRef<boolean>(false)
557
+ // A failed mnemonic build must not silently fall back to a different stored key.
558
+ const mnemonicMissingRef = useRef(false)
557
559
  const [walletBuilding, setWalletBuilding] = useState<boolean>(false)
558
560
  const [backupRestore, setBackupRestoreState] = useState<BackupRestoreState>({
559
561
  phase: 'idle',
@@ -1197,6 +1199,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1197
1199
  const message = e instanceof Error ? e.message : String(e)
1198
1200
  console.error('[WalletContext] backup restore failed:', message)
1199
1201
  setBackupRestore({ phase: 'failed', chunks: 0, total: 0, error: message })
1202
+ // This storage was never published to the app. Release its
1203
+ // connection before a retry opens the same database again.
1204
+ try {
1205
+ await phoneStorage.destroy()
1206
+ } catch {}
1200
1207
  throw e
1201
1208
  }
1202
1209
  }
@@ -1711,7 +1718,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1711
1718
  console.error('Error building wallet:', error)
1712
1719
  onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
1713
1720
  logWithTimestamp(F, 'Error building wallet', error.message)
1714
- return null
1721
+ // SimpleWalletManager authenticates whenever its builder resolves,
1722
+ // even to null. Reject so a failed restore cannot mark a wallet built.
1723
+ throw error
1715
1724
  }
1716
1725
  },
1717
1726
  [
@@ -1755,6 +1764,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1755
1764
  }
1756
1765
 
1757
1766
  walletBuildingRef.current = true
1767
+ mnemonicMissingRef.current = false
1758
1768
  setWalletBuilding(true)
1759
1769
 
1760
1770
  try {
@@ -1767,6 +1777,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1767
1777
  if (__DEV__)
1768
1778
  console.warn(`[perf] getMnemonic (auth/keychain): ${(performance.now() - __tMnemonicStart).toFixed(0)}ms`)
1769
1779
  if (!mnemonic) {
1780
+ mnemonicMissingRef.current = true
1770
1781
  walletBuildingRef.current = false
1771
1782
  setWalletBuilding(false)
1772
1783
  return
@@ -1790,7 +1801,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1790
1801
 
1791
1802
  // Armed before the keys go in, because providing both is what triggers
1792
1803
  // buildWallet — the only place a fresh, empty database exists to replay into.
1793
- restoreIntentRef.current = opts?.restoreFromBackup === true
1804
+ // An automatic build has no options: preserve the request armed by
1805
+ // rebuildWallet until buildWallet consumes it. Explicit false still
1806
+ // allows the import screen to continue without restoring on retry.
1807
+ if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
1794
1808
 
1795
1809
  // Provide the primary key and privileged key manager to authenticate the wallet
1796
1810
  await swm.providePrimaryKey(primaryKey)
@@ -1858,7 +1872,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1858
1872
  const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
1859
1873
 
1860
1874
  // Same arming point as the mnemonic path — see the comment there.
1861
- restoreIntentRef.current = opts?.restoreFromBackup === true
1875
+ // An automatic build has no options: preserve the request armed by
1876
+ // rebuildWallet until buildWallet consumes it. Explicit false still
1877
+ // allows the import screen to continue without restoring on retry.
1878
+ if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
1862
1879
 
1863
1880
  await swm.providePrimaryKey(primaryKey)
1864
1881
 
@@ -2012,15 +2029,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2012
2029
  ;(async () => {
2013
2030
  // Try mnemonic-based build first (calls getMnemonic internally)
2014
2031
  await buildWalletFromMnemonic()
2015
- // If still not built (no mnemonic), try recovered key. walletBuiltRef is
2016
- // the reliable signal here — this closure's walletBuilt is frozen at
2017
- // false, and the old `!walletBuildingRef.current` check was wrong twice
2018
- // over: it reads false after a SUCCESSFUL build too (both builders clear
2019
- // it on completion), so a wallet holding both a mnemonic and a leftover
2020
- // recoveredKey would build TWICE — two wallet stacks, two monitors.
2021
- if (!walletBuiltRef.current && !walletBuildingRef.current) {
2022
- // buildWalletFromMnemonic finished without building (no mnemonic found).
2023
- // Try recovered key as a fallback.
2032
+ // Only missing mnemonic material allows a recovered-key fallback. A
2033
+ // restore failure must remain failed so the import screen can offer a
2034
+ // retry; a leftover WIF must not build over that partial replay.
2035
+ if (mnemonicMissingRef.current && !walletBuiltRef.current && !walletBuildingRef.current) {
2024
2036
  const recoveredWif = await getRecoveredKey()
2025
2037
  if (recoveredWif) {
2026
2038
  await buildWalletFromRecoveredKey(recoveredWif)