@bsv/expo-wallet-toolbox 0.9.0 → 0.11.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 CHANGED
@@ -1,5 +1,161 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Upgrading from 0.10.0
6
+
7
+ - `guardVaultAccess` takes a third argument, `{ lookup }`. Pass your
8
+ `StorageExpoSQLite` where you build the wallet; without it, external calls
9
+ that name an outpoint or a `sendWith` txid are refused. See below.
10
+ - `VAULT_ABORT_REPLAY_MARKER` is no longer exported.
11
+ - `VaultErrorCode` gains `'key-opens-nothing'`, so an exhaustive switch over it
12
+ needs a case.
13
+ - The `export_unencrypted_*` translation keys are gone (see Export below).
14
+
15
+ ### External-wallet guard: point lookups instead of a history scan (breaking)
16
+
17
+ `guardVaultAccess` used to page the wallet's entire action history, with
18
+ locking scripts, before every external `createAction`, `signAction`,
19
+ `abortAction`, `internalizeAction` and `relinquishOutput`. It refused every
20
+ such call once history passed 10,000 actions, refused a call when history
21
+ changed during the scan, and queued the app's own admin calls behind it.
22
+
23
+ - **New third argument `guardVaultAccess(wallet, adminOriginator, { lookup })`**
24
+ (`GuardVaultAccessOptions`, `VaultGuardLookup`). `StorageExpoSQLite`
25
+ implements the lookup: pass it where you build the wallet. Re-wrapping the
26
+ same wallet later keeps it. Without a lookup, an external call that names an
27
+ outpoint or a `sendWith` txid is refused.
28
+ - **What an external caller is refused now:** naming an outpoint that is
29
+ admin state (createAction inputs, `relinquishOutput`, `internalizeAction`
30
+ outputs), and a `sendWith` txid that is labelled `vault` or `admin*` or
31
+ creates or spends an admin-basket output. An outpoint is admin state when
32
+ it sits in an `admin`-prefixed basket, or when it has no basket but is
33
+ tagged `vault` or was created by a `vault`/`admin*`-labelled transaction:
34
+ a Vault output relinquished by "forget unreachable deposits" stays out of
35
+ reach. Each check reads only the named rows and never a locking script
36
+ (`core/storage/methods/vaultGuardSql.ts`).
37
+ - **What is now allowed:** creating, receiving and spending R1C outputs outside
38
+ admin baskets, and `signAction`/`abortAction` by reference. The admin
39
+ originator passes straight through without queueing.
40
+ - **Storage backstop:** `StorageExpoSQLite.validateResolvedActionInput`
41
+ refuses a non-admin input whose stored output is admin state, by the same
42
+ rule (previously: any R1C script).
43
+ - **Removed:** `VAULT_ABORT_REPLAY_MARKER`. `replayPendingAborts` relies on
44
+ the pending-abort authority tag alone.
45
+
46
+ External `listActions` is unchanged: it still scans to hide Vault actions.
47
+
48
+ ### Vault: forget deposits no current key can open
49
+
50
+ Each Vault setup on the same YubiKeys writes fresh PIV keys, yet an earlier
51
+ setup's deposits still authenticate, and the encrypted backup and the chain
52
+ restore both brought them back after they were deleted.
53
+
54
+ - **New `forgetUnreachableVaultOutputs`** relinquishes every Vault output that
55
+ shares no key with the authenticated key list, so the cleared basket reaches
56
+ the backup on the next push.
57
+ - **`getVaultKeyCoverage` reports `unreachableOutputs`.** The Vault screen shows
58
+ them in their own row with a confirm-to-forget, and leaves them out of the
59
+ re-lock badges.
60
+ - **`recoverVaultFromChain` internalizes only deposits that share a key with
61
+ the live set** (the verified local key list, otherwise the newest setup
62
+ found). The rest are counted in the result's new `unreachable` field, and
63
+ the restore notice names them.
64
+ - **Storage fix:** `relinquishOutput` now actually clears the basket.
65
+ `sqlBindValue` had dropped `basketId: undefined` from the `SET` clause, so a
66
+ relinquish, or a synced one arriving through `EntityOutput.mergeExisting`,
67
+ left the output in its basket. `outputs.basketId` undefined now binds as
68
+ `NULL`.
69
+
70
+ ### Vault: restore with one tapped YubiKey
71
+
72
+ - **New `recoverVaultWithKey`** scans the chain, then has the tapped card sign
73
+ a fresh challenge (`proveHeldVaultKey`, PIN + touch) and checks it against
74
+ every key the found deposits list for that serial. The matching key picks
75
+ its setup and proves possession in one step; only that setup's deposits are
76
+ restored. A card that opens nothing raises the new `key-opens-nothing`
77
+ error.
78
+ - The Vault screen's not-set-up view gains **Restore with a YubiKey** when NFC
79
+ hardware is supported.
80
+ - `recoverVaultFromChain` behaves as before; the scan is now split internally
81
+ so the YubiKey step can run between scanning and inserting.
82
+
83
+ ### Vault: chain restore works against the live WhatsOnChain API
84
+
85
+ Restore from the blockchain could never finish on mainnet:
86
+
87
+ - WhatsOnChain answers 404 for an address with no history. That is now a
88
+ genuine miss, not a scan failure, so the scan no longer gives up with
89
+ `chain-scan-failed` after 20 empty indexes.
90
+ - `GET /tx/{txid}/out/{vout}` answers 502 for every output, so no found
91
+ deposit was ever reported unspent. The lookup now uses `POST /utxos/spent`,
92
+ which reports each outpoint as unspent, spent (naming the spender), or
93
+ unknown.
94
+
95
+ Both were checked against live mainnet responses.
96
+
97
+ ### Export: straight to the share sheet
98
+
99
+ Export Wallet Data no longer shows a "This File Is Not Encrypted" confirmation
100
+ before the OS share sheet (the alert-then-share handoff was unreliable on
101
+ device); the tap opens the native save prompt directly, from Settings and the
102
+ Vault screen. The export itself is unchanged: a raw SQLite image. The unused
103
+ `export_unencrypted_*` strings are dropped from all locales.
104
+
105
+ ### Backup: a restore no longer fails on an inconclusive coin review
106
+
107
+ Restoring from a recovery phrase failed with "Could not restore your history"
108
+ whenever the post-restore `reviewSpendableOutputs` came back
109
+ `WERR_UTXO_REVIEW_INCONCLUSIVE` (for example, when the UTXO provider could not
110
+ answer), even though the replay was complete. The review is best-effort:
111
+ `WalletContext` and `restoreOnImport` now log its failure and keep the restored
112
+ wallet; the monitor and Check Wallet rerun it.
113
+
114
+ ## 0.10.0
115
+
116
+ ### `verifyFramePayment` takes its chain tracker separately (breaking)
117
+
118
+ `verifyFramePayment(wallet, frame, originator, opts)` becomes
119
+ `verifyFramePayment({ wallet, chainTracker }, frame, originator, opts)`
120
+ (new `FrameVerifyDeps`), and `DerivingWallet` is back to `getPublicKey` only.
121
+ The 0.8.0 shape asked one "wallet" object for both key derivation and
122
+ `getServices().getChainTracker()`; the permissions manager has only the first,
123
+ and that mismatch is the bug below. A host calling `verifyFramePayment`
124
+ itself passes its permissions manager as `wallet` unchanged and
125
+ `await storage.getServices().getChainTracker()` as `chainTracker`. The
126
+ tracker is used only for BSV frames.
127
+
128
+ ### Nearby receive: BSV frames verify again; the header window keeps up (#25)
129
+
130
+ - **Every Nearby BSV payment was declined on receive** (`NearbyFlow`).
131
+ `settleReceived` handed the permissions manager to `verifyFramePayment` as
132
+ the `DerivingWallet`, but the permissions manager has no `getServices()`,
133
+ so the SPV check threw a `TypeError` that went out as `decode_failed`.
134
+ NearbyFlow now passes the permissions manager unchanged, with the chain
135
+ tracker from `storage.getServices()`; if storage cannot supply one it
136
+ declines `save_failed` having queued nothing.
137
+ - **New decline kind `root_unverified`** (`core/localpay/verify.ts`,
138
+ `types.ts`). `tx.verify` returns false for a bad script or value and for a
139
+ merkle root the device cannot confirm alike, so an offline payee whose
140
+ header window did not reach the payment's block looked like a malformed
141
+ payment. The chain tracker is now observed during verification; a refused
142
+ root raises `FrameVerifyError('root_unverified')`, the payer is told
143
+ `root_unverified` (new `DeclineReason`), the request stays live, and the
144
+ payee sees `local_pay_root_unverified` (go online briefly, then retry).
145
+ Payers on older builds show the code verbatim. `FrameVerifyKind` and
146
+ `DeclineReason` gain the member, so a host switching exhaustively on either
147
+ needs a case for it.
148
+ - **The local header window is topped up while online, not only on
149
+ reconnect** (`core/headers/headerSyncTriggers.ts`,
150
+ `startHeaderSyncTriggers`). A phone that stayed on one network, or whose
151
+ NetInfo was silent while suspended, never saw a reconnect, so its window
152
+ trailed the chain by hours and it refused any coin mined since. The sync
153
+ now also runs on returning to the foreground and every
154
+ `HEADER_SYNC_INTERVAL_MS` (10 minutes) while online; each pass fetches only
155
+ the headers above the local tip.
156
+ - Copy: `local_pay_declined_root_unverified` and `local_pay_root_unverified`,
157
+ 12 languages.
158
+
3
159
  ## 0.9.0
4
160
 
5
161
  0.8.0 has release notes below but was never published to npm. Hosts upgrading
package/README.md CHANGED
@@ -562,6 +562,13 @@ are required — both hard-won during this package's extraction:
562
562
 
563
563
  ## Breaking changes
564
564
 
565
+ **0.10.0:** `verifyFramePayment` takes `{ wallet, chainTracker }`
566
+ (`FrameVerifyDeps`) as its first argument instead of a single wallet, and
567
+ `DerivingWallet` no longer includes `getServices()`. Pass the permissions
568
+ manager as `wallet` and `await storage.getServices().getChainTracker()` as
569
+ `chainTracker`. The 0.8.0 note below about `DerivingWallet` gaining
570
+ `getServices()` no longer applies.
571
+
565
572
  **0.9.0:** `useWallet().logout` now returns `Promise<boolean>` (it was
566
573
  `() => void`). It resolves once teardown has finished, and resolves to
567
574
  `false` when the secrets layer could not confirm erasure. Await it before
@@ -62,8 +62,9 @@ export interface RestoreOnImportDeps {
62
62
  onProgress?: (chunks: number, total: number) => void
63
63
  /**
64
64
  * After a successful replay, check that restored coins are still spendable.
65
- * Awaited before this function resolves. Absent on a no-backup / unconfigured
66
- * import, which has nothing to validate.
65
+ * Awaited before this function resolves, but best-effort: a failure is logged and
66
+ * never fails the restore (the monitor and Check Wallet rerun it). Absent on a
67
+ * no-backup / unconfigured import, which has nothing to validate.
67
68
  */
68
69
  validateRestoredCoins?: () => Promise<void>
69
70
  }
@@ -169,7 +170,13 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
169
170
  }
170
171
 
171
172
  if (deps.validateRestoredCoins) {
172
- await deps.validateRestoredCoins()
173
+ try {
174
+ await deps.validateRestoredCoins()
175
+ } catch (error) {
176
+ // Everything above is already replayed; uncertainty about some coins must not
177
+ // take the recovered history away from the user.
178
+ console.warn('[backup] post-restore coin validation did not finish; restore kept:', error)
179
+ }
173
180
  }
174
181
 
175
182
  return {
@@ -282,6 +282,7 @@ import { OfflineFirstChaintracks } from '../headers/OfflineFirstChaintracks'
282
282
  import { prewarmOwnRoots } from '../headers/prewarm'
283
283
  import { syncHeaders } from '../headers/syncHeaders'
284
284
  import type { HeaderSource } from '../headers/syncHeaders'
285
+ import { startHeaderSyncTriggers } from '../headers/headerSyncTriggers'
285
286
 
286
287
  // Auto-approve accounting (misc-p2-04). Previously a single global cooldown
287
288
  // timer let multiple paired origins accidentally throttle each other while
@@ -1483,7 +1484,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1483
1484
  // call below) so the post-restore pass actually sees the replayed coins.
1484
1485
  validateRestoredCoins: async () => {
1485
1486
  await addLocalStorage()
1486
- await wallet.reviewSpendableOutputs(false, true)
1487
+ try {
1488
+ await wallet.reviewSpendableOutputs(false, true)
1489
+ } catch (error) {
1490
+ // The replay above is complete. This review is a best-effort
1491
+ // spendability pass: when it cannot finish (an inconclusive
1492
+ // provider, a lookup outage, anything) the toolbox has changed
1493
+ // nothing, and the monitor and Check Wallet in Settings rerun it.
1494
+ // A restore must never be lost to it, so give the user everything
1495
+ // that was recovered and only log.
1496
+ console.warn('[WalletContext] Post-restore coin review did not finish; kept restore:', error)
1497
+ }
1487
1498
  }
1488
1499
  })
1489
1500
  console.log(
@@ -1749,9 +1760,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1749
1760
  }
1750
1761
 
1751
1762
  // Publish one idempotently guarded manager for both trusted in-app
1752
- // Vault calls and external WalletClient calls. Admin output mutations
1753
- // therefore share the guard's FIFO with external inventory scan+use;
1754
- // external call sites may safely apply guardVaultAccess again.
1763
+ // Vault calls and external WalletClient calls; external call sites may
1764
+ // safely apply guardVaultAccess again. The guard's admin-basket and
1765
+ // held-transaction checks are point lookups against this device's
1766
+ // SQLite storage; with no local storage those external calls are
1767
+ // refused rather than let through.
1755
1768
  //
1756
1769
  // wrapCreateActionForTokenInputs wraps the RAW permissionsManager
1757
1770
  // FIRST, and guardVaultAccess is applied to ITS result (never the
@@ -1787,7 +1800,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1787
1800
  () => mandalaRef.current?.store,
1788
1801
  () => mandalaEndpoints !== undefined
1789
1802
  ),
1790
- adminOriginator
1803
+ adminOriginator,
1804
+ { lookup: phoneStorage }
1791
1805
  )
1792
1806
 
1793
1807
  // THE MANDALA RUNTIME'S ONE CONSTRUCTION SITE.
@@ -2913,21 +2927,29 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2913
2927
  // both refs fresh on every reconnect, independent of that init's own
2914
2928
  // guarding, so it re-validates the pairing itself before syncing rather than
2915
2929
  // trusting it was never broken.
2930
+ //
2931
+ // Reconnects alone left the window hours behind on a phone that stayed on
2932
+ // one network, which an offline payee then pays for by refusing any coin
2933
+ // mined since. So the same pass also runs on returning to the foreground and
2934
+ // every HEADER_SYNC_INTERVAL_MS while online (see headerSyncTriggers.ts).
2916
2935
  useEffect(() => {
2917
2936
  if (!walletBuilt) return
2918
- return subscribeOnline(online => {
2919
- if (!online) return
2920
- const ct = offlineChaintracksRef.current
2921
- const store = headerStoreRef.current
2922
- if (!ct || !store) return
2923
- if (store.chain !== toWalletChain(selectedNetwork)) return
2924
- void (async () => {
2925
- try {
2926
- await runHeaderSync(store, ct)
2927
- } catch {
2928
- // Best-effort. The next reconnect retries.
2929
- }
2930
- })()
2937
+ return startHeaderSyncTriggers({
2938
+ sync: async () => {
2939
+ const ct = offlineChaintracksRef.current
2940
+ const store = headerStoreRef.current
2941
+ if (!ct || !store) return
2942
+ if (store.chain !== toWalletChain(selectedNetwork)) return
2943
+ await runHeaderSync(store, ct)
2944
+ },
2945
+ isOnline: getOnline,
2946
+ subscribeOnline,
2947
+ subscribeForeground: cb => {
2948
+ const sub = AppState.addEventListener('change', next => {
2949
+ if (next === 'active') cb()
2950
+ })
2951
+ return () => sub.remove()
2952
+ }
2931
2953
  })
2932
2954
  }, [walletBuilt, selectedNetwork, runHeaderSync])
2933
2955
 
@@ -0,0 +1,65 @@
1
+ /**
2
+ * When the local header window is topped up.
3
+ *
4
+ * An offline payee can only verify a nearby payment whose ancestry bottoms out
5
+ * at a block it already holds a header for, so the window has to keep up with
6
+ * the chain while the device has signal — not only at wallet build. Reconnects
7
+ * alone are not enough: a phone that stays on one Wi-Fi network never sees
8
+ * one, and on iOS NetInfo delivers nothing while the app is suspended, so a
9
+ * phone brought back to the foreground may not either.
10
+ *
11
+ * So a sync is attempted on each of:
12
+ * · coming online (every NetInfo event that reads online),
13
+ * · returning to the foreground,
14
+ * · a fixed interval while the app runs.
15
+ *
16
+ * Each attempt is gated on `isOnline()` and is cheap when there is nothing to
17
+ * do: `syncHeaders` asks for the present height and fetches only the headers
18
+ * above the local tip (one or two per ten minutes on mainnet). Overlap is the
19
+ * caller's `sync` to prevent (WalletContext's `runHeaderSync` single-flights).
20
+ */
21
+
22
+ /** One block's worth of time: the window never trails the tip by more than about one block while online. */
23
+ export const HEADER_SYNC_INTERVAL_MS = 10 * 60 * 1000
24
+
25
+ export interface HeaderSyncTriggerDeps {
26
+ /** Runs one sync pass. Must not throw into the caller; rejections are swallowed here anyway. */
27
+ sync: () => Promise<unknown>
28
+ isOnline: () => Promise<boolean>
29
+ subscribeOnline: (cb: (online: boolean) => void) => () => void
30
+ subscribeForeground: (cb: () => void) => () => void
31
+ intervalMs?: number
32
+ setInterval?: (fn: () => void, ms: number) => unknown
33
+ clearInterval?: (handle: unknown) => void
34
+ }
35
+
36
+ /** Starts every trigger; returns the function that stops them all. */
37
+ export function startHeaderSyncTriggers(deps: HeaderSyncTriggerDeps): () => void {
38
+ const schedule = deps.setInterval ?? ((fn, ms) => setInterval(fn, ms))
39
+ const cancel = deps.clearInterval ?? (handle => clearInterval(handle as ReturnType<typeof setInterval>))
40
+ let stopped = false
41
+
42
+ const attempt = async (knownOnline: boolean) => {
43
+ if (stopped) return
44
+ try {
45
+ if (!knownOnline && !(await deps.isOnline())) return
46
+ if (stopped) return
47
+ await deps.sync()
48
+ } catch {
49
+ // Best-effort. The next trigger retries.
50
+ }
51
+ }
52
+
53
+ const unsubscribeOnline = deps.subscribeOnline(online => {
54
+ if (online) void attempt(true)
55
+ })
56
+ const unsubscribeForeground = deps.subscribeForeground(() => void attempt(false))
57
+ const interval = schedule(() => void attempt(false), deps.intervalMs ?? HEADER_SYNC_INTERVAL_MS)
58
+
59
+ return () => {
60
+ stopped = true
61
+ unsubscribeOnline()
62
+ unsubscribeForeground()
63
+ cancel(interval)
64
+ }
65
+ }