@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -40,22 +40,27 @@
40
40
  * only by a spend's unlocking script; it provides domain separation between
41
41
  * locks, not spending authority.
42
42
  */
43
- import { Beef, Hash, LockingScript, Transaction, UnlockingScript, Utils } from '@bsv/sdk'
43
+ import { Beef, Hash, LockingScript, OP, P2PKH, PublicKey, Script, Transaction, UnlockingScript, Utils } from '@bsv/sdk'
44
44
  import { isBackupPushEnabled } from '../../backup/preference'
45
45
  import { getBackupUrl, isVaultAvailable, isVaultEnabled } from '../../toolboxConfig'
46
- import { specOpFailedActions } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
46
+ import { sdk as toolboxSdk } from '@bsv/wallet-toolbox-mobile'
47
47
  import { noteVaultProgress, requestVaultSigner } from './ceremonyHost'
48
48
  import {
49
+ MAX_DESCRIPTOR_CIPHERTEXT_BYTES,
49
50
  R1C_LOCK_LEN,
50
51
  R1C_UNLOCK_LEN,
51
52
  SALT_BYTES,
52
53
  VaultInstructions,
54
+ VaultInstructionsV7,
53
55
  bakedCommitments,
54
56
  buildLock,
55
57
  buildUnlock,
56
58
  commitment,
57
59
  decodeVaultInstructions,
60
+ decodeVaultInstructionsV7,
58
61
  encodeVaultInstructions,
62
+ encodeVaultInstructionsV7,
63
+ pushData,
59
64
  pushTxDerCheck,
60
65
  sighashPreimage,
61
66
  signerDigest,
@@ -63,12 +68,129 @@ import {
63
68
  verifyVaultInput
64
69
  } from './r1comb'
65
70
  import { VaultError } from './types'
66
- import { metaFromVerifiedOutputs, VAULT_MIN_KEYS } from './VaultKeyService'
67
- import { vaultStore, VaultKeyRecord, VaultMeta, type VaultScopeToken } from './vaultStore'
71
+ import { metaFromVerifiedOutputs, VAULT_MAX_KEYS, VAULT_MIN_KEYS } from './VaultKeyService'
72
+ import { vaultStore, VaultKeyRecord, VaultMeta, type VaultScopeToken, type VaultStoreScope } from './vaultStore'
73
+ import { computeVaultMetaAuthorityTag, verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
74
+ import { forgetSerialsNoLongerEnrolledForIdentity } from './enrolledSerialRegistry'
68
75
 
69
76
  export const VAULT_BASKET = 'admin vault'
70
77
  /** Wallet HMAC domain used only for Vault output salts. */
71
78
  export const VAULT_SALT_PROTOCOL = [2, 'vault salt'] as const
79
+ /** Wallet key domain for the v7 chain-published marker address. */
80
+ export const VAULT_MARKER_PROTOCOL = [2, 'vault marker'] as const
81
+ /** Wallet encryption domain for the v7 chain-published encrypted descriptor. */
82
+ export const VAULT_DESCRIPTOR_PROTOCOL = [2, 'vault descriptor'] as const
83
+ /** OP_RETURN tag identifying a v7 vault descriptor output. */
84
+ export const VAULT_DESCRIPTOR_TAG = 'r1c7'
85
+
86
+ /**
87
+ * keyID shared by the marker and descriptor derivations for output index `k`
88
+ * on `chain` — folds the chain in (unlike the chain-agnostic 'vault salt'
89
+ * HMAC, which stays untouched) so an identical enrolled-serial-set reused
90
+ * across two networks derives unrelated addresses/ciphertext keys instead of
91
+ * reusing the same discoverable marker address.
92
+ */
93
+ export function vaultChainKeyId(chain: VaultScopeToken['chain'], saltKeyId: string): string {
94
+ return `${chain}:${saltKeyId}`
95
+ }
96
+
97
+ /** The deterministic P2PKH marker script for output index `saltKeyId` on
98
+ * `chain` — reproducible from nothing but the wallet root, chain and index. */
99
+ export async function deriveVaultMarkerScript(
100
+ w: VaultWallet,
101
+ adminOriginator: string,
102
+ chain: VaultScopeToken['chain'],
103
+ saltKeyId: string
104
+ ): Promise<LockingScript> {
105
+ const { publicKey } = await w.getPublicKey({
106
+ protocolID: [...VAULT_MARKER_PROTOCOL],
107
+ keyID: vaultChainKeyId(chain, saltKeyId),
108
+ counterparty: 'self',
109
+ seekPermission: false
110
+ }, adminOriginator)
111
+ return new P2PKH().lock(PublicKey.fromString(publicKey).toAddress())
112
+ }
113
+
114
+ /**
115
+ * `OP_FALSE OP_RETURN <'r1c7'> <ciphertext>` — basketless, 0-sat,
116
+ * chain-published.
117
+ *
118
+ * @bsv/sdk's Script chunk parser treats OP_RETURN specially: everything after
119
+ * it is captured as ONE raw data blob on the OP_RETURN chunk itself (nothing
120
+ * past OP_RETURN ever executes, so no library tries to keep parsing it as
121
+ * further opcodes — matches ordinary OP_RETURN scripts industry-wide). The
122
+ * tag and ciphertext are still push-encoded (pushData) WITHIN that blob, so
123
+ * parseVaultDescriptorScript can split them back out with an ordinary
124
+ * (non-OP_RETURN) chunk parse of the blob alone.
125
+ */
126
+ export function buildVaultDescriptorScript(ciphertext: number[]): LockingScript {
127
+ const tagBytes = Utils.toArray(VAULT_DESCRIPTOR_TAG, 'utf8') as number[]
128
+ const payload = [...pushData(tagBytes), ...pushData(ciphertext)]
129
+ return new LockingScript([{ op: OP.OP_FALSE }, { op: OP.OP_RETURN, data: payload }])
130
+ }
131
+
132
+ /** Parse a script built by buildVaultDescriptorScript. Returns null for
133
+ * anything else — including an oversized ciphertext, which is never trusted,
134
+ * only reported as unusable by the caller. */
135
+ export function parseVaultDescriptorScript(lockingScript: LockingScript): { ciphertext: number[] } | null {
136
+ const chunks = lockingScript.chunks
137
+ if (chunks.length !== 2) return null
138
+ if (chunks[0].op !== OP.OP_0 && chunks[0].op !== OP.OP_FALSE) return null
139
+ if (chunks[1].op !== OP.OP_RETURN || !chunks[1].data) return null
140
+ let inner: { op: number; data?: number[] }[]
141
+ try {
142
+ inner = Script.fromBinary(chunks[1].data).chunks
143
+ } catch {
144
+ return null
145
+ }
146
+ if (inner.length !== 2) return null
147
+ const tag = inner[0].data
148
+ if (!tag || Utils.toUTF8(tag) !== VAULT_DESCRIPTOR_TAG) return null
149
+ const ciphertext = inner[1].data
150
+ if (!ciphertext || ciphertext.length === 0 || ciphertext.length > MAX_DESCRIPTOR_CIPHERTEXT_BYTES) return null
151
+ return { ciphertext }
152
+ }
153
+
154
+ /** Encrypt a v7 customInstructions JSON string for the descriptor output,
155
+ * enforcing the byte budget at creation time (fail closed, never truncate). */
156
+ export async function encryptVaultDescriptorPlaintext(
157
+ w: VaultWallet,
158
+ adminOriginator: string,
159
+ chain: VaultScopeToken['chain'],
160
+ saltKeyId: string,
161
+ plaintext: string
162
+ ): Promise<number[]> {
163
+ const { ciphertext } = await w.encrypt({
164
+ plaintext: Utils.toArray(plaintext, 'utf8') as number[],
165
+ protocolID: [...VAULT_DESCRIPTOR_PROTOCOL],
166
+ keyID: vaultChainKeyId(chain, saltKeyId),
167
+ counterparty: 'self',
168
+ seekPermission: false
169
+ }, adminOriginator)
170
+ if (!Array.isArray(ciphertext) || ciphertext.length === 0 || ciphertext.length > MAX_DESCRIPTOR_CIPHERTEXT_BYTES) {
171
+ throw new VaultError('template-invalid', 'Vault descriptor ciphertext exceeds its byte budget')
172
+ }
173
+ return ciphertext
174
+ }
175
+
176
+ /** Decrypt a descriptor's ciphertext back to its plaintext customInstructions
177
+ * JSON string. Throws (never silently returns garbage) on any wallet-level
178
+ * decrypt failure — the caller decides how an unusable record is reported. */
179
+ export async function decryptVaultDescriptorPlaintext(
180
+ w: VaultWallet,
181
+ adminOriginator: string,
182
+ chain: VaultScopeToken['chain'],
183
+ saltKeyId: string,
184
+ ciphertext: number[]
185
+ ): Promise<string> {
186
+ const { plaintext } = await w.decrypt({
187
+ ciphertext,
188
+ protocolID: [...VAULT_DESCRIPTOR_PROTOCOL],
189
+ keyID: vaultChainKeyId(chain, saltKeyId),
190
+ counterparty: 'self'
191
+ }, adminOriginator)
192
+ return Utils.toUTF8(plaintext)
193
+ }
72
194
 
73
195
  /**
74
196
  * Storage-backed lookup of the transactions reserving a set of outpoints.
@@ -186,6 +308,9 @@ export const VAULT_HARD_MAX_INPUTS = 48
186
308
  * whole module is testable without the toolbox). */
187
309
  export interface VaultWallet {
188
310
  createHmac(args: unknown, originator: string): Promise<{ hmac: number[] }>
311
+ /** XR-002: verifies a vault-meta authority tag (metaAuthority.ts) before an
312
+ * output-creating operation trusts local meta. */
313
+ verifyHmac(args: unknown, originator: string): Promise<{ valid: boolean }>
189
314
  createAction(args: unknown, originator: string): Promise<CreateActionResult>
190
315
  signAction(args: unknown, originator: string): Promise<{
191
316
  txid?: string
@@ -194,6 +319,30 @@ export interface VaultWallet {
194
319
  listOutputs(args: unknown, originator: string): Promise<ListOutputsResult>
195
320
  abortAction(args: unknown, originator: string): Promise<unknown>
196
321
  listActions?(args: unknown, originator: string): Promise<{ actions: VaultActionRow[]; totalActions?: number }>
322
+ /** Marker key derivation (v7 output creation and chain recovery). */
323
+ getPublicKey(args: unknown, originator: string): Promise<{ publicKey: string }>
324
+ /** Descriptor encryption (v7 output creation). */
325
+ encrypt(args: unknown, originator: string): Promise<{ ciphertext: number[] }>
326
+ /** Descriptor decryption (chain recovery). */
327
+ decrypt(args: unknown, originator: string): Promise<{ plaintext: number[] }>
328
+ /** Insert a chain-recovered v7 output into the admin vault basket. */
329
+ internalizeAction(args: unknown, originator: string): Promise<{ accepted: true }>
330
+ /** Network status lookup (mirrors storage/methods/processOfflineActions.ts'
331
+ * networkAlreadyHas). NEW-07: no longer consulted by resolveHeldVaultDeposit
332
+ * — a bare 'mined'/'known' answer from this is an unauthenticated claim,
333
+ * exactly what networkAlreadyHas itself refuses to trust without a
334
+ * validated proof (EntityProvenTx.fromTxid). Kept on the interface only for
335
+ * structural compatibility with the real wallet surface this is cast from;
336
+ * not currently called anywhere in this module. */
337
+ getStatusForTxids?(txids: string[]): Promise<{ results?: { txid: string; status: string }[] }>
338
+ }
339
+
340
+ /** VaultWallet's createHmac/verifyHmac require `originator`; the SDK's own
341
+ * WalletInterface types it optional, which structurally is all
342
+ * metaAuthority.ts's HmacCapableWallet needs. Every call in this module
343
+ * already always supplies `adminOriginator`, so narrowing costs nothing. */
344
+ function asHmacWallet(w: VaultWallet): HmacCapableWallet {
345
+ return w as unknown as HmacCapableWallet
197
346
  }
198
347
 
199
348
  /** The fields of a listActions row the reservation heal needs. `inputs` arrives
@@ -284,13 +433,15 @@ function canonicalVaultOutpoint(outpoint: string): string {
284
433
  }
285
434
 
286
435
  /** Page the entire basket without retaining its large scripts or BEEF. The
287
- * callback must consume each page synchronously; only compact identities stay
288
- * live across pages so pagination aliases and repeats still fail closed. */
436
+ * callback consumes each page (v7's per-output salt re-derivation makes this
437
+ * async — awaited sequentially within a page before the next page is
438
+ * fetched); only compact identities stay live across pages so pagination
439
+ * aliases and repeats still fail closed. */
289
440
  async function scanVaultOutputPages(
290
441
  w: VaultWallet,
291
442
  adminOriginator: string,
292
443
  include: 'locking scripts' | 'entire transactions',
293
- onPage: (outputs: ListOutputsResult['outputs'], page: ListOutputsResult) => void,
444
+ onPage: (outputs: ListOutputsResult['outputs'], page: ListOutputsResult) => void | Promise<void>,
294
445
  scopeToken?: VaultScopeToken,
295
446
  ): Promise<number> {
296
447
  const seen = new Set<string>()
@@ -329,7 +480,7 @@ async function scanVaultOutputPages(
329
480
  seen.add(canonicalOutpoint)
330
481
  outputs.push({ ...rawOutput, outpoint: canonicalOutpoint })
331
482
  }
332
- onPage(outputs, page)
483
+ await onPage(outputs, page)
333
484
  if (page.outputs.length === 0) {
334
485
  if (expectedTotal !== undefined && offset < expectedTotal) {
335
486
  throw new VaultError('no-transaction', 'Vault output listing made no progress before its reported total')
@@ -385,20 +536,39 @@ interface VerifiedVaultOutput {
385
536
  satoshis: number
386
537
  ci: VaultInstructions
387
538
  lockingScript: LockingScript
539
+ /** The salt that authenticates `ci` against `lockingScript`: read directly
540
+ * off a v6 record, or re-derived (never persisted) for a v7 one. Callers
541
+ * that need to build a v7 witness (buildUnlock) use this instead of
542
+ * `ci.salt`, which does not exist on a v7 record. */
543
+ salt: string
388
544
  }
389
545
 
390
- function verifyInstructionsAgainstLock(ci: VaultInstructions, lockingScript: LockingScript, where: string): void {
546
+ /**
547
+ * Resolve the salt that authenticates `ci`'s lock. v6 carries it directly in
548
+ * the (untrusted) record; a separate later pass, verifyVaultSaltDerivations,
549
+ * re-derives it from the wallet to confirm the claim wasn't fabricated. v7
550
+ * carries no salt at all — it is always freshly re-derived here via the same
551
+ * unchanged HMAC protocol, from fields the record does carry (saltKeyId and
552
+ * the serial list), so there is no separate claim to falsify: deriving IS
553
+ * the authentication.
554
+ */
555
+ export async function resolveVaultSalt(w: VaultWallet, adminOriginator: string, ci: VaultInstructions): Promise<string> {
556
+ if (ci.v === 6) return ci.salt
557
+ return await deriveVaultSalt(w, adminOriginator, ci.saltKeyId, ci.keys.map(key => key.serial))
558
+ }
559
+
560
+ function verifyInstructionsAgainstLock(ci: VaultInstructions, lockingScript: LockingScript, where: string, salt: string): void {
391
561
  let baked: string[]
392
562
  try {
393
563
  baked = bakedCommitments(lockingScript)
394
564
  } catch {
395
565
  throw new VaultError('template-invalid', `${where} is not an R1C lock`)
396
566
  }
397
- const expected = ci.keys.map(key => commitment(key.pubkey, ci.salt))
567
+ const expected = ci.keys.map(key => commitment(key.pubkey, salt))
398
568
  if (baked.length !== expected.length || baked.some((c, i) => c !== expected[i])) {
399
569
  throw new VaultError('template-invalid', `${where} recovery metadata does not match its real lock`)
400
570
  }
401
- const rebuilt = buildLock({ commitments: expected, saltHex64: ci.salt })
571
+ const rebuilt = buildLock({ commitments: expected, saltHex64: salt })
402
572
  if (rebuilt.toHex() !== lockingScript.toHex()) {
403
573
  throw new VaultError('template-invalid', `${where} recovery metadata does not rebuild its real lock`)
404
574
  }
@@ -406,11 +576,14 @@ function verifyInstructionsAgainstLock(ci: VaultInstructions, lockingScript: Loc
406
576
 
407
577
  /** Validate both the recoverability record and the real source output. The
408
578
  * customInstructions are an index; authorization comes only from the exact
409
- * commitments baked into the locking script carried by the BEEF. */
410
- function verifyListedVaultOutput(
579
+ * commitments baked into the locking script carried by the BEEF. Async: a v7
580
+ * record's salt is re-derived from the wallet (see resolveVaultSalt). */
581
+ async function verifyListedVaultOutput(
582
+ w: VaultWallet,
583
+ adminOriginator: string,
411
584
  output: ListOutputsResult['outputs'][number],
412
585
  sources: Beef
413
- ): VerifiedVaultOutput {
586
+ ): Promise<VerifiedVaultOutput> {
414
587
  if (!Number.isSafeInteger(output.satoshis) || output.satoshis < 0) {
415
588
  throw new VaultError('no-transaction', `Vault output ${output.outpoint} has an invalid value`)
416
589
  }
@@ -428,8 +601,9 @@ function verifyListedVaultOutput(
428
601
  if (sourceSatoshis !== output.satoshis) {
429
602
  throw new VaultError('no-transaction', `Vault output ${output.outpoint} value disagrees with its source transaction`)
430
603
  }
431
- verifyInstructionsAgainstLock(ci, source.lockingScript, `Vault output ${output.outpoint}`)
432
- return { outpoint: canonicalOutpoint, satoshis: sourceSatoshis, ci, lockingScript: source.lockingScript }
604
+ const salt = await resolveVaultSalt(w, adminOriginator, ci)
605
+ verifyInstructionsAgainstLock(ci, source.lockingScript, `Vault output ${output.outpoint}`, salt)
606
+ return { outpoint: canonicalOutpoint, satoshis: sourceSatoshis, ci, lockingScript: source.lockingScript, salt }
433
607
  }
434
608
 
435
609
  function sumVaultSatoshis(outputs: readonly Pick<VerifiedVaultOutput, 'satoshis'>[], where: string): number {
@@ -463,7 +637,7 @@ async function reduceVerifiedVaultOutputs<T>(
463
637
  if (!expectedChain) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
464
638
  const state = initial()
465
639
  const inventory = emptyVaultSaltInventory()
466
- const outputs = await scanVaultOutputPages(w, adminOriginator, 'entire transactions', (listed, page) => {
640
+ const outputs = await scanVaultOutputPages(w, adminOriginator, 'entire transactions', async (listed, page) => {
467
641
  if (listed.length === 0) return
468
642
  if (!page.BEEF?.length) {
469
643
  throw new VaultError('no-transaction', 'Vault output listing did not include source transactions')
@@ -475,8 +649,8 @@ async function reduceVerifiedVaultOutputs<T>(
475
649
  throw new VaultError('no-transaction', 'Vault output listing returned malformed source transactions')
476
650
  }
477
651
  for (const listedOutput of listed) {
478
- const output = verifyListedVaultOutput(listedOutput, sources)
479
- rememberVaultSalt(inventory, output.ci, output.lockingScript, output.outpoint, expectedChain)
652
+ const output = await verifyListedVaultOutput(w, adminOriginator, listedOutput, sources)
653
+ rememberVaultSalt(inventory, output.ci, output.lockingScript, output.outpoint, expectedChain, output.salt)
480
654
  reduce(state, output, sources)
481
655
  }
482
656
  }, scopeToken)
@@ -537,6 +711,17 @@ const PENDING_ACTION_STATUSES = new Set(['unsigned', 'nosend', 'nonfinal', 'unpr
537
711
  */
538
712
  const BROADCAST_ACTION_STATUSES = new Set(['sending', 'unproven'])
539
713
 
714
+ /**
715
+ * The statuses in which the network has ACCEPTED a transaction: ARC answered
716
+ * with an accepted status ('unproven'), or it is mined ('completed'). `sending`
717
+ * is absent: the toolbox has posted it but holds no acceptance yet and may
718
+ * still be retrying. A key removal is final once its re-lock is accepted, not
719
+ * once it is mined (owner decision, 2026-09-25): should an accepted re-lock
720
+ * still be dropped, its sources return as outputs committed to a key the
721
+ * vault no longer lists, which the coverage badge offers to re-lock.
722
+ */
723
+ const ACCEPTED_ACTION_STATUSES = new Set(['unproven', 'completed'])
724
+
540
725
  /** Authenticate pagination while consuming one action at a time. Detailed
541
726
  * action rows may contain several 45 KB source/output scripts, so callers must
542
727
  * retain only the small facts or references they need after this callback. */
@@ -544,7 +729,7 @@ async function scanVaultActions(
544
729
  w: VaultWallet,
545
730
  adminOriginator: string,
546
731
  details: Record<string, unknown>,
547
- onAction: (action: VaultActionRow) => void,
732
+ onAction: (action: VaultActionRow) => void | Promise<void>,
548
733
  scopeToken?: VaultScopeToken,
549
734
  includeFailed = false
550
735
  ): Promise<void> {
@@ -581,7 +766,7 @@ async function scanVaultActions(
581
766
  if (!identity) throw new VaultError('no-transaction', 'Vault action listing returned an unidentified row')
582
767
  if (seen.has(identity)) throw new VaultError('no-transaction', `Vault action listing repeated ${identity}`)
583
768
  seen.add(identity)
584
- onAction(action)
769
+ await onAction(action)
585
770
  }
586
771
  if (actions.length === 0) {
587
772
  if (expectedTotal !== undefined && offset < expectedTotal) {
@@ -601,7 +786,7 @@ async function scanVaultActions(
601
786
  await scan(details)
602
787
  if (!includeFailed) return
603
788
  const ordinaryLabels = Array.isArray(details.labels) ? details.labels.filter(label => typeof label === 'string') : ['vault']
604
- await scan({ ...details, labels: [specOpFailedActions, ...ordinaryLabels] })
789
+ await scan({ ...details, labels: [toolboxSdk.specOpFailedActions, ...ordinaryLabels] })
605
790
  }
606
791
 
607
792
  const actionClaimsVaultSpend = (action: VaultActionRow): boolean => {
@@ -629,12 +814,14 @@ const actionTouchesVault = (action: VaultActionRow): boolean => {
629
814
  * output to one ordinary P2PKH change output before allowing abortAction. A
630
815
  * label by itself is never authority to mutate another action.
631
816
  */
632
- function isValidHeldVaultDeposit(
817
+ async function isValidHeldVaultDeposit(
818
+ w: VaultWallet,
819
+ adminOriginator: string,
633
820
  action: VaultActionRow,
634
821
  meta: VaultMeta,
635
822
  expectedChain: VaultScopeToken['chain'],
636
823
  saltInventory?: VaultSaltInventory
637
- ): boolean {
824
+ ): Promise<boolean> {
638
825
  const labels = new Set(action.labels ?? [])
639
826
  if (!labels.has('vault-deposit') || labels.has('vault-withdraw') || labels.has('vault-relock')) return false
640
827
  if (!action.reference) return false
@@ -660,7 +847,7 @@ function isValidHeldVaultDeposit(
660
847
  }
661
848
 
662
849
  const outputs = action.outputs ?? []
663
- if (outputs.length < 1 || outputs.length > 2) return false
850
+ if (outputs.length < 1 || outputs.length > 4) return false
664
851
  const indices = new Set<number>()
665
852
  for (const output of outputs) {
666
853
  if (!Number.isSafeInteger(output.outputIndex) || output.outputIndex < 0 || indices.has(output.outputIndex)) return false
@@ -681,26 +868,73 @@ function isValidHeldVaultDeposit(
681
868
  ) return false
682
869
  if (ci.revision === meta.revision && !sameInstructionKeys(meta.keys, ci.keys)) return false
683
870
  let lock: LockingScript
871
+ let salt: string
684
872
  try {
685
873
  lock = LockingScript.fromHex(output.lockingScript)
686
- verifyInstructionsAgainstLock(ci, lock, 'Held Vault deposit')
874
+ salt = await resolveVaultSalt(w, adminOriginator, ci)
875
+ verifyInstructionsAgainstLock(ci, lock, 'Held Vault deposit', salt)
687
876
  } catch {
688
877
  return false
689
878
  }
690
879
 
691
- const implicit = outputs.filter(candidate => candidate !== output)
692
- if (implicit.length === 1) {
693
- const change = implicit[0]
694
- if (
695
- !Number.isSafeInteger(change.satoshis) ||
696
- change.satoshis <= 0 ||
697
- !change.lockingScript
698
- ) return false
880
+ // v6: everything but the vault output is at most one ordinary P2PKH
881
+ // implicit change output — UNCHANGED, since a v6-shaped held deposit can
882
+ // still exist from a build predating this release.
883
+ //
884
+ // v7: the marker (index 1) and descriptor (index 2) are fixed, expected
885
+ // outputs — authenticated the same byte-exact/decrypt-and-compare way the
886
+ // creation-time validators check them — with at most one implicit P2PKH
887
+ // change at index 3. Recognizing this shape (instead of falling through to
888
+ // the v6 1-2-output cap) is what keeps a v7 deposit from wedging every
889
+ // subsequent vault operation behind 'action-pending' after a crash.
890
+ if (ci.v === 7) {
891
+ if (outputs.length < 3 || outputs.length > 4) return false
892
+ const markerOutput = outputs.find(candidate => candidate.outputIndex === 1)
893
+ const descriptorOutput = outputs.find(candidate => candidate.outputIndex === 2)
894
+ if (!markerOutput || !descriptorOutput) return false
895
+ if (markerOutput.basket || descriptorOutput.basket) return false
896
+ if (markerOutput.satoshis !== 1 || descriptorOutput.satoshis !== 0) return false
897
+ if (!markerOutput.lockingScript || !descriptorOutput.lockingScript) return false
699
898
  try {
700
- if (!isStandardP2PKH(LockingScript.fromHex(change.lockingScript))) return false
899
+ const expectedMarker = await deriveVaultMarkerScript(w, adminOriginator, expectedChain, ci.saltKeyId)
900
+ if (markerOutput.lockingScript.toLowerCase() !== expectedMarker.toHex().toLowerCase()) return false
901
+ const parsedDescriptor = parseVaultDescriptorScript(LockingScript.fromHex(descriptorOutput.lockingScript))
902
+ if (!parsedDescriptor) return false
903
+ const descriptorPlaintext = await decryptVaultDescriptorPlaintext(
904
+ w, adminOriginator, expectedChain, ci.saltKeyId, parsedDescriptor.ciphertext
905
+ )
906
+ if (descriptorPlaintext !== output.customInstructions) return false
701
907
  } catch {
702
908
  return false
703
909
  }
910
+ const implicit = outputs.filter(candidate => candidate.outputIndex >= 3)
911
+ if (implicit.length > 1) return false
912
+ if (implicit.length === 1) {
913
+ const change = implicit[0]
914
+ if (!Number.isSafeInteger(change.satoshis) || change.satoshis <= 0 || !change.lockingScript) return false
915
+ try {
916
+ if (!isStandardP2PKH(LockingScript.fromHex(change.lockingScript))) return false
917
+ } catch {
918
+ return false
919
+ }
920
+ }
921
+ } else {
922
+ const implicit = outputs.filter(candidate => candidate !== output)
923
+ if (implicit.length === 1) {
924
+ const change = implicit[0]
925
+ if (
926
+ !Number.isSafeInteger(change.satoshis) ||
927
+ change.satoshis <= 0 ||
928
+ !change.lockingScript
929
+ ) return false
930
+ try {
931
+ if (!isStandardP2PKH(LockingScript.fromHex(change.lockingScript))) return false
932
+ } catch {
933
+ return false
934
+ }
935
+ } else if (implicit.length > 1) {
936
+ return false
937
+ }
704
938
  }
705
939
  if (saltInventory) {
706
940
  rememberVaultSalt(
@@ -708,7 +942,8 @@ function isValidHeldVaultDeposit(
708
942
  ci,
709
943
  lock,
710
944
  vaultActionOutputId(action, output.outputIndex),
711
- expectedChain
945
+ expectedChain,
946
+ salt
712
947
  )
713
948
  }
714
949
  return true
@@ -740,7 +975,7 @@ async function reconcileHeldVaultDeposits(
740
975
  includeInputSourceLockingScripts: true,
741
976
  includeOutputs: true,
742
977
  includeOutputLockingScripts: true
743
- }, action => {
978
+ }, async action => {
744
979
  const labels = new Set(action.labels ?? [])
745
980
  if (!labels.has('vault-deposit') || action.status === 'completed' || action.status === 'failed') return
746
981
  // A deposit that reached the network is a live unconfirmed deposit, not a
@@ -751,7 +986,10 @@ async function reconcileHeldVaultDeposits(
751
986
  // block every vault transfer — including the re-lock the refusal asks
752
987
  // for — until the merkle proof arrives.
753
988
  if (BROADCAST_ACTION_STATUSES.has(action.status)) return
754
- if (!PENDING_ACTION_STATUSES.has(action.status) || !isValidHeldVaultDeposit(action, meta, expectedChain, saltInventory)) {
989
+ if (
990
+ !PENDING_ACTION_STATUSES.has(action.status) ||
991
+ !(await isValidHeldVaultDeposit(w, adminOriginator, action, meta, expectedChain, saltInventory))
992
+ ) {
755
993
  throw new VaultError('action-pending', 'A Vault deposit has an unknown or potentially broadcast state')
756
994
  }
757
995
  if (action.status === 'unsigned') unsigned.push(action.reference!)
@@ -774,6 +1012,124 @@ async function reconcileHeldVaultDeposits(
774
1012
  throw new VaultError('action-pending', 'A signed Vault deposit needs manual broadcast-state reconciliation')
775
1013
  }
776
1014
 
1015
+ export type VaultDepositResolution =
1016
+ | { kind: 'broadcast' }
1017
+ | { kind: 'already-known' }
1018
+ | { kind: 'nothing-held' }
1019
+ | { kind: 'failed'; error: unknown }
1020
+
1021
+ /**
1022
+ * XR-006 / INT-03: the identical crash window exists for a withdrawal or
1023
+ * re-lock (spends existing R1C outputs) as for a deposit (creates one) — the
1024
+ * gap is between signAction and the sendWith that releases it. Unlike a
1025
+ * deposit's shape (one new vault output plus its marker/descriptor), a
1026
+ * withdraw/relock's OWN authority already comes from the hardware signature
1027
+ * already on these exact bytes; this only needs to correctly identify the
1028
+ * one held candidate to resend, not re-validate the full output plan. Every
1029
+ * input must be an authentic current R1C source (never an ordinary P2PKH
1030
+ * input, which would make this a deposit, not a spend) so a decoy action
1031
+ * cannot be resent as though it were the held vault spend.
1032
+ */
1033
+ function isValidHeldVaultSpend(action: VaultActionRow): boolean {
1034
+ const labels = new Set(action.labels ?? [])
1035
+ if (!labels.has('vault-withdraw') && !labels.has('vault-relock')) return false
1036
+ if (!action.reference) return false
1037
+ if (action.status !== 'nosend' || !action.txid || !/^[0-9a-fA-F]{64}$/.test(action.txid)) return false
1038
+ const inputs = action.inputs ?? []
1039
+ if (inputs.length === 0 || inputs.length > VAULT_HARD_MAX_INPUTS) return false
1040
+ for (const input of inputs) {
1041
+ if (!input.sourceOutpoint || !/^[0-9a-fA-F]{64}[.:]\d+$/.test(input.sourceOutpoint)) return false
1042
+ if (!isR1CSourceScript(input.sourceLockingScript)) return false
1043
+ }
1044
+ return true
1045
+ }
1046
+
1047
+ /**
1048
+ * Resolve the ONE held, signed (noSend) Vault action reconcileHeldVaultDeposits
1049
+ * refuses to touch automatically (F-04) — the crash window is between
1050
+ * signAction and the sendWith that releases it, so the transaction may or may
1051
+ * not have already escaped to the network. Covers both a held DEPOSIT
1052
+ * (creates a new R1C output) and a held WITHDRAWAL or RE-LOCK (spends
1053
+ * existing ones) — see isValidHeldVaultSpend: before XR-006/INT-03, only the
1054
+ * deposit shape was ever recognized here, so a crashed signed withdraw/
1055
+ * re-lock had no reconciliation path and froze every subsequent Vault read
1056
+ * via inspectHiddenVaultReservations indefinitely.
1057
+ *
1058
+ * NEW-07: this never trusts a bare network-status claim ('mined'/'known' from
1059
+ * getStatusForTxids) to decide the held transaction is already resolved — a
1060
+ * wrong or malicious status service could otherwise make this report success
1061
+ * while the signed bytes were never released, leaving the vault blocked with
1062
+ * the user told everything is fine (exactly the unauthenticated-claim trap
1063
+ * XQ-009 closed for processOfflineActions.ts' networkAlreadyHas). Instead,
1064
+ * ALWAYS release the wallet's own already-signed bytes with the EXACT same
1065
+ * sendWith call depositToVault's own release uses (~line 1764) — never a
1066
+ * second transaction. Re-sending identical signed bytes is safe: a
1067
+ * broadcaster/storage layer that already has them answers accordingly
1068
+ * (classifyReqDetails maps its own trusted "already sent" knowledge to an
1069
+ * `unproven` sendWithResults status), and requireReleasedHeldTransaction
1070
+ * already accepts that alongside a fresh `sending` as a confirmed release —
1071
+ * so this only needs to tell the two apart afterward, for a more precise
1072
+ * resolution kind, never to decide up front whether to call sendWith at all.
1073
+ * `abortAction` is never called here — only reconcileHeldVaultDeposits'
1074
+ * unsigned/no-txid branch may free inputs.
1075
+ */
1076
+ export async function resolveHeldVaultDeposit(
1077
+ w: VaultWallet,
1078
+ adminOriginator: string,
1079
+ meta: VaultMeta,
1080
+ scopeToken?: VaultScopeToken
1081
+ ): Promise<VaultDepositResolution> {
1082
+ const captured = scopeToken ?? vaultStore.captureScopeToken()
1083
+ return await withVaultMutation(async () => {
1084
+ try {
1085
+ const expectedChain = captured.chain ?? vaultStore.getScope()?.chain
1086
+ if (!expectedChain) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1087
+ let held: VaultActionRow | undefined
1088
+ await scanVaultActions(w, adminOriginator, {
1089
+ labels: [],
1090
+ includeLabels: true,
1091
+ includeInputs: true,
1092
+ includeInputSourceLockingScripts: true,
1093
+ includeOutputs: true,
1094
+ includeOutputLockingScripts: true
1095
+ }, async action => {
1096
+ if (action.status === 'unsigned') return
1097
+ if (!PENDING_ACTION_STATUSES.has(action.status) || BROADCAST_ACTION_STATUSES.has(action.status)) return
1098
+ if (await isValidHeldVaultDeposit(w, adminOriginator, action, meta, expectedChain)) {
1099
+ held = action
1100
+ } else if (isValidHeldVaultSpend(action)) {
1101
+ held = action
1102
+ }
1103
+ }, captured)
1104
+ assertVaultScope(captured)
1105
+ if (!held?.txid) return { kind: 'nothing-held' }
1106
+ const txid = held.txid
1107
+ const labels = new Set(held.labels ?? [])
1108
+ const isSpend = labels.has('vault-withdraw') || labels.has('vault-relock')
1109
+ const description = isSpend ? 'Vault transfer' : 'Vault deposit'
1110
+ assertVaultScope(captured)
1111
+ const released = await w.createAction(
1112
+ { description: `Broadcast ${description}`, options: { sendWith: [txid] } },
1113
+ adminOriginator
1114
+ )
1115
+ assertVaultScope(captured)
1116
+ requireReleasedHeldTransaction(released, txid, description)
1117
+ // requireReleasedHeldTransaction has already confirmed exactly one
1118
+ // result for this txid in an accepted state ('sending' or 'unproven').
1119
+ // 'unproven' is the toolbox's own trusted classification of a resend it
1120
+ // recognizes as already delivered (classifyReqDetails' 'alreadySent') —
1121
+ // report that distinction back, but only ever AFTER the release itself
1122
+ // succeeded, never in place of it.
1123
+ const releasedStatus = released.sendWithResults?.find(
1124
+ result => result.txid?.toLowerCase() === txid.toLowerCase()
1125
+ )?.status
1126
+ return { kind: releasedStatus === 'unproven' ? 'already-known' : 'broadcast' }
1127
+ } catch (error) {
1128
+ return { kind: 'failed', error }
1129
+ }
1130
+ })
1131
+ }
1132
+
777
1133
  /** Return true only for an exact current R1C lock. */
778
1134
  function isR1CSourceScript(scriptHex: string | undefined): boolean {
779
1135
  if (!scriptHex) return false
@@ -891,28 +1247,48 @@ function saltKeyIndex(ci: VaultInstructions): number {
891
1247
  return value
892
1248
  }
893
1249
 
1250
+ /** Canonical serialisation for either version, used only to fingerprint an
1251
+ * already-authenticated record (never persisted). */
1252
+ function encodeVaultInstructionsAny(ci: VaultInstructions): string {
1253
+ return ci.v === 6 ? encodeVaultInstructions(ci) : encodeVaultInstructionsV7(ci)
1254
+ }
1255
+
1256
+ /**
1257
+ * Remember one authenticated output's salt-derivation facts. `salt` is the
1258
+ * value ALREADY confirmed (by the caller) to authenticate `ci` against
1259
+ * `lock` — see resolveVaultSalt. For v6 this is still recorded as a
1260
+ * `derivationClaims` entry: v6's stored salt is an untrusted claim inside
1261
+ * `ci`, and a separate later pass (verifyVaultSaltDerivations) independently
1262
+ * re-derives it from the wallet to confirm it wasn't fabricated, before it
1263
+ * may advance `maxKeyIndex`'s trust. v7 has no separate claim to falsify —
1264
+ * `salt` was already derived directly from the wallet by resolveVaultSalt, so
1265
+ * deriving it WAS the authentication, and no claim needs re-verifying.
1266
+ */
894
1267
  function rememberVaultSalt(
895
1268
  inventory: VaultSaltInventory,
896
1269
  ci: VaultInstructions,
897
1270
  lock: LockingScript,
898
1271
  outputId: string,
899
- expectedChain: VaultScopeToken['chain']
1272
+ expectedChain: VaultScopeToken['chain'],
1273
+ salt: string
900
1274
  ): void {
901
1275
  if (ci.chain !== expectedChain) {
902
1276
  throw new VaultError('template-invalid', 'Vault output belongs to a different network')
903
1277
  }
904
1278
  const scriptHash = Utils.toHex(Hash.sha256(lock.toBinary()))
905
1279
  const outputFingerprint = Utils.toHex(Hash.sha256(Utils.toArray(
906
- `${scriptHash}\u0000${encodeVaultInstructions(ci)}`,
1280
+ `${scriptHash}\u0000${encodeVaultInstructionsAny(ci)}`,
907
1281
  'utf8'
908
1282
  ) as number[]))
909
1283
  const knownOutput = inventory.outputFingerprints.get(outputId)
910
1284
  if (knownOutput !== undefined && knownOutput !== outputFingerprint) {
911
1285
  throw new VaultError('template-invalid', 'One Vault output has conflicting authenticated representations')
912
1286
  }
913
- const serials = ci.keys.map(key => key.serial)
914
- const claimId = JSON.stringify([ci.saltKeyId, Utils.toHex(vaultSaltHmacData(serials)), ci.salt])
915
- inventory.derivationClaims.set(claimId, { saltKeyId: ci.saltKeyId, serials, salt: ci.salt })
1287
+ if (ci.v === 6) {
1288
+ const serials = ci.keys.map(key => key.serial)
1289
+ const claimId = JSON.stringify([ci.saltKeyId, Utils.toHex(vaultSaltHmacData(serials)), salt])
1290
+ inventory.derivationClaims.set(claimId, { saltKeyId: ci.saltKeyId, serials, salt })
1291
+ }
916
1292
  inventory.outputFingerprints.set(outputId, outputFingerprint)
917
1293
  inventory.outputRecords.set(outputId.toLowerCase(), {
918
1294
  lockingScript: lock.toHex(),
@@ -922,7 +1298,7 @@ function rememberVaultSalt(
922
1298
  }
923
1299
 
924
1300
  /** Derive one canonical 32-byte wallet HMAC under the exact Vault domain. */
925
- async function deriveVaultSalt(
1301
+ export async function deriveVaultSalt(
926
1302
  w: VaultWallet,
927
1303
  adminOriginator: string,
928
1304
  saltKeyId: string,
@@ -978,7 +1354,7 @@ async function addHistoricalVaultSaltInventory(
978
1354
  labels: [],
979
1355
  includeOutputs: true,
980
1356
  includeOutputLockingScripts: true
981
- }, action => {
1357
+ }, async action => {
982
1358
  for (const output of action.outputs ?? []) {
983
1359
  if (output.basket !== VAULT_BASKET) continue
984
1360
  const ci = decodeVaultInstructions(output.customInstructions)
@@ -991,7 +1367,8 @@ async function addHistoricalVaultSaltInventory(
991
1367
  } catch {
992
1368
  throw new VaultError('template-invalid', 'Vault history contains a malformed locking script')
993
1369
  }
994
- verifyInstructionsAgainstLock(ci, lock, 'Vault history output')
1370
+ const salt = await resolveVaultSalt(w, adminOriginator, ci)
1371
+ verifyInstructionsAgainstLock(ci, lock, 'Vault history output', salt)
995
1372
  // Salt/script reuse is wallet-global, so retain valid history from prior
996
1373
  // enrollments after a drained Vault is disabled and set up again. Only a
997
1374
  // record claiming the current enrollment ID must agree with its immutable
@@ -1007,7 +1384,7 @@ async function addHistoricalVaultSaltInventory(
1007
1384
  ) {
1008
1385
  throw new VaultError('template-invalid', 'Vault history conflicts with the active vault enrollment')
1009
1386
  }
1010
- rememberVaultSalt(inventory, ci, lock, vaultActionOutputId(action, output.outputIndex), expectedChain)
1387
+ rememberVaultSalt(inventory, ci, lock, vaultActionOutputId(action, output.outputIndex), expectedChain, salt)
1011
1388
  }
1012
1389
  }, scopeToken, true)
1013
1390
  assertVaultScope(scopeToken)
@@ -1088,9 +1465,15 @@ async function abortActions(
1088
1465
  let scanned = 0
1089
1466
  const seen: string[] = []
1090
1467
  const seenRows = new Set<string>()
1091
- // By reference, so the same orphan is never aborted twice — a second
1092
- // abortAction on it would be rejected, and counting it again would report a
1093
- // heal that did not happen.
1468
+ // References this scan has already attempted, so the same orphan is never
1469
+ // aborted twice — a second abortAction on it would be rejected regardless
1470
+ // of the first attempt's outcome.
1471
+ const attempted = new Set<string>()
1472
+ // Only references whose abortAction call actually SUCCEEDED. A refused or
1473
+ // rejected abort never released the input, so it must not be counted as
1474
+ // freed — the caller (freeReservedInputs) uses this size to decide whether
1475
+ // a retry can proceed, and a miscount here would retry against an input
1476
+ // that is still genuinely reserved.
1094
1477
  const aborted = new Set<string>()
1095
1478
  try {
1096
1479
  let offset = 0
@@ -1122,12 +1505,15 @@ async function abortActions(
1122
1505
  seenRows.add(rowId)
1123
1506
  if (!matches(a)) continue
1124
1507
  seen.push(`${a.status}${a.reference ? '' : '/no-ref'}`)
1125
- if (a.reference && ABORTABLE.has(a.status) && !aborted.has(a.reference)) {
1126
- aborted.add(a.reference)
1508
+ if (a.reference && ABORTABLE.has(a.status) && !attempted.has(a.reference)) {
1509
+ attempted.add(a.reference)
1127
1510
  assertVaultScope(scopeToken)
1128
- await w.abortAction({ reference: a.reference }, adminOriginator).catch(err =>
1511
+ try {
1512
+ await w.abortAction({ reference: a.reference }, adminOriginator)
1513
+ aborted.add(a.reference)
1514
+ } catch (err) {
1129
1515
  console.log('[vault] abortAction rejected:', (err as Error)?.message)
1130
- )
1516
+ }
1131
1517
  assertVaultScope(scopeToken)
1132
1518
  }
1133
1519
  }
@@ -1185,14 +1571,18 @@ async function abortReservingOutpoints(
1185
1571
  assertVaultScope(scopeToken)
1186
1572
  const rows = await findSpendingReferences(outpoints)
1187
1573
  assertVaultScope(scopeToken)
1574
+ const attempted = new Set<string>()
1188
1575
  const aborted = new Set<string>()
1189
1576
  for (const r of rows) {
1190
- if (!ABORTABLE.has(r.status) || aborted.has(r.reference)) continue
1191
- aborted.add(r.reference)
1577
+ if (!ABORTABLE.has(r.status) || attempted.has(r.reference)) continue
1578
+ attempted.add(r.reference)
1192
1579
  assertVaultScope(scopeToken)
1193
- await w.abortAction({ reference: r.reference }, adminOriginator).catch(err =>
1580
+ try {
1581
+ await w.abortAction({ reference: r.reference }, adminOriginator)
1582
+ aborted.add(r.reference)
1583
+ } catch (err) {
1194
1584
  console.log('[vault] abortAction rejected:', (err as Error)?.message)
1195
- )
1585
+ }
1196
1586
  assertVaultScope(scopeToken)
1197
1587
  }
1198
1588
  console.log('[vault] abort by outpoint · matched=%d · aborted=%d', rows.length, aborted.size)
@@ -1224,8 +1614,18 @@ async function abortReservingOutpoints(
1224
1614
  *
1225
1615
  * `ours` bounds the damage: only a reservation on an outpoint THIS withdrawal
1226
1616
  * is trying to spend justifies aborting somebody else's transaction.
1617
+ *
1618
+ * Exported (XQ-016 review follow-up) ONLY so its interaction with the real,
1619
+ * non-mocked vendor `abortAction` can be exercised directly —
1620
+ * __tests__/vault/xq016VaultAbortRealVendorInteraction.test.ts. `ABORTABLE`
1621
+ * above includes `'nosend'`, and this function (via `abortReservingOutpoints`
1622
+ * / `abortActions`) is reachable from the live withdrawal-creation retry path
1623
+ * in `createSignableVaultTx`, so it DOES call the vendor's `abortAction` on a
1624
+ * real signed `nosend` orphan — see that test for the verified behavior.
1625
+ * Every other caller in this module still calls it unexported-style, from
1626
+ * within the same module scope; this export adds no new call site.
1227
1627
  */
1228
- async function freeReservedInputs(
1628
+ export async function freeReservedInputs(
1229
1629
  w: VaultWallet,
1230
1630
  adminOriginator: string,
1231
1631
  e: unknown,
@@ -1287,6 +1687,37 @@ export async function getVaultBalance(w: VaultWallet, adminOriginator: string):
1287
1687
  * wallet salt-key derivations all authenticate. Conflict selection belongs to
1288
1688
  * VaultKeyService; possession of a restored key is still required separately
1289
1689
  * before any spend. */
1690
+ /** F-06: whether a scan-derived record should replace an existing local one —
1691
+ * a strictly higher revision, or the same revision naming a strict superset
1692
+ * of the existing key set (a partial local record catching up to what chain
1693
+ * evidence already shows). Anything else (equal, older, or merely
1694
+ * different) keeps the existing record: this is a one-way ratchet, never a
1695
+ * merge or an overwrite by a same-revision disagreement. */
1696
+ function recoveredSupersedesExisting(existing: VaultMeta, recovered: VaultMeta): boolean {
1697
+ if (recovered.revision > existing.revision) return true
1698
+ if (recovered.revision < existing.revision) return false
1699
+ const existingKeys = new Set(existing.keys.map(k => k.pubkey))
1700
+ const recoveredKeys = new Set(recovered.keys.map(k => k.pubkey))
1701
+ if (recoveredKeys.size <= existingKeys.size) return false
1702
+ for (const pubkey of existingKeys) {
1703
+ if (!recoveredKeys.has(pubkey)) return false
1704
+ }
1705
+ return true
1706
+ }
1707
+
1708
+ /** Restore a missing scoped cache only from currently spendable outputs whose
1709
+ * real source values, exact R1C locks, salted commitments, v6 recovery records, and
1710
+ * wallet salt-key derivations all authenticate. Conflict selection belongs to
1711
+ * VaultKeyService; possession of a restored key is still required separately
1712
+ * before any spend.
1713
+ *
1714
+ * F-06: an existing local record is no longer trusted unconditionally — a
1715
+ * post-reinstall SecureStore snapshot (WHEN_UNLOCKED_THIS_DEVICE_ONLY items
1716
+ * survive app deletion on iOS) can be stale relative to what chain outputs
1717
+ * now show. The SAME authenticated scan the no-record branch always ran now
1718
+ * always runs; the existing record is kept only when it is not superseded
1719
+ * (recoveredSupersedesExisting), and restored the same way — through
1720
+ * vaultStore.restoreVerifiedMeta — when it is. */
1290
1721
  export async function recoverVaultMetaFromOutputs(
1291
1722
  w: VaultWallet,
1292
1723
  adminOriginator: string
@@ -1295,7 +1726,6 @@ export async function recoverVaultMetaFromOutputs(
1295
1726
  return await withVaultMutation(async () => {
1296
1727
  assertVaultScope(scopeToken)
1297
1728
  const existing = await vaultStore.getMeta(scopeToken)
1298
- if (existing) return existing
1299
1729
  const scan = await reduceVerifiedVaultOutputs(
1300
1730
  w,
1301
1731
  adminOriginator,
@@ -1306,14 +1736,101 @@ export async function recoverVaultMetaFromOutputs(
1306
1736
  }),
1307
1737
  scopeToken
1308
1738
  )
1309
- if (scan.outputs === 0) return null
1739
+ if (scan.outputs === 0) return existing
1310
1740
  await verifyVaultSaltDerivations(w, adminOriginator, scan.inventory)
1311
1741
  const recovered = metaFromVerifiedOutputs(scan.state)
1312
- await vaultStore.restoreVerifiedMeta(recovered, scopeToken)
1742
+ if (existing && !recoveredSupersedesExisting(existing, recovered)) return existing
1743
+ const scope = vaultStore.getScope()
1744
+ await vaultStore.restoreVerifiedMeta(
1745
+ recovered,
1746
+ scopeToken,
1747
+ scope ? next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope) : undefined
1748
+ )
1313
1749
  return await vaultStore.getMeta(scopeToken)
1314
1750
  })
1315
1751
  }
1316
1752
 
1753
+ /**
1754
+ * XR-002 (SEC2-088): the gate every operation that builds a NEW R1C output
1755
+ * from local vault metadata must pass first — `meta.keys`/`meta.revision`
1756
+ * become that output's lock directly (newVaultOutput). A SecureStore-only
1757
+ * attacker who forges a higher revision or a substituted key set cannot
1758
+ * compute metaAuthority.ts's wallet-root tag, so a mismatch here means
1759
+ * `meta` was never written by this package's own legitimate code.
1760
+ *
1761
+ * A missing/invalid tag is not immediately fatal — it is exactly the state
1762
+ * every enrollment created before this fix shipped is in. Recover instead of
1763
+ * refusing outright, using the SAME authenticated on-chain scan
1764
+ * recoverVaultMetaFromOutputs already uses, but with STRICT equality (never
1765
+ * the "supersedes" ratchet, which exists for a different problem — a stale
1766
+ * local cache after reinstall — and would let a forged revision that happens
1767
+ * to be LOWER than real chain evidence slip through as "not superseded,
1768
+ * keep it"): if a verified on-chain output for this exact vaultId proves
1769
+ * `meta` byte-for-byte, adopt it and tag it going forward
1770
+ * (vaultStore.restoreVerifiedMeta). Chain evidence that DISAGREES, or a
1771
+ * vault with no chain evidence at all yet (a genuinely first-ever deposit,
1772
+ * which legitimately shipped code always tags immediately at
1773
+ * finalizeEnrollment), is the "never silently trust-on-first-use when a
1774
+ * safer route exists" case: refuse and point at the safer route already
1775
+ * available — disable (offered exactly at this zero-balance state) and
1776
+ * re-enroll, which produces a freshly, correctly tagged record.
1777
+ *
1778
+ * Deliberately NEVER called for withdrawing an EXISTING output: that spend's
1779
+ * authority is the output's own REAL R1C lock, independently verified
1780
+ * against chain-listed BEEF (verifyListedVaultOutput / spendVaultOutputs) —
1781
+ * never local meta. Gating a plain withdrawal here would block access to
1782
+ * funds I1 requires stay reachable, over data that was never load-bearing
1783
+ * for that spend in the first place.
1784
+ */
1785
+ export async function requireAuthenticatedMeta(
1786
+ w: VaultWallet,
1787
+ adminOriginator: string,
1788
+ scopeToken: VaultScopeToken,
1789
+ meta: VaultMeta
1790
+ ): Promise<VaultMeta> {
1791
+ assertVaultScope(scopeToken)
1792
+ const scope = vaultStore.getScope()
1793
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1794
+ const tag = await vaultStore.getMetaTag(scopeToken)
1795
+ if (await verifyVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, meta, scope, tag)) return meta
1796
+
1797
+ const scan = await reduceVerifiedVaultOutputs(
1798
+ w,
1799
+ adminOriginator,
1800
+ () => [] as { instructions: VaultInstructions; txid: string }[],
1801
+ (records, output) => {
1802
+ if (output.ci.vaultId !== meta.vaultId) return
1803
+ records.push({ instructions: output.ci, txid: output.outpoint.slice(0, 64).toLowerCase() })
1804
+ },
1805
+ scopeToken
1806
+ )
1807
+ if (scan.state.length === 0) {
1808
+ throw new VaultError(
1809
+ 'template-invalid',
1810
+ 'Vault enrollment metadata could not be authenticated and has no on-chain history to verify it against; disable and re-enroll this vault'
1811
+ )
1812
+ }
1813
+ await verifyVaultSaltDerivations(w, adminOriginator, scan.inventory)
1814
+ const recovered = metaFromVerifiedOutputs(scan.state)
1815
+ if (
1816
+ recovered.vaultId !== meta.vaultId ||
1817
+ recovered.createdAt !== meta.createdAt ||
1818
+ recovered.revision !== meta.revision ||
1819
+ !sameInstructionKeys(meta.keys, recovered.keys)
1820
+ ) {
1821
+ throw new VaultError(
1822
+ 'template-invalid',
1823
+ 'Local vault enrollment metadata disagrees with authenticated on-chain history; re-verify before continuing'
1824
+ )
1825
+ }
1826
+ await vaultStore.restoreVerifiedMeta(recovered, scopeToken, next =>
1827
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
1828
+ )
1829
+ const reconciled = await vaultStore.getMeta(scopeToken)
1830
+ if (!reconciled) throw new VaultError('not-enrolled', 'Vault is not set up')
1831
+ return reconciled
1832
+ }
1833
+
1317
1834
  /**
1318
1835
  * Clear authorization metadata only after an authoritative, serialized empty
1319
1836
  * check. In addition to spendable outputs, any non-final vault action blocks
@@ -1344,7 +1861,7 @@ export async function disableVaultWhenSafe(
1344
1861
  includeInputSourceLockingScripts: true,
1345
1862
  includeOutputs: true,
1346
1863
  includeOutputLockingScripts: true
1347
- }, action => {
1864
+ }, async action => {
1348
1865
  const labels = new Set(action.labels ?? [])
1349
1866
  const inputs = action.inputs ?? []
1350
1867
  const r1cInputs = inputs.filter(input => isR1CSourceScript(input.sourceLockingScript))
@@ -1385,7 +1902,8 @@ export async function disableVaultWhenSafe(
1385
1902
  } catch {
1386
1903
  throw new VaultError('template-invalid', 'Vault action history has a malformed output script')
1387
1904
  }
1388
- verifyInstructionsAgainstLock(ci, lock, 'Vault action history output')
1905
+ const salt = await resolveVaultSalt(w, adminOriginator, ci)
1906
+ verifyInstructionsAgainstLock(ci, lock, 'Vault action history output', salt)
1389
1907
  }
1390
1908
  const touchesVault =
1391
1909
  r1cInputs.length > 0 ||
@@ -1432,26 +1950,53 @@ export async function disableVaultWhenSafe(
1432
1950
  // ── vault outputs ────────────────────────────────────────────────────────
1433
1951
 
1434
1952
  /**
1435
- * One new vault output committed to `keys` (spec §4.1 step 3, §2.7).
1953
+ * One new vault output committed to `keys` (spec §4.1 step 3, §2.7), plus its
1954
+ * v7 marker and encrypted descriptor (design v7 §1.2 item 2). New creations
1955
+ * are v7 only — existing v6 outputs are unaffected and keep working through
1956
+ * the unchanged v6 read path.
1436
1957
  *
1437
1958
  * Each salt is the wallet's 32-byte createHmac result under the next positive
1438
1959
  * decimal key ID, with the ordered YubiKey serial list as canonically framed
1439
- * input. A unique key ID normally makes commitments and script hashes distinct
1440
- * when the enrolled key set is unchanged. Disconnected devices can reuse an
1441
- * index, and identical scripts remain valid and independently spendable. The
1442
- * key list is written into the output's
1443
- * customInstructions in commitment order — informational (the lock is the
1444
- * truth; the withdraw path re-checks it), but it is what lets balance,
1445
- * selection and coverage work without parsing a 45 KB script. Used by the
1446
- * deposit, the withdraw path's re-vaulted remainder, and the re-lock.
1960
+ * input — UNCHANGED from v6, and never persisted for v7: it is derived here,
1961
+ * used to build the lock, and then dropped. A unique key ID normally makes
1962
+ * commitments and script hashes distinct when the enrolled key set is
1963
+ * unchanged. Disconnected devices can reuse an index, and identical scripts
1964
+ * remain valid and independently spendable.
1965
+ *
1966
+ * The marker (1-sat P2PKH to a wallet-derived address keyed by chain+index)
1967
+ * and the descriptor (0-sat OP_RETURN carrying the same v7 JSON, BRC-2
1968
+ * encrypted under a wallet-derived key keyed by chain+index) are chain-
1969
+ * published, basketless, and are what let a clean device with only the
1970
+ * mnemonic find and decrypt this output's recovery record (chainRecovery.ts)
1971
+ * without the local DB or backup. The vault output's own customInstructions
1972
+ * is still written too — informational, exactly as v6's was — but is no
1973
+ * longer the only copy of anything.
1974
+ *
1975
+ * Used by the deposit, the withdraw path's re-vaulted remainder, and the
1976
+ * re-lock. Every caller must push all three returned outputs into its
1977
+ * transaction's outputs array, in this order, so validateDepositPlan /
1978
+ * validateSignableVaultPlan can pin them byte-exact.
1447
1979
  */
1448
1980
  interface VaultOutputSpec {
1449
1981
  satoshis: number
1450
1982
  lockingScript: string
1451
1983
  outputDescription: string
1452
- basket: string
1453
- customInstructions: string
1454
- tags: string[]
1984
+ basket?: string
1985
+ customInstructions?: string
1986
+ tags?: string[]
1987
+ }
1988
+
1989
+ /** A new Vault output commits VAULT_MIN_KEYS..VAULT_MAX_KEYS keys. */
1990
+ function requireLockableKeyCount(count: number): void {
1991
+ if (count < VAULT_MIN_KEYS) {
1992
+ throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${count} remain`)
1993
+ }
1994
+ if (count > VAULT_MAX_KEYS) {
1995
+ throw new VaultError(
1996
+ 'too-many-active-keys',
1997
+ `A vault output commits at most ${VAULT_MAX_KEYS} keys; remove one of the ${count} first`
1998
+ )
1999
+ }
1455
2000
  }
1456
2001
 
1457
2002
  async function newVaultOutput(
@@ -1462,7 +2007,12 @@ async function newVaultOutput(
1462
2007
  outputDescription: string,
1463
2008
  inventory: VaultSaltInventory,
1464
2009
  chain: VaultScopeToken['chain']
1465
- ): Promise<VaultOutputSpec> {
2010
+ ): Promise<[vault: VaultOutputSpec, marker: VaultOutputSpec, descriptor: VaultOutputSpec]> {
2011
+ // Every output-creating path (deposit, re-lock, partial-withdrawal
2012
+ // remainder) comes through here. The key list may briefly hold one key more
2013
+ // than a lock commits (VAULT_MAX_ACTIVE_KEYS); never lock to it, and never
2014
+ // to fewer than VAULT_MIN_KEYS.
2015
+ requireLockableKeyCount(meta.keys.length)
1466
2016
  const pubkeys = meta.keys.map(k => k.pubkey)
1467
2017
  const keyIndex = inventory.maxKeyIndex + 1
1468
2018
  if (!Number.isSafeInteger(keyIndex)) {
@@ -1471,28 +2021,44 @@ async function newVaultOutput(
1471
2021
  const saltKeyId = String(keyIndex)
1472
2022
  const salt = await deriveVaultSalt(w, adminOriginator, saltKeyId, meta.keys.map(key => key.serial))
1473
2023
  const lockingScript = buildLock({ commitments: pubkeys.map(pk => commitment(pk, salt)), saltHex64: salt })
1474
- const output: VaultOutputSpec = {
2024
+ const v7: VaultInstructionsV7 = {
2025
+ v: 7,
2026
+ type: 'R1C',
2027
+ saltKeyId,
2028
+ chain,
2029
+ vaultId: meta.vaultId,
2030
+ revision: meta.revision,
2031
+ createdAt: meta.createdAt,
2032
+ keys: meta.keys.map(key => ({ ...key }))
2033
+ }
2034
+ const customInstructions = encodeVaultInstructionsV7(v7)
2035
+ const vaultOutput: VaultOutputSpec = {
1475
2036
  satoshis,
1476
2037
  lockingScript: lockingScript.toHex(),
1477
2038
  outputDescription,
1478
2039
  basket: VAULT_BASKET,
1479
- customInstructions: encodeVaultInstructions({
1480
- v: 6,
1481
- type: 'R1C',
1482
- salt,
1483
- saltKeyId,
1484
- chain,
1485
- vaultId: meta.vaultId,
1486
- revision: meta.revision,
1487
- createdAt: meta.createdAt,
1488
- keys: meta.keys.map(key => ({ ...key }))
1489
- }),
2040
+ customInstructions,
1490
2041
  tags: ['vault']
1491
2042
  }
1492
- const ci = decodeVaultInstructions(output.customInstructions)
2043
+
2044
+ const markerScript = await deriveVaultMarkerScript(w, adminOriginator, chain, saltKeyId)
2045
+ const markerOutput: VaultOutputSpec = {
2046
+ satoshis: 1,
2047
+ lockingScript: markerScript.toHex(),
2048
+ outputDescription: 'Vault marker'
2049
+ }
2050
+
2051
+ const descriptorCiphertext = await encryptVaultDescriptorPlaintext(w, adminOriginator, chain, saltKeyId, customInstructions)
2052
+ const descriptorOutput: VaultOutputSpec = {
2053
+ satoshis: 0,
2054
+ lockingScript: buildVaultDescriptorScript(descriptorCiphertext).toHex(),
2055
+ outputDescription: 'Vault descriptor'
2056
+ }
2057
+
2058
+ const ci = decodeVaultInstructionsV7(customInstructions)
1493
2059
  if (!ci) throw new VaultError('template-invalid', 'Derived Vault output metadata is invalid')
1494
- rememberVaultSalt(inventory, ci, lockingScript, `pending:${saltKeyId}`, chain)
1495
- return output
2060
+ rememberVaultSalt(inventory, ci, lockingScript, `pending:${saltKeyId}`, chain, salt)
2061
+ return [vaultOutput, markerOutput, descriptorOutput]
1496
2062
  }
1497
2063
 
1498
2064
  /**
@@ -1572,14 +2138,21 @@ function requireReleasedHeldTransaction(
1572
2138
  }
1573
2139
  }
1574
2140
 
1575
- type VaultOutputPlan = VaultOutputSpec
2141
+ type VaultOutputPlan = readonly [vault: VaultOutputSpec, marker: VaultOutputSpec, descriptor: VaultOutputSpec]
1576
2142
 
1577
2143
  /**
1578
2144
  * Check the wallet-funded deposit transaction before it is released from
1579
- * `noSend`. The requested R1C output is byte-exact and pinned at output zero;
1580
- * the wallet may add only one standard P2PKH change output. BRC-100 does not
1581
- * expose a derivation proof for wallet-selected inputs or change, so ownership
1582
- * of those standard wallet coins remains the narrow wallet-core trust boundary.
2145
+ * `noSend`. The three requested outputs (vault, marker, descriptor) are
2146
+ * byte-exact and pinned at outputs 0..2, mirroring how the vault output alone
2147
+ * used to be pinned at output zero; the wallet may add only one standard
2148
+ * P2PKH change output after them. BRC-100 does not expose a derivation proof
2149
+ * for wallet-selected inputs or change, so ownership of those standard wallet
2150
+ * coins remains the narrow wallet-core trust boundary — pinning the marker
2151
+ * and descriptor byte-exact the same way keeps a bug or compromise in that
2152
+ * boundary from silently substituting a different marker/descriptor than
2153
+ * admin code itself built (an availability regression future recovery would
2154
+ * hit, not a spend-authority break: output 0, the actual spend authority,
2155
+ * stays independently pinned either way).
1583
2156
  */
1584
2157
  function validateDepositPlan(tx: Transaction, expected: VaultOutputPlan): void {
1585
2158
  if (tx.version !== 1) {
@@ -1609,18 +2182,23 @@ function validateDepositPlan(tx: Transaction, expected: VaultOutputPlan): void {
1609
2182
  if (!Number.isSafeInteger(inputValue)) throw new VaultError('no-transaction', 'Vault deposit input value overflow')
1610
2183
  }
1611
2184
 
1612
- const vaultOutput = tx.outputs[0]
1613
- if (
1614
- !vaultOutput ||
1615
- !Number.isSafeInteger(vaultOutput.satoshis) ||
1616
- vaultOutput.satoshis !== expected.satoshis ||
1617
- vaultOutput.lockingScript.toHex() !== expected.lockingScript
1618
- ) {
1619
- throw new VaultError('no-transaction', 'Wallet changed the approved Vault deposit output')
2185
+ let explicitValue = 0
2186
+ for (let i = 0; i < expected.length; i++) {
2187
+ const actual = tx.outputs[i]
2188
+ const expectedOutput = expected[i]
2189
+ if (
2190
+ !actual ||
2191
+ !Number.isSafeInteger(actual.satoshis) ||
2192
+ actual.satoshis !== expectedOutput.satoshis ||
2193
+ actual.lockingScript.toHex() !== expectedOutput.lockingScript
2194
+ ) {
2195
+ throw new VaultError('no-transaction', `Wallet changed the approved Vault deposit output ${i}`)
2196
+ }
2197
+ explicitValue += expectedOutput.satoshis
1620
2198
  }
1621
- const implicit = tx.outputs.slice(1)
2199
+ const implicit = tx.outputs.slice(expected.length)
1622
2200
  if (implicit.length > 1) throw new VaultError('no-transaction', 'Wallet injected an unexpected Vault deposit output')
1623
- let outputValue = expected.satoshis
2201
+ let outputValue = explicitValue
1624
2202
  if (implicit.length === 1) {
1625
2203
  const change = implicit[0]
1626
2204
  const changeSatoshis = change.satoshis
@@ -1644,7 +2222,7 @@ function validateDepositPlan(tx: Transaction, expected: VaultOutputPlan): void {
1644
2222
  if (!Number.isSafeInteger(fee) || fee < 0 || fee > maxFee) {
1645
2223
  throw new VaultError('no-transaction', `Vault deposit fee ${fee} exceeds the safety ceiling ${maxFee}`)
1646
2224
  }
1647
- if (implicit.length === 0 && inputValue - expected.satoshis > maxFee) {
2225
+ if (implicit.length === 0 && inputValue - explicitValue > maxFee) {
1648
2226
  throw new VaultError('no-transaction', 'Vault deposit omitted expected wallet change')
1649
2227
  }
1650
2228
  }
@@ -1681,7 +2259,8 @@ export async function depositToVault(
1681
2259
  assertVaultScope(scopeToken)
1682
2260
  await requirePrivateBackup(opts, 'Vault deposit')
1683
2261
  assertVaultScope(scopeToken)
1684
- const meta = await requireMeta(scopeToken)
2262
+ // XR-002: authenticate meta BEFORE it is used to build a new output.
2263
+ const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
1685
2264
  if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal before depositing')
1686
2265
  if (meta.recovery?.required) {
1687
2266
  const adopted = new Set(meta.recovery.adoptedSerials)
@@ -1721,7 +2300,7 @@ export async function depositToVault(
1721
2300
  {
1722
2301
  description: 'Vault deposit',
1723
2302
  version: 1,
1724
- outputs: [output],
2303
+ outputs: [...output],
1725
2304
  labels: ['vault', 'vault-deposit'],
1726
2305
  options: { randomizeOutputs: false, noSend: true, signAndProcess: false }
1727
2306
  },
@@ -1792,6 +2371,10 @@ interface SelectedVaultOutput {
1792
2371
  ci: VaultInstructions
1793
2372
  /** The output's REAL locking script, read from the listed BEEF. */
1794
2373
  lockingScript: LockingScript
2374
+ /** The salt authenticating `ci` against `lockingScript` — see
2375
+ * resolveVaultSalt. Used to build the withdraw witness instead of
2376
+ * `ci.salt`, which a v7 record does not carry. */
2377
+ salt: string
1795
2378
  }
1796
2379
 
1797
2380
  interface VaultSelection {
@@ -1836,7 +2419,14 @@ async function selectVaultInputs(
1836
2419
  chosenSerial: string,
1837
2420
  amount: number | 'all',
1838
2421
  requiredPubkey?: string,
1839
- scopeToken?: VaultScopeToken
2422
+ scopeToken?: VaultScopeToken,
2423
+ // P1: 'repair-unsigned' aborts a genuinely stale, provably-unbroadcast
2424
+ // reservation from a past crash — exactly what a real withdraw/re-lock
2425
+ // needs before reserving new inputs. A "read-only" preview must not do
2426
+ // that: it can otherwise abort a LIVE in-flight ceremony's own unsigned
2427
+ // reservation out from under it. previewVaultWithdrawal passes false;
2428
+ // every mutating caller keeps the default.
2429
+ repair = true
1840
2430
  ): Promise<VaultSelection> {
1841
2431
  const meta = await vaultStore.getMeta(scopeToken)
1842
2432
  if (!meta) throw new VaultError('not-enrolled', 'Vault is not set up')
@@ -1919,7 +2509,7 @@ async function selectVaultInputs(
1919
2509
  if (state.selected.length > cap) state.selected.pop()
1920
2510
  },
1921
2511
  scopeToken,
1922
- 'repair-unsigned'
2512
+ repair ? 'repair-unsigned' : 'block'
1923
2513
  )
1924
2514
  const scan = verified.state
1925
2515
  if (scan.decodable === 0) throw new VaultError('vault-empty', 'Vault is empty')
@@ -2335,7 +2925,7 @@ async function spendVaultOutputs(
2335
2925
  preimage,
2336
2926
  derSig: der,
2337
2927
  pubkeyHex33: signer.pubkey,
2338
- saltHex64: selected[i].ci.salt
2928
+ saltHex64: selected[i].salt
2339
2929
  })
2340
2930
  })
2341
2931
  }
@@ -2462,8 +3052,15 @@ export async function previewVaultWithdrawal(
2462
3052
  amount: number | 'all'
2463
3053
  ): Promise<{ selectedTotal: number; cappedInputs: number; unreachable: VaultSpendResult['unreachable'] }> {
2464
3054
  requireWithdrawalAmount(amount)
2465
- const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount)
2466
- return { selectedTotal: sel.acc, cappedInputs: sel.cappedInputs, unreachable: sel.unreachable }
3055
+ const scopeToken = vaultStore.captureScopeToken()
3056
+ return await withVaultMutation(async () => {
3057
+ assertVaultScope(scopeToken)
3058
+ // repair: false — this reads only; a genuinely stale unsigned reservation
3059
+ // from a past crash is still cleaned up by the next real withdraw/re-lock
3060
+ // (see selectVaultInputs' `repair` param and the P1 fix note there).
3061
+ const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount, undefined, scopeToken, false)
3062
+ return { selectedTotal: sel.acc, cappedInputs: sel.cappedInputs, unreachable: sel.unreachable }
3063
+ })
2467
3064
  }
2468
3065
 
2469
3066
  /**
@@ -2495,22 +3092,33 @@ export async function withdrawFromVault(
2495
3092
  await requireOnline(opts)
2496
3093
  assertVaultScope(scopeToken)
2497
3094
  const meta = await requireMeta(scopeToken)
2498
- await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2499
3095
  const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount, undefined, scopeToken)
2500
3096
  const want = amount === 'all' ? sel.acc : amount
2501
3097
  const remainder = sel.acc - want
2502
3098
  const outputs: VaultSpendPlan['outputs'] = []
2503
3099
  if (remainder >= VAULT_DEPOSIT_MIN) {
3100
+ // P2-774: reconcileHeldVaultDeposits' gate exists only to protect
3101
+ // salt-index-allocation integrity for a call that is about to allocate a
3102
+ // NEW one (spec's high-water-mark check) — a full-balance withdrawal
3103
+ // (no remainder here) creates no vault output and does not need it, so
3104
+ // only THIS branch, which re-vaults the remainder, still requires it.
3105
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2504
3106
  // Re-vaulting CREATES a vault output, which the release flag gates (spec
2505
3107
  // §5.5). Withdrawing pre-existing outputs — 'all' — never is.
2506
3108
  requireReleased(opts, scopeToken, 'Re-vaulting a remainder')
2507
3109
  await requirePrivateBackup(opts, 'Re-vaulting a remainder')
2508
3110
  assertVaultScope(scopeToken)
2509
- await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, sel.meta, scopeToken)
2510
- outputs.push(await newVaultOutput(
3111
+ // XR-002: authenticate meta BEFORE it is used to build the re-vaulted
3112
+ // remainder's new output. Scoped to exactly this branch — the only one
3113
+ // that creates an output — so an otherwise-unauthenticated meta never
3114
+ // blocks a plain 'all' withdrawal, whose authority is its spent outputs'
3115
+ // own real locks, never local meta (see requireAuthenticatedMeta).
3116
+ const authenticatedMeta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, sel.meta)
3117
+ await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, authenticatedMeta, scopeToken)
3118
+ outputs.push(...await newVaultOutput(
2511
3119
  w,
2512
3120
  adminOriginator,
2513
- sel.meta,
3121
+ authenticatedMeta,
2514
3122
  remainder,
2515
3123
  'Vault change',
2516
3124
  sel.saltInventory,
@@ -2531,24 +3139,42 @@ export async function withdrawFromVault(
2531
3139
 
2532
3140
  // ── re-lock (spec §4.3) ──────────────────────────────────────────────────
2533
3141
 
3142
+ /** Fixed byte cost of the v7 marker output: 8-byte value + a 3-byte
3143
+ * script-length prefix (the existing formula's own conservative convention)
3144
+ * + the 25-byte P2PKH script. */
3145
+ const VAULT_MARKER_OUTPUT_BYTES = 8 + 3 + 25
3146
+
3147
+ /** Worst-case byte cost of the v7 descriptor output: OP_FALSE OP_RETURN (2 B)
3148
+ * + the tag push (1 + tag length) + the ciphertext push at its hard cap
3149
+ * (MAX_DESCRIPTOR_CIPHERTEXT_BYTES, needing a 3-byte PUSHDATA2 header at that
3150
+ * size), plus the same 8-byte value + 3-byte length-prefix convention. */
3151
+ const VAULT_MAX_DESCRIPTOR_OUTPUT_BYTES =
3152
+ 8 + 3 + 2 + (1 + Utils.toArray(VAULT_DESCRIPTOR_TAG, 'utf8').length) + (3 + MAX_DESCRIPTOR_CIPHERTEXT_BYTES)
3153
+
2534
3154
  /**
2535
3155
  * Fee reserve for a re-lock, in the toolbox's own arithmetic (100 sat/kB,
2536
3156
  * rounded up per kB) plus 10 %.
2537
3157
  *
2538
3158
  * size = 10 + inputCount·(41 + 3 + R1C_UNLOCK_LEN) + (3 + lockLen + 8)
3159
+ * + marker + descriptor
2539
3160
  *
2540
3161
  * — version/locktime/counts (10); per input the outpoint + sequence (41), a
2541
- * 3-byte script-length prefix and the DECLARED unlock length; one output: an
2542
- * 8-byte value, a 3-byte prefix and the new lock. The +10 % is computed in
2543
- * integers (`ceil(kb·satPerKb·11 / 10)`): `11200 * 1.1` is
2544
- * `12320.000000000002` in doubles, and a float ceil would over-charge by one.
3162
+ * 3-byte script-length prefix and the DECLARED unlock length; the vault
3163
+ * output itself: an 8-byte value, a 3-byte prefix and the new lock; plus the
3164
+ * v7 marker and descriptor outputs that ride alongside every re-lock output
3165
+ * (VAULT_MARKER_OUTPUT_BYTES, VAULT_MAX_DESCRIPTOR_OUTPUT_BYTES — the latter
3166
+ * priced at its hard worst case, not the actual per-key-count size, so the
3167
+ * estimate never under-reserves). The +10 % is computed in integers
3168
+ * (`ceil(kb·satPerKb·11 / 10)`): `11200 * 1.1` is `12320.000000000002` in
3169
+ * doubles, and a float ceil would over-charge by one.
2545
3170
  *
2546
3171
  * The re-lock output is `acc − this`; the toolbox's real fee is at most this
2547
3172
  * and the surplus becomes ordinary default-basket change (folded into the fee
2548
- * when below dust). ≈ 2,900 sat per pass plus ≈ 260 sat per input.
3173
+ * when below dust).
2549
3174
  */
2550
3175
  export function estimateRelockFee(inputCount: number, lockLen: number, satPerKb = 100): number {
2551
- const size = 10 + inputCount * (41 + 3 + R1C_UNLOCK_LEN) + (3 + lockLen + 8)
3176
+ const size = 10 + inputCount * (41 + 3 + R1C_UNLOCK_LEN) + (3 + lockLen + 8) +
3177
+ VAULT_MARKER_OUTPUT_BYTES + VAULT_MAX_DESCRIPTOR_OUTPUT_BYTES
2552
3178
  const kb = Math.ceil(size / 1000)
2553
3179
  return Math.ceil((kb * satPerKb * 11) / 10)
2554
3180
  }
@@ -2581,7 +3207,12 @@ export async function relockVault(
2581
3207
  assertVaultScope(scopeToken)
2582
3208
  await requirePrivateBackup(opts, 'Re-locking the vault')
2583
3209
  assertVaultScope(scopeToken)
2584
- const meta = await requireMeta(scopeToken)
3210
+ // XR-002: authenticate meta BEFORE anything below uses it — relockVault
3211
+ // always builds a new output, so unlike withdrawFromVault this runs
3212
+ // unconditionally, and early enough that a reconciled/retagged meta is
3213
+ // what selectVaultInputs (re-reading vaultStore.getMeta itself) and the
3214
+ // fee estimate below both see.
3215
+ const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
2585
3216
  await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2586
3217
  const revokePubkey = opts?.revokePubkey
2587
3218
  const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, 'all', revokePubkey, scopeToken)
@@ -2594,9 +3225,8 @@ export async function relockVault(
2594
3225
  if (revokePubkey && sel.meta.pendingRemoval?.key.pubkey !== revokePubkey) {
2595
3226
  throw new VaultError('not-enrolled', 'The key being revoked does not match the pending removal')
2596
3227
  }
2597
- if (sel.keys.length < VAULT_MIN_KEYS) {
2598
- throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${sel.keys.length} remain`)
2599
- }
3228
+ // Before the fee estimate below, which cannot size a lock outside 2..5.
3229
+ requireLockableKeyCount(sel.keys.length)
2600
3230
  await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, sel.meta, scopeToken)
2601
3231
  const fee = estimateRelockFee(sel.selected.length, R1C_LOCK_LEN(sel.keys.length))
2602
3232
  const relocked = sel.acc - fee
@@ -2612,7 +3242,7 @@ export async function relockVault(
2612
3242
  sel,
2613
3243
  reason,
2614
3244
  {
2615
- outputs: [await newVaultOutput(
3245
+ outputs: await newVaultOutput(
2616
3246
  w,
2617
3247
  adminOriginator,
2618
3248
  sel.meta,
@@ -2620,7 +3250,7 @@ export async function relockVault(
2620
3250
  'Vault re-lock',
2621
3251
  sel.saltInventory,
2622
3252
  scopeToken.chain
2623
- )],
3253
+ ),
2624
3254
  labels: ['vault', 'vault-relock'],
2625
3255
  inputDescription: 'Vault re-lock',
2626
3256
  // Fixed, like the deposit and withdrawal descriptions (see
@@ -2631,7 +3261,17 @@ export async function relockVault(
2631
3261
  opts,
2632
3262
  scopeToken
2633
3263
  )
2634
- if (revokePubkey) await vaultStore.markKeyRemovalBroadcast(scopeToken)
3264
+ if (revokePubkey) {
3265
+ // The tag covers pendingRemoval.state, so the 'broadcast' write must be
3266
+ // re-tagged like every other meta write, or the stored meta stops
3267
+ // verifying and every later check falls back to a chain re-scan.
3268
+ assertVaultScope(scopeToken)
3269
+ const scope = vaultStore.getScope()
3270
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
3271
+ await vaultStore.markKeyRemovalBroadcast(scopeToken, next =>
3272
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3273
+ )
3274
+ }
2635
3275
  return result
2636
3276
  })
2637
3277
  }
@@ -2715,14 +3355,27 @@ export async function beginVaultKeyRemoval(
2715
3355
  const scopeToken = vaultStore.captureScopeToken()
2716
3356
  return await withVaultMutation(async () => {
2717
3357
  assertVaultScope(scopeToken)
2718
- const meta = await requireMeta(scopeToken)
3358
+ // XR-002: this is a meta-mutating write (beginKeyRemoval), not an
3359
+ // output-creating one, but its own `next` must still be tagged from an
3360
+ // already-trustworthy `meta` — see vaultStore.addKey's laundering
3361
+ // caveat, which applies identically here.
3362
+ const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
3363
+ const scope = vaultStore.getScope()
3364
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
2719
3365
  const target = meta.keys.find(key => key.serial === serial)
2720
3366
  if (!target) throw new VaultError('not-enrolled', `Key ${serial} is not enrolled`)
2721
3367
  if (meta.keys.length <= VAULT_MIN_KEYS) {
2722
3368
  throw new VaultError('last-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys`)
2723
3369
  }
2724
- await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
3370
+ // P2-774: beginVaultKeyRemoval allocates no new salt index — the tombstone
3371
+ // transition below creates no vault output — so reconcileHeldVaultDeposits'
3372
+ // allocation-integrity gate does not apply here (unlike depositToVault and
3373
+ // relockVault, which do). A held signed deposit reserves only ordinary
3374
+ // wallet inputs, not any vault-basket output this removal's eventual
3375
+ // re-lock would need, so it must not block starting a removal either —
3376
+ // see the 'vault-deposit' exemption just below.
2725
3377
  let pendingAction = false
3378
+ let heldDeposit = false
2726
3379
  await scanVaultActions(
2727
3380
  w,
2728
3381
  adminOriginator,
@@ -2734,11 +3387,12 @@ export async function beginVaultKeyRemoval(
2734
3387
  // what the activity list shows as "Accepted" and stands until the merkle
2735
3388
  // proof arrives, so blocking on it refused every removal on a funded
2736
3389
  // vault and told the user to re-lock — the step this refusal itself
2737
- // prevented.
3390
+ // prevented. A 'vault-deposit' holds no EXISTING vault output — see the
3391
+ // note above — so it is exempt from this check the same way.
2738
3392
  action => {
2739
- if (PENDING_ACTION_STATUSES.has(action.status) && !BROADCAST_ACTION_STATUSES.has(action.status)) {
2740
- pendingAction = true
2741
- }
3393
+ if (!PENDING_ACTION_STATUSES.has(action.status) || BROADCAST_ACTION_STATUSES.has(action.status)) return
3394
+ if ((action.labels ?? []).includes('vault-deposit')) heldDeposit = true
3395
+ else pendingAction = true
2742
3396
  },
2743
3397
  scopeToken
2744
3398
  )
@@ -2749,10 +3403,11 @@ export async function beginVaultKeyRemoval(
2749
3403
  const before = await reduceVerifiedVaultOutputs(
2750
3404
  w,
2751
3405
  adminOriginator,
2752
- () => ({ wouldOrphan: false }),
3406
+ () => ({ wouldOrphan: false, targetCommitted: false }),
2753
3407
  (state, output) => {
2754
3408
  requireOutputMetaConsistency([output], meta)
2755
3409
  if (!output.ci.keys.some(key => remaining.has(key.pubkey))) state.wouldOrphan = true
3410
+ if (output.ci.keys.some(key => key.pubkey === target.pubkey)) state.targetCommitted = true
2756
3411
  },
2757
3412
  scopeToken,
2758
3413
  'repair-unsigned'
@@ -2760,32 +3415,54 @@ export async function beginVaultKeyRemoval(
2760
3415
  if (before.state.wouldOrphan) {
2761
3416
  throw new VaultError('relock-required', 'A vault output would lose every remaining key')
2762
3417
  }
2763
- const pending = await vaultStore.beginKeyRemoval(serial, scopeToken)
2764
- if (before.outputs > 0) return { complete: false, meta: pending }
3418
+ // No output commits the key (an empty vault, or a key added and not yet
3419
+ // re-locked to — the owner's add-then-remove flow): there is nothing to
3420
+ // re-lock, so the removal finishes here. A held deposit may still commit
3421
+ // it once broadcast, so that case waits until the deposit is resolved.
3422
+ if (!before.state.targetCommitted && heldDeposit) {
3423
+ throw new VaultError('action-pending', 'Resolve the held vault deposit before removing this key')
3424
+ }
3425
+ const pending = await vaultStore.beginKeyRemoval(serial, scopeToken, next =>
3426
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3427
+ )
3428
+ if (before.state.targetCommitted) return { complete: false, meta: pending }
2765
3429
 
2766
- // Empty removal has no transaction to prove. Recheck after the metadata
2767
- // transition because the wallet monitor is outside the process mutex.
3430
+ // Nothing to re-lock, so no transaction to prove. Recheck after the
3431
+ // metadata transition because the wallet monitor is outside the process
3432
+ // mutex: an output committing the key must not have appeared meanwhile.
2768
3433
  const after = await reduceVerifiedVaultOutputs(
2769
3434
  w,
2770
3435
  adminOriginator,
2771
- () => undefined,
2772
- () => {},
3436
+ () => ({ targetCommitted: false }),
3437
+ (state, output) => {
3438
+ if (output.ci.keys.some(key => key.pubkey === target.pubkey)) state.targetCommitted = true
3439
+ },
2773
3440
  scopeToken
2774
3441
  )
2775
- if (after.outputs > 0) {
2776
- await vaultStore.cancelUnbroadcastKeyRemoval(scopeToken)
3442
+ if (after.state.targetCommitted) {
3443
+ await vaultStore.cancelUnbroadcastKeyRemoval(scopeToken, next =>
3444
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3445
+ )
2777
3446
  throw new VaultError('action-pending', 'A vault output appeared while removing the key')
2778
3447
  }
2779
- return { complete: true, meta: await vaultStore.finalizeEmptyKeyRemoval(scopeToken) }
3448
+ const finalMeta = await vaultStore.finalizeEmptyKeyRemoval(scopeToken, next =>
3449
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
3450
+ )
3451
+ // XQ-014: `serial` is now fully removed from this chain — forget it
3452
+ // device-wide unless another chain of this same identity still holds it.
3453
+ await forgetSerialsNoLongerEnrolledForIdentity([serial], () => vaultStore.enrolledSerialsAcrossChains(scopeToken))
3454
+ return { complete: true, meta: finalMeta }
2780
3455
  })
2781
3456
  }
2782
3457
 
2783
- function actionCarriesCurrentRelock(
3458
+ async function actionCarriesCurrentRelock(
3459
+ w: VaultWallet,
3460
+ adminOriginator: string,
2784
3461
  action: VaultActionRow,
2785
3462
  meta: VaultMeta,
2786
3463
  expectedChain: VaultScopeToken['chain'],
2787
3464
  saltInventory?: VaultSaltInventory
2788
- ): boolean {
3465
+ ): Promise<boolean> {
2789
3466
  if (action.status === 'failed' || !action.labels?.includes('vault-relock')) return false
2790
3467
  const vaultOutputs = (action.outputs ?? []).filter(output => output.basket === VAULT_BASKET)
2791
3468
  if (vaultOutputs.length !== 1) return false
@@ -2807,7 +3484,8 @@ function actionCarriesCurrentRelock(
2807
3484
  } catch {
2808
3485
  throw new VaultError('template-invalid', 'Vault re-lock action has a malformed locking script')
2809
3486
  }
2810
- verifyInstructionsAgainstLock(ci, lock, `Vault re-lock ${action.txid ?? action.reference ?? ''}`)
3487
+ const salt = await resolveVaultSalt(w, adminOriginator, ci)
3488
+ verifyInstructionsAgainstLock(ci, lock, `Vault re-lock ${action.txid ?? action.reference ?? ''}`, salt)
2811
3489
  const carriesCurrentRelock = (
2812
3490
  ci.vaultId === meta.vaultId &&
2813
3491
  ci.createdAt === meta.createdAt &&
@@ -2820,7 +3498,8 @@ function actionCarriesCurrentRelock(
2820
3498
  ci,
2821
3499
  lock,
2822
3500
  vaultActionOutputId(action, output.outputIndex),
2823
- expectedChain
3501
+ expectedChain,
3502
+ salt
2824
3503
  )
2825
3504
  }
2826
3505
  return carriesCurrentRelock
@@ -2857,23 +3536,25 @@ function actionSpendsPendingRemovalKey(
2857
3536
  * replacement authenticates against the pending revision, and every input is
2858
3537
  * a real R1C lock that still authorizes the tombstoned key. Anything less is
2859
3538
  * an unknown broadcast/source state and remains fail-closed. */
2860
- function isUnbroadcastPendingRemovalRelock(
3539
+ async function isUnbroadcastPendingRemovalRelock(
3540
+ w: VaultWallet,
3541
+ adminOriginator: string,
2861
3542
  action: VaultActionRow,
2862
3543
  meta: VaultMeta,
2863
3544
  expectedChain: VaultScopeToken['chain'],
2864
3545
  saltInventory: VaultSaltInventory
2865
- ): boolean {
3546
+ ): Promise<boolean> {
2866
3547
  const pending = meta.pendingRemoval
2867
3548
  if (!pending || action.status !== 'unsigned' || !!action.txid || !action.reference) return false
2868
- if (!actionCarriesCurrentRelock(action, meta, expectedChain, saltInventory)) return false
3549
+ if (!(await actionCarriesCurrentRelock(w, adminOriginator, action, meta, expectedChain, saltInventory))) return false
2869
3550
  return actionSpendsPendingRemovalKey(action, meta, saltInventory)
2870
3551
  }
2871
3552
 
2872
3553
  /** Reconcile a durable pending removal. A bounded broadcast marker is inferred
2873
3554
  * after a crash only from an authenticated matching re-lock action. The
2874
- * tombstone is cleared only when no pending/failed Vault action exists, a
2875
- * matching re-lock is completed, and two authenticated scans find no lock
2876
- * authorizing the key. */
3555
+ * tombstone is cleared only when every Vault action is accepted by the network
3556
+ * (ACCEPTED_ACTION_STATUSES) or is a failed deposit, a matching re-lock is
3557
+ * accepted, and two authenticated scans find no lock authorizing the key. */
2877
3558
  export async function finalizeVaultKeyRemoval(
2878
3559
  w: VaultWallet,
2879
3560
  adminOriginator: string
@@ -2881,7 +3562,14 @@ export async function finalizeVaultKeyRemoval(
2881
3562
  const scopeToken = vaultStore.captureScopeToken()
2882
3563
  return await withVaultMutation(async () => {
2883
3564
  assertVaultScope(scopeToken)
2884
- let meta = await requireMeta(scopeToken)
3565
+ // XR-002: same laundering caveat as beginVaultKeyRemoval — this function
3566
+ // writes meta (markKeyRemovalBroadcast / finalizeEmptyKeyRemoval /
3567
+ // finalizeProvenKeyRemoval below) from whatever `meta` currently is.
3568
+ let meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
3569
+ const scope = vaultStore.getScope()
3570
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
3571
+ const tagger = (next: Parameters<typeof computeVaultMetaAuthorityTag>[2]) =>
3572
+ computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope)
2885
3573
  const pendingAtStart = meta.pendingRemoval
2886
3574
  if (!pendingAtStart) return false
2887
3575
  const first = await reduceVerifiedVaultOutputs(
@@ -2901,7 +3589,7 @@ export async function finalizeVaultKeyRemoval(
2901
3589
  const unsignedRelockReferences: string[] = []
2902
3590
  let invalidCurrentRelock = false
2903
3591
  let matchingRelock = false
2904
- let completedMatchingRelock = false
3592
+ let acceptedMatchingRelock = false
2905
3593
  let actionStateBlocks = false
2906
3594
  const actionSaltInventory = emptyVaultSaltInventory()
2907
3595
  await addHistoricalVaultSaltInventory(w, adminOriginator, actionSaltInventory, meta, scopeToken)
@@ -2912,26 +3600,26 @@ export async function finalizeVaultKeyRemoval(
2912
3600
  includeInputSourceLockingScripts: true,
2913
3601
  includeOutputs: true,
2914
3602
  includeOutputLockingScripts: true
2915
- }, action => {
2916
- if (isUnbroadcastPendingRemovalRelock(action, meta, scopeToken.chain, actionSaltInventory)) {
3603
+ }, async action => {
3604
+ if (await isUnbroadcastPendingRemovalRelock(w, adminOriginator, action, meta, scopeToken.chain, actionSaltInventory)) {
2917
3605
  unsignedRelockReferences.push(action.reference!)
2918
3606
  }
2919
- if (action.txid && actionCarriesCurrentRelock(action, meta, scopeToken.chain, actionSaltInventory)) {
3607
+ if (action.txid && await actionCarriesCurrentRelock(w, adminOriginator, action, meta, scopeToken.chain, actionSaltInventory)) {
2920
3608
  if (!actionSpendsPendingRemovalKey(action, meta, actionSaltInventory)) invalidCurrentRelock = true
2921
3609
  else {
2922
3610
  matchingRelock = true
2923
- if (action.status === 'completed') completedMatchingRelock = true
3611
+ if (ACCEPTED_ACTION_STATUSES.has(action.status)) acceptedMatchingRelock = true
2924
3612
  }
2925
3613
  }
2926
3614
  if (!actionTouchesVault(action)) return
2927
- if (PENDING_ACTION_STATUSES.has(action.status)) {
2928
- actionStateBlocks = true
2929
- } else if (action.status === 'failed') {
3615
+ if (ACCEPTED_ACTION_STATUSES.has(action.status)) return
3616
+ if (action.status === 'failed') {
2930
3617
  const labels = new Set(action.labels ?? [])
2931
3618
  if (!(labels.has('vault-deposit') && !labels.has('vault-withdraw') && !labels.has('vault-relock'))) {
2932
3619
  actionStateBlocks = true
2933
3620
  }
2934
- } else if (action.status !== 'completed') {
3621
+ } else {
3622
+ // Not yet accepted ('sending' included) or an unknown status.
2935
3623
  actionStateBlocks = true
2936
3624
  }
2937
3625
  }, scopeToken, true)
@@ -2976,7 +3664,7 @@ export async function finalizeVaultKeyRemoval(
2976
3664
  }
2977
3665
 
2978
3666
  if (invalidCurrentRelock) return false
2979
- if (matchingRelock) await vaultStore.markKeyRemovalBroadcast(scopeToken)
3667
+ if (matchingRelock) await vaultStore.markKeyRemovalBroadcast(scopeToken, tagger)
2980
3668
  meta = await requireMeta(scopeToken)
2981
3669
  const pending = meta.pendingRemoval
2982
3670
  if (!pending) return true
@@ -2997,11 +3685,15 @@ export async function finalizeVaultKeyRemoval(
2997
3685
  'allow'
2998
3686
  )
2999
3687
  if (second.state.authorizesPendingKey) return false
3000
- await vaultStore.finalizeEmptyKeyRemoval(scopeToken)
3688
+ await vaultStore.finalizeEmptyKeyRemoval(scopeToken, tagger)
3689
+ // XQ-014: the tombstoned key is now fully removed from this chain.
3690
+ await forgetSerialsNoLongerEnrolledForIdentity([pending.key.serial], () =>
3691
+ vaultStore.enrolledSerialsAcrossChains(scopeToken)
3692
+ )
3001
3693
  return true
3002
3694
  }
3003
3695
 
3004
- if (!completedMatchingRelock) return false
3696
+ if (!acceptedMatchingRelock) return false
3005
3697
 
3006
3698
  const second = await reduceVerifiedVaultOutputs(
3007
3699
  w,
@@ -3015,7 +3707,11 @@ export async function finalizeVaultKeyRemoval(
3015
3707
  'allow'
3016
3708
  )
3017
3709
  if (second.state.authorizesPendingKey) return false
3018
- await vaultStore.finalizeProvenKeyRemoval(scopeToken)
3710
+ await vaultStore.finalizeProvenKeyRemoval(scopeToken, tagger)
3711
+ // XQ-014: the tombstoned key is now fully removed from this chain.
3712
+ await forgetSerialsNoLongerEnrolledForIdentity([pending.key.serial], () =>
3713
+ vaultStore.enrolledSerialsAcrossChains(scopeToken)
3714
+ )
3019
3715
  return true
3020
3716
  })
3021
3717
  }