@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.
Files changed (86) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.md +1 -4
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/inbox.ts +169 -64
  16. package/core/bridge/memoryInboxStore.ts +10 -1
  17. package/core/constants.ts +7 -11
  18. package/core/context/WalletConnectionContext.tsx +85 -48
  19. package/core/context/WalletContext.tsx +30 -32
  20. package/core/context/usePairingAttempt.ts +31 -0
  21. package/core/e2e/broadcaster.ts +25 -0
  22. package/core/e2e/consentFixture.ts +46 -0
  23. package/core/e2e/mode.ts +42 -0
  24. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  25. package/core/headers/headerConsensus.ts +230 -0
  26. package/core/headers/headerStore.ts +344 -122
  27. package/core/headers/prewarm.ts +4 -7
  28. package/core/headers/syncHeaders.ts +82 -12
  29. package/core/i18n/translations.tsx +47 -12
  30. package/core/identity/handleRegistry/client.ts +4 -2
  31. package/core/identity/handleRegistry/resolver.ts +7 -11
  32. package/core/index.ts +2 -0
  33. package/core/localpay/pending.ts +39 -4
  34. package/core/network/boundedFetch.ts +101 -0
  35. package/core/networks.ts +11 -13
  36. package/core/pay/rails/address.ts +5 -4
  37. package/core/pay/rails/handle.ts +3 -1
  38. package/core/pay/rails/sweep.ts +791 -0
  39. package/core/peerpay/brc29.ts +4 -0
  40. package/core/peerpay/handleResendRequests.ts +15 -2
  41. package/core/peerpay/outbox.ts +115 -2
  42. package/core/profiles/assertProfileEmpty.ts +2 -2
  43. package/core/profiles/profileStore.ts +3 -2
  44. package/core/services/arcadeBroadcastProvider.ts +260 -114
  45. package/core/services/secrets/kek.ts +5 -0
  46. package/core/services/secrets/migration.ts +27 -2
  47. package/core/services/secrets/policy.ts +6 -0
  48. package/core/services/vault/VaultKeyService.ts +5 -2
  49. package/core/services/vault/ceremony.ts +2 -2
  50. package/core/services/vault/ceremonyHost.ts +1 -1
  51. package/core/services/vault/guard.ts +10 -0
  52. package/core/services/vault/outputAuthority.ts +76 -0
  53. package/core/services/vault/transfers.ts +52 -28
  54. package/core/services/vault/vaultStore.ts +60 -14
  55. package/core/services/walletConnectionValidation.ts +13 -1
  56. package/core/services/walletServiceConfig.ts +8 -7
  57. package/core/stores/ConnectionStore.ts +17 -0
  58. package/core/toolboxConfig.ts +60 -1
  59. package/expo-module.config.json +5 -0
  60. package/ios/BoundedBody.swift +15 -0
  61. package/ios/BsvBoundedFetch.podspec +17 -0
  62. package/ios/BsvBoundedFetchModule.swift +121 -0
  63. package/package.json +7 -3
  64. package/ui/components/pay/AddressReceive.tsx +6 -2
  65. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  66. package/ui/components/pay/PayCellRow.tsx +3 -1
  67. package/ui/components/pay/PayForm.tsx +12 -2
  68. package/ui/components/pay/RecipientField.tsx +1 -0
  69. package/ui/components/pay/RequestHub.tsx +1 -0
  70. package/ui/components/pay/UniversalSend.tsx +110 -42
  71. package/ui/components/ui/ListRow.tsx +10 -2
  72. package/ui/components/vault/KeyChooser.tsx +1 -1
  73. package/ui/components/wallet/AmountInput.tsx +4 -1
  74. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  75. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  76. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  77. package/ui/components/wallet/ProfileButton.tsx +1 -0
  78. package/ui/importDatabases.ts +31 -6
  79. package/ui/screens/ConnectionsScreen.tsx +12 -3
  80. package/ui/screens/PairScreen.tsx +10 -3
  81. package/ui/screens/PayScreen.tsx +1 -0
  82. package/ui/screens/TrustScreen.tsx +6 -3
  83. package/ui/screens/VaultScreen.tsx +13 -3
  84. package/ui/screens/VaultTransferScreen.tsx +6 -3
  85. package/ui/screens/WalletConfigScreen.tsx +17 -2
  86. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -0,0 +1,76 @@
1
+ /** Fresh hardware authority for new funds. A valid root MAC proves that an
2
+ * enrollment was once approved, but cannot distinguish a retired enrollment
3
+ * replayed from storage. R1C is 1-of-N: prove one key that the new lock commits
4
+ * to, for this exact output, before any funding action is created. */
5
+ import { Hash, Utils } from '@bsv/sdk'
6
+ import { p256 } from '@noble/curves/nist.js'
7
+ import { requestVaultSigner } from './ceremonyHost'
8
+ import { randomBytes } from './random'
9
+ import { VaultError } from './types'
10
+ import { vaultStore, type VaultMeta, type VaultScopeToken } from './vaultStore'
11
+
12
+ interface VaultOutputAuthorityContext {
13
+ satoshis: number
14
+ saltKeyId: string
15
+ lockingScript: string
16
+ }
17
+
18
+ export async function requireVaultOutputKeyPossession(
19
+ meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'lastUsedSerial'>,
20
+ scope: VaultScopeToken,
21
+ output: VaultOutputAuthorityContext,
22
+ chosenSerial?: string
23
+ ): Promise<void> {
24
+ vaultStore.assertScopeToken(scope)
25
+ const chosen =
26
+ chosenSerial !== undefined
27
+ ? meta.keys.find(key => key.serial === chosenSerial)
28
+ : (meta.keys.find(key => key.serial === meta.lastUsedSerial) ?? meta.keys[0])
29
+ if (!chosen) throw new VaultError('not-enrolled', 'Choose a key committed to the new vault output')
30
+ const digest = Hash.sha256(
31
+ Utils.toArray(
32
+ JSON.stringify({
33
+ v: 1,
34
+ kind: 'vault-new-output',
35
+ walletScope: scope.storageKey,
36
+ chain: scope.chain,
37
+ vaultId: meta.vaultId,
38
+ revision: meta.revision,
39
+ createdAt: meta.createdAt,
40
+ keys: meta.keys.map(key => ({ serial: key.serial, slot: key.slot, pubkey: key.pubkey })),
41
+ satoshis: output.satoshis,
42
+ saltKeyId: output.saltKeyId,
43
+ lockingScriptHash: Utils.toHex(Hash.sha256(Utils.toArray(output.lockingScript, 'hex'))),
44
+ nonce: Utils.toHex(randomBytes(32))
45
+ }),
46
+ 'utf8'
47
+ )
48
+ )
49
+ const signer = await requestVaultSigner('Verify vault key for new funds', chosen.serial)
50
+ try {
51
+ vaultStore.assertScopeToken(scope)
52
+ if (signer.serial !== chosen.serial || signer.pubkey !== chosen.pubkey) {
53
+ throw new VaultError('wrong-key', 'Hardware does not match the new vault output key')
54
+ }
55
+ const signature = await signer.sign(Utils.toHex(digest))
56
+ vaultStore.assertScopeToken(scope)
57
+ let valid = false
58
+ try {
59
+ const der = p256.Signature.fromBytes(Uint8Array.from(signature), 'der')
60
+ valid = p256.verify(
61
+ der.toBytes(),
62
+ Uint8Array.from(digest),
63
+ Uint8Array.from(Utils.toArray(chosen.pubkey, 'hex')),
64
+ {
65
+ prehash: false,
66
+ lowS: false
67
+ }
68
+ )
69
+ } catch {
70
+ /* malformed signatures are failed possession proofs */
71
+ }
72
+ if (!valid) throw new VaultError('wrong-key', 'Hardware failed the new vault output possession challenge')
73
+ } finally {
74
+ signer.release()
75
+ }
76
+ }
@@ -3,8 +3,9 @@
3
3
  * and the `admin vault` basket, over 1-of-N P-256 comb-verifier outputs
4
4
  * (r1comb.ts, spec §2).
5
5
  *
6
- * Deposit: NO hardware. A vault output has a wallet-derived HMAC salt and one
7
- * comb commitment for every enrolled key. The HMAC uses [2, "vault salt"],
6
+ * Deposit: proves one enrolled hardware key before creating new funds. Each
7
+ * output has a wallet-derived HMAC salt and one comb commitment per enrolled
8
+ * key. The HMAC uses [2, "vault salt"],
8
9
  * counterparty "self", the rolling key ID "1", "2", ... and the canonically
9
10
  * framed YubiKey serials in commitment order. The lock contains only salted
10
11
  * table commitments; versioned customInstructions retain the derivation ID,
@@ -71,6 +72,7 @@ import { VaultError } from './types'
71
72
  import { metaFromVerifiedOutputs, VAULT_MAX_KEYS, VAULT_MIN_KEYS } from './VaultKeyService'
72
73
  import { vaultStore, VaultKeyRecord, VaultMeta, type VaultScopeToken, type VaultStoreScope } from './vaultStore'
73
74
  import { computeVaultMetaAuthorityTag, verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
75
+ import { requireVaultOutputKeyPossession } from './outputAuthority'
74
76
  import { forgetSerialsNoLongerEnrolledForIdentity } from './enrolledSerialRegistry'
75
77
 
76
78
  export const VAULT_BASKET = 'admin vault'
@@ -218,6 +220,8 @@ export type SpendingReferenceLookup = (outpoints: string[]) => Promise<{ referen
218
220
  * none of them still works.
219
221
  */
220
222
  export interface VaultTransferOptions {
223
+ /** Enrolled key to prove before creating a new vault output (deposit UI). */
224
+ outputKeySerial?: string
221
225
  /** Storage-backed reservation heal. See SpendingReferenceLookup. */
222
226
  findSpendingReferences?: SpendingReferenceLookup
223
227
  /**
@@ -1064,10 +1068,7 @@ async function reconcileHeldVaultDeposits(
1064
1068
  }
1065
1069
 
1066
1070
  export type VaultDepositResolution =
1067
- | { kind: 'broadcast' }
1068
- | { kind: 'already-known' }
1069
- | { kind: 'nothing-held' }
1070
- | { kind: 'failed'; error: unknown }
1071
+ { kind: 'broadcast' } | { kind: 'already-known' } | { kind: 'nothing-held' } | { kind: 'failed'; error: unknown }
1071
1072
 
1072
1073
  /**
1073
1074
  * XR-006 / INT-03: the identical crash window exists for a withdrawal or
@@ -1910,12 +1911,11 @@ export async function requireAuthenticatedMeta(
1910
1911
  'Local vault enrollment metadata disagrees with authenticated on-chain history; re-verify before continuing'
1911
1912
  )
1912
1913
  }
1913
- await vaultStore.restoreVerifiedMeta(recovered, scopeToken, next =>
1914
+ // Return the exact snapshot signed inside the restoration queue. A fresh
1915
+ // storage read here could have been replaced after that authentication.
1916
+ return await vaultStore.restoreVerifiedMeta(recovered, scopeToken, next =>
1914
1917
  computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
1915
1918
  )
1916
- const reconciled = await vaultStore.getMeta(scopeToken)
1917
- if (!reconciled) throw new VaultError('not-enrolled', 'Vault is not set up')
1918
- return reconciled
1919
1919
  }
1920
1920
 
1921
1921
  /**
@@ -2093,13 +2093,15 @@ async function newVaultOutput(
2093
2093
  satoshis: number,
2094
2094
  outputDescription: string,
2095
2095
  inventory: VaultSaltInventory,
2096
- chain: VaultScopeToken['chain']
2096
+ scopeToken: VaultScopeToken,
2097
+ chosenSerial?: string
2097
2098
  ): Promise<[vault: VaultOutputSpec, marker: VaultOutputSpec, descriptor: VaultOutputSpec]> {
2098
2099
  // Every output-creating path (deposit, re-lock, partial-withdrawal
2099
2100
  // remainder) comes through here. The key list may briefly hold one key more
2100
2101
  // than a lock commits (VAULT_MAX_ACTIVE_KEYS); never lock to it, and never
2101
2102
  // to fewer than VAULT_MIN_KEYS.
2102
2103
  requireLockableKeyCount(meta.keys.length)
2104
+ const { chain } = scopeToken
2103
2105
  const pubkeys = meta.keys.map(k => k.pubkey)
2104
2106
  const keyIndex = inventory.maxKeyIndex + 1
2105
2107
  if (!Number.isSafeInteger(keyIndex)) {
@@ -2113,6 +2115,16 @@ async function newVaultOutput(
2113
2115
  meta.keys.map(key => key.serial)
2114
2116
  )
2115
2117
  const lockingScript = buildLock({ commitments: pubkeys.map(pk => commitment(pk, salt)), saltHex64: salt })
2118
+ await requireVaultOutputKeyPossession(
2119
+ meta,
2120
+ scopeToken,
2121
+ {
2122
+ satoshis,
2123
+ saltKeyId,
2124
+ lockingScript: lockingScript.toHex()
2125
+ },
2126
+ chosenSerial
2127
+ )
2116
2128
  const v7: VaultInstructionsV7 = {
2117
2129
  v: 7,
2118
2130
  type: 'R1C',
@@ -2336,8 +2348,8 @@ function validateDepositPlan(tx: Transaction, expected: VaultOutputPlan): void {
2336
2348
  /**
2337
2349
  * Move `satoshis` from the default basket into the vault (spec §4.1).
2338
2350
  *
2339
- * No hardware: a deposit needs the key LIST, not a key. Every refusal is
2340
- * checked BEFORE the one createAction below, cheapest first, and nothing is
2351
+ * A fresh hardware proof confirms one key committed to the new output is
2352
+ * still usable. Every refusal is checked BEFORE createAction, and nothing is
2341
2353
  * spent until it runs. A pre-creation refusal consumes no numeric salt ID.
2342
2354
  * Once createAction persists an output, pending and failed history retain its
2343
2355
  * ID so a later output cannot reuse it.
@@ -2391,7 +2403,8 @@ export async function depositToVault(
2391
2403
  satoshis,
2392
2404
  'Vault deposit',
2393
2405
  saltInventory,
2394
- scopeToken.chain
2406
+ scopeToken,
2407
+ opts?.outputKeySerial
2395
2408
  )
2396
2409
  let reference: string | undefined
2397
2410
  let heldTxid: string | undefined
@@ -3239,7 +3252,8 @@ export async function withdrawFromVault(
3239
3252
  remainder,
3240
3253
  'Vault change',
3241
3254
  sel.saltInventory,
3242
- scopeToken.chain
3255
+ scopeToken,
3256
+ chosenSerial
3243
3257
  ))
3244
3258
  )
3245
3259
  }
@@ -3376,7 +3390,8 @@ export async function relockVault(
3376
3390
  relocked,
3377
3391
  'Vault re-lock',
3378
3392
  sel.saltInventory,
3379
- scopeToken.chain
3393
+ scopeToken,
3394
+ chosenSerial
3380
3395
  ),
3381
3396
  labels: ['vault', 'vault-relock'],
3382
3397
  inputDescription: 'Vault re-lock',
@@ -3395,8 +3410,11 @@ export async function relockVault(
3395
3410
  assertVaultScope(scopeToken)
3396
3411
  const scope = vaultStore.getScope()
3397
3412
  if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
3398
- await vaultStore.markKeyRemovalBroadcast(scopeToken, next =>
3399
- computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3413
+ const currentMeta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
3414
+ await vaultStore.markKeyRemovalBroadcast(
3415
+ scopeToken,
3416
+ next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope),
3417
+ currentMeta
3400
3418
  )
3401
3419
  }
3402
3420
  return result
@@ -3606,8 +3624,11 @@ export async function beginVaultKeyRemoval(
3606
3624
  if (!before.state.targetCommitted && heldDeposit) {
3607
3625
  throw new VaultError('action-pending', 'Resolve the held vault deposit before removing this key')
3608
3626
  }
3609
- const pending = await vaultStore.beginKeyRemoval(serial, scopeToken, next =>
3610
- computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3627
+ const pending = await vaultStore.beginKeyRemoval(
3628
+ serial,
3629
+ scopeToken,
3630
+ next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope),
3631
+ meta
3611
3632
  )
3612
3633
  if (before.state.targetCommitted) return { complete: false, meta: pending }
3613
3634
 
@@ -3624,13 +3645,17 @@ export async function beginVaultKeyRemoval(
3624
3645
  scopeToken
3625
3646
  )
3626
3647
  if (after.state.targetCommitted) {
3627
- await vaultStore.cancelUnbroadcastKeyRemoval(scopeToken, next =>
3628
- computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3648
+ await vaultStore.cancelUnbroadcastKeyRemoval(
3649
+ scopeToken,
3650
+ next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope),
3651
+ pending
3629
3652
  )
3630
3653
  throw new VaultError('action-pending', 'A vault output appeared while removing the key')
3631
3654
  }
3632
- const finalMeta = await vaultStore.finalizeEmptyKeyRemoval(scopeToken, next =>
3633
- computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3655
+ const finalMeta = await vaultStore.finalizeEmptyKeyRemoval(
3656
+ scopeToken,
3657
+ next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope),
3658
+ pending
3634
3659
  )
3635
3660
  // XQ-014: `serial` is now fully removed from this chain — forget it
3636
3661
  // device-wide unless another chain of this same identity still holds it.
@@ -3854,8 +3879,7 @@ export async function finalizeVaultKeyRemoval(w: VaultWallet, adminOriginator: s
3854
3879
  }
3855
3880
 
3856
3881
  if (invalidCurrentRelock) return false
3857
- if (matchingRelock) await vaultStore.markKeyRemovalBroadcast(scopeToken, tagger)
3858
- meta = await requireMeta(scopeToken)
3882
+ if (matchingRelock) meta = await vaultStore.markKeyRemovalBroadcast(scopeToken, tagger, meta)
3859
3883
  const pending = meta.pendingRemoval
3860
3884
  if (!pending) return true
3861
3885
  if (actionStateBlocks) return false
@@ -3875,7 +3899,7 @@ export async function finalizeVaultKeyRemoval(w: VaultWallet, adminOriginator: s
3875
3899
  'allow'
3876
3900
  )
3877
3901
  if (second.state.authorizesPendingKey) return false
3878
- await vaultStore.finalizeEmptyKeyRemoval(scopeToken, tagger)
3902
+ await vaultStore.finalizeEmptyKeyRemoval(scopeToken, tagger, meta)
3879
3903
  // XQ-014: the tombstoned key is now fully removed from this chain.
3880
3904
  await forgetSerialsNoLongerEnrolledForIdentity([pending.key.serial], () =>
3881
3905
  vaultStore.enrolledSerialsAcrossChains(scopeToken)
@@ -3897,7 +3921,7 @@ export async function finalizeVaultKeyRemoval(w: VaultWallet, adminOriginator: s
3897
3921
  'allow'
3898
3922
  )
3899
3923
  if (second.state.authorizesPendingKey) return false
3900
- await vaultStore.finalizeProvenKeyRemoval(scopeToken, tagger)
3924
+ await vaultStore.finalizeProvenKeyRemoval(scopeToken, tagger, meta)
3901
3925
  // XQ-014: the tombstoned key is now fully removed from this chain.
3902
3926
  await forgetSerialsNoLongerEnrolledForIdentity([pending.key.serial], () =>
3903
3927
  vaultStore.enrolledSerialsAcrossChains(scopeToken)
@@ -114,11 +114,7 @@ export interface VaultEnrollmentDraftEntry {
114
114
  }
115
115
 
116
116
  export type VaultEnrollmentQuarantineStage =
117
- | 'pin-change-uncertain'
118
- | 'pin-changed'
119
- | 'puk-change-uncertain'
120
- | 'puk-changed'
121
- | 'generation-uncertain'
117
+ 'pin-change-uncertain' | 'pin-changed' | 'puk-change-uncertain' | 'puk-changed' | 'generation-uncertain'
122
118
 
123
119
  /** An irreversible/ambiguous global PIV credential change occurred before a
124
120
  * public slot key existed. No credential is stored. Generic enrollment must
@@ -234,6 +230,17 @@ export type VaultMetaTagger = (
234
230
  next: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'pendingRemoval'>
235
231
  ) => Promise<string>
236
232
 
233
+ /** Match the record actually read inside the mutation queue to the snapshot
234
+ * authenticated by its caller. Never re-tag a separately loaded key list. */
235
+ function requireAuthenticatedSnapshot(meta: VaultMeta, expected?: VaultMeta, tagger?: VaultMetaTagger): void {
236
+ if (tagger && !expected) {
237
+ throw new VaultError('template-invalid', 'A tagged mutation requires an authenticated metadata snapshot')
238
+ }
239
+ if (expected && JSON.stringify(meta) !== JSON.stringify(expected)) {
240
+ throw new VaultError('template-invalid', 'Vault metadata changed after authentication; reload and retry')
241
+ }
242
+ }
243
+
237
244
  /** XR-001: same contract as VaultMetaTagger, for one `ready` draft record. */
238
245
  export type VaultDraftTagger = (record: VaultKeyRecord) => Promise<string>
239
246
 
@@ -966,7 +973,11 @@ export const vaultStore = {
966
973
  * they are taken from `checked` directly, never from `current`. Either
967
974
  * way `current`'s own (possibly forged, possibly absent) tag never
968
975
  * "launders" into the fresh one. */
969
- async restoreVerifiedMeta(meta: VaultMeta, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<void> {
976
+ async restoreVerifiedMeta(
977
+ meta: VaultMeta,
978
+ scopeToken?: VaultScopeToken,
979
+ tagger?: VaultMetaTagger
980
+ ): Promise<VaultMeta> {
970
981
  const token = scopeToken ?? captureScope(true)
971
982
  const checked = checkedMeta(meta)
972
983
  return enqueueMutation(async () => {
@@ -999,7 +1010,7 @@ export const vaultStore = {
999
1010
  if (pendingRemoval) restored.pendingRemoval = pendingRemoval
1000
1011
  else delete restored.pendingRemoval
1001
1012
  await writeMetaAndTag(token, restored, tagger)
1002
- return
1013
+ return restored
1003
1014
  }
1004
1015
 
1005
1016
  const knownSerials = new Set([
@@ -1023,6 +1034,7 @@ export const vaultStore = {
1023
1034
  restored.lastUsedSerial = current.lastUsedSerial
1024
1035
  }
1025
1036
  await writeMetaAndTag(token, restored, tagger)
1037
+ return restored
1026
1038
  })
1027
1039
  },
1028
1040
 
@@ -1061,11 +1073,17 @@ export const vaultStore = {
1061
1073
  * this with a `tagger` — see VaultKeyService.addVaultKey's
1062
1074
  * requireTaggedMeta call, which does exactly that.
1063
1075
  */
1064
- async addKey(k: VaultKeyRecord, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1076
+ async addKey(
1077
+ k: VaultKeyRecord,
1078
+ scopeToken?: VaultScopeToken,
1079
+ tagger?: VaultMetaTagger,
1080
+ expectedMeta?: VaultMeta
1081
+ ): Promise<VaultMeta> {
1065
1082
  const token = scopeToken ?? captureScope(true)
1066
1083
  if (!isVaultKeyRecord(k)) throw new VaultError('template-invalid', 'Invalid vault key record')
1067
1084
  return enqueueMutation(async () => {
1068
1085
  const meta = await requireMeta(token)
1086
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1069
1087
  if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
1070
1088
  if (meta.keys.length >= MAX_ACTIVE_KEYS) {
1071
1089
  throw new VaultError('too-many-keys', `The vault already has ${MAX_ACTIVE_KEYS} keys`)
@@ -1083,10 +1101,16 @@ export const vaultStore = {
1083
1101
  * trustworthy by the caller (transfers.ts's beginVaultKeyRemoval gates its
1084
1102
  * whole flow on requireAuthenticatedMeta before reaching here) before a
1085
1103
  * `tagger` is supplied. */
1086
- async beginKeyRemoval(serial: string, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1104
+ async beginKeyRemoval(
1105
+ serial: string,
1106
+ scopeToken?: VaultScopeToken,
1107
+ tagger?: VaultMetaTagger,
1108
+ expectedMeta?: VaultMeta
1109
+ ): Promise<VaultMeta> {
1087
1110
  const token = scopeToken ?? captureScope(true)
1088
1111
  return enqueueMutation(async () => {
1089
1112
  const meta = await requireMeta(token)
1113
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1090
1114
  if (meta.pendingRemoval) throw new VaultError('relock-required', 'Another key removal is already pending')
1091
1115
  if (meta.keys.length <= MIN_KEYS) {
1092
1116
  throw new VaultError('last-keys', `A vault needs at least ${MIN_KEYS} keys`)
@@ -1117,10 +1141,15 @@ export const vaultStore = {
1117
1141
  })
1118
1142
  },
1119
1143
 
1120
- async markKeyRemovalBroadcast(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1144
+ async markKeyRemovalBroadcast(
1145
+ scopeToken?: VaultScopeToken,
1146
+ tagger?: VaultMetaTagger,
1147
+ expectedMeta?: VaultMeta
1148
+ ): Promise<VaultMeta> {
1121
1149
  const token = scopeToken ?? captureScope(true)
1122
1150
  return enqueueMutation(async () => {
1123
1151
  const meta = await requireMeta(token)
1152
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1124
1153
  const pending = meta.pendingRemoval
1125
1154
  if (!pending) throw new VaultError('not-enrolled', 'No key removal is pending')
1126
1155
  if (pending.state === 'broadcast') return meta
@@ -1136,10 +1165,15 @@ export const vaultStore = {
1136
1165
  /** Caller must establish from authenticated action history and two complete
1137
1166
  * output scans that no spendable lock still authorizes the removed key and
1138
1167
  * that no relevant action is pending before invoking. */
1139
- async finalizeProvenKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1168
+ async finalizeProvenKeyRemoval(
1169
+ scopeToken?: VaultScopeToken,
1170
+ tagger?: VaultMetaTagger,
1171
+ expectedMeta?: VaultMeta
1172
+ ): Promise<VaultMeta> {
1140
1173
  const token = scopeToken ?? captureScope(true)
1141
1174
  return enqueueMutation(async () => {
1142
1175
  const meta = await requireMeta(token)
1176
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1143
1177
  const pending = meta.pendingRemoval
1144
1178
  if (!pending || pending.state !== 'broadcast') {
1145
1179
  throw new VaultError('template-invalid', 'No broadcast key removal is ready for proven finalization')
@@ -1158,10 +1192,15 @@ export const vaultStore = {
1158
1192
  * those scans and serializes them with deposits; this method only permits
1159
1193
  * the corresponding untouched, unbroadcast state transition.
1160
1194
  */
1161
- async finalizeEmptyKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1195
+ async finalizeEmptyKeyRemoval(
1196
+ scopeToken?: VaultScopeToken,
1197
+ tagger?: VaultMetaTagger,
1198
+ expectedMeta?: VaultMeta
1199
+ ): Promise<VaultMeta> {
1162
1200
  const token = scopeToken ?? captureScope(true)
1163
1201
  return enqueueMutation(async () => {
1164
1202
  const meta = await requireMeta(token)
1203
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1165
1204
  const pending = meta.pendingRemoval
1166
1205
  if (!pending || pending.state !== 'prepared') {
1167
1206
  throw new VaultError('template-invalid', 'Empty-vault removal does not match the pending state')
@@ -1177,10 +1216,15 @@ export const vaultStore = {
1177
1216
  * Restore a prepared key only after the caller has proved no transaction was
1178
1217
  * broadcast (for example, its reserved action was successfully aborted).
1179
1218
  */
1180
- async cancelUnbroadcastKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
1219
+ async cancelUnbroadcastKeyRemoval(
1220
+ scopeToken?: VaultScopeToken,
1221
+ tagger?: VaultMetaTagger,
1222
+ expectedMeta?: VaultMeta
1223
+ ): Promise<VaultMeta> {
1181
1224
  const token = scopeToken ?? captureScope(true)
1182
1225
  return enqueueMutation(async () => {
1183
1226
  const meta = await requireMeta(token)
1227
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1184
1228
  const pending = meta.pendingRemoval
1185
1229
  if (!pending || pending.state !== 'prepared') {
1186
1230
  throw new VaultError('relock-required', 'A broadcast or unknown removal cannot be cancelled')
@@ -1201,11 +1245,13 @@ export const vaultStore = {
1201
1245
  serial: string,
1202
1246
  nickname: string,
1203
1247
  scopeToken?: VaultScopeToken,
1204
- tagger?: VaultMetaTagger
1248
+ tagger?: VaultMetaTagger,
1249
+ expectedMeta?: VaultMeta
1205
1250
  ): Promise<VaultMeta> {
1206
1251
  const token = scopeToken ?? captureScope(true)
1207
1252
  return enqueueMutation(async () => {
1208
1253
  const meta = await requireMeta(token)
1254
+ requireAuthenticatedSnapshot(meta, expectedMeta, tagger)
1209
1255
  if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
1210
1256
  const clean = nickname.trim()
1211
1257
  if (clean.length < 1 || clean.length > 64) throw new VaultError('template-invalid', 'Invalid vault key nickname')
@@ -304,7 +304,9 @@ export function validateRelayUrl(raw: unknown): string {
304
304
  return url.origin
305
305
  }
306
306
 
307
- export function parseRelayResponse(raw: unknown): string {
307
+ export type OriginSessionTuple = Pick<ConnectParams, 'topic' | 'backendIdentityKey' | 'protocolID'>
308
+
309
+ export function parseRelayResponse(raw: unknown, expected?: OriginSessionTuple): string {
308
310
  const text = requireBoundedString(raw, 'relay response', MAX_RELAY_RESPONSE_BYTES)
309
311
  let data: unknown
310
312
  try {
@@ -320,6 +322,16 @@ export function parseRelayResponse(raw: unknown): string {
320
322
  ) {
321
323
  throw new Error('Origin server did not return a relay URL')
322
324
  }
325
+ if (expected) {
326
+ const session = data as Partial<OriginSessionTuple>
327
+ if (
328
+ session.topic !== expected.topic ||
329
+ session.backendIdentityKey !== expected.backendIdentityKey ||
330
+ session.protocolID !== expected.protocolID
331
+ ) {
332
+ throw new Error('Origin session does not match the approved pairing tuple')
333
+ }
334
+ }
323
335
  return validateRelayUrl((data as { relay: string }).relay)
324
336
  }
325
337
 
@@ -2,6 +2,7 @@ import type { AppChain } from '../config'
2
2
  import { toWalletChain } from '../config'
3
3
  import { getServiceConfig } from '../toolboxConfig'
4
4
  import { NETWORKS } from '../networks'
5
+ import { BROADCAST_PROVIDER_BUDGET_MS } from './arcadeBroadcastProvider'
5
6
  import { ChaintracksServiceClient, Services } from '@bsv/wallet-toolbox-mobile'
6
7
  import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
7
8
  import type { ChainTracker } from '@bsv/sdk'
@@ -74,7 +75,7 @@ export function createServiceOptions(
74
75
  }
75
76
 
76
77
  // One resolved Arcade endpoint feeds BOTH option slots. `arcUrl` is the
77
- // toolbox's generic ARC slot (broadcast fallback, `services.arcTaal`).
78
+ // toolbox's generic ARC slot (generic ARC slot).
78
79
  // `arcadeUrl` is what makes `Services` construct its `Arcade` provider —
79
80
  // and that provider is the only `getMerklePath` source that can answer for
80
81
  // a transaction the moment Arcade sees it mined (GET /tx/{txid} carries
@@ -92,11 +93,6 @@ export function createServiceOptions(
92
93
  }
93
94
  const arcade = { arcUrl: arcadeUrl, arcConfig, arcadeUrl, arcadeConfig: arcConfig }
94
95
 
95
- // XR-066: taalApiKey must never fall back to whatsOnChainApiKey. TAAL and
96
- // WhatsOnChain are different origins (createTaalBroadcastService sends
97
- // this key as a Bearer token to arc.taal.com et al. on every ordinary
98
- // broadcast) — a host that scoped a key to WhatsOnChain must not have it
99
- // silently disclosed to TAAL just because it left taalApiKey unset.
100
96
  const updateMsecs = network === 'main' ? 60 * 60 * 1000 : 60 * 60 * 1000000
101
97
  return {
102
98
  ...base,
@@ -105,7 +101,6 @@ export function createServiceOptions(
105
101
  fiatUpdateMsecs: updateMsecs,
106
102
  // A network with no WhatsOnChain gets no key: there is no host to send it to.
107
103
  whatsOnChainApiKey: NETWORKS[network].woc ? (svc.whatsOnChainApiKey ?? '') : '',
108
- taalApiKey: NETWORKS[network].taalArcUrl ? (svc.taalApiKey ?? '') : '',
109
104
  chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
110
105
  }
111
106
  }
@@ -139,6 +134,12 @@ export function createServices(
139
134
  chaintracksOverride
140
135
  )
141
136
  const services = new Services(serviceOptions)
137
+ // Each provider gets one flat budget. The toolbox default (5 s + 50 ms per KB,
138
+ // max 30 s) is shorter than a serial walk of a long unconfirmed chain; the walk
139
+ // inside a provider stops at the same cap (BROADCAST_PROVIDER_BUDGET_MS).
140
+ services.postBeefUntilSuccessSoftTimeoutMs = BROADCAST_PROVIDER_BUDGET_MS
141
+ services.postBeefUntilSuccessSoftTimeoutPerKbMs = 0
142
+ services.postBeefUntilSuccessSoftTimeoutMaxMs = BROADCAST_PROVIDER_BUDGET_MS
142
143
  // `ChaintracksClientApi` declares `isValidRootForHeight` and `currentHeight`
143
144
  // (ChaintracksClientApi.d.ts:137-138), which is the whole of `ChainTracker`, so
144
145
  // an override is always usable as one directly.
@@ -34,6 +34,20 @@ class ConnectionStore {
34
34
  * list; mobx wraps it as an ObservableMap, but nothing here relies on
35
35
  * that reactivity. */
36
36
  private pendingAuthorityTags = new Map<string, string>()
37
+ private revocations = new Map<string, number>()
38
+ private allRevocations = 0
39
+
40
+ revocationVersion(sessionId?: string): number {
41
+ // Clipboard approval starts before its topic is known. Any intervening
42
+ // revocation must invalidate that gesture before it can claim a new topic.
43
+ if (sessionId === undefined) return this.allRevocations
44
+ return this.revocations.get(sessionId) ?? 0
45
+ }
46
+
47
+ private revokePending(sessionId: string) {
48
+ this.allRevocations++
49
+ this.revocations.set(sessionId, this.revocationVersion(sessionId) + 1)
50
+ }
37
51
 
38
52
  constructor() {
39
53
  makeAutoObservable(this)
@@ -68,6 +82,7 @@ class ConnectionStore {
68
82
  }
69
83
 
70
84
  setStatus(sessionId: string, status: Connection['status']) {
85
+ if (status === 'disconnected') this.revokePending(sessionId)
71
86
  const conn = this.connections.find(c => c.sessionId === sessionId)
72
87
  if (conn) {
73
88
  conn.status = status
@@ -76,6 +91,8 @@ class ConnectionStore {
76
91
  }
77
92
 
78
93
  remove(sessionId: string) {
94
+ this.revokePending(sessionId)
95
+ this.pendingAuthorityTags.delete(sessionId)
79
96
  this.connections = this.connections.filter(c => c.sessionId !== sessionId)
80
97
  void this.save()
81
98
  }