@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,94 +1,74 @@
1
1
  /**
2
2
  * Vault transfers — internal movements between the `default` change basket
3
- * and the `admin vault` basket, over plain K1 (secp256k1) P2PKH outputs.
3
+ * and the `admin vault` basket, over 1-of-N P-256 comb-verifier outputs
4
+ * (r1comb.ts, spec §2).
4
5
  *
5
- * Deposit: ONE YubiKey tap. The card unwraps the vault key; the next deposit
6
- * index derives that node's child public-key hash, which IS the P2PKH lock.
7
- * Nothing here can produce a vault address without the tap — no xpub is
8
- * stored anywhere, so the unwrapped node is the only source of the material.
9
- * Funding and change stay with the toolbox, out of the default basket.
6
+ * Deposit: NO hardware. A vault output has a wallet-derived HMAC salt and one
7
+ * comb commitment for every enrolled key. The HMAC uses [2, "vault salt"],
8
+ * counterparty "self", the rolling key ID "1", "2", ... and the canonically
9
+ * framed YubiKey serials in commitment order. The lock contains only salted
10
+ * table commitments; versioned customInstructions retain the derivation ID,
11
+ * salt and full key records for authenticated indexing and recovery. Funding and change stay
12
+ * with the toolbox, out of the default basket. The release and private-backup
13
+ * configuration gates must be enabled before creating any vault output.
10
14
  *
11
- * Withdraw: ONE tap for the whole transaction. The same unwrapped node derives
12
- * the child private key each selected input names, and signs it in software.
13
- * The toolbox returns the withdrawn value (minus fee, minus any re-vaulted
14
- * remainder) as change into the default basket — that change IS the internal
15
- * transfer. Vault inputs carry a custom unlockingScriptLength the toolbox
16
- * cannot itself produce, so we build each unlocking script ourselves and
17
- * finalize with signAction.
15
+ * Withdraw (Task 10): the user names a key BEFORE the tap. Only outputs
16
+ * committed to that key are selected (filter → sort → cap), each one's REAL
17
+ * lock out of the listed BEEF is checked for the key's commitment, and the
18
+ * card then signs one 32-byte digest per input in batches of
19
+ * VAULT_INPUTS_PER_TAP (ceremonyHost). Every unlock is validated locally with
20
+ * strict Spend flags before signAction. The toolbox returns the withdrawn
21
+ * value (minus fee, minus any re-vaulted remainder) as change into the default
22
+ * basket — that change IS the internal transfer.
18
23
  *
19
- * Sweep: recovery for a lost YubiKey, signed from the SAME HD node reached
20
- * the other way — main mnemonic + vault passphrase (see vaultDerivation.ts).
21
- * No card, no ceremony. Always empties the vault (subject to the input cap)
22
- * and never re-vaults.
24
+ * Re-lock (Task 11): the same selection with amount 'all', but the ONLY
25
+ * output is a new vault output committed to the CURRENT key set — how a key
26
+ * added later gains access to old deposits, and how a removed key loses it
27
+ * (spec §4.3).
23
28
  *
24
- * One rail built for the ~960 KB R1-K1 script survives it on its own merits:
25
- * the deferred-broadcast finish on withdrawal (see the PAST THE POINT OF NO
26
- * ABORT comment). The other — the two-transaction deposit that staged exact
27
- * funding so no change output was ever a sibling of the giant script — is
28
- * retired: a K1 deposit is ONE ordinary createAction (see depositToVault).
29
- * What remains of the staging machinery exists only to recover money the old
30
- * flow stranded on real wallets (see reclaimStagingOutputs).
29
+ * The staged noSend finish on output-creating spends (see the PAST THE POINT
30
+ * OF NO ABORT comment) lets this module validate final signed bytes before the
31
+ * initial sendWith release, without using the offline queue.
31
32
  *
32
33
  * The `admin vault` basket name is admin-reserved: WalletPermissionsManager
33
34
  * blocks any non-admin originator (web pages) from listing, inserting into, or
34
35
  * relinquishing it. All calls here use the admin originator.
35
36
  *
36
- * SECURITY: the vault HD node passes through this module for the length of ONE
37
- * operation and is never stored. It arrives either as a VaultKeyHandle — read
38
- * at its point of use, released in a finally — or, on the sweep, as a node the
39
- * caller owns; neither is ever put in module state, a cache, or a closure that
40
- * outlives the call. Nothing key-shaped is logged: not the node, not a child
41
- * key, not a seed.
37
+ * SECURITY: no private key material passes through this module — ever. A VaultSigner
38
+ * (serial, public key, sign()) arrives from ceremonyHost for the length of ONE
39
+ * withdrawal or re-lock and is released in a finally. Each salt is revealed
40
+ * only by a spend's unlocking script; it provides domain separation between
41
+ * locks, not spending authority.
42
42
  */
43
- import { Beef, HD, Hash, LockingScript, P2PKH, PublicKey, Transaction, TransactionSignature, UnlockingScript, Utils } from '@bsv/sdk'
44
- import { vaultStore } from './vaultStore'
45
- import { VaultError } from './types'
46
- import { backupAttestation } from './backupAttestation'
47
- import { VaultKeyHandle } from './ceremony'
48
- import { noteVaultProgress, requestVaultKey } from './ceremonyHost'
49
- import { bip32KeyID, indexFromKeyID, depositPrivKey, depositPubKeyHash } from './vaultDerivation'
43
+ import { Beef, Hash, LockingScript, Transaction, UnlockingScript, Utils } from '@bsv/sdk'
44
+ import { isBackupPushEnabled } from '../../backup/preference'
45
+ import { getBackupUrl, isVaultAvailable, isVaultEnabled } from '../../toolboxConfig'
46
+ import { specOpFailedActions } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
47
+ import { noteVaultProgress, requestVaultSigner } from './ceremonyHost'
50
48
  import {
51
- K1_UNLOCK_LEN,
52
- buildVaultLockingScript,
49
+ R1C_LOCK_LEN,
50
+ R1C_UNLOCK_LEN,
51
+ SALT_BYTES,
52
+ VaultInstructions,
53
+ bakedCommitments,
54
+ buildLock,
55
+ buildUnlock,
56
+ commitment,
53
57
  decodeVaultInstructions,
54
58
  encodeVaultInstructions,
55
- VaultInstructions
56
- } from './k1'
59
+ pushTxDerCheck,
60
+ sighashPreimage,
61
+ signerDigest,
62
+ vaultSaltHmacData,
63
+ verifyVaultInput
64
+ } from './r1comb'
65
+ import { VaultError } from './types'
66
+ import { metaFromVerifiedOutputs, VAULT_MIN_KEYS } from './VaultKeyService'
67
+ import { vaultStore, VaultKeyRecord, VaultMeta, type VaultScopeToken } from './vaultStore'
57
68
 
58
69
  export const VAULT_BASKET = 'admin vault'
59
-
60
- /**
61
- * LEGACY — the intermediate basket the retired two-transaction deposit split
62
- * its funding into (tx1 carved out deposit + tx2 fee here; tx2 spent it into
63
- * the vault). No new outputs are ever created in it. It survives only so that
64
- * reclaimStagingOutputs can find and recover coins the old flow stranded on
65
- * real wallets (tx1 landed, tx2 failed).
66
- */
67
- export const VAULT_STAGING_BASKET = 'vault staging'
68
-
69
- /** LEGACY — BRC-42 protocol the staging output's P2PKH key was derived under.
70
- * Reclaim-only: the key lives in the ordinary wallet key deriver (counterparty
71
- * 'self'), so spending a staging coin needs no ceremony and no YubiKey. */
72
- const STAGING_PROTOCOL: [number, string] = [2, 'vault deposit staging']
73
-
74
- /** P2PKH unlock, worst case: push(73-byte DER+hashtype sig) + push(33-byte key). */
75
- const STAGING_UNLOCK_LEN = 108
76
-
77
- interface StagingInstructions {
78
- v: 1
79
- type: 'staging'
80
- keyID: string
81
- }
82
-
83
- function decodeStagingInstructions(s: string | undefined): StagingInstructions | null {
84
- if (!s) return null
85
- try {
86
- const o = JSON.parse(s)
87
- return o && o.v === 1 && o.type === 'staging' && typeof o.keyID === 'string' ? o : null
88
- } catch {
89
- return null
90
- }
91
- }
70
+ /** Wallet HMAC domain used only for Vault output salts. */
71
+ export const VAULT_SALT_PROTOCOL = [2, 'vault salt'] as const
92
72
 
93
73
  /**
94
74
  * Storage-backed lookup of the transactions reserving a set of outpoints.
@@ -105,7 +85,8 @@ export type SpendingReferenceLookup = (
105
85
  * Injected dependencies for a vault transfer.
106
86
  *
107
87
  * Injected rather than imported so the module stays testable without native
108
- * modules or a database, and optional so a caller that has neither still works.
88
+ * modules, a database or a configured host, and optional so a caller that has
89
+ * none of them still works.
109
90
  */
110
91
  export interface VaultTransferOptions {
111
92
  /** Storage-backed reservation heal. See SpendingReferenceLookup. */
@@ -122,55 +103,78 @@ export interface VaultTransferOptions {
122
103
  * reaches the offline drain" a testable invariant.
123
104
  */
124
105
  isOnline?: () => Promise<boolean>
106
+ /** Injected BUILD half of the availability gate so the module stays
107
+ * config-free in tests. Defaults to isVaultEnabled() from toolboxConfig.
108
+ * Half-dead since task 11: it can still refuse, but `() => true` no longer
109
+ * enables anything, because the mainnet half is not injectable and runs
110
+ * regardless — see requireReleased. */
111
+ vaultEnabled?: () => boolean
112
+ /** Private encrypted backup must have a configured service and must not be
113
+ * opted out before any operation creates a new Vault output. */
114
+ backupEnabled?: () => Promise<boolean>
115
+ /** Two-phase key revocation: spend only outputs still authorizing this
116
+ * pubkey and write replacements under the remaining active keys. A durable
117
+ * pendingRemoval tombstone must already retain the revoked key record. */
118
+ revokePubkey?: string
125
119
  }
126
120
 
127
121
  export interface VaultSpendResult {
128
122
  txid: string
129
123
  /**
130
- * Vault outputs left untouched because of the input cap.
131
- *
132
- * Non-zero means the withdrawal was partial: the caller should tell the user
133
- * that funds remain and that repeating the withdrawal will move them (each
134
- * pass also consolidates, so the next one needs fewer inputs).
124
+ * Vault outputs the chosen key COULD open but which were left untouched by
125
+ * the input cap (VAULT_MAX_INPUTS). Non-zero means the withdrawal was
126
+ * partial: repeating it with the same key moves them (each pass also
127
+ * consolidates, so the next one needs fewer inputs).
128
+ */
129
+ cappedInputs: number
130
+ /**
131
+ * Outputs the chosen key is NOT committed to (spec §4.2 step 8): they need
132
+ * one of `keys`. `serial` is present when the pubkey is still in meta —
133
+ * absent for a key that has since been removed.
135
134
  */
136
- remainingInputs: number
135
+ unreachable: { count: number; satoshis: number; keys: { serial?: string; pubkey: string }[] }
136
+ }
137
+
138
+ /** How the vault's outputs relate to the CURRENT key list (spec §3.4 badges). */
139
+ export interface VaultKeyCoverage {
140
+ /** Strictly authenticated current-format outputs in the basket. */
141
+ outputs: number
142
+ /** Outputs whose key set differs from the current one, in either direction. */
143
+ stale: number
144
+ /** Current pubkeys absent from at least one output — "not yet open to X". */
145
+ missingKeys: string[]
146
+ /** Outputs committed to a pubkey no longer in meta — "still open to a removed key". */
147
+ removedKeyOutputs: number
137
148
  }
138
149
 
139
150
  /**
140
- * Dust-fold threshold for withdrawal remainders — not a deposit floor.
141
- *
142
- * The old 200,000 figure was R1 fee economics: a ~960 KB script paid for
143
- * twice, once to create the output and once to push the preimage that spent
144
- * it, made anything smaller not worth moving. A K1 vault output costs 25 bytes
145
- * to create and ~107 to spend, so at the wallet's fee rate moving one is a
146
- * couple of satoshis and the script no longer argues for any floor at all.
147
- * Deposits are no longer capped by this constant.
151
+ * Deposit floor AND withdrawal-remainder fold threshold (spec §4.1 step 1,
152
+ * §4.2 step 4).
148
153
  *
149
- * What remains is dust hygiene on the withdrawal side: a sub-floor remainder
150
- * left over after a partial withdrawal is folded into the withdrawal (via the
151
- * toolbox's own change) rather than re-vaulted, since an output this small
152
- * isn't worth the index it would burn.
154
+ * An R1C output costs roughly 45 KB to create and ~2.5 KB of unlock plus its
155
+ * source transaction in the BEEF to spend, so at the wallet's fee rate one
156
+ * output is a few thousand satoshis of fees over its life. 100,000 keeps that
157
+ * under a few percent of the smallest deposit, and gives the re-lock (whose
158
+ * fee comes out of the vault) room to run. The screen renders the floor
159
+ * inline; `below-dust` is the defensive service-side refusal.
153
160
  */
154
- export const VAULT_DEPOSIT_MIN = 10_000
161
+ export const VAULT_DEPOSIT_MIN = 100_000
155
162
 
156
163
  /**
157
164
  * Vault inputs per withdrawal.
158
165
  *
159
- * Nothing about the SCRIPTS bounds this any more. The old cap of 6 was
160
- * defending against ~1.83 MB of inputBEEF per input (a measured 146 MB Hermes
161
- * array at 20 inputs) and Arcade's 10 MB transaction policy — both artifacts of
162
- * the R1-K1 script. A K1 input contributes an ordinary source transaction and a
163
- * ~107-byte unlocking script; 32 of them is a few kilobytes on the wire.
164
- *
165
- * What still bounds it is createAction ergonomics. Every input is one more coin
166
- * to reserve atomically and release if anything fails, one more sighash
167
- * preimage formatted over a transaction that itself grows with each input (the
168
- * signing loop below is O(n²) in preimage bytes), and one more chance for a
169
- * stuck reservation to wedge the whole withdrawal. 32 drains any realistic
170
- * vault in one pass while staying well inside all of that; the hard ceiling is
171
- * the value no future tuning may exceed without redoing that reasoning. (It is
172
- * also the vault-side control services/walletArgLimits.ts refers to — the vault
173
- * bypasses the wallet-argument caps structurally, so this IS its bound.)
166
+ * What bounds this is size and createAction ergonomics. Each vault input
167
+ * contributes its ~45 KB source transaction to the inputBEEF (32 inputs ≈
168
+ * 1.5 MB, with listOutputs' missing response cap) plus a
169
+ * 2.5 KB unlocking script; every input is one more coin to reserve atomically
170
+ * and release if anything fails, one more sighash preimage over a transaction
171
+ * that grows with each input, one more on-card signature inside the tap
172
+ * batches, and one more chance for a stuck reservation to wedge the whole
173
+ * withdrawal. 32 drains any realistic vault in one pass while staying well
174
+ * inside all of that; the hard ceiling is the value no future tuning may
175
+ * exceed without redoing that reasoning. (It is also the vault-side control
176
+ * services/walletArgLimits.ts refers to — the vault bypasses the
177
+ * wallet-argument caps structurally, so this IS its bound.)
174
178
  *
175
179
  * Consolidation is automatic: a capped withdrawal re-vaults its remainder as one
176
180
  * output, so repeated withdrawals converge on a single vault UTXO.
@@ -181,14 +185,15 @@ export const VAULT_HARD_MAX_INPUTS = 48
181
185
  /** The subset of the wallet interface transfers depends on (injected so the
182
186
  * whole module is testable without the toolbox). */
183
187
  export interface VaultWallet {
188
+ createHmac(args: unknown, originator: string): Promise<{ hmac: number[] }>
184
189
  createAction(args: unknown, originator: string): Promise<CreateActionResult>
185
- signAction(args: unknown, originator: string): Promise<{ txid?: string; tx?: number[] }>
190
+ signAction(args: unknown, originator: string): Promise<{
191
+ txid?: string
192
+ tx?: number[]
193
+ }>
186
194
  listOutputs(args: unknown, originator: string): Promise<ListOutputsResult>
187
- getPublicKey(args: unknown, originator: string): Promise<{ publicKey: string }>
188
- /** Signs the staging input of a deposit's tx2 (BRC-42 key, counterparty 'self'). */
189
- createSignature(args: unknown, originator: string): Promise<{ signature: number[] }>
190
195
  abortAction(args: unknown, originator: string): Promise<unknown>
191
- listActions?(args: unknown, originator: string): Promise<{ actions: VaultActionRow[] }>
196
+ listActions?(args: unknown, originator: string): Promise<{ actions: VaultActionRow[]; totalActions?: number }>
192
197
  }
193
198
 
194
199
  /** The fields of a listActions row the reservation heal needs. `inputs` arrives
@@ -199,51 +204,817 @@ export interface VaultActionRow {
199
204
  txid?: string
200
205
  status: string
201
206
  reference?: string
202
- inputs?: { sourceOutpoint?: string }[]
207
+ labels?: string[]
208
+ inputs?: { sourceOutpoint?: string; sourceSatoshis?: number; sourceLockingScript?: string }[]
209
+ outputs?: {
210
+ satoshis: number
211
+ spendable: boolean
212
+ customInstructions?: string
213
+ lockingScript?: string
214
+ outputIndex: number
215
+ basket: string
216
+ }[]
203
217
  }
204
218
 
205
219
  interface CreateActionResult {
206
220
  txid?: string
207
221
  tx?: number[]
208
222
  signableTransaction?: { tx: number[]; reference: string }
223
+ sendWithResults?: { txid?: string; status?: string }[]
209
224
  }
210
225
  interface ListOutputsResult {
211
226
  outputs: {
212
227
  outpoint: string
213
228
  satoshis: number
214
229
  customInstructions?: string
230
+ lockingScript?: string
215
231
  }[]
216
- /** Present when `include: 'entire transactions'` was requested — the AtomicBEEF
217
- * (well, the multi-tx BEEF) covering every listed output's source transaction.
218
- * Forwarded verbatim as createAction's inputBEEF; see spendVaultOutputs. */
232
+ totalOutputs?: number
233
+ /** Present when `include: 'entire transactions'` was requested — the
234
+ * multi-tx BEEF covering every listed output's source transaction. Forwarded
235
+ * verbatim as createAction's inputBEEF and read for each output's REAL lock. */
219
236
  BEEF?: number[]
220
237
  }
221
238
 
222
239
  // ── helpers ───────────────────────────────────────────────────────────────
223
240
 
224
241
  /**
225
- * Reserve the next deposit slot: take the next BIP32 index and lock to that
226
- * child of the vault node. Used by both depositToVault and the withdraw path's
227
- * re-vaulted-remainder output.
242
+ * Process-wide serialization for every operation that can change the vault
243
+ * basket or its authorization metadata. UI state is not a lock: two screens,
244
+ * a fast double tap, or a disable action racing a transfer can otherwise make
245
+ * decisions from the same stale output set.
246
+ */
247
+ let vaultMutationTail: Promise<void> = Promise.resolve()
248
+
249
+ async function withVaultMutation<T>(work: () => Promise<T>): Promise<T> {
250
+ let release!: () => void
251
+ const predecessor = vaultMutationTail
252
+ vaultMutationTail = new Promise<void>(resolve => { release = resolve })
253
+ await predecessor
254
+ try {
255
+ return await work()
256
+ } finally {
257
+ release()
258
+ }
259
+ }
260
+
261
+ const assertVaultScope = (scopeToken?: VaultScopeToken): void => {
262
+ if (scopeToken) vaultStore.assertScopeToken(scopeToken)
263
+ }
264
+
265
+ const VAULT_LIST_PAGE = 64
266
+ const VAULT_ACTION_PAGE = 200
267
+ /** Rows carrying full R1C scripts are several megabytes at the normal
268
+ * withdrawal input cap. Keep those bridge pages small without limiting how
269
+ * many pages can be inspected. */
270
+ const VAULT_SCRIPT_ACTION_PAGE = 8
271
+
272
+ /** Accept the two outpoint separators used by wallet surfaces, then retain one
273
+ * canonical spelling everywhere this module compares identities. Decimal
274
+ * output indexes are canonicalized too so textual aliases cannot make one coin
275
+ * appear to be two different Vault outputs. */
276
+ function canonicalVaultOutpoint(outpoint: string): string {
277
+ const match = /^([0-9a-fA-F]{64})[.:](0|[1-9][0-9]*)$/.exec(outpoint)
278
+ if (!match) throw new VaultError('no-transaction', `Vault output has invalid outpoint ${outpoint}`)
279
+ const vout = Number(match[2])
280
+ if (!Number.isSafeInteger(vout)) {
281
+ throw new VaultError('no-transaction', `Vault output has invalid outpoint ${outpoint}`)
282
+ }
283
+ return `${match[1].toLowerCase()}.${vout}`
284
+ }
285
+
286
+ /** 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. */
289
+ async function scanVaultOutputPages(
290
+ w: VaultWallet,
291
+ adminOriginator: string,
292
+ include: 'locking scripts' | 'entire transactions',
293
+ onPage: (outputs: ListOutputsResult['outputs'], page: ListOutputsResult) => void,
294
+ scopeToken?: VaultScopeToken,
295
+ ): Promise<number> {
296
+ const seen = new Set<string>()
297
+ let offset = 0
298
+ let expectedTotal: number | undefined
299
+ for (;;) {
300
+ assertVaultScope(scopeToken)
301
+ const page = await w.listOutputs(
302
+ { basket: VAULT_BASKET, include, includeCustomInstructions: true, limit: VAULT_LIST_PAGE, offset },
303
+ adminOriginator
304
+ )
305
+ assertVaultScope(scopeToken)
306
+ if (!page || !Array.isArray(page.outputs)) {
307
+ throw new VaultError('no-transaction', 'Vault output listing returned an invalid page')
308
+ }
309
+ if (page.outputs.length > VAULT_LIST_PAGE) {
310
+ throw new VaultError('no-transaction', 'Vault output listing exceeded its requested page size')
311
+ }
312
+ if (page.totalOutputs !== undefined) {
313
+ if (!Number.isSafeInteger(page.totalOutputs) || page.totalOutputs < 0) {
314
+ throw new VaultError('no-transaction', 'Vault output listing returned an invalid total')
315
+ }
316
+ if (expectedTotal !== undefined && expectedTotal !== page.totalOutputs) {
317
+ throw new VaultError('no-transaction', 'Vault output listing changed while it was being read')
318
+ }
319
+ expectedTotal = page.totalOutputs
320
+ } else if (expectedTotal !== undefined) {
321
+ throw new VaultError('no-transaction', 'Vault output listing dropped its total while it was being read')
322
+ }
323
+ const outputs: ListOutputsResult['outputs'] = []
324
+ for (const rawOutput of page.outputs) {
325
+ const canonicalOutpoint = canonicalVaultOutpoint(rawOutput.outpoint)
326
+ if (seen.has(canonicalOutpoint)) {
327
+ throw new VaultError('no-transaction', `Vault output listing repeated ${rawOutput.outpoint}`)
328
+ }
329
+ seen.add(canonicalOutpoint)
330
+ outputs.push({ ...rawOutput, outpoint: canonicalOutpoint })
331
+ }
332
+ onPage(outputs, page)
333
+ if (page.outputs.length === 0) {
334
+ if (expectedTotal !== undefined && offset < expectedTotal) {
335
+ throw new VaultError('no-transaction', 'Vault output listing made no progress before its reported total')
336
+ }
337
+ break
338
+ }
339
+ offset += page.outputs.length
340
+ if (expectedTotal !== undefined) {
341
+ if (offset > expectedTotal) throw new VaultError('no-transaction', 'Vault output listing exceeded its reported total')
342
+ if (offset === expectedTotal) break
343
+ // Some storage providers return fewer rows than requested. A short page
344
+ // is not the end while the authoritative total says rows remain.
345
+ continue
346
+ }
347
+ if (page.outputs.length < VAULT_LIST_PAGE) break
348
+ }
349
+ return offset
350
+ }
351
+
352
+ /** An empty-basket safety decision needs one authoritative row, not every
353
+ * locking script in the basket. A contradictory total still fails closed. */
354
+ async function vaultHasOutputs(
355
+ w: VaultWallet,
356
+ adminOriginator: string,
357
+ scopeToken?: VaultScopeToken
358
+ ): Promise<boolean> {
359
+ assertVaultScope(scopeToken)
360
+ const page = await w.listOutputs(
361
+ { basket: VAULT_BASKET, include: 'locking scripts', includeCustomInstructions: true, limit: 1, offset: 0 },
362
+ adminOriginator
363
+ )
364
+ assertVaultScope(scopeToken)
365
+ if (!page || !Array.isArray(page.outputs)) {
366
+ throw new VaultError('no-transaction', 'Vault output listing returned an invalid page')
367
+ }
368
+ if (
369
+ page.totalOutputs !== undefined &&
370
+ (!Number.isSafeInteger(page.totalOutputs) || page.totalOutputs < page.outputs.length)
371
+ ) {
372
+ throw new VaultError('no-transaction', 'Vault output listing returned an invalid total')
373
+ }
374
+ if (page.outputs.length > 1) {
375
+ throw new VaultError('no-transaction', 'Vault output listing exceeded its requested limit')
376
+ }
377
+ if (page.outputs.length === 0 && (page.totalOutputs ?? 0) > 0) {
378
+ throw new VaultError('no-transaction', 'Vault output listing made no progress before its reported total')
379
+ }
380
+ return page.outputs.length > 0
381
+ }
382
+
383
+ interface VerifiedVaultOutput {
384
+ outpoint: string
385
+ satoshis: number
386
+ ci: VaultInstructions
387
+ lockingScript: LockingScript
388
+ }
389
+
390
+ function verifyInstructionsAgainstLock(ci: VaultInstructions, lockingScript: LockingScript, where: string): void {
391
+ let baked: string[]
392
+ try {
393
+ baked = bakedCommitments(lockingScript)
394
+ } catch {
395
+ throw new VaultError('template-invalid', `${where} is not an R1C lock`)
396
+ }
397
+ const expected = ci.keys.map(key => commitment(key.pubkey, ci.salt))
398
+ if (baked.length !== expected.length || baked.some((c, i) => c !== expected[i])) {
399
+ throw new VaultError('template-invalid', `${where} recovery metadata does not match its real lock`)
400
+ }
401
+ const rebuilt = buildLock({ commitments: expected, saltHex64: ci.salt })
402
+ if (rebuilt.toHex() !== lockingScript.toHex()) {
403
+ throw new VaultError('template-invalid', `${where} recovery metadata does not rebuild its real lock`)
404
+ }
405
+ }
406
+
407
+ /** Validate both the recoverability record and the real source output. The
408
+ * customInstructions are an index; authorization comes only from the exact
409
+ * commitments baked into the locking script carried by the BEEF. */
410
+ function verifyListedVaultOutput(
411
+ output: ListOutputsResult['outputs'][number],
412
+ sources: Beef
413
+ ): VerifiedVaultOutput {
414
+ if (!Number.isSafeInteger(output.satoshis) || output.satoshis < 0) {
415
+ throw new VaultError('no-transaction', `Vault output ${output.outpoint} has an invalid value`)
416
+ }
417
+ const ci = decodeVaultInstructions(output.customInstructions)
418
+ if (!ci) throw new VaultError('template-invalid', `Vault output ${output.outpoint} has invalid recovery metadata`)
419
+ const canonicalOutpoint = canonicalVaultOutpoint(output.outpoint)
420
+ const [txid, voutText] = canonicalOutpoint.split('.')
421
+ const vout = Number(voutText)
422
+ const source = sources.findTxid(txid)?.tx?.outputs[vout]
423
+ if (!source) throw new VaultError('no-transaction', `No source transaction for vault output ${output.outpoint}`)
424
+ const sourceSatoshis = source.satoshis
425
+ if (typeof sourceSatoshis !== 'number' || !Number.isSafeInteger(sourceSatoshis) || sourceSatoshis < 0) {
426
+ throw new VaultError('no-transaction', `Vault output ${output.outpoint} source has an invalid value`)
427
+ }
428
+ if (sourceSatoshis !== output.satoshis) {
429
+ throw new VaultError('no-transaction', `Vault output ${output.outpoint} value disagrees with its source transaction`)
430
+ }
431
+ verifyInstructionsAgainstLock(ci, source.lockingScript, `Vault output ${output.outpoint}`)
432
+ return { outpoint: canonicalOutpoint, satoshis: sourceSatoshis, ci, lockingScript: source.lockingScript }
433
+ }
434
+
435
+ function sumVaultSatoshis(outputs: readonly Pick<VerifiedVaultOutput, 'satoshis'>[], where: string): number {
436
+ let sum = 0
437
+ for (const output of outputs) {
438
+ sum += output.satoshis
439
+ if (!Number.isSafeInteger(sum)) throw new VaultError('no-transaction', `${where} value exceeds the safe integer range`)
440
+ }
441
+ return sum
442
+ }
443
+
444
+ interface VerifiedVaultScan<T> {
445
+ state: T
446
+ inventory: VaultSaltInventory
447
+ outputs: number
448
+ }
449
+
450
+ /** Authenticate every current Vault output against its real source
451
+ * transaction, reducing it immediately so page BEEF and 45 KB scripts can be
452
+ * reclaimed. The compact inventory retains every distinct HMAC claim so each
453
+ * output's wallet provenance is authenticated before the result is returned. */
454
+ async function reduceVerifiedVaultOutputs<T>(
455
+ w: VaultWallet,
456
+ adminOriginator: string,
457
+ initial: () => T,
458
+ reduce: (state: T, output: VerifiedVaultOutput, sources: Beef) => void,
459
+ scopeToken?: VaultScopeToken,
460
+ pendingMode: 'block' | 'repair-unsigned' | 'allow' = 'block'
461
+ ): Promise<VerifiedVaultScan<T>> {
462
+ const expectedChain = scopeToken?.chain ?? vaultStore.getScope()?.chain
463
+ if (!expectedChain) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
464
+ const state = initial()
465
+ const inventory = emptyVaultSaltInventory()
466
+ const outputs = await scanVaultOutputPages(w, adminOriginator, 'entire transactions', (listed, page) => {
467
+ if (listed.length === 0) return
468
+ if (!page.BEEF?.length) {
469
+ throw new VaultError('no-transaction', 'Vault output listing did not include source transactions')
470
+ }
471
+ let sources: Beef
472
+ try {
473
+ sources = Beef.fromBinary(page.BEEF)
474
+ } catch {
475
+ throw new VaultError('no-transaction', 'Vault output listing returned malformed source transactions')
476
+ }
477
+ for (const listedOutput of listed) {
478
+ const output = verifyListedVaultOutput(listedOutput, sources)
479
+ rememberVaultSalt(inventory, output.ci, output.lockingScript, output.outpoint, expectedChain)
480
+ reduce(state, output, sources)
481
+ }
482
+ }, scopeToken)
483
+ assertVaultScope(scopeToken)
484
+ await verifyVaultSaltDerivations(w, adminOriginator, inventory)
485
+ assertVaultScope(scopeToken)
486
+ if (pendingMode !== 'allow') {
487
+ const repaired = await inspectHiddenVaultReservations(
488
+ w,
489
+ adminOriginator,
490
+ scopeToken,
491
+ pendingMode === 'repair-unsigned'
492
+ )
493
+ if (repaired) {
494
+ // abortAction restores the hidden source rows. Re-read and authenticate
495
+ // them; a second reservation is blocked rather than retried forever.
496
+ return await reduceVerifiedVaultOutputs(w, adminOriginator, initial, reduce, scopeToken, 'block')
497
+ }
498
+ }
499
+ return { state, inventory, outputs }
500
+ }
501
+
502
+ const sameInstructionKeys = (a: readonly VaultKeyRecord[], b: Readonly<VaultInstructions['keys']>): boolean =>
503
+ a.length === b.length && a.every((key, i) => (
504
+ key.serial === b[i].serial &&
505
+ key.slot === b[i].slot &&
506
+ key.pubkey === b[i].pubkey &&
507
+ key.nickname === b[i].nickname &&
508
+ key.enrolledAt === b[i].enrolledAt
509
+ ))
510
+
511
+ /** Refuse to combine two enrollments or use a cache older than an output. Old
512
+ * revisions are expected until a re-lock, but the active revision must carry
513
+ * the exact active key records that a new output would encode. */
514
+ function requireOutputMetaConsistency(outputs: readonly VerifiedVaultOutput[], meta: VaultMeta): void {
515
+ for (const output of outputs) {
516
+ const { ci } = output
517
+ if (ci.vaultId !== meta.vaultId || ci.createdAt !== meta.createdAt) {
518
+ throw new VaultError('template-invalid', 'Vault basket contains outputs from conflicting enrollments')
519
+ }
520
+ if (ci.revision > meta.revision) {
521
+ throw new VaultError('template-invalid', 'Vault recovery metadata is newer than the local enrollment')
522
+ }
523
+ if (ci.revision === meta.revision && !sameInstructionKeys(meta.keys, ci.keys)) {
524
+ throw new VaultError('template-invalid', 'Vault outputs disagree on the active key metadata')
525
+ }
526
+ }
527
+ }
528
+
529
+ const PENDING_ACTION_STATUSES = new Set(['unsigned', 'nosend', 'nonfinal', 'unprocessed', 'sending', 'unproven'])
530
+
531
+ /**
532
+ * The pending statuses in which the transaction has already been handed to the
533
+ * network: it has a txid and its outputs are ordinary unconfirmed UTXOs. These
534
+ * are LIVE transactions, not reservations — `unprocessed` is deliberately
535
+ * absent, because the toolbox advances a request to `sending` only once it has
536
+ * actually posted it.
537
+ */
538
+ const BROADCAST_ACTION_STATUSES = new Set(['sending', 'unproven'])
539
+
540
+ /** Authenticate pagination while consuming one action at a time. Detailed
541
+ * action rows may contain several 45 KB source/output scripts, so callers must
542
+ * retain only the small facts or references they need after this callback. */
543
+ async function scanVaultActions(
544
+ w: VaultWallet,
545
+ adminOriginator: string,
546
+ details: Record<string, unknown>,
547
+ onAction: (action: VaultActionRow) => void,
548
+ scopeToken?: VaultScopeToken,
549
+ includeFailed = false
550
+ ): Promise<void> {
551
+ if (!w.listActions) throw new VaultError('no-transaction', 'Wallet cannot inspect pending vault actions')
552
+ const seen = new Set<string>()
553
+ const pageSize = details.includeInputSourceLockingScripts || details.includeOutputLockingScripts
554
+ ? VAULT_SCRIPT_ACTION_PAGE
555
+ : VAULT_ACTION_PAGE
556
+ const scan = async (query: Record<string, unknown>): Promise<void> => {
557
+ let expectedTotal: number | undefined
558
+ let offset = 0
559
+ for (;;) {
560
+ assertVaultScope(scopeToken)
561
+ const page = await w.listActions!({ labels: ['vault'], limit: pageSize, offset, ...query }, adminOriginator)
562
+ assertVaultScope(scopeToken)
563
+ const actions = page?.actions
564
+ if (!Array.isArray(actions)) throw new VaultError('no-transaction', 'Vault action listing returned an invalid page')
565
+ if (actions.length > pageSize) {
566
+ throw new VaultError('no-transaction', 'Vault action listing exceeded its requested page size')
567
+ }
568
+ if (page.totalActions !== undefined) {
569
+ if (!Number.isSafeInteger(page.totalActions) || page.totalActions < 0) {
570
+ throw new VaultError('no-transaction', 'Vault action listing returned an invalid total')
571
+ }
572
+ if (expectedTotal !== undefined && expectedTotal !== page.totalActions) {
573
+ throw new VaultError('no-transaction', 'Vault action listing changed while it was being read')
574
+ }
575
+ expectedTotal = page.totalActions
576
+ } else if (expectedTotal !== undefined) {
577
+ throw new VaultError('no-transaction', 'Vault action listing dropped its total while it was being read')
578
+ }
579
+ for (const action of actions) {
580
+ const identity = action.reference ?? action.txid
581
+ if (!identity) throw new VaultError('no-transaction', 'Vault action listing returned an unidentified row')
582
+ if (seen.has(identity)) throw new VaultError('no-transaction', `Vault action listing repeated ${identity}`)
583
+ seen.add(identity)
584
+ onAction(action)
585
+ }
586
+ if (actions.length === 0) {
587
+ if (expectedTotal !== undefined && offset < expectedTotal) {
588
+ throw new VaultError('no-transaction', 'Vault action listing made no progress before its reported total')
589
+ }
590
+ break
591
+ }
592
+ offset += actions.length
593
+ if (expectedTotal !== undefined) {
594
+ if (offset > expectedTotal) throw new VaultError('no-transaction', 'Vault action listing exceeded its reported total')
595
+ if (offset === expectedTotal) break
596
+ continue
597
+ }
598
+ if (actions.length < pageSize) break
599
+ }
600
+ }
601
+ await scan(details)
602
+ if (!includeFailed) return
603
+ const ordinaryLabels = Array.isArray(details.labels) ? details.labels.filter(label => typeof label === 'string') : ['vault']
604
+ await scan({ ...details, labels: [specOpFailedActions, ...ordinaryLabels] })
605
+ }
606
+
607
+ const actionClaimsVaultSpend = (action: VaultActionRow): boolean => {
608
+ const labels = new Set(action.labels ?? [])
609
+ return labels.has('vault-withdraw') || labels.has('vault-relock')
610
+ }
611
+
612
+ const actionTouchesVault = (action: VaultActionRow): boolean => {
613
+ const labels = new Set(action.labels ?? [])
614
+ return (
615
+ labels.has('vault-deposit') ||
616
+ actionClaimsVaultSpend(action) ||
617
+ (action.outputs ?? []).some(output => output.basket === VAULT_BASKET) ||
618
+ (action.inputs ?? []).some(input => isR1CSourceScript(input.sourceLockingScript))
619
+ )
620
+ }
621
+
622
+ /**
623
+ * Authenticate the action-history shape produced by depositToVault before it
624
+ * is released from noSend. The unsigned/no-txid shape can be aborted. A signed
625
+ * noSend shape remains a manual, fail-closed case because local status alone
626
+ * cannot disprove an earlier ambiguous sendWith attempt.
228
627
  *
229
- * `hd` is caller-owned and operation-scoped — read from the armed handle at
230
- * the call site, never held here. There is no stored xpub to fall back on:
231
- * without a node in hand this function cannot produce an address at all, which
232
- * is exactly the property that makes every deposit a deliberate tap.
628
+ * This deliberately authenticates the R1C output and constrains every other
629
+ * output to one ordinary P2PKH change output before allowing abortAction. A
630
+ * label by itself is never authority to mutate another action.
233
631
  */
234
- async function nextDepositTarget(hd: HD): Promise<{
235
- instructions: VaultInstructions
236
- lockingScript: string
237
- }> {
238
- const index = await vaultStore.takeNextIndex()
239
- if (index == null) throw new VaultError('not-enrolled', 'Vault is not set up')
240
- const script = buildVaultLockingScript({ k1PublicKeyHash: depositPubKeyHash(hd, index) })
632
+ function isValidHeldVaultDeposit(
633
+ action: VaultActionRow,
634
+ meta: VaultMeta,
635
+ expectedChain: VaultScopeToken['chain'],
636
+ saltInventory?: VaultSaltInventory
637
+ ): boolean {
638
+ const labels = new Set(action.labels ?? [])
639
+ if (!labels.has('vault-deposit') || labels.has('vault-withdraw') || labels.has('vault-relock')) return false
640
+ if (!action.reference) return false
641
+ if (action.status === 'unsigned') {
642
+ if (action.txid) return false
643
+ } else if (action.status === 'nosend') {
644
+ if (!action.txid || !/^[0-9a-fA-F]{64}$/.test(action.txid)) return false
645
+ } else {
646
+ return false
647
+ }
648
+
649
+ const inputs = action.inputs ?? []
650
+ if (inputs.length === 0 || inputs.length > VAULT_HARD_MAX_INPUTS) return false
651
+ for (const input of inputs) {
652
+ if (!input.sourceOutpoint || !/^[0-9a-fA-F]{64}[.:]\d+$/.test(input.sourceOutpoint)) return false
653
+ if (!Number.isSafeInteger(input.sourceSatoshis) || input.sourceSatoshis! < 0 || !input.sourceLockingScript) return false
654
+ try {
655
+ const sourceLock = LockingScript.fromHex(input.sourceLockingScript)
656
+ if (isR1CSourceScript(input.sourceLockingScript) || !isStandardP2PKH(sourceLock)) return false
657
+ } catch {
658
+ return false
659
+ }
660
+ }
661
+
662
+ const outputs = action.outputs ?? []
663
+ if (outputs.length < 1 || outputs.length > 2) return false
664
+ const indices = new Set<number>()
665
+ for (const output of outputs) {
666
+ if (!Number.isSafeInteger(output.outputIndex) || output.outputIndex < 0 || indices.has(output.outputIndex)) return false
667
+ indices.add(output.outputIndex)
668
+ }
669
+ const vaultOutputs = outputs.filter(output => output.basket === VAULT_BASKET)
670
+ if (vaultOutputs.length !== 1 || vaultOutputs[0].outputIndex !== 0) return false
671
+ const output = vaultOutputs[0]
672
+ if (!Number.isSafeInteger(output.satoshis) || output.satoshis < VAULT_DEPOSIT_MIN) return false
673
+ if (!output.customInstructions || !output.lockingScript) return false
674
+ const ci = decodeVaultInstructions(output.customInstructions)
675
+ if (
676
+ !ci ||
677
+ ci.chain !== expectedChain ||
678
+ ci.vaultId !== meta.vaultId ||
679
+ ci.createdAt !== meta.createdAt ||
680
+ ci.revision > meta.revision
681
+ ) return false
682
+ if (ci.revision === meta.revision && !sameInstructionKeys(meta.keys, ci.keys)) return false
683
+ let lock: LockingScript
684
+ try {
685
+ lock = LockingScript.fromHex(output.lockingScript)
686
+ verifyInstructionsAgainstLock(ci, lock, 'Held Vault deposit')
687
+ } catch {
688
+ return false
689
+ }
690
+
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
699
+ try {
700
+ if (!isStandardP2PKH(LockingScript.fromHex(change.lockingScript))) return false
701
+ } catch {
702
+ return false
703
+ }
704
+ }
705
+ if (saltInventory) {
706
+ rememberVaultSalt(
707
+ saltInventory,
708
+ ci,
709
+ lock,
710
+ vaultActionOutputId(action, output.outputIndex),
711
+ expectedChain
712
+ )
713
+ }
714
+ return true
715
+ }
716
+
717
+ /**
718
+ * Reconcile strictly authenticated deposit reservations left by a crash.
719
+ * Unsigned/no-txid actions are provably unbroadcast and are aborted. Signed
720
+ * noSend actions are never automatically sent or aborted: a crash may have
721
+ * happened during sendWith, so either action could duplicate or conflict with
722
+ * a transaction that already escaped. A deposit already posted to the network
723
+ * (BROADCAST_ACTION_STATUSES) is not a reservation at all and is ignored.
724
+ */
725
+ async function reconcileHeldVaultDeposits(
726
+ w: VaultWallet,
727
+ adminOriginator: string,
728
+ meta: VaultMeta,
729
+ scopeToken?: VaultScopeToken
730
+ ): Promise<{ abortedUnsigned: number }> {
731
+ const expectedChain = scopeToken?.chain ?? vaultStore.getScope()?.chain
732
+ if (!expectedChain) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
733
+ const unsigned: string[] = []
734
+ const saltInventory = emptyVaultSaltInventory()
735
+ let signed = 0
736
+ await scanVaultActions(w, adminOriginator, {
737
+ labels: [],
738
+ includeLabels: true,
739
+ includeInputs: true,
740
+ includeInputSourceLockingScripts: true,
741
+ includeOutputs: true,
742
+ includeOutputLockingScripts: true
743
+ }, action => {
744
+ const labels = new Set(action.labels ?? [])
745
+ if (!labels.has('vault-deposit') || action.status === 'completed' || action.status === 'failed') return
746
+ // A deposit that reached the network is a live unconfirmed deposit, not a
747
+ // held reservation: there is nothing to abort and nothing to reconcile,
748
+ // and its vault output is authenticated on the ordinary listOutputs path
749
+ // like any other. `unproven` is what the activity list shows as
750
+ // "Accepted" and can stand for many minutes, so treating it as held would
751
+ // block every vault transfer — including the re-lock the refusal asks
752
+ // for — until the merkle proof arrives.
753
+ if (BROADCAST_ACTION_STATUSES.has(action.status)) return
754
+ if (!PENDING_ACTION_STATUSES.has(action.status) || !isValidHeldVaultDeposit(action, meta, expectedChain, saltInventory)) {
755
+ throw new VaultError('action-pending', 'A Vault deposit has an unknown or potentially broadcast state')
756
+ }
757
+ if (action.status === 'unsigned') unsigned.push(action.reference!)
758
+ else signed++
759
+ }, scopeToken)
760
+ assertVaultScope(scopeToken)
761
+ await verifyVaultSaltDerivations(w, adminOriginator, saltInventory)
762
+ assertVaultScope(scopeToken)
763
+ if (signed > 1) {
764
+ throw new VaultError('action-pending', 'Multiple signed Vault deposits require manual reconciliation')
765
+ }
766
+ let abortedUnsigned = 0
767
+ for (const reference of unsigned) {
768
+ assertVaultScope(scopeToken)
769
+ await w.abortAction({ reference }, adminOriginator)
770
+ assertVaultScope(scopeToken)
771
+ abortedUnsigned++
772
+ }
773
+ if (signed === 0) return { abortedUnsigned }
774
+ throw new VaultError('action-pending', 'A signed Vault deposit needs manual broadcast-state reconciliation')
775
+ }
776
+
777
+ /** Return true only for an exact current R1C lock. */
778
+ function isR1CSourceScript(scriptHex: string | undefined): boolean {
779
+ if (!scriptHex) return false
780
+ try {
781
+ const lock = LockingScript.fromHex(scriptHex)
782
+ const commitments = bakedCommitments(lock)
783
+ return commitments.length >= 1 && commitments.length <= 5
784
+ } catch {
785
+ return false
786
+ }
787
+ }
788
+
789
+ /**
790
+ * listOutputs exposes only spendable rows, so a reservation can otherwise
791
+ * make a Vault source disappear from balances and safety decisions. Scan all
792
+ * action labels and authenticate source scripts instead. A strictly unsigned,
793
+ * txid-less action is provably unbroadcast and may be aborted to restore its
794
+ * sources; a signed but unposted state (nosend, unprocessed, nonfinal) or a
795
+ * malformed one blocks. An action already posted to the network holds nothing
796
+ * back — see BROADCAST_ACTION_STATUSES at the skip below.
797
+ */
798
+ async function inspectHiddenVaultReservations(
799
+ w: VaultWallet,
800
+ adminOriginator: string,
801
+ scopeToken: VaultScopeToken | undefined,
802
+ repairUnsigned: boolean
803
+ ): Promise<boolean> {
804
+ const abortable: string[] = []
805
+ await scanVaultActions(w, adminOriginator, {
806
+ labels: [],
807
+ includeLabels: true,
808
+ includeInputs: true,
809
+ includeInputSourceLockingScripts: true
810
+ }, action => {
811
+ // Completed history cannot reserve or hide an output. Ignore it before
812
+ // interpreting old labels or source scripts; pre-release Vault actions
813
+ // may use a different template and are not recovery authority.
814
+ if (action.status === 'completed') return
815
+ const inputs = action.inputs ?? []
816
+ const r1cInputs = inputs.filter(input => isR1CSourceScript(input.sourceLockingScript))
817
+ const claimsVaultSpend = actionClaimsVaultSpend(action)
818
+ if (claimsVaultSpend && (inputs.length === 0 || r1cInputs.length !== inputs.length)) {
819
+ throw new VaultError('template-invalid', 'Vault action history has missing or malformed R1C source scripts')
820
+ }
821
+ if (r1cInputs.length === 0) return
822
+ for (const input of r1cInputs) {
823
+ if (
824
+ input.sourceSatoshis !== undefined &&
825
+ (!Number.isSafeInteger(input.sourceSatoshis) || input.sourceSatoshis < 0)
826
+ ) {
827
+ throw new VaultError('no-transaction', 'Vault action history has an invalid source value')
828
+ }
829
+ }
830
+ if (repairUnsigned && action.status === 'unsigned' && !action.txid && action.reference && r1cInputs.length === inputs.length) {
831
+ abortable.push(action.reference)
832
+ return
833
+ }
834
+ // A spend already posted to the network is not holding its source back: it
835
+ // has SPENT it, listOutputs is right to omit it, and whatever the spend
836
+ // created is listed in its place. Blocking here would fail every balance
837
+ // read, coverage check and transfer for as long as the spend sits at
838
+ // 'unproven' — and, because the transfer screen waits for the balance to
839
+ // settle, would report a completed withdrawal as a failure.
840
+ if (BROADCAST_ACTION_STATUSES.has(action.status)) return
841
+ throw new VaultError('action-pending', 'A pending or failed action is holding a Vault output')
842
+ }, scopeToken)
843
+ for (const reference of abortable) {
844
+ assertVaultScope(scopeToken)
845
+ await w.abortAction({ reference }, adminOriginator)
846
+ assertVaultScope(scopeToken)
847
+ }
848
+ return abortable.length > 0
849
+ }
850
+
851
+ /** Include every current-format vault output in full action history. Active
852
+ * listOutputs covers imported/recovered coins; history also covers spent and
853
+ * completed outputs, preserving the wallet-scoped never-reuse invariant when
854
+ * a local counter would otherwise repeat. Pending rows close the
855
+ * pre-listOutputs visibility window. */
856
+ interface VaultSaltInventory {
857
+ derivationClaims: Map<string, { saltKeyId: string; serials: string[]; salt: string }>
858
+ outputFingerprints: Map<string, string>
859
+ outputRecords: Map<string, { lockingScript: string; pubkeys: Set<string> }>
860
+ maxKeyIndex: number
861
+ }
862
+
863
+ function emptyVaultSaltInventory(): VaultSaltInventory {
241
864
  return {
242
- instructions: { v: 3, type: 'K1', keyID: bip32KeyID(index) },
243
- lockingScript: script.toHex()
865
+ derivationClaims: new Map(),
866
+ outputFingerprints: new Map(),
867
+ outputRecords: new Map(),
868
+ maxKeyIndex: 0
869
+ }
870
+ }
871
+
872
+ /** Stable identity for a Vault output represented in action history. */
873
+ function vaultActionOutputId(action: VaultActionRow, outputIndex: number): string {
874
+ if (!Number.isSafeInteger(outputIndex) || outputIndex < 0) {
875
+ throw new VaultError('template-invalid', 'Vault action history contains an invalid output index')
876
+ }
877
+ const actionId = typeof action.txid === 'string' && /^[0-9a-fA-F]{64}$/.test(action.txid)
878
+ ? action.txid.toLowerCase()
879
+ : action.reference
880
+ ? `ref:${action.reference}`
881
+ : undefined
882
+ if (!actionId) throw new VaultError('template-invalid', 'Vault action history output has no stable transaction identity')
883
+ return `${actionId}.${outputIndex}`
884
+ }
885
+
886
+ function saltKeyIndex(ci: VaultInstructions): number {
887
+ const value = Number(ci.saltKeyId)
888
+ if (!Number.isSafeInteger(value) || value < 1) {
889
+ throw new VaultError('template-invalid', 'Vault output has an invalid salt key index')
890
+ }
891
+ return value
892
+ }
893
+
894
+ function rememberVaultSalt(
895
+ inventory: VaultSaltInventory,
896
+ ci: VaultInstructions,
897
+ lock: LockingScript,
898
+ outputId: string,
899
+ expectedChain: VaultScopeToken['chain']
900
+ ): void {
901
+ if (ci.chain !== expectedChain) {
902
+ throw new VaultError('template-invalid', 'Vault output belongs to a different network')
903
+ }
904
+ const scriptHash = Utils.toHex(Hash.sha256(lock.toBinary()))
905
+ const outputFingerprint = Utils.toHex(Hash.sha256(Utils.toArray(
906
+ `${scriptHash}\u0000${encodeVaultInstructions(ci)}`,
907
+ 'utf8'
908
+ ) as number[]))
909
+ const knownOutput = inventory.outputFingerprints.get(outputId)
910
+ if (knownOutput !== undefined && knownOutput !== outputFingerprint) {
911
+ throw new VaultError('template-invalid', 'One Vault output has conflicting authenticated representations')
912
+ }
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 })
916
+ inventory.outputFingerprints.set(outputId, outputFingerprint)
917
+ inventory.outputRecords.set(outputId.toLowerCase(), {
918
+ lockingScript: lock.toHex(),
919
+ pubkeys: new Set(ci.keys.map(key => key.pubkey))
920
+ })
921
+ inventory.maxKeyIndex = Math.max(inventory.maxKeyIndex, saltKeyIndex(ci))
922
+ }
923
+
924
+ /** Derive one canonical 32-byte wallet HMAC under the exact Vault domain. */
925
+ async function deriveVaultSalt(
926
+ w: VaultWallet,
927
+ adminOriginator: string,
928
+ saltKeyId: string,
929
+ serials: readonly string[]
930
+ ): Promise<string> {
931
+ try {
932
+ const derived = await w.createHmac({
933
+ protocolID: [...VAULT_SALT_PROTOCOL],
934
+ keyID: saltKeyId,
935
+ counterparty: 'self',
936
+ data: vaultSaltHmacData(serials),
937
+ seekPermission: false
938
+ }, adminOriginator)
939
+ const hmac = derived.hmac
940
+ if (
941
+ !Array.isArray(hmac) || hmac.length !== SALT_BYTES ||
942
+ hmac.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 0xff)
943
+ ) {
944
+ throw new Error('non-canonical HMAC')
945
+ }
946
+ return Utils.toHex(hmac)
947
+ } catch {
948
+ throw new VaultError('template-invalid', 'Wallet could not derive a canonical Vault salt HMAC')
949
+ }
950
+ }
951
+
952
+ /** Do not let unauthenticated derivation metadata choose the next HD index.
953
+ * Every current or historical key ID and ordered serial list must reproduce
954
+ * its recorded HMAC salt before its index may advance the high-water mark. */
955
+ async function verifyVaultSaltDerivations(
956
+ w: VaultWallet,
957
+ adminOriginator: string,
958
+ inventory: VaultSaltInventory
959
+ ): Promise<void> {
960
+ for (const claim of inventory.derivationClaims.values()) {
961
+ const actualSalt = await deriveVaultSalt(w, adminOriginator, claim.saltKeyId, claim.serials)
962
+ if (actualSalt !== claim.salt) {
963
+ throw new VaultError('template-invalid', `Vault salt derivation ${claim.saltKeyId} does not belong to this wallet`)
964
+ }
244
965
  }
245
966
  }
246
967
 
968
+ async function addHistoricalVaultSaltInventory(
969
+ w: VaultWallet,
970
+ adminOriginator: string,
971
+ inventory: VaultSaltInventory,
972
+ meta: VaultMeta,
973
+ scopeToken?: VaultScopeToken
974
+ ): Promise<void> {
975
+ const expectedChain = scopeToken?.chain ?? vaultStore.getScope()?.chain
976
+ if (!expectedChain) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
977
+ await scanVaultActions(w, adminOriginator, {
978
+ labels: [],
979
+ includeOutputs: true,
980
+ includeOutputLockingScripts: true
981
+ }, action => {
982
+ for (const output of action.outputs ?? []) {
983
+ if (output.basket !== VAULT_BASKET) continue
984
+ const ci = decodeVaultInstructions(output.customInstructions)
985
+ if (!ci || !output.lockingScript) {
986
+ throw new VaultError('template-invalid', 'Vault history contains unreadable recovery metadata or script')
987
+ }
988
+ let lock: LockingScript
989
+ try {
990
+ lock = LockingScript.fromHex(output.lockingScript)
991
+ } catch {
992
+ throw new VaultError('template-invalid', 'Vault history contains a malformed locking script')
993
+ }
994
+ verifyInstructionsAgainstLock(ci, lock, 'Vault history output')
995
+ // Salt/script reuse is wallet-global, so retain valid history from prior
996
+ // enrollments after a drained Vault is disabled and set up again. Only a
997
+ // record claiming the current enrollment ID must agree with its immutable
998
+ // creation time, may not be newer than the local active revision, and
999
+ // must carry the active ordered key set when revisions are equal.
1000
+ if (
1001
+ ci.vaultId === meta.vaultId &&
1002
+ (
1003
+ ci.createdAt !== meta.createdAt ||
1004
+ ci.revision > meta.revision ||
1005
+ (ci.revision === meta.revision && !sameInstructionKeys(meta.keys, ci.keys))
1006
+ )
1007
+ ) {
1008
+ throw new VaultError('template-invalid', 'Vault history conflicts with the active vault enrollment')
1009
+ }
1010
+ rememberVaultSalt(inventory, ci, lock, vaultActionOutputId(action, output.outputIndex), expectedChain)
1011
+ }
1012
+ }, scopeToken, true)
1013
+ assertVaultScope(scopeToken)
1014
+ await verifyVaultSaltDerivations(w, adminOriginator, inventory)
1015
+ assertVaultScope(scopeToken)
1016
+ }
1017
+
247
1018
  /** True for the toolbox's WERR_REVIEW_ACTIONS — an undelayed action that needs
248
1019
  * review, in our case a double-spend against a vault UTXO still reserved by a
249
1020
  * stuck prior attempt whose reserving transaction DOES have a txid. */
@@ -310,36 +1081,63 @@ async function abortActions(
310
1081
  w: VaultWallet,
311
1082
  adminOriginator: string,
312
1083
  matches: (a: VaultActionRow) => boolean,
313
- opts: { includeInputs?: boolean; stopAfter: number }
1084
+ opts: { includeInputs?: boolean; stopAfter: number },
1085
+ scopeToken?: VaultScopeToken
314
1086
  ): Promise<number> {
315
1087
  if (!w.listActions) return 0
316
1088
  let scanned = 0
317
1089
  const seen: string[] = []
1090
+ const seenRows = new Set<string>()
318
1091
  // By reference, so the same orphan is never aborted twice — a second
319
1092
  // abortAction on it would be rejected, and counting it again would report a
320
1093
  // heal that did not happen.
321
1094
  const aborted = new Set<string>()
322
1095
  try {
323
1096
  let offset = 0
324
- for (let page = 0; page < 25 && aborted.size < opts.stopAfter; page++) {
1097
+ let expectedTotal: number | undefined
1098
+ while (aborted.size < opts.stopAfter) {
1099
+ assertVaultScope(scopeToken)
325
1100
  const res = await w.listActions(
326
1101
  { labels: [], limit: 200, offset, ...(opts.includeInputs ? { includeInputs: true } : {}) },
327
1102
  adminOriginator
328
1103
  )
1104
+ assertVaultScope(scopeToken)
329
1105
  const actions = res.actions ?? []
330
- if (actions.length === 0) break
1106
+ if (res.totalActions !== undefined) {
1107
+ if (!Number.isSafeInteger(res.totalActions) || res.totalActions < 0) throw new Error('invalid action total')
1108
+ if (expectedTotal !== undefined && expectedTotal !== res.totalActions) throw new Error('action total changed')
1109
+ expectedTotal = res.totalActions
1110
+ } else if (expectedTotal !== undefined) {
1111
+ throw new Error('action total disappeared')
1112
+ }
1113
+ if (actions.length === 0) {
1114
+ if (expectedTotal !== undefined && offset < expectedTotal) throw new Error('action listing made no progress')
1115
+ break
1116
+ }
331
1117
  scanned += actions.length
332
- for (const a of actions) {
1118
+ for (let i = 0; i < actions.length; i++) {
1119
+ const a = actions[i]
1120
+ const rowId = a.reference ?? a.txid
1121
+ if (!rowId || seenRows.has(rowId)) throw new Error(`action listing repeated or omitted identity at ${offset + i}`)
1122
+ seenRows.add(rowId)
333
1123
  if (!matches(a)) continue
334
1124
  seen.push(`${a.status}${a.reference ? '' : '/no-ref'}`)
335
1125
  if (a.reference && ABORTABLE.has(a.status) && !aborted.has(a.reference)) {
336
1126
  aborted.add(a.reference)
1127
+ assertVaultScope(scopeToken)
337
1128
  await w.abortAction({ reference: a.reference }, adminOriginator).catch(err =>
338
1129
  console.log('[vault] abortAction rejected:', (err as Error)?.message)
339
1130
  )
1131
+ assertVaultScope(scopeToken)
340
1132
  }
341
1133
  }
342
1134
  offset += actions.length
1135
+ if (expectedTotal !== undefined) {
1136
+ if (offset > expectedTotal) throw new Error('action listing exceeded its total')
1137
+ if (offset === expectedTotal) break
1138
+ } else if (actions.length < 200) {
1139
+ break
1140
+ }
343
1141
  }
344
1142
  console.log(
345
1143
  '[vault] abort scan · scanned=%d · matches=[%s] · aborted=%d',
@@ -354,10 +1152,15 @@ async function abortActions(
354
1152
  }
355
1153
 
356
1154
  /** Abort the orphaned transactions the review error blames, by txid. */
357
- async function abortReservingTxids(w: VaultWallet, adminOriginator: string, txids: string[]): Promise<number> {
1155
+ async function abortReservingTxids(
1156
+ w: VaultWallet,
1157
+ adminOriginator: string,
1158
+ txids: string[],
1159
+ scopeToken?: VaultScopeToken
1160
+ ): Promise<number> {
358
1161
  if (txids.length === 0) return 0
359
1162
  const want = new Set(txids)
360
- return await abortActions(w, adminOriginator, a => a.txid != null && want.has(a.txid), { stopAfter: want.size })
1163
+ return await abortActions(w, adminOriginator, a => a.txid != null && want.has(a.txid), { stopAfter: want.size }, scopeToken)
361
1164
  }
362
1165
 
363
1166
  /** Abort the orphaned transactions holding these outpoints, matched on each
@@ -367,7 +1170,8 @@ async function abortReservingOutpoints(
367
1170
  w: VaultWallet,
368
1171
  adminOriginator: string,
369
1172
  outpoints: string[],
370
- findSpendingReferences?: SpendingReferenceLookup
1173
+ findSpendingReferences?: SpendingReferenceLookup,
1174
+ scopeToken?: VaultScopeToken
371
1175
  ): Promise<number> {
372
1176
  if (outpoints.length === 0) return 0
373
1177
 
@@ -378,14 +1182,18 @@ async function abortReservingOutpoints(
378
1182
  // retry parsed thousands of transactions to find one outpoint.
379
1183
  if (findSpendingReferences) {
380
1184
  try {
1185
+ assertVaultScope(scopeToken)
381
1186
  const rows = await findSpendingReferences(outpoints)
1187
+ assertVaultScope(scopeToken)
382
1188
  const aborted = new Set<string>()
383
1189
  for (const r of rows) {
384
1190
  if (!ABORTABLE.has(r.status) || aborted.has(r.reference)) continue
385
1191
  aborted.add(r.reference)
1192
+ assertVaultScope(scopeToken)
386
1193
  await w.abortAction({ reference: r.reference }, adminOriginator).catch(err =>
387
1194
  console.log('[vault] abortAction rejected:', (err as Error)?.message)
388
1195
  )
1196
+ assertVaultScope(scopeToken)
389
1197
  }
390
1198
  console.log('[vault] abort by outpoint · matched=%d · aborted=%d', rows.length, aborted.size)
391
1199
  return aborted.size
@@ -401,8 +1209,10 @@ async function abortReservingOutpoints(
401
1209
  adminOriginator,
402
1210
  a => (a.inputs ?? []).some(i => i.sourceOutpoint != null && want.has(sameOutpoint(i.sourceOutpoint))),
403
1211
  // No count to stop at: one orphan can hold several of our outpoints, and
404
- // several orphans can each hold one. The 25-page cap is the bound.
405
- { includeInputs: true, stopAfter: Number.POSITIVE_INFINITY }
1212
+ // several orphans can each hold one. Pagination is guarded by row identity
1213
+ // and the provider's stable total rather than an arbitrary page cap.
1214
+ { includeInputs: true, stopAfter: Number.POSITIVE_INFINITY },
1215
+ scopeToken
406
1216
  )
407
1217
  }
408
1218
 
@@ -420,22 +1230,23 @@ async function freeReservedInputs(
420
1230
  adminOriginator: string,
421
1231
  e: unknown,
422
1232
  ours: string[],
423
- findSpendingReferences?: SpendingReferenceLookup
1233
+ findSpendingReferences?: SpendingReferenceLookup,
1234
+ scopeToken?: VaultScopeToken
424
1235
  ): Promise<number> {
425
1236
  if (isReviewActionsError(e)) {
426
- return await abortReservingTxids(w, adminOriginator, competingTxids(e))
1237
+ return await abortReservingTxids(w, adminOriginator, competingTxids(e), scopeToken)
427
1238
  }
428
1239
  const mine = new Set(ours.map(sameOutpoint))
429
1240
  const wedged = unspendableInputOutpoints(e).filter(o => mine.has(o))
430
- return await abortReservingOutpoints(w, adminOriginator, wedged, findSpendingReferences)
1241
+ return await abortReservingOutpoints(w, adminOriginator, wedged, findSpendingReferences, scopeToken)
431
1242
  }
432
1243
 
433
1244
  /**
434
1245
  * Refuse a vault transfer while offline.
435
1246
  *
436
- * Checked before anything else: before the deposit's backup attestation, and
437
- * before the withdrawal arms the YubiKey — an offline user must not be asked to
438
- * present a key for a transfer that cannot proceed.
1247
+ * Checked before anything else, including before a withdrawal arms the
1248
+ * YubiKey: an offline user must not be asked to present a key for a transfer
1249
+ * that cannot proceed.
439
1250
  */
440
1251
  async function requireOnline(opts?: VaultTransferOptions): Promise<void> {
441
1252
  if (!opts?.isOnline) return
@@ -446,706 +1257,1765 @@ async function requireOnline(opts?: VaultTransferOptions): Promise<void> {
446
1257
 
447
1258
  // ── balance ─────────────────────────────────────────────────────────────
448
1259
 
1260
+ /**
1261
+ * Sum of every strictly authenticated current-format output in the basket.
1262
+ * Missing instructions, malformed data, source-value mismatches, and locks
1263
+ * that do not exactly match their records fail the whole scan closed.
1264
+ * includeCustomInstructions is required: listOutputs omits the field unless
1265
+ * asked, and without it everything would read as undecodable.
1266
+ */
449
1267
  export async function getVaultBalance(w: VaultWallet, adminOriginator: string): Promise<number> {
450
- const res = await w.listOutputs({ basket: VAULT_BASKET, limit: 1000 }, adminOriginator)
451
- return res.outputs.reduce((sum, o) => sum + (o.satoshis ?? 0), 0)
1268
+ const scopeToken = vaultStore.captureScopeToken()
1269
+ const { state } = await reduceVerifiedVaultOutputs(
1270
+ w,
1271
+ adminOriginator,
1272
+ () => ({ satoshis: 0 }),
1273
+ (balance, output) => {
1274
+ balance.satoshis += output.satoshis
1275
+ if (!Number.isSafeInteger(balance.satoshis)) {
1276
+ throw new VaultError('no-transaction', 'Vault balance value exceeds the safe integer range')
1277
+ }
1278
+ },
1279
+ scopeToken
1280
+ )
1281
+ assertVaultScope(scopeToken)
1282
+ return state.satoshis
452
1283
  }
453
1284
 
454
- // ── deposit ─────────────────────────────────────────────────────────────
455
-
456
- /**
457
- * Move `satoshis` from the default basket into the vault.
458
- *
459
- * Costs exactly one tap, and every refusal is checked BEFORE it: a user must
460
- * never be asked to present a key for a transfer that was never going to
461
- * proceed, and — because the tap gates the derivation, and nothing is spent
462
- * until the single createAction below it — cancelling it moves no money.
463
- *
464
- * `reason` is what the ceremony sheet shows while the key is armed.
465
- */
466
- export async function depositToVault(
1285
+ /** Restore a missing scoped cache only from currently spendable outputs whose
1286
+ * real source values, exact R1C locks, salted commitments, v6 recovery records, and
1287
+ * wallet salt-key derivations all authenticate. Conflict selection belongs to
1288
+ * VaultKeyService; possession of a restored key is still required separately
1289
+ * before any spend. */
1290
+ export async function recoverVaultMetaFromOutputs(
467
1291
  w: VaultWallet,
468
- adminOriginator: string,
469
- satoshis: number,
470
- reason: string,
471
- opts?: VaultTransferOptions
472
- ): Promise<{ txid: string }> {
473
- await requireOnline(opts)
474
-
475
- // Depositing into a wallet with no recovery path would hide funds behind a
476
- // hardware key the user cannot get past. Advisory — the wizard is the real
477
- // gate — but it also covers the deep link straight to the transfer screen.
478
- //
479
- // DELIBERATELY NOT in nextDepositTarget, even though that is the single
480
- // funnel for every vault-basket output: partial withdrawals re-vault their
481
- // remainder through it, so a check there would block withdrawals.
482
- //
483
- // Checked BEFORE the tap (and so before nextDepositTarget) so a refusal
484
- // neither raises a ceremony nor burns a deposit index.
485
- const { publicKey: identityKey } = await w.getPublicKey({ identityKey: true }, adminOriginator)
486
- if (!(await backupAttestation.get(identityKey))) {
487
- throw new VaultError('backup-required', 'Back up this wallet before depositing')
488
- }
489
-
490
- // ── the tap ─────────────────────────────────────────────────────────────
491
- //
492
- // A deposit address is a child of the vault node and there is no stored
493
- // xpub, so this is the only way to produce one. release() in the finally is
494
- // what drops the key and (on iOS) dismisses the NFC sheet — it must fire
495
- // whether the deposit succeeds or fails to build.
496
- const handle = await requestVaultKey(reason)
497
- try {
498
- return await lockDeposit(w, adminOriginator, satoshis, handle)
499
- } finally {
500
- handle.release()
501
- }
1292
+ adminOriginator: string
1293
+ ): Promise<VaultMeta | null> {
1294
+ const scopeToken = vaultStore.captureScopeToken()
1295
+ return await withVaultMutation(async () => {
1296
+ assertVaultScope(scopeToken)
1297
+ const existing = await vaultStore.getMeta(scopeToken)
1298
+ if (existing) return existing
1299
+ const scan = await reduceVerifiedVaultOutputs(
1300
+ w,
1301
+ adminOriginator,
1302
+ () => [] as { instructions: VaultInstructions; txid: string }[],
1303
+ (records, output) => records.push({
1304
+ instructions: output.ci,
1305
+ txid: output.outpoint.slice(0, 64).toLowerCase()
1306
+ }),
1307
+ scopeToken
1308
+ )
1309
+ if (scan.outputs === 0) return null
1310
+ await verifyVaultSaltDerivations(w, adminOriginator, scan.inventory)
1311
+ const recovered = metaFromVerifiedOutputs(scan.state)
1312
+ await vaultStore.restoreVerifiedMeta(recovered, scopeToken)
1313
+ return await vaultStore.getMeta(scopeToken)
1314
+ })
502
1315
  }
503
1316
 
504
1317
  /**
505
- * The deposit itself, run inside an armed ceremony: ONE ordinary createAction
506
- * carrying the vault output, funded by the toolbox's own coin selection and
507
- * change machinery.
508
- *
509
- * This used to be two chained transactions (tx1 staged exact funding into
510
- * VAULT_STAGING_BASKET, tx2 spent only that into the vault) so that the
511
- * ~960 KB R1-K1 script never shared a transaction with a default-basket
512
- * change output — change born next to it dragged the whole script into the
513
- * inputBEEF of every later payment that spent that change. A K1 vault output
514
- * is a 25-byte P2PKH lock, so that cost is gone and the deposit is one
515
- * transaction like any other spend. The 'vault-deposit' label still matters:
516
- * the patched toolbox (see patches/) suppresses UTXO-pool growth for it, so
517
- * the deposit stays minimal — at most one change output — instead of
518
- * splitting change toward numberOfDesiredUTXOs.
519
- *
520
- * `handle` is operation-scoped: `hd` is read once, at its only point of use,
521
- * and neither the handle nor the node is stored anywhere that outlives this
522
- * call (see VaultKeyHandle). A released or relocked handle refuses there.
1318
+ * Clear authorization metadata only after an authoritative, serialized empty
1319
+ * check. In addition to spendable outputs, any non-final vault action blocks
1320
+ * disablement: a signed withdrawal/re-lock may temporarily reserve its source
1321
+ * while its replacement is not listable yet.
523
1322
  *
524
- * KNOWN TRADE: the deposit index is taken BEFORE createAction, so a funding
525
- * failure (insufficient change for deposit + fee) burns an index the old
526
- * two-tx flow would not have (its derivation ran only after tx1 landed).
527
- * Accepted deliberately: index holes are harmless — withdraw and sweep read
528
- * each output's STORED keyID, nothing ever walks the index space — and the
529
- * alternative (deriving after createAction) would spend real money before
530
- * knowing an address exists for it.
1323
+ * Returns false for a funded or pending vault and leaves metadata untouched.
1324
+ * Read errors throw and therefore also fail closed.
531
1325
  */
532
- async function lockDeposit(
1326
+ export async function disableVaultWhenSafe(
533
1327
  w: VaultWallet,
534
1328
  adminOriginator: string,
535
- satoshis: number,
536
- handle: VaultKeyHandle
537
- ): Promise<{ txid: string }> {
538
- // Announce work before starting it: the ceremony sheet is on screen for the
539
- // whole deposit, and this also refreshes the retention window so a slow
540
- // createAction cannot have the key relocked out from under it.
541
- noteVaultProgress({ phase: 'preparing' })
542
- const target = await nextDepositTarget(handle.hd)
543
-
544
- // One call builds, signs AND broadcasts: with no caller-supplied inputs
545
- // there is no signableTransaction step — every funding input is toolbox
546
- // change the toolbox signs itself. Undelayed, so a failed broadcast surfaces
547
- // here rather than leaving the deposit looking sent while it sits in the
548
- // monitor's queue.
549
- noteVaultProgress({ phase: 'broadcasting' })
550
- const created = await w.createAction(
551
- {
552
- description: 'Move to vault',
553
- outputs: [
554
- {
555
- satoshis,
556
- lockingScript: target.lockingScript,
557
- outputDescription: 'Vault deposit',
558
- basket: VAULT_BASKET,
559
- customInstructions: encodeVaultInstructions(target.instructions),
560
- tags: ['vault']
1329
+ clearMetadata: (scopeToken?: VaultScopeToken) => Promise<void>
1330
+ ): Promise<boolean> {
1331
+ const scopeToken = vaultStore.captureScopeToken()
1332
+ return await withVaultMutation(async () => {
1333
+ assertVaultScope(scopeToken)
1334
+ const meta = await vaultStore.getMeta(scopeToken)
1335
+ if (!meta || meta.pendingRemoval) return false
1336
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
1337
+ if (await vaultHasOutputs(w, adminOriginator, scopeToken)) return false
1338
+
1339
+ let blocked = false
1340
+ await scanVaultActions(w, adminOriginator, {
1341
+ labels: [],
1342
+ includeLabels: true,
1343
+ includeInputs: true,
1344
+ includeInputSourceLockingScripts: true,
1345
+ includeOutputs: true,
1346
+ includeOutputLockingScripts: true
1347
+ }, action => {
1348
+ const labels = new Set(action.labels ?? [])
1349
+ const inputs = action.inputs ?? []
1350
+ const r1cInputs = inputs.filter(input => isR1CSourceScript(input.sourceLockingScript))
1351
+ const claimsSpend = actionClaimsVaultSpend(action)
1352
+ // A posted transaction (BROADCAST_ACTION_STATUSES) reserves nothing this
1353
+ // check cannot already see: it has a txid and its outputs are ordinary
1354
+ // unconfirmed UTXOs, which is why reconcileHeldVaultDeposits skips the
1355
+ // same statuses. Only a signed-but-unposted action can hold a Vault
1356
+ // source back invisibly, and `unproven` can stand for hours — or never
1357
+ // resolve locally — so treating it as live refuses a drained Vault its
1358
+ // disablement for as long as the merkle proof is missing.
1359
+ const reserving =
1360
+ PENDING_ACTION_STATUSES.has(action.status) && !BROADCAST_ACTION_STATUSES.has(action.status)
1361
+ // Only a live action can still be holding a Vault source back, and its
1362
+ // source scripts are evidence for that decision only while it is live.
1363
+ // Settled history cannot satisfy this rule and must not be asked to:
1364
+ // storage RESTORES the sources of a terminally failed action and clears
1365
+ // their `spentBy`, which is exactly what empties `inputs` here, and
1366
+ // completed pre-release spends predate this template (see
1367
+ // inspectHiddenVaultReservations). Demanding exact R1C sources from
1368
+ // either shape reads an ordinary drained history as malformed and
1369
+ // refuses to disable an empty Vault for good.
1370
+ if (reserving && claimsSpend && (inputs.length === 0 || r1cInputs.length !== inputs.length)) {
1371
+ throw new VaultError('template-invalid', 'Vault action history has missing or malformed R1C source scripts')
1372
+ }
1373
+ const vaultOutputs = (action.outputs ?? []).filter(output => output.basket === VAULT_BASKET)
1374
+ for (const output of vaultOutputs) {
1375
+ const ci = decodeVaultInstructions(output.customInstructions)
1376
+ if (!ci || !output.lockingScript) {
1377
+ throw new VaultError('template-invalid', 'Vault action history has unreadable output metadata or script')
561
1378
  }
562
- ],
563
- labels: ['vault', 'vault-deposit'],
564
- options: { randomizeOutputs: false, acceptDelayedBroadcast: false }
565
- },
566
- adminOriginator
567
- )
568
- const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
569
- if (!txid) throw new VaultError('no-transaction', 'Deposit produced no transaction')
570
- return { txid }
1379
+ if (ci.chain !== scopeToken.chain) {
1380
+ throw new VaultError('template-invalid', 'Vault action history output belongs to a different network')
1381
+ }
1382
+ let lock: LockingScript
1383
+ try {
1384
+ lock = LockingScript.fromHex(output.lockingScript)
1385
+ } catch {
1386
+ throw new VaultError('template-invalid', 'Vault action history has a malformed output script')
1387
+ }
1388
+ verifyInstructionsAgainstLock(ci, lock, 'Vault action history output')
1389
+ }
1390
+ const touchesVault =
1391
+ r1cInputs.length > 0 ||
1392
+ vaultOutputs.length > 0 ||
1393
+ labels.has('vault-withdraw') ||
1394
+ labels.has('vault-relock') ||
1395
+ labels.has('vault-deposit')
1396
+ if (reserving && touchesVault) blocked = true
1397
+ if (action.status === 'failed') {
1398
+ // A failed deposit has no Vault source to hide. A failed spend still
1399
+ // listing inputs has NOT been unwound — storage drops `spentBy` in the
1400
+ // same write that makes the source spendable again — so it may still
1401
+ // be hiding a Vault output from listOutputs, and labels/scripts that
1402
+ // cannot classify it fail closed the same way. A failed spend listing
1403
+ // no inputs at all is holding nothing back, and the authoritative
1404
+ // empty check is then the only word that counts.
1405
+ if (r1cInputs.length > 0 || (claimsSpend && inputs.length > 0)) {
1406
+ blocked = true
1407
+ }
1408
+ }
1409
+ }, scopeToken, true)
1410
+ if (blocked) return false
1411
+ // A completed output can be absent from listOutputs but still be the only
1412
+ // durable recovery record for this enrollment. Authenticate every history
1413
+ // HMAC before allowing its local descriptor to be cleared.
1414
+ await addHistoricalVaultSaltInventory(
1415
+ w,
1416
+ adminOriginator,
1417
+ emptyVaultSaltInventory(),
1418
+ meta,
1419
+ scopeToken
1420
+ )
1421
+ // The monitor is outside the JS mutex. Re-read immediately before the
1422
+ // destructive metadata clear so an output that became visible during the
1423
+ // action scan blocks the operation.
1424
+ if (await vaultHasOutputs(w, adminOriginator, scopeToken)) return false
1425
+ assertVaultScope(scopeToken)
1426
+ await clearMetadata(scopeToken)
1427
+ assertVaultScope(scopeToken)
1428
+ return true
1429
+ })
571
1430
  }
572
1431
 
573
- // ── legacy staging reclaim ────────────────────────────────────────────────
1432
+ // ── vault outputs ────────────────────────────────────────────────────────
574
1433
 
575
- export interface ReclaimResult {
576
- /** Absent when there was nothing to reclaim. */
577
- txid?: string
578
- /** How many staging outputs the reclaim spent. */
579
- reclaimed: number
580
- /** Their total value (the fee comes out of it; the rest returns as change). */
1434
+ /**
1435
+ * One new vault output committed to `keys` (spec §4.1 step 3, §2.7).
1436
+ *
1437
+ * Each salt is the wallet's 32-byte createHmac result under the next positive
1438
+ * 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.
1447
+ */
1448
+ interface VaultOutputSpec {
581
1449
  satoshis: number
1450
+ lockingScript: string
1451
+ outputDescription: string
1452
+ basket: string
1453
+ customInstructions: string
1454
+ tags: string[]
1455
+ }
1456
+
1457
+ async function newVaultOutput(
1458
+ w: VaultWallet,
1459
+ adminOriginator: string,
1460
+ meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys'>,
1461
+ satoshis: number,
1462
+ outputDescription: string,
1463
+ inventory: VaultSaltInventory,
1464
+ chain: VaultScopeToken['chain']
1465
+ ): Promise<VaultOutputSpec> {
1466
+ const pubkeys = meta.keys.map(k => k.pubkey)
1467
+ const keyIndex = inventory.maxKeyIndex + 1
1468
+ if (!Number.isSafeInteger(keyIndex)) {
1469
+ throw new VaultError('template-invalid', 'Vault salt key index is exhausted')
1470
+ }
1471
+ const saltKeyId = String(keyIndex)
1472
+ const salt = await deriveVaultSalt(w, adminOriginator, saltKeyId, meta.keys.map(key => key.serial))
1473
+ const lockingScript = buildLock({ commitments: pubkeys.map(pk => commitment(pk, salt)), saltHex64: salt })
1474
+ const output: VaultOutputSpec = {
1475
+ satoshis,
1476
+ lockingScript: lockingScript.toHex(),
1477
+ outputDescription,
1478
+ 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
+ }),
1490
+ tags: ['vault']
1491
+ }
1492
+ const ci = decodeVaultInstructions(output.customInstructions)
1493
+ if (!ci) throw new VaultError('template-invalid', 'Derived Vault output metadata is invalid')
1494
+ rememberVaultSalt(inventory, ci, lockingScript, `pending:${saltKeyId}`, chain)
1495
+ return output
582
1496
  }
583
1497
 
584
1498
  /**
585
- * Recover money the retired two-transaction deposit stranded.
1499
+ * The availability gate (spec D15 / §5.5, task 11). Gates every path that
1500
+ * CREATES a vault output; never a withdrawal of pre-existing outputs.
586
1501
  *
587
- * The old flow could leave a funded staging output behind (tx1 landed, tx2
588
- * failed — the 2026-08-22 device crash mid-deposit is exactly this shape),
589
- * and that money is INVISIBLE: the main balance counts only the 'default'
590
- * basket and the vault balance only 'admin vault', so a stranded coin shows
591
- * up in neither. Now that deposits no longer consume staging outputs, this
592
- * sweep is the only way that money comes back.
1502
+ * Two halves, matching `isVaultAvailable`. The build flag is injectable so this
1503
+ * module stays config-free in tests; the mainnet rule is not injectable and
1504
+ * takes its chain from the operation's own scope token rather than a module
1505
+ * read of `vaultStore.getScope()`. That token is captured before the first
1506
+ * await and re-asserted by the `assertVaultScope` immediately preceding every
1507
+ * call here, so a network switch landing mid-flight aborts the operation
1508
+ * instead of letting it write an output under the wrong chain — a live
1509
+ * `getScope()` read would simply see the new chain and carry on.
593
1510
  *
594
- * Spends EVERY decodable staging output regardless of amount — unlike the old
595
- * deposit-time reuse, which matched by exact satoshis — with no outputs of its
596
- * own, so the toolbox returns the whole value (minus fee) as default-basket
597
- * change. The staging key is an ordinary BRC-42 wallet key (counterparty
598
- * 'self'), so no ceremony, no tap, no vault HD node is involved.
1511
+ * In production `opts.vaultEnabled` is never supplied, so the first check is
1512
+ * exactly the build half and the second reduces to the chain half.
1513
+ */
1514
+ function requireReleased(opts: VaultTransferOptions | undefined, scopeToken: VaultScopeToken, what: string): void {
1515
+ const enabled = opts?.vaultEnabled ?? isVaultEnabled
1516
+ if (!enabled()) throw new VaultError('not-released', `${what} is switched off in this build`)
1517
+ if (!isVaultAvailable(scopeToken.chain)) {
1518
+ throw new VaultError('not-on-mainnet', `${what} is only available on mainnet`)
1519
+ }
1520
+ }
1521
+
1522
+ /** A real private-backup configuration needs both a host endpoint and the
1523
+ * user's permission to push. The preference alone defaults to true and is not
1524
+ * evidence that any backup service exists. */
1525
+ async function defaultPrivateBackupEnabled(): Promise<boolean> {
1526
+ try {
1527
+ return getBackupUrl() !== '' && await isBackupPushEnabled()
1528
+ } catch {
1529
+ return false
1530
+ }
1531
+ }
1532
+
1533
+ /** Gate creation of an R1C output. This confirms configuration only; the
1534
+ * asynchronous backup monitor does not provide an exact-record receipt. */
1535
+ async function requirePrivateBackup(opts: VaultTransferOptions | undefined, what: string): Promise<void> {
1536
+ const enabled = opts?.backupEnabled ?? defaultPrivateBackupEnabled
1537
+ if (!(await enabled())) {
1538
+ throw new VaultError('backup-off', `${what} requires encrypted private backup`)
1539
+ }
1540
+ }
1541
+
1542
+ /** The enrolled key list, or the refusal an output-creating operation owes. */
1543
+ async function requireMeta(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1544
+ const meta = await vaultStore.getMeta(scopeToken)
1545
+ if (!meta) throw new VaultError('not-enrolled', 'Vault is not set up')
1546
+ if (meta.keys.length < VAULT_MIN_KEYS) {
1547
+ throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${meta.keys.length} enrolled`)
1548
+ }
1549
+ return meta
1550
+ }
1551
+
1552
+ /**
1553
+ * A `sendWith` release is successful only when the wallet reports exactly the
1554
+ * transaction we asked it to release in a state the toolbox defines as
1555
+ * accepted or queued for retry. Missing, duplicate, unrelated, failed, and
1556
+ * future/unknown statuses are all ambiguous and therefore remain held.
1557
+ */
1558
+ function requireReleasedHeldTransaction(
1559
+ released: CreateActionResult,
1560
+ txid: string,
1561
+ description: string
1562
+ ): void {
1563
+ const results = released.sendWithResults
1564
+ if (
1565
+ !Array.isArray(results) ||
1566
+ results.length !== 1 ||
1567
+ typeof results[0]?.txid !== 'string' ||
1568
+ results[0].txid.toLowerCase() !== txid.toLowerCase() ||
1569
+ (results[0].status !== 'sending' && results[0].status !== 'unproven')
1570
+ ) {
1571
+ throw new VaultError('no-transaction', `Wallet did not confirm release of the held ${description}`)
1572
+ }
1573
+ }
1574
+
1575
+ type VaultOutputPlan = VaultOutputSpec
1576
+
1577
+ /**
1578
+ * 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.
1583
+ */
1584
+ function validateDepositPlan(tx: Transaction, expected: VaultOutputPlan): void {
1585
+ if (tx.version !== 1) {
1586
+ throw new VaultError('bad-version', `Vault deposit is version ${tx.version}; expected 1`)
1587
+ }
1588
+ if (tx.inputs.length === 0 || tx.inputs.length > VAULT_HARD_MAX_INPUTS) {
1589
+ throw new VaultError('no-transaction', 'Vault deposit has an invalid wallet funding input count')
1590
+ }
1591
+
1592
+ let inputValue = 0
1593
+ const seenInputs = new Set<string>()
1594
+ for (const input of tx.inputs) {
1595
+ const txid = (input.sourceTXID ?? input.sourceTransaction?.id('hex'))?.toLowerCase()
1596
+ const vout = input.sourceOutputIndex
1597
+ if (!txid || !/^[0-9a-f]{64}$/.test(txid) || !Number.isSafeInteger(vout) || vout < 0) {
1598
+ throw new VaultError('no-transaction', 'Vault deposit has an invalid wallet funding outpoint')
1599
+ }
1600
+ const outpoint = `${txid}.${vout}`
1601
+ if (seenInputs.has(outpoint)) throw new VaultError('no-transaction', `Vault deposit repeats funding input ${outpoint}`)
1602
+ seenInputs.add(outpoint)
1603
+ const source = input.sourceTransaction?.outputs[vout]
1604
+ const sourceSatoshis = source?.satoshis
1605
+ if (typeof sourceSatoshis !== 'number' || !Number.isSafeInteger(sourceSatoshis) || sourceSatoshis < 0) {
1606
+ throw new VaultError('no-transaction', `Vault deposit has no authenticated value for funding input ${outpoint}`)
1607
+ }
1608
+ inputValue += sourceSatoshis
1609
+ if (!Number.isSafeInteger(inputValue)) throw new VaultError('no-transaction', 'Vault deposit input value overflow')
1610
+ }
1611
+
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')
1620
+ }
1621
+ const implicit = tx.outputs.slice(1)
1622
+ if (implicit.length > 1) throw new VaultError('no-transaction', 'Wallet injected an unexpected Vault deposit output')
1623
+ let outputValue = expected.satoshis
1624
+ if (implicit.length === 1) {
1625
+ const change = implicit[0]
1626
+ const changeSatoshis = change.satoshis
1627
+ if (
1628
+ typeof changeSatoshis !== 'number' ||
1629
+ !Number.isSafeInteger(changeSatoshis) ||
1630
+ changeSatoshis <= 0 ||
1631
+ !isStandardP2PKH(change.lockingScript)
1632
+ ) {
1633
+ throw new VaultError('no-transaction', 'Vault deposit has invalid implicit wallet change')
1634
+ }
1635
+ outputValue += changeSatoshis
1636
+ if (!Number.isSafeInteger(outputValue)) throw new VaultError('no-transaction', 'Vault deposit output value overflow')
1637
+ }
1638
+ const fee = inputValue - outputValue
1639
+ // Add a conservative P2PKH witness allowance when checking the unsigned
1640
+ // proposal; on the signed pass this merely makes the same ceiling looser by
1641
+ // a small fixed amount.
1642
+ const signedSizeCeiling = tx.toBinary().length + tx.inputs.length * 110
1643
+ const maxFee = Math.max(200, Math.ceil(signedSizeCeiling / 1000) * 200)
1644
+ if (!Number.isSafeInteger(fee) || fee < 0 || fee > maxFee) {
1645
+ throw new VaultError('no-transaction', `Vault deposit fee ${fee} exceeds the safety ceiling ${maxFee}`)
1646
+ }
1647
+ if (implicit.length === 0 && inputValue - expected.satoshis > maxFee) {
1648
+ throw new VaultError('no-transaction', 'Vault deposit omitted expected wallet change')
1649
+ }
1650
+ }
1651
+
1652
+ // ── deposit ─────────────────────────────────────────────────────────────
1653
+
1654
+ /**
1655
+ * Move `satoshis` from the default basket into the vault (spec §4.1).
1656
+ *
1657
+ * No hardware: a deposit needs the key LIST, not a key. Every refusal is
1658
+ * checked BEFORE the one createAction below, cheapest first, and nothing is
1659
+ * spent until it runs. A pre-creation refusal consumes no numeric salt ID.
1660
+ * Once createAction persists an output, pending and failed history retain its
1661
+ * ID so a later output cannot reuse it.
599
1662
  *
600
- * Safe to call speculatively: returns {reclaimed: 0} without touching the
601
- * wallet when the basket is empty.
1663
+ * Salt derivation is deterministic, but the full ordered YubiKey serial/public
1664
+ * key descriptor remains separate wallet metadata. A configured, enabled
1665
+ * encrypted private backup is therefore a precondition for moving new funds.
602
1666
  */
603
- export async function reclaimStagingOutputs(
1667
+ export async function depositToVault(
604
1668
  w: VaultWallet,
605
1669
  adminOriginator: string,
606
- opts?: {
607
- /**
608
- * Storage-backed release of staging outputs stranded by a definitively
609
- * invalid spender. Returns how many outputs were made spendable again.
610
- *
611
- * Runs FIRST because a stranded coin usually sits spendable=0: when the
612
- * old tx2 failed, the toolbox restored its inputs but then re-stranded
613
- * them — markStaleInputsAsSpent asked the indexers whether the staging
614
- * outpoint was a UTXO seconds after tx1 broadcast, and indexer lag
615
- * answered "no" — and listOutputs only returns spendable coins. See
616
- * releaseVaultStagingStrandedByInvalidTx in StorageExpoSQLite for the
617
- * deliberately narrow predicate.
618
- */
619
- releaseStrandedStaging?: () => Promise<number>
620
- /** Storage-backed reservation heal for the retry below. See SpendingReferenceLookup. */
621
- findSpendingReferences?: SpendingReferenceLookup
622
- }
623
- ): Promise<ReclaimResult> {
624
- if (opts?.releaseStrandedStaging) {
625
- await opts.releaseStrandedStaging().catch(e => {
626
- console.log('[vault] stranded-staging release failed:', (e as Error)?.message)
627
- return 0
628
- })
629
- }
630
-
631
- const staged = (await w.listOutputs(
632
- { basket: VAULT_STAGING_BASKET, include: 'entire transactions', includeCustomInstructions: true, limit: 100 },
633
- adminOriginator
634
- )) as ListOutputsResult
635
- const coins = staged.outputs
636
- .map(o => ({ ...o, si: decodeStagingInstructions(o.customInstructions) }))
637
- .filter((o): o is typeof o & { si: StagingInstructions } => o.si != null)
638
- if (coins.length === 0) return { reclaimed: 0, satoshis: 0 }
639
-
640
- const totalSats = coins.reduce((s, c) => s + c.satoshis, 0)
641
- const caArgs = {
642
- description: 'Recover vault deposit funding',
643
- inputs: coins.map(c => ({
644
- outpoint: c.outpoint,
645
- unlockingScriptLength: STAGING_UNLOCK_LEN,
646
- inputDescription: 'Stranded vault deposit funding'
647
- })),
648
- outputs: [],
649
- // 'vault-deposit' is load-bearing twice: the patched toolbox suppresses
650
- // UTXO-pool growth for it (no extra funding inputs pulled in), and the
651
- // stranded-release predicates (both arms — spendable=0 re-strands AND
652
- // stale spentBy on spendable=1 coins, see findSql.ts) match on it — so if
653
- // THIS transaction fails at broadcast and re-strands the coins, the same
654
- // heal releases them for the next attempt. 'vault-reclaim' is for
655
- // history and forensics only.
656
- labels: ['vault', 'vault-deposit', 'vault-reclaim'],
657
- // Mandatory, not an optimization: these inputs carry unlockingScriptLength
658
- // and no unlockingScript, so isSignAction is true and the signer resolves
659
- // each input's sourceTransaction ONLY from args.inputBEEF. trustSelf just
660
- // skips storage re-walking proof ancestry for our own coins.
661
- inputBEEF: staged.BEEF?.length ? staged.BEEF : undefined,
662
- options: { randomizeOutputs: false, acceptDelayedBroadcast: false, trustSelf: 'known' }
663
- }
664
- let created: CreateActionResult
665
- try {
666
- created = await w.createAction(caArgs, adminOriginator)
667
- } catch (e) {
668
- // A prior failed attempt (or a concurrent reclaim from a quick screen
669
- // remount) can leave a coin reserved by an orphaned transaction, and until
670
- // that is aborted every later reclaim is refused outright — the same
671
- // wedge the withdraw path heals. Abort it and retry ONCE; anything else
672
- // frees nothing and rethrows untouched.
673
- const freed = await freeReservedInputs(
674
- w,
675
- adminOriginator,
676
- e,
677
- coins.map(c => c.outpoint),
678
- opts?.findSpendingReferences
679
- )
680
- if (freed === 0) throw e
681
- created = await w.createAction(caArgs, adminOriginator)
1670
+ satoshis: number,
1671
+ opts?: VaultTransferOptions
1672
+ ): Promise<{ txid: string }> {
1673
+ const scopeToken = vaultStore.captureScopeToken()
1674
+ return await withVaultMutation(async () => {
1675
+ assertVaultScope(scopeToken)
1676
+ requireReleased(opts, scopeToken, 'Vault deposit')
1677
+ if (!Number.isSafeInteger(satoshis) || satoshis < VAULT_DEPOSIT_MIN) {
1678
+ throw new VaultError('below-dust', `Vault deposits must be at least ${VAULT_DEPOSIT_MIN} satoshis`)
682
1679
  }
683
-
684
- if (!created.signableTransaction) {
685
- const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
686
- if (!txid) throw new VaultError('no-transaction', 'Reclaim produced no transaction')
687
- return { txid, reclaimed: coins.length, satoshis: totalSats }
1680
+ await requireOnline(opts)
1681
+ assertVaultScope(scopeToken)
1682
+ await requirePrivateBackup(opts, 'Vault deposit')
1683
+ assertVaultScope(scopeToken)
1684
+ const meta = await requireMeta(scopeToken)
1685
+ if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal before depositing')
1686
+ if (meta.recovery?.required) {
1687
+ const adopted = new Set(meta.recovery.adoptedSerials)
1688
+ if (meta.keys.filter(key => adopted.has(key.serial)).length < VAULT_MIN_KEYS) {
1689
+ throw new VaultError('key-not-adopted', 'Verify at least two recovered YubiKeys before depositing new funds')
1690
+ }
688
1691
  }
1692
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
1693
+ const existing = await reduceVerifiedVaultOutputs(
1694
+ w,
1695
+ adminOriginator,
1696
+ () => undefined,
1697
+ (_state, output) => requireOutputMetaConsistency([output], meta),
1698
+ scopeToken,
1699
+ 'repair-unsigned'
1700
+ )
1701
+ const saltInventory = existing.inventory
1702
+ await addHistoricalVaultSaltInventory(w, adminOriginator, saltInventory, meta, scopeToken)
689
1703
 
690
- const { tx: atomic, reference } = created.signableTransaction
691
- const spends: Record<number, { unlockingScript: string }> = {}
1704
+ const output = await newVaultOutput(
1705
+ w,
1706
+ adminOriginator,
1707
+ meta,
1708
+ satoshis,
1709
+ 'Vault deposit',
1710
+ saltInventory,
1711
+ scopeToken.chain
1712
+ )
1713
+ let reference: string | undefined
1714
+ let heldTxid: string | undefined
1715
+ let broadcastAttempted = false
692
1716
  try {
693
- const tx = Transaction.fromAtomicBEEF(atomic)
694
- for (const c of coins) {
695
- // Preimage formatting is O(tx size) per input; yield between inputs so a
696
- // large reclaim cannot hang the JS thread (same reasoning as the
697
- // withdraw signing loop below).
698
- await new Promise<void>(resolve => setTimeout(resolve, 0))
699
-
700
- // The toolbox is free to add funding inputs of its own, so each staging
701
- // input is located by outpoint, never assumed by position — and the
702
- // signature commits to EVERY input via otherInputs, or the nodes reject
703
- // the spend with "false stack entry at end of script execution" (the
704
- // 2026-08-21 production deposit failure).
705
- const [cTxid, cVoutStr] = c.outpoint.split('.')
706
- const cVout = Number(cVoutStr)
707
- const inputIndex = tx.inputs.findIndex(
708
- i =>
709
- (i.sourceTXID ?? i.sourceTransaction?.id('hex'))?.toLowerCase() === cTxid.toLowerCase() &&
710
- i.sourceOutputIndex === cVout
711
- )
712
- if (inputIndex < 0) {
713
- throw new VaultError('no-transaction', 'Staging input missing from the signable transaction')
714
- }
715
- const { publicKey: stagingPub } = await w.getPublicKey(
716
- { protocolID: STAGING_PROTOCOL, keyID: c.si.keyID, counterparty: 'self' },
717
- adminOriginator
718
- )
719
- const subscript = new P2PKH().lock(PublicKey.fromString(stagingPub).toAddress())
720
- const input = tx.inputs[inputIndex]
721
- const scope = TransactionSignature.SIGHASH_ALL | TransactionSignature.SIGHASH_FORKID
722
- const preimage = TransactionSignature.format({
723
- sourceTXID: cTxid,
724
- sourceOutputIndex: input.sourceOutputIndex,
725
- sourceSatoshis: c.satoshis,
726
- transactionVersion: tx.version,
727
- otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
728
- outputs: tx.outputs,
729
- inputIndex,
730
- inputSequence: input.sequence ?? 0xffffffff,
731
- subscript,
732
- lockTime: tx.lockTime,
733
- scope
734
- })
735
- const { signature } = await w.createSignature(
736
- {
737
- protocolID: STAGING_PROTOCOL,
738
- keyID: c.si.keyID,
739
- counterparty: 'self',
740
- hashToDirectlySign: Array.from(Hash.hash256(preimage))
741
- },
1717
+ // Build and sign into `noSend` first. This gives this module a real
1718
+ // transaction to inspect before any deposit can leave the device.
1719
+ assertVaultScope(scopeToken)
1720
+ const created = await w.createAction(
1721
+ {
1722
+ description: 'Vault deposit',
1723
+ version: 1,
1724
+ outputs: [output],
1725
+ labels: ['vault', 'vault-deposit'],
1726
+ options: { randomizeOutputs: false, noSend: true, signAndProcess: false }
1727
+ },
1728
+ adminOriginator
1729
+ )
1730
+ assertVaultScope(scopeToken)
1731
+
1732
+ let signedBytes: number[] | undefined
1733
+ let reportedTxid = created.txid
1734
+ if (created.signableTransaction) {
1735
+ reference = created.signableTransaction.reference
1736
+ const unsigned = Transaction.fromAtomicBEEF(created.signableTransaction.tx)
1737
+ validateDepositPlan(unsigned, output)
1738
+ assertVaultScope(scopeToken)
1739
+ const signed = await w.signAction(
1740
+ { reference, spends: {}, options: { noSend: true } },
742
1741
  adminOriginator
743
1742
  )
744
- spends[inputIndex] = {
745
- unlockingScript: new UnlockingScript([
746
- { op: signature.length + 1, data: [...signature, scope] },
747
- { op: 33, data: Utils.toArray(stagingPub, 'hex') }
748
- ]).toHex()
749
- }
1743
+ assertVaultScope(scopeToken)
1744
+ signedBytes = signed.tx
1745
+ reportedTxid = signed.txid ?? reportedTxid
1746
+ } else {
1747
+ signedBytes = created.tx
750
1748
  }
1749
+ if (!signedBytes) throw new VaultError('no-transaction', 'Vault deposit produced no inspectable transaction')
1750
+
1751
+ const signedTx = Transaction.fromAtomicBEEF(signedBytes)
1752
+ validateDepositPlan(signedTx, output)
1753
+ heldTxid = signedTx.id('hex')
1754
+ if (reportedTxid && reportedTxid.toLowerCase() !== heldTxid) {
1755
+ throw new VaultError('no-transaction', 'Vault deposit transaction ID disagrees with its signed transaction')
1756
+ }
1757
+ // `sendWith` releases this already-inspected noSend action. Once the call
1758
+ // begins its broadcast outcome can be ambiguous, so cleanup below must no
1759
+ // longer free its inputs.
1760
+ assertVaultScope(scopeToken)
1761
+ broadcastAttempted = true
1762
+ const released = await w.createAction(
1763
+ { description: 'Broadcast Vault deposit', options: { sendWith: [heldTxid] } },
1764
+ adminOriginator
1765
+ )
1766
+ assertVaultScope(scopeToken)
1767
+ requireReleasedHeldTransaction(released, heldTxid, 'Vault deposit')
1768
+ return { txid: heldTxid }
751
1769
  } catch (e) {
752
- // Nothing was signed: release the reservation so the coins stay listed
753
- // for the next reclaim attempt.
754
- await w.abortAction({ reference }, adminOriginator).catch(() => {})
1770
+ // noSend guarantees the transaction cannot leave before sendWith. A
1771
+ // locally detected plan/signing failure before that call may therefore
1772
+ // release its reservation, even if signAction already produced bytes.
1773
+ if (!broadcastAttempted && reference) {
1774
+ await w.abortAction({ reference }, adminOriginator).catch(() => {})
1775
+ }
755
1776
  throw e
756
1777
  }
757
-
758
- const signed = await w.signAction(
759
- { reference, spends, options: { acceptDelayedBroadcast: false } },
760
- adminOriginator
761
- )
762
- const txid = signed.txid ?? (signed.tx ? Transaction.fromAtomicBEEF(signed.tx).id('hex') : undefined)
763
- if (!txid) throw new VaultError('no-transaction', 'Reclaim produced no transaction')
764
- return { txid, reclaimed: coins.length, satoshis: totalSats }
1778
+ })
765
1779
  }
766
1780
 
1781
+ // ── withdraw / re-lock: selection (spec §4.2 steps 2–3) ───────────────────
1782
+
1783
+ /** How many times the signable transaction may be re-created to dodge a
1784
+ * pushTxDerCheck hit (spec D4b) before giving up. Each re-creation bumps the
1785
+ * offending input's sequence number, which changes every preimage. */
1786
+ const PUSH_TX_RETRY_MAX = 8
1787
+
1788
+ /** One vault output the chosen key can open, with its real lock in hand. */
1789
+ interface SelectedVaultOutput {
1790
+ outpoint: string
1791
+ satoshis: number
1792
+ ci: VaultInstructions
1793
+ /** The output's REAL locking script, read from the listed BEEF. */
1794
+ lockingScript: LockingScript
1795
+ }
767
1796
 
768
- // ── withdraw / sweep (shared spend core) ─────────────────────────────────
1797
+ interface VaultSelection {
1798
+ /** Full current metadata snapshot used by any replacement output. */
1799
+ meta: VaultMeta
1800
+ /** The CURRENT key list (meta.keys) — what a re-vault or re-lock commits to. */
1801
+ keys: VaultKeyRecord[]
1802
+ chosen: VaultKeyRecord
1803
+ /** Largest first, capped, every one proven committed to `chosen`. */
1804
+ selected: SelectedVaultOutput[]
1805
+ /** Sum of `selected`. */
1806
+ acc: number
1807
+ cappedInputs: number
1808
+ unreachable: VaultSpendResult['unreachable']
1809
+ beef?: number[]
1810
+ /** Salts, derivation IDs and script hashes already present in authenticated history. */
1811
+ saltInventory: VaultSaltInventory
1812
+ }
769
1813
 
770
1814
  /**
771
- * How a spend reaches the vault key: a thunk, read at every point of use.
772
- *
773
- * There is only one key and only one script family left, so there is nothing to
774
- * discriminate on — a withdrawal (tap-unwrapped) and a recovery sweep
775
- * (mnemonic + passphrase) hand over the same node. What differs is REVOCABILITY,
776
- * and that is why this is a thunk rather than the node itself.
1815
+ * list → authenticate current records and exact locks → filter to the chosen
1816
+ * key → sort largest first → cap →
1817
+ * prove each selected output's REAL lock commits to the chosen key → amount
1818
+ * checks. Nothing is reserved, tapped or signed here, so every refusal is free.
777
1819
  *
778
- * A withdrawal passes `() => handle.hd`, so every read goes back through
779
- * VaultKeyHandle's getter — the one thing that can refuse. Dereferencing once
780
- * up front would hand this module a raw node that outlives the ceremony's
781
- * opinion of it: cancel(), a key detaching, and the retention ceiling
782
- * (armedAt + 3×) would all become advisory mid-withdrawal, exactly the
783
- * "a reference the caller already took is beyond its reach" case
784
- * VaultKeyHandle's docblock warns about. With the thunk, a relock lands on the
785
- * next derive and unwinds through the abort path below.
786
- *
787
- * The sweep wraps its caller-owned node as `() => hd`: no ceremony exists to
788
- * revoke it, so the thunk is transparent there.
1820
+ * `include: 'entire transactions'` IS required, twice over. Structurally:
1821
+ * every input carries unlockingScriptLength but no unlockingScript, so
1822
+ * @bsv/sdk's validateCreateActionArgs sets isSignAction=true and
1823
+ * buildSignableTransaction resolves each input's sourceTransaction ONLY from
1824
+ * args.inputBEEF (buildSignableTransaction.js:14,101) — omit it and
1825
+ * createAction.js's makeSignableTransactionBeef throws WERR_INTERNAL before
1826
+ * signing starts. And for the commitment check: the BEEF is where each
1827
+ * output's REAL lock comes from — customInstructions are never trusted over
1828
+ * it (a record can claim any key list; only the lock says who can spend).
1829
+ * `include` is one-of, so this call cannot also ask for 'locking scripts'.
1830
+ * includeCustomInstructions is required too: listOutputs omits the field
1831
+ * unless asked, and without it every output decodes as null.
789
1832
  */
790
- type VaultKeySource = () => HD
1833
+ async function selectVaultInputs(
1834
+ w: VaultWallet,
1835
+ adminOriginator: string,
1836
+ chosenSerial: string,
1837
+ amount: number | 'all',
1838
+ requiredPubkey?: string,
1839
+ scopeToken?: VaultScopeToken
1840
+ ): Promise<VaultSelection> {
1841
+ const meta = await vaultStore.getMeta(scopeToken)
1842
+ if (!meta) throw new VaultError('not-enrolled', 'Vault is not set up')
1843
+ if (meta.pendingRemoval) {
1844
+ if (!requiredPubkey || requiredPubkey !== meta.pendingRemoval.key.pubkey) {
1845
+ throw new VaultError('relock-required', 'Finish the pending key removal before another vault transfer')
1846
+ }
1847
+ } else if (requiredPubkey) {
1848
+ throw new VaultError('not-enrolled', 'No matching key removal is pending')
1849
+ }
1850
+ const chosen = meta.keys.find(k => k.serial === chosenSerial)
1851
+ if (!chosen) throw new VaultError('not-enrolled', `Key ${chosenSerial} is not one of this vault's keys`)
1852
+ await vaultStore.requireKeyAdopted(chosen.serial, scopeToken)
791
1853
 
792
- /** One selected vault input, resolved against the key that will spend it. */
793
- interface PreparedSpend<T> {
794
- o: T
795
- /** BIP32 child index this output's keyID names. */
796
- index: number
797
- /** The output's REAL locking script, read from the listed BEEF. */
798
- lockingScript: LockingScript
1854
+ // Hand the JS thread back once so React can paint before the bridge and
1855
+ // database work below; one 64-output page can carry roughly 3 MB of BEEF.
1856
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
1857
+ assertVaultScope(scopeToken)
1858
+ const hasPubkey = (output: VerifiedVaultOutput, pubkey: string): boolean =>
1859
+ output.ci.keys.some(key => key.pubkey === pubkey)
1860
+ const cap = Math.min(VAULT_MAX_INPUTS, VAULT_HARD_MAX_INPUTS)
1861
+ interface Candidate {
1862
+ output: SelectedVaultOutput
1863
+ sourceBeef: number[]
1864
+ }
1865
+ interface SelectionScan {
1866
+ decodable: number
1867
+ mine: number
1868
+ total: number
1869
+ reachable: number
1870
+ unreachableCount: number
1871
+ unreachableSatoshis: number
1872
+ otherPubkeys: Set<string>
1873
+ selected: Candidate[]
1874
+ }
1875
+ const add = (current: number, value: number, where: string): number => {
1876
+ const next = current + value
1877
+ if (!Number.isSafeInteger(next)) throw new VaultError('no-transaction', `${where} value exceeds the safe integer range`)
1878
+ return next
1879
+ }
1880
+ const verified = await reduceVerifiedVaultOutputs(
1881
+ w,
1882
+ adminOriginator,
1883
+ (): SelectionScan => ({
1884
+ decodable: 0,
1885
+ mine: 0,
1886
+ total: 0,
1887
+ reachable: 0,
1888
+ unreachableCount: 0,
1889
+ unreachableSatoshis: 0,
1890
+ otherPubkeys: new Set(),
1891
+ selected: []
1892
+ }),
1893
+ (state, output, sources) => {
1894
+ requireOutputMetaConsistency([output], meta)
1895
+ if (requiredPubkey && !hasPubkey(output, requiredPubkey)) return
1896
+ state.decodable++
1897
+ state.total = add(state.total, output.satoshis, 'Vault selection')
1898
+ if (!hasPubkey(output, chosen.pubkey)) {
1899
+ state.unreachableCount++
1900
+ state.unreachableSatoshis = add(state.unreachableSatoshis, output.satoshis, 'Unreachable vault outputs')
1901
+ for (const key of output.ci.keys) state.otherPubkeys.add(key.pubkey)
1902
+ return
1903
+ }
1904
+ state.mine++
1905
+ state.reachable = add(state.reachable, output.satoshis, 'Reachable vault outputs')
1906
+
1907
+ // Maintain the same stable, largest-first top-N selection as sort/slice,
1908
+ // but extract and retain a source proof only when this row enters it.
1909
+ let position = state.selected.findIndex(candidate => candidate.output.satoshis < output.satoshis)
1910
+ if (position < 0) position = state.selected.length
1911
+ if (position >= cap && state.selected.length >= cap) return
1912
+ let sourceBeef: number[]
1913
+ try {
1914
+ sourceBeef = sources.toBinaryAtomic(output.outpoint.slice(0, 64))
1915
+ } catch {
1916
+ throw new VaultError('no-transaction', `Vault output ${output.outpoint} has no complete source proof`)
1917
+ }
1918
+ state.selected.splice(position, 0, { output, sourceBeef })
1919
+ if (state.selected.length > cap) state.selected.pop()
1920
+ },
1921
+ scopeToken,
1922
+ 'repair-unsigned'
1923
+ )
1924
+ const scan = verified.state
1925
+ if (scan.decodable === 0) throw new VaultError('vault-empty', 'Vault is empty')
1926
+
1927
+ const otherPubkeys = [...scan.otherPubkeys]
1928
+ const unreachable: VaultSpendResult['unreachable'] = {
1929
+ count: scan.unreachableCount,
1930
+ satoshis: scan.unreachableSatoshis,
1931
+ keys: otherPubkeys.map(pubkey => ({ serial: meta.keys.find(k => k.pubkey === pubkey)?.serial, pubkey }))
1932
+ }
1933
+ if (scan.mine === 0) {
1934
+ throw new VaultError('key-not-committed', `Key ${chosen.serial} is not committed to any vault output`)
1935
+ }
1936
+ const cappedInputs = scan.mine - scan.selected.length
1937
+
1938
+ // Every row was already checked against its real BEEF source, including
1939
+ // exact value and exact commitment list. Merge only the bounded input set's
1940
+ // dependency closures; unrelated source transactions never accumulate.
1941
+ const sourceBeef = new Beef()
1942
+ try {
1943
+ for (const candidate of scan.selected) sourceBeef.mergeBeef(candidate.sourceBeef)
1944
+ } catch {
1945
+ throw new VaultError('no-transaction', 'Selected Vault inputs have malformed source proofs')
1946
+ }
1947
+ const selected = scan.selected.map(candidate => candidate.output)
1948
+ const acc = sumVaultSatoshis(selected, 'Selected vault outputs')
1949
+
1950
+ if (amount !== 'all') {
1951
+ if (amount > scan.total) throw new VaultError('amount-exceeds-balance', 'Withdrawal exceeds vault balance')
1952
+ if (amount > scan.reachable && scan.reachable < scan.total) {
1953
+ // Another key could open more: say which, rather than blaming the balance.
1954
+ throw new VaultError(
1955
+ 'key-cannot-cover',
1956
+ `Key ${chosen.serial} can open ${scan.reachable} of the ${scan.total} satoshis in the vault`,
1957
+ undefined,
1958
+ { reachable: scan.reachable, total: scan.total }
1959
+ )
1960
+ }
1961
+ if (amount > acc) {
1962
+ // The key holds enough (checked above) but not within the input cap. The
1963
+ // remedy is a smaller withdrawal, which also consolidates.
1964
+ throw new VaultError(
1965
+ 'too-many-inputs',
1966
+ `Withdrawing ${amount} satoshis would need more than ${cap} vault inputs; withdraw a smaller amount first`
1967
+ )
1968
+ }
1969
+ }
1970
+ return {
1971
+ meta,
1972
+ keys: meta.keys,
1973
+ chosen,
1974
+ selected,
1975
+ acc,
1976
+ cappedInputs,
1977
+ unreachable,
1978
+ beef: sourceBeef.toBinary(),
1979
+ saltInventory: verified.inventory
1980
+ }
1981
+ }
1982
+
1983
+ // ── withdraw / re-lock: build, sign on the card, verify, finalise ─────────
1984
+
1985
+ /** What a spend adds to the transaction beyond its vault inputs. */
1986
+ interface VaultSpendPlan {
1987
+ outputs: VaultOutputSpec[]
1988
+ labels: string[]
1989
+ inputDescription: string
1990
+ /** The action's own description — fixed per operation, unlike `reason`
1991
+ * (the ceremony's NFC prompt text, which names the amount and varies call
1992
+ * to call). Kept separate so the amount never leaks into what the activity
1993
+ * list shows for a withdrawal, and so a copy change to one never touches
1994
+ * the other. */
1995
+ description: string
1996
+ }
1997
+
1998
+ interface PreparedInput {
1999
+ /** Position in the signable transaction — located by outpoint, never assumed. */
2000
+ inputIndex: number
2001
+ preimage: number[]
2002
+ }
2003
+
2004
+ /** A reserved, parsed, D4b-clean signable transaction awaiting the card. This
2005
+ * is the ONLY shape createSignableVaultTx returns: a vault spend that came back
2006
+ * already signed is an invariant violation, and it throws (see below). */
2007
+ interface SignableBuild {
2008
+ tx: Transaction
2009
+ reference: string
2010
+ prepared: PreparedInput[]
2011
+ }
2012
+
2013
+ const isStandardP2PKH = (lockingScript: LockingScript): boolean => {
2014
+ const b = lockingScript.toBinary()
2015
+ return b.length === 25 && b[0] === 0x76 && b[1] === 0xa9 && b[2] === 0x14 && b[23] === 0x88 && b[24] === 0xac
799
2016
  }
800
2017
 
801
2018
  /**
802
- * Resolve every selected input's derivation index and prevout script, and
803
- * prove the key in hand actually opens it.
804
- *
805
- * THE WRONG-KEY CHECK, and it runs before the caller reserves, burns, or signs
806
- * anything: not one createAction has been issued when this throws, so a
807
- * mismatch costs no reservation to unwind and no deposit index. That matters
808
- * twice over.
809
- *
810
- * - On a withdrawal it is the "wrong YubiKey" signal: a card enrolled against
811
- * a different seed unwraps a different node, whose children hash to
812
- * different addresses than the ones these outputs are locked to.
813
- * - On the recovery sweep it is the PASSPHRASE-TYPO guard. A mistyped vault
814
- * passphrase yields a valid-looking HD node that simply is not this vault's,
815
- * so EVERY output mismatches. Without this the sweep would happily build a
816
- * transaction signed with the wrong keys — or, worse, a future
817
- * "skip what we can't sign" refinement would report an empty vault and let
818
- * the user believe their funds were gone. It has to be loud.
2019
+ * How many implicit default-basket change outputs a vault SPEND may carry.
819
2020
  *
820
- * The comparison is against the script the output is ACTUALLY locked with (out
821
- * of the BEEF the same listOutputs call returned), never a script rebuilt from
822
- * the output's own customInstructions — a rebuild is self-consistent by
823
- * construction and can never disagree with itself.
2021
+ * The wallet core grows its UTXO pool by splitting change across several
2022
+ * outputs (`generateChange`'s `targetNetCount`, itself capped per transaction
2023
+ * at `maxChangeOutputsPerTransaction`, currently 8). createAction exempts the
2024
+ * `vault-deposit` label from that growth, so a deposit still arrives with a
2025
+ * single change output and validateDepositPlan stays strict; `vault-withdraw`
2026
+ * and `vault-relock` are NOT exempted and arrive with up to eight. Mirror the
2027
+ * toolbox's cap rather than assume one, and raise this if the toolbox ever
2028
+ * raises its own.
2029
+ */
2030
+ const VAULT_MAX_IMPLICIT_CHANGE = 8
2031
+
2032
+ /**
2033
+ * Validate the wallet core's proposed transaction before the display-less
2034
+ * YubiKey signs it. Vault sources and caller-approved explicit outputs are
2035
+ * exact. The one irreducible trust boundary is ownership of the toolbox's
2036
+ * implicit default-basket change scripts: BRC-100 exposes no derivation proof
2037
+ * for them. We therefore permit only standard P2PKH change outputs, bound
2038
+ * their TOTAL by the selected inputs minus explicit outputs, and cap the fee.
824
2039
  *
825
- * `getHd()` is called per input rather than once: a relock partway through
826
- * refuses on the next input instead of quietly finishing the pass with a key
827
- * the ceremony has already declared dead. Nothing has been reserved yet, so
828
- * that refusal costs nothing at all.
2040
+ * The count is not part of that boundary — one unprovable change script is
2041
+ * the same trust as eight — so it is capped only to keep the plan, and the
2042
+ * size the fee ceiling is derived from, bounded. See
2043
+ * VAULT_MAX_IMPLICIT_CHANGE for why a vault spend arrives with more than one.
829
2044
  */
830
- function prepareSpends<T extends { outpoint: string; satoshis: number; ci: VaultInstructions }>(
831
- selected: T[],
832
- getHd: VaultKeySource,
833
- beefBytes?: number[]
834
- ): PreparedSpend<T>[] {
835
- const sources = beefBytes?.length ? Beef.fromBinary(beefBytes) : undefined
836
- return selected.map(o => {
837
- const index = indexFromKeyID(o.ci.keyID)
838
- if (index == null) throw new VaultError('bad-derivation-index', `Not a BIP32 vault output: ${o.ci.keyID}`)
839
-
840
- const [txid, voutStr] = o.outpoint.split('.')
841
- // Beef indexes by exact txid string; storage writes lowercase, but so does
842
- // every other txid comparison in this file — match them rather than trust it.
843
- const lockingScript = sources?.findTxid(txid.toLowerCase())?.tx?.outputs[Number(voutStr)]?.lockingScript
844
- if (!lockingScript) {
845
- // Fail closed rather than sign blind: without the prevout script there is
846
- // nothing to check the derived child against — and createAction would
847
- // refuse this input moments later anyway (see the listOutputs comment).
848
- throw new VaultError('no-transaction', `No source transaction for vault output ${o.outpoint}`)
2045
+ function validateSignableVaultPlan(tx: Transaction, sel: VaultSelection, plan: VaultSpendPlan): void {
2046
+ const selectedByOutpoint = new Map<string, SelectedVaultOutput>()
2047
+ for (const selected of sel.selected) {
2048
+ const canonical = sameOutpoint(selected.outpoint)
2049
+ if (selectedByOutpoint.has(canonical)) {
2050
+ throw new VaultError('no-transaction', `Duplicate selected vault input ${selected.outpoint}`)
849
2051
  }
2052
+ selectedByOutpoint.set(canonical, selected)
2053
+ }
2054
+ if (tx.inputs.length !== selectedByOutpoint.size) {
2055
+ throw new VaultError('no-transaction', 'Signable transaction changed the approved vault input set')
2056
+ }
850
2057
 
851
- const mine = buildVaultLockingScript({ k1PublicKeyHash: depositPubKeyHash(getHd(), index) })
852
- if (mine.toHex() !== lockingScript.toHex()) {
853
- throw new VaultError(
854
- 'wrong-key',
855
- 'This vault output was locked to a different key — wrong YubiKey, or wrong vault passphrase'
856
- )
2058
+ const seen = new Set<string>()
2059
+ for (const input of tx.inputs) {
2060
+ const txid = (input.sourceTXID ?? input.sourceTransaction?.id('hex'))?.toLowerCase()
2061
+ const vout = input.sourceOutputIndex
2062
+ if (!txid || !Number.isSafeInteger(vout) || vout < 0) {
2063
+ throw new VaultError('no-transaction', 'Signable transaction contains an invalid input outpoint')
857
2064
  }
858
- return { o, index, lockingScript }
859
- })
2065
+ const outpoint = `${txid}.${vout}`
2066
+ const selected = selectedByOutpoint.get(outpoint)
2067
+ if (!selected || seen.has(outpoint)) {
2068
+ throw new VaultError('no-transaction', `Signable transaction contains an unapproved or duplicate input ${outpoint}`)
2069
+ }
2070
+ const source = input.sourceTransaction?.outputs[vout]
2071
+ if (
2072
+ !source ||
2073
+ source.satoshis !== selected.satoshis ||
2074
+ source.lockingScript.toHex() !== selected.lockingScript.toHex()
2075
+ ) {
2076
+ throw new VaultError('no-transaction', `Signable input ${outpoint} changed its authenticated source`)
2077
+ }
2078
+ seen.add(outpoint)
2079
+ }
2080
+ if (seen.size !== selectedByOutpoint.size) {
2081
+ throw new VaultError('no-transaction', 'Signable transaction omitted an approved vault input')
2082
+ }
2083
+
2084
+ let explicitValue = 0
2085
+ for (let i = 0; i < plan.outputs.length; i++) {
2086
+ const expected = plan.outputs[i]
2087
+ const actual = tx.outputs[i]
2088
+ const actualSatoshis = actual?.satoshis
2089
+ if (
2090
+ !actual ||
2091
+ typeof actualSatoshis !== 'number' ||
2092
+ !Number.isSafeInteger(actualSatoshis) ||
2093
+ actualSatoshis < 0 ||
2094
+ actualSatoshis !== expected.satoshis ||
2095
+ actual.lockingScript.toHex() !== expected.lockingScript
2096
+ ) {
2097
+ throw new VaultError('no-transaction', `Signable transaction changed approved output ${i}`)
2098
+ }
2099
+ explicitValue += expected.satoshis
2100
+ if (!Number.isSafeInteger(explicitValue)) throw new VaultError('no-transaction', 'Approved output value overflow')
2101
+ }
2102
+
2103
+ const implicit = tx.outputs.slice(plan.outputs.length)
2104
+ if (implicit.length > VAULT_MAX_IMPLICIT_CHANGE) {
2105
+ throw new VaultError('no-transaction', 'Signable transaction injected an unexpected output')
2106
+ }
2107
+ let implicitValue = 0
2108
+ for (const change of implicit) {
2109
+ const changeSatoshis = change.satoshis
2110
+ if (
2111
+ typeof changeSatoshis !== 'number' ||
2112
+ !Number.isSafeInteger(changeSatoshis) ||
2113
+ changeSatoshis <= 0 ||
2114
+ !isStandardP2PKH(change.lockingScript)
2115
+ ) {
2116
+ throw new VaultError('no-transaction', 'Signable transaction has invalid implicit wallet change')
2117
+ }
2118
+ implicitValue += changeSatoshis
2119
+ if (!Number.isSafeInteger(implicitValue)) {
2120
+ throw new VaultError('no-transaction', 'Implicit change value overflow')
2121
+ }
2122
+ }
2123
+
2124
+ const inputValue = sumVaultSatoshis(sel.selected, 'Signable vault inputs')
2125
+ if (explicitValue > inputValue || implicitValue > inputValue - explicitValue) {
2126
+ throw new VaultError('no-transaction', 'Signable transaction outputs exceed approved vault inputs')
2127
+ }
2128
+ const fee = inputValue - explicitValue - implicitValue
2129
+ // Empty unlock placeholders understate final size. Add the maximum R1C
2130
+ // witnesses, then allow twice the wallet's normal 100 sat/kB policy rate.
2131
+ const signedSizeCeiling = tx.toBinary().length + sel.selected.length * R1C_UNLOCK_LEN
2132
+ const maxFee = Math.max(200, Math.ceil(signedSizeCeiling / 1000) * 200)
2133
+ if (!Number.isSafeInteger(fee) || fee < 0 || fee > maxFee) {
2134
+ throw new VaultError('no-transaction', `Signable transaction fee ${fee} exceeds the Vault safety ceiling ${maxFee}`)
2135
+ }
2136
+ if (implicit.length === 0 && inputValue - explicitValue > maxFee) {
2137
+ throw new VaultError('no-transaction', 'Signable transaction omitted expected wallet change')
2138
+ }
860
2139
  }
861
2140
 
862
- async function spendVaultOutputs(
2141
+ /**
2142
+ * createAction with transaction version 1, then the two checks that must
2143
+ * pass before the FIRST card signature: the parsed signable transaction is
2144
+ * version 1 (`bad-version`), and every input's preimage passes pushTxDerCheck
2145
+ * (D4b). A D4b hit aborts the reservation and re-creates the action with that
2146
+ * input's `sequenceNumber` bumped — the toolbox default is 0xffffffff, so
2147
+ * "bumped" means decremented; lockTime is 0, so any value is final — which
2148
+ * changes every preimage. Bounded by PUSH_TX_RETRY_MAX.
2149
+ *
2150
+ * The freeReservedInputs retry-once around createAction is unchanged: a prior
2151
+ * failed attempt can leave a vault UTXO reserved by an orphaned transaction,
2152
+ * in either of the two error shapes freeReservedInputs recognises.
2153
+ */
2154
+ async function createSignableVaultTx(
863
2155
  w: VaultWallet,
864
2156
  adminOriginator: string,
865
- amount: number | 'all',
2157
+ sel: VaultSelection,
866
2158
  reason: string,
867
- getHd: VaultKeySource,
868
- opts: { revaultRemainder: boolean } & VaultTransferOptions
869
- ): Promise<VaultSpendResult> {
870
- // Announce work BEFORE starting it, then hand the JS thread back once so
871
- // React can actually paint the sheet. listOutputs and createAction both cross
872
- // the bridge and touch the database; without this yield the phase change is
873
- // queued behind that work and the user stares at a frozen screen anyway.
874
- noteVaultProgress({ phase: 'preparing' })
875
- await new Promise<void>(resolve => setTimeout(resolve, 0))
2159
+ plan: VaultSpendPlan,
2160
+ opts?: VaultTransferOptions,
2161
+ scopeToken?: VaultScopeToken
2162
+ ): Promise<SignableBuild> {
2163
+ const outpoints = sel.selected.map(o => o.outpoint)
2164
+ /** outpoint → sequenceNumber override, set by a pushTxDerCheck hit. */
2165
+ const sequences = new Map<string, number>()
2166
+
2167
+ for (let attempt = 1; ; attempt++) {
2168
+ const caArgs = {
2169
+ description: plan.description,
2170
+ version: 1,
2171
+ inputs: sel.selected.map(o => ({
2172
+ outpoint: o.outpoint,
2173
+ unlockingScriptLength: R1C_UNLOCK_LEN,
2174
+ inputDescription: plan.inputDescription,
2175
+ ...(sequences.has(o.outpoint) ? { sequenceNumber: sequences.get(o.outpoint) } : {})
2176
+ })),
2177
+ outputs: plan.outputs,
2178
+ labels: plan.labels,
2179
+ // From the 'entire transactions' listOutputs call — required, not
2180
+ // optional (see selectVaultInputs). trustSelf: 'known' lets storage skip
2181
+ // re-walking each source transaction's own merkle-proof ancestry for a
2182
+ // basket this wallet already trusts; it does not replace inputBEEF.
2183
+ inputBEEF: sel.beef?.length ? sel.beef : undefined,
2184
+ options: { randomizeOutputs: false, acceptDelayedBroadcast: false, trustSelf: 'known' }
2185
+ }
876
2186
 
877
- // `include: 'entire transactions'` IS required, and for two reasons.
878
- //
879
- // The first is structural: every input here carries unlockingScriptLength but
880
- // no unlockingScript, so @bsv/sdk's validateCreateActionArgs sets
881
- // isSignAction=true for this createAction call. buildSignableTransaction
882
- // then resolves each input's sourceTransaction ONLY from args.inputBEEF
883
- // (buildSignableTransaction.js:14,101) — trustSelf and storage's own
884
- // "known input" shortcut (storage/methods/createAction.js's
885
- // localKnownInputTxids) are a STORAGE-side allowance to skip merkle-proof
886
- // verification, not a substitute for the client supplying inputBEEF at all.
887
- // Omit it and createAction.js's makeSignableTransactionBeef throws
888
- // WERR_INTERNAL('Every signableTransaction input must have a
889
- // sourceTransaction') on the very first input, before signing ever starts.
890
- // (reclaimStagingOutputs is in the same boat, not exempt from it: its
891
- // staging inputs also carry an unlockingScriptLength with no
892
- // unlockingScript, so isSignAction is true there too. It needs no separate
893
- // note here because it already threads `staged.BEEF` through as inputBEEF
894
- // for exactly this reason.)
895
- //
896
- // The second is the wrong-key check below: the BEEF is where each vault
897
- // output's REAL locking script comes from, which is what the derived child
898
- // is compared against. `include` is one-of ('locking scripts' OR 'entire
899
- // transactions' — see the SDK's validateListOutputsArgs), so this call
900
- // cannot ask for both, and the BEEF is the one that is mandatory anyway.
901
- //
902
- // Under K1 the whole payload is ordinary-sized — a vault source transaction
903
- // is a few hundred bytes, not the ~1.83 MB per input the R1-K1 script cost.
904
- // includeCustomInstructions IS also required: listOutputs omits that field
905
- // unless asked, and without it every output filters out as unreadable.
906
- const list = await w.listOutputs(
907
- { basket: VAULT_BASKET, include: 'entire transactions', includeCustomInstructions: true, limit: 1000 },
908
- adminOriginator
909
- )
910
- const spendable = list.outputs
911
- .map(o => ({ ...o, ci: decodeVaultInstructions(o.customInstructions) }))
912
- .filter((o): o is typeof o & { ci: VaultInstructions } => o.ci != null)
913
- .sort((a, b) => b.satoshis - a.satoshis) // largest first
914
- if (spendable.length === 0) throw new VaultError('vault-empty', 'Vault is empty')
2187
+ const createOnce = async (): Promise<CreateActionResult> => {
2188
+ assertVaultScope(scopeToken)
2189
+ const result = await w.createAction(caArgs, adminOriginator)
2190
+ try {
2191
+ assertVaultScope(scopeToken)
2192
+ } catch (scopeError) {
2193
+ // The original wallet object is still pinned to scope A. If it made a
2194
+ // reservation before the scope switched, release that reversible A
2195
+ // action without touching the now-current scope B.
2196
+ const reference = result.signableTransaction?.reference
2197
+ if (reference) await w.abortAction({ reference }, adminOriginator).catch(() => {})
2198
+ throw scopeError
2199
+ }
2200
+ return result
2201
+ }
915
2202
 
916
- const total = spendable.reduce((s, o) => s + o.satoshis, 0)
917
- if (amount !== 'all' && amount > total) {
918
- throw new VaultError('amount-exceeds-balance', 'Withdrawal exceeds vault balance')
919
- }
2203
+ let created: CreateActionResult
2204
+ try {
2205
+ created = await createOnce()
2206
+ } catch (e) {
2207
+ if (e instanceof VaultError && e.code === 'scope-changed') throw e
2208
+ assertVaultScope(scopeToken)
2209
+ const freed = await freeReservedInputs(w, adminOriginator, e, outpoints, opts?.findSpendingReferences, scopeToken)
2210
+ if (freed === 0) throw e
2211
+ created = await createOnce()
2212
+ }
920
2213
 
921
- // Bounded input count — see VAULT_MAX_INPUTS for what the bound is defending
922
- // against now that the scripts are 25/~107 bytes rather than ~960 KB.
923
- //
924
- // Largest first (already sorted), so the fewest inputs cover the most value.
925
- const cap = Math.min(VAULT_MAX_INPUTS, VAULT_HARD_MAX_INPUTS)
926
- const selected = spendable.slice(0, cap)
927
- const acc = selected.reduce((s, o) => s + o.satoshis, 0)
928
- const remainingInputs = spendable.length - selected.length
929
-
930
- // 'all' means "as much as one safe transaction can carry"; the untouched
931
- // outputs stay in the vault and the re-vaulted remainder consolidates what was
932
- // spent, so repeating the withdrawal drains it.
933
- const want = amount === 'all' ? acc : amount
934
- if (want > acc) {
935
- // The vault holds enough (checked above) but not within the input cap. Say
936
- // so, rather than blaming the balance: the remedy is a smaller withdrawal,
937
- // which also consolidates and makes the next one cheaper.
938
- throw new VaultError(
939
- 'too-many-inputs',
940
- `Withdrawing ${want} satoshis would need more than ${cap} vault inputs; withdraw a smaller amount first`
941
- )
942
- }
2214
+ if (!created.signableTransaction) {
2215
+ // Inputs carrying unlockingScriptLength always come back signable. If the
2216
+ // toolbox ever handed back a finished transaction here it would have
2217
+ // spent R1C outputs WITHOUT our unlocks — never a success to report, so
2218
+ // this fails closed. A non-signable result carries no reference (the
2219
+ // toolbox has already finalised whatever it built), so there is nothing
2220
+ // reservable left to abort; refusing is the whole remedy.
2221
+ if (created.txid || created.tx) {
2222
+ throw new VaultError('no-transaction', 'createAction returned a signed transaction for vault inputs; refusing')
2223
+ }
2224
+ throw new VaultError('no-transaction', 'Vault spend produced no transaction')
2225
+ }
943
2226
 
944
- // Resolve every selected input against the key in hand BEFORE anything is
945
- // reserved, burned, or signed — see prepareSpends.
946
- const prepared = prepareSpends(selected, getHd, list.BEEF)
2227
+ const { reference } = created.signableTransaction
2228
+ try {
2229
+ const tx = Transaction.fromAtomicBEEF(created.signableTransaction.tx)
2230
+ if (tx.version !== 1) {
2231
+ throw new VaultError('bad-version', `Signable transaction is version ${tx.version}; expected 1`)
2232
+ }
2233
+ validateSignableVaultPlan(tx, sel, plan)
2234
+ const prepared: PreparedInput[] = sel.selected.map(o => {
2235
+ const [txid, voutStr] = o.outpoint.split('.')
2236
+ const vout = Number(voutStr)
2237
+ // Locate each approved vault input by outpoint. The plan validator has
2238
+ // already rejected extra, missing, and duplicate inputs.
2239
+ const inputIndex = tx.inputs.findIndex(
2240
+ i =>
2241
+ (i.sourceTXID ?? i.sourceTransaction?.id('hex'))?.toLowerCase() === txid.toLowerCase() &&
2242
+ i.sourceOutputIndex === vout
2243
+ )
2244
+ if (inputIndex < 0) {
2245
+ throw new VaultError('no-transaction', `Vault input ${o.outpoint} missing from the signable transaction`)
2246
+ }
2247
+ return { inputIndex, preimage: sighashPreimage(tx, inputIndex, o.satoshis) }
2248
+ })
947
2249
 
948
- const outputs: unknown[] = []
949
- const remainder = acc - want
950
- // A sub-floor remainder is folded into the withdrawal rather than re-vaulted:
951
- // an output below VAULT_DEPOSIT_MIN is not worth what it costs to move. It
952
- // still reaches the user — as part of the toolbox's own default-basket
953
- // change alongside the withdrawn amount — it is just not re-vaulted.
954
- //
955
- // The SAME node the inputs were checked against locks it: one tap covers a
956
- // withdrawal and its own change output, and a wrong-key failure above has
957
- // already aborted without burning an index here. Read through the thunk (and
958
- // BEFORE takeNextIndex, inside nextDepositTarget) so a relock at this instant
959
- // refuses without burning an index either.
960
- if (opts.revaultRemainder && remainder >= VAULT_DEPOSIT_MIN) {
961
- const target = await nextDepositTarget(getHd())
962
- outputs.push({
963
- satoshis: remainder,
964
- lockingScript: target.lockingScript,
965
- outputDescription: 'Vault change',
966
- basket: VAULT_BASKET,
967
- customInstructions: encodeVaultInstructions(target.instructions),
968
- tags: ['vault']
969
- })
970
- }
971
-
972
- const caArgs = {
973
- description: reason,
974
- inputs: selected.map(o => ({
975
- outpoint: o.outpoint,
976
- unlockingScriptLength: K1_UNLOCK_LEN,
977
- inputDescription: 'Vault withdrawal'
978
- })),
979
- outputs,
980
- labels: ['vault', 'vault-withdraw'],
981
- // inputBEEF, from the 'entire transactions' listOutputs call above — see
982
- // the comment there for why this is required, not optional. trustSelf:
983
- // 'known' is kept alongside it: it is what lets storage skip re-walking
984
- // each source transaction's own merkle-proof ancestry for a basket this
985
- // wallet already trusts (its own prior deposits), rather than what makes
986
- // inputBEEF itself unnecessary.
987
- inputBEEF: list.BEEF?.length ? list.BEEF : undefined,
988
- options: { randomizeOutputs: false, acceptDelayedBroadcast: false, trustSelf: 'known' }
989
- }
990
-
991
- let created: CreateActionResult
992
- try {
993
- created = await w.createAction(caArgs, adminOriginator)
994
- } catch (e) {
995
- // A prior failed attempt can leave a vault UTXO reserved by an orphaned
996
- // transaction, and until it is aborted every later withdrawal is refused
997
- // outright. Two error shapes, depending on whether the orphan ever got a
998
- // txid — see freeReservedInputs. Abort it and retry ONCE; anything else
999
- // frees nothing and rethrows untouched.
1000
- const freed = await freeReservedInputs(
1001
- w,
1002
- adminOriginator,
1003
- e,
1004
- selected.map(o => o.outpoint),
1005
- opts.findSpendingReferences
1006
- )
1007
- if (freed === 0) throw e
1008
- created = await w.createAction(caArgs, adminOriginator)
2250
+ const badAt = prepared.findIndex(p => !pushTxDerCheck(p.preimage).ok)
2251
+ if (badAt < 0) return { tx, reference, prepared }
2252
+ if (attempt >= PUSH_TX_RETRY_MAX) {
2253
+ throw new VaultError(
2254
+ 'no-transaction',
2255
+ `Could not build a signable vault transaction in ${PUSH_TX_RETRY_MAX} attempts`
2256
+ )
2257
+ }
2258
+ const bad = sel.selected[badAt]
2259
+ const current = sequences.get(bad.outpoint) ?? (tx.inputs[prepared[badAt].inputIndex].sequence ?? 0xffffffff)
2260
+ sequences.set(bad.outpoint, current - 1)
2261
+ } catch (e) {
2262
+ await w.abortAction({ reference }, adminOriginator).catch(() => {})
2263
+ throw e
2264
+ }
2265
+ // D4b hit: this reservation is worthless — release it and rebuild with the
2266
+ // bumped sequence.
2267
+ assertVaultScope(scopeToken)
2268
+ await w.abortAction({ reference }, adminOriginator).catch(() => {})
2269
+ assertVaultScope(scopeToken)
1009
2270
  }
2271
+ }
1010
2272
 
1011
- if (!created.signableTransaction) {
1012
- const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
1013
- if (!txid) throw new VaultError('no-transaction', 'Withdrawal produced no transaction')
1014
- return { txid, remainingInputs }
1015
- }
2273
+ /**
2274
+ * Spec §4.2 steps 5–8, shared by withdrawFromVault and relockVault.
2275
+ *
2276
+ * ORDER, and why: build + screen (no card) → tap (requestVaultSigner) → sign
2277
+ * every input SEQUENTIALLY → release the signer → verify every unlock locally
2278
+ * with the strict flags → signAction. Verification runs after release so the
2279
+ * NFC sheet is down while the interpreter works; anything failing before
2280
+ * signAction aborts the reservation; nothing after it does.
2281
+ *
2282
+ * SEQUENTIAL BY DESIGN — do not "simplify" this into an
2283
+ * unlockingScriptTemplate + tx.sign(). @bsv/sdk's Transaction.sign() fans
2284
+ * every template's sign() out through Promise.all and takes ownership of the
2285
+ * whole input set; this loop keeps each input's script ours to build, in a
2286
+ * known order, one card round trip at a time (the card signs one digest per
2287
+ * command). The yield before each signature keeps the JS thread responsive
2288
+ * for the sheet.
2289
+ */
2290
+ async function spendVaultOutputs(
2291
+ w: VaultWallet,
2292
+ adminOriginator: string,
2293
+ sel: VaultSelection,
2294
+ reason: string,
2295
+ plan: VaultSpendPlan,
2296
+ opts?: VaultTransferOptions,
2297
+ scopeToken?: VaultScopeToken
2298
+ ): Promise<VaultSpendResult> {
2299
+ const { tx, reference, prepared } = await createSignableVaultTx(w, adminOriginator, sel, reason, plan, opts, scopeToken)
2300
+ const result = (txid: string): VaultSpendResult => ({ txid, cappedInputs: sel.cappedInputs, unreachable: sel.unreachable })
2301
+ const { chosen, selected } = sel
2302
+ const total = selected.length
1016
2303
 
1017
- const { tx: atomic, reference } = created.signableTransaction
1018
- let builtSpends: Record<number, { unlockingScript: string }>
2304
+ const unlocks: { inputIndex: number; unlockingScript: UnlockingScript }[] = []
1019
2305
  try {
1020
- const tx = Transaction.fromAtomicBEEF(atomic)
1021
- const spends: Record<number, { unlockingScript: string }> = {}
1022
-
1023
- // SEQUENTIAL BY DESIGN, still — do not "simplify" this into an
1024
- // unlockingScriptTemplate + tx.sign(). @bsv/sdk's Transaction.sign() fans
1025
- // every template's sign() out through Promise.all
1026
- // (dist/cjs/src/transaction/Transaction.js) and takes ownership of the
1027
- // whole input set; this loop keeps each input's script ours to build, in a
1028
- // known order, with the derived key never leaving the iteration that used
1029
- // it. The yield is what keeps the JS thread from disappearing for the
1030
- // length of the loop: one ECDSA signature is fast, but the preimage is
1031
- // re-formatted over the entire transaction for every input, so the cost
1032
- // grows with the square of the input count.
1033
- //
1034
- // getHd() per input, never hoisted: the loop yields between inputs, so a
1035
- // cancel(), a detached key, or the retention ceiling can land BETWEEN two
1036
- // signatures. Reading through the thunk turns that into a refusal on the
1037
- // next input, which unwinds into the catch below and aborts the reservation
1038
- // — a half-signed `spends` map never reaches signAction.
1039
- for (let i = 0; i < prepared.length; i++) {
1040
- await new Promise<void>(resolve => setTimeout(resolve, 0))
1041
-
1042
- const { o, index, lockingScript } = prepared[i]
1043
- const unlocker = new P2PKH().unlock(
1044
- depositPrivKey(getHd(), index),
1045
- 'all',
1046
- false,
1047
- o.satoshis,
1048
- lockingScript
2306
+ // ── the tap(s): one on-card signature per input ────────────────────
2307
+ const signer = await requestVaultSigner(reason, chosen.serial)
2308
+ assertVaultScope(scopeToken)
2309
+ // The commitment check above ran against chosen.pubkey, but every unlock
2310
+ // is built with signer.pubkey — they must be the same key, or the card
2311
+ // would sign for a lock it cannot open (a stale slot, or a ceremony that
2312
+ // failed to enforce the serial). Release first: the signing loop's own
2313
+ // finally has not been entered yet.
2314
+ if (signer.pubkey !== chosen.pubkey) {
2315
+ signer.release()
2316
+ throw new VaultError(
2317
+ 'serial-mismatch',
2318
+ 'Signer public key does not match the chosen key',
2319
+ undefined,
2320
+ { tapped: signer.serial, chosen: chosen.serial }
1049
2321
  )
1050
- spends[i] = { unlockingScript: (await unlocker.sign(tx, i)).toHex() }
2322
+ }
2323
+ try {
2324
+ for (let i = 0; i < total; i++) {
2325
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
2326
+ noteVaultProgress({ phase: 'preparing', signed: i, total })
2327
+ const { inputIndex, preimage } = prepared[i]
2328
+ const der = await signer.sign(signerDigest(preimage), { index: i, total })
2329
+ assertVaultScope(scopeToken)
2330
+ // buildUnlock throws template-invalid if fullR is the point at
2331
+ // infinity — a 2^-256 event; it unwinds through the abort below.
2332
+ unlocks.push({
2333
+ inputIndex,
2334
+ unlockingScript: buildUnlock({
2335
+ preimage,
2336
+ derSig: der,
2337
+ pubkeyHex33: signer.pubkey,
2338
+ saltHex64: selected[i].ci.salt
2339
+ })
2340
+ })
2341
+ }
2342
+ } finally {
2343
+ // Dismisses the NFC sheet and drops the PIN whether or not every input
2344
+ // was signed; the local verification below needs no card.
2345
+ signer.release()
1051
2346
  }
1052
2347
 
1053
- builtSpends = spends
2348
+ // ── strict local Spend per input (spec §4.2 step 7) ────────────────
2349
+ // Honest unlocks are minimal, so the strict local flags are at least as
2350
+ // strong as the node policy used for the same version-1 transaction.
2351
+ for (let i = 0; i < total; i++) {
2352
+ verifyVaultInput({
2353
+ tx,
2354
+ inputIndex: unlocks[i].inputIndex,
2355
+ sourceSatoshis: selected[i].satoshis,
2356
+ lockingScript: selected[i].lockingScript,
2357
+ unlockingScript: unlocks[i].unlockingScript
2358
+ })
2359
+ }
1054
2360
  } catch (e) {
1055
- // Nothing was signed, so the reservation is worthless — release it, or the
1056
- // vault UTXO stays spendable=false and the next withdrawal is refused
1057
- // outright.
2361
+ // Nothing reached signAction, so the reservation is worthless — release
2362
+ // it, or the vault UTXO stays spendable=false and the next attempt is
2363
+ // refused outright.
1058
2364
  await w.abortAction({ reference }, adminOriginator).catch(() => {})
1059
2365
  throw e
1060
2366
  }
1061
2367
 
1062
- // PAST THE POINT OF NO ABORT.
1063
- //
1064
- // acceptDelayedBroadcast: true hands the signed transaction to storage and
1065
- // lets the monitor's SendWaiting task carry it to the network. A slow or
1066
- // timing-out broadcaster therefore cannot cost the user a signed
1067
- // transaction, and this call no longer waits on the network before the UI
1068
- // can move on.
2368
+ const spends: Record<number, { unlockingScript: string }> = {}
2369
+ for (const u of unlocks) spends[u.inputIndex] = { unlockingScript: u.unlockingScript.toHex() }
2370
+
2371
+ // PAST THE POINT OF NO ABORT. Output-creating spends are first signed into a
2372
+ // held noSend action and revalidated before sendWith. A plain withdrawal has
2373
+ // no new Vault output and can go directly to the broadcaster. A throw after
2374
+ // either signAction begins remains ambiguous and is never followed by
2375
+ // abortAction.
1069
2376
  //
1070
- // Deliberately OUTSIDE the try above: once a transaction is signed, aborting
1071
- // it is the dangerous move, not the safe one — the network may already have
1072
- // accepted it, and abandoning it locally would leave the wallet blind to
1073
- // funds that really moved. A failure here is reported as "we will try
1074
- // again", never as a cancellation.
2377
+ // The broadcasting note is inert once the signer is released (noteProgress
2378
+ // ignores notes with nothing armed); the transfer screen shows its own
2379
+ // spinner. Kept so the phase sequence reads complete.
1075
2380
  noteVaultProgress({ phase: 'broadcasting' })
2381
+ assertVaultScope(scopeToken)
2382
+ const createsVaultOutput = plan.outputs.some(output => output.basket === VAULT_BASKET)
1076
2383
  const signed = await w.signAction(
1077
- { reference, spends: builtSpends, options: { acceptDelayedBroadcast: true } },
2384
+ {
2385
+ reference,
2386
+ spends,
2387
+ options: createsVaultOutput ? { noSend: true } : { acceptDelayedBroadcast: false }
2388
+ },
1078
2389
  adminOriginator
1079
2390
  )
1080
- const txid = signed.txid ?? (signed.tx ? Transaction.fromAtomicBEEF(signed.tx).id('hex') : undefined)
1081
- if (!txid) throw new VaultError('no-transaction', 'Withdrawal produced no transaction')
1082
- return { txid, remainingInputs }
2391
+ assertVaultScope(scopeToken)
2392
+ let txid = signed.txid ?? (signed.tx ? Transaction.fromAtomicBEEF(signed.tx).id('hex') : undefined)
2393
+ if (!txid) throw new VaultError('no-transaction', 'Vault spend produced no transaction')
2394
+ txid = txid.toLowerCase()
2395
+
2396
+ if (createsVaultOutput) {
2397
+ if (!signed.tx) throw new VaultError('no-transaction', 'Held Vault spend returned no inspectable signed transaction')
2398
+ const signedTx = Transaction.fromAtomicBEEF(signed.tx)
2399
+ if (signedTx.id('hex') !== txid) {
2400
+ throw new VaultError('no-transaction', 'Held Vault spend transaction ID disagrees with its signed transaction')
2401
+ }
2402
+ validateSignableVaultPlan(signedTx, sel, plan)
2403
+ for (const unlock of unlocks) {
2404
+ if (signedTx.inputs[unlock.inputIndex]?.unlockingScript?.toHex() !== unlock.unlockingScript.toHex()) {
2405
+ throw new VaultError('no-transaction', 'Wallet changed a verified Vault unlocking script while signing')
2406
+ }
2407
+ }
2408
+ assertVaultScope(scopeToken)
2409
+ const released = await w.createAction(
2410
+ { description: `Broadcast ${plan.description}`, options: { sendWith: [txid] } },
2411
+ adminOriginator
2412
+ )
2413
+ assertVaultScope(scopeToken)
2414
+ requireReleasedHeldTransaction(released, txid, plan.description)
2415
+ }
2416
+ // Best-effort: the transaction is already with the monitor, so a failed
2417
+ // SecureStore write here (the chooser's "last used" default) must never
2418
+ // turn a completed transfer into a reported failure.
2419
+ try {
2420
+ await vaultStore.noteLastUsed(chosen.serial, scopeToken)
2421
+ } catch (e) {
2422
+ console.log('[vault] noteLastUsed failed (transfer already complete):', (e as Error)?.message)
2423
+ }
2424
+ return result(txid)
2425
+ }
2426
+
2427
+ // ── withdraw ────────────────────────────────────────────────────────────
2428
+
2429
+ /**
2430
+ * Cheapest refusal first, shared by the preview and the withdrawal. Every
2431
+ * amount comparison in selectVaultInputs is `amount > x`, which is false for
2432
+ * NaN, 0 and negatives: unguarded, NaN would withdraw everything the key can
2433
+ * open, a negative would fund a re-vault output LARGER than the inputs from
2434
+ * the hot wallet (bypassing the deposit gates), 0 would pay a fee to re-lock
2435
+ * everything.
2436
+ */
2437
+ function requireWithdrawalAmount(amount: number | 'all'): void {
2438
+ if (amount !== 'all' && (!Number.isSafeInteger(amount) || amount <= 0)) {
2439
+ throw new VaultError('below-dust', 'Withdrawal amount must be a positive integer number of satoshis')
2440
+ }
2441
+ }
2442
+
2443
+ /**
2444
+ * What a withdrawal with the CHOSEN key would select, without reserving,
2445
+ * tapping or signing anything (spec §4.2 step 4 needs it BEFORE the tap).
2446
+ *
2447
+ * `selectedTotal` is the chosen key's selectable total — its committed
2448
+ * outputs, largest first, within the input cap — which is what
2449
+ * withdrawFromVault folds or re-vaults the remainder against, and which can
2450
+ * be LESS than the vault balance when other keys hold part of it or the cap
2451
+ * applies. The screen computes the remainder-fold confirmation from this
2452
+ * figure, never from the whole balance. Throws exactly what the withdrawal's
2453
+ * own selection would (`not-enrolled`, `vault-empty`, `key-not-committed`,
2454
+ * `key-cannot-cover`, `amount-exceeds-balance`, `too-many-inputs`,
2455
+ * `below-dust`), so those surface inline before any NFC sheet. Reads the
2456
+ * wallet database only; no network, so it is not gated on being online.
2457
+ */
2458
+ export async function previewVaultWithdrawal(
2459
+ w: VaultWallet,
2460
+ adminOriginator: string,
2461
+ chosenSerial: string,
2462
+ amount: number | 'all'
2463
+ ): Promise<{ selectedTotal: number; cappedInputs: number; unreachable: VaultSpendResult['unreachable'] }> {
2464
+ requireWithdrawalAmount(amount)
2465
+ const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount)
2466
+ return { selectedTotal: sel.acc, cappedInputs: sel.cappedInputs, unreachable: sel.unreachable }
1083
2467
  }
1084
2468
 
1085
2469
  /**
1086
- * Withdraw from the vault. ONE tap covers the whole transaction — every input
1087
- * AND the re-vaulted remainder derive from the same unwrapped node — and the
1088
- * key is always released in a finally: on iOS that is what dismisses the
1089
- * system NFC sheet, and it must fire whether the withdrawal succeeds, fails to
1090
- * build, or fails to sign.
2470
+ * Withdraw from the vault with the CHOSEN key (spec §4.2).
2471
+ *
2472
+ * `amount: 'all'` means "as much as one transaction can carry of what this
2473
+ * key can open": the untouched outputs stay in the vault and are reported as
2474
+ * `cappedInputs` (repeat to move them); outputs other keys own are reported as
2475
+ * `unreachable` (repeat with one of those keys). A remainder ≥ VAULT_DEPOSIT_MIN
2476
+ * is re-vaulted as one output committed to the CURRENT key set (so a partial
2477
+ * withdrawal also brings old deposits up to date with the key list); a smaller
2478
+ * one is folded into the withdrawal as toolbox change.
1091
2479
  */
1092
2480
  export async function withdrawFromVault(
1093
2481
  w: VaultWallet,
1094
2482
  adminOriginator: string,
1095
2483
  amount: number | 'all',
1096
2484
  reason: string,
2485
+ chosenSerial: string,
1097
2486
  opts?: VaultTransferOptions
1098
2487
  ): Promise<VaultSpendResult> {
1099
- // Before the ceremony: no key prompt for a transfer that cannot proceed.
2488
+ const scopeToken = vaultStore.captureScopeToken()
2489
+ return await withVaultMutation(async () => {
2490
+ assertVaultScope(scopeToken)
2491
+ // Cheapest refusal first, as in depositToVault — see requireWithdrawalAmount.
2492
+ requireWithdrawalAmount(amount)
2493
+ // An offline user is never asked to present a key for a transfer that
2494
+ // cannot proceed.
1100
2495
  await requireOnline(opts)
1101
- const handle = await requestVaultKey(reason)
1102
- try {
1103
- // A THUNK, not `handle.hd` — see VaultKeySource. The spend reads it afresh
1104
- // at every derive and every signature, so each read goes back through the
1105
- // handle's getter and a relock (cancel, key detached, retention ceiling)
1106
- // refuses on the next one. A normal withdrawal finishes inside the armed
1107
- // window, but the ceiling makes that expected rather than guaranteed, so
1108
- // "finishes in time" is not something this code may assume: a relock
1109
- // mid-spend surfaces as key-removed-mid-op and unwinds through
1110
- // spendVaultOutputs' abort path, leaving no reservation behind. Nothing is
1111
- // stored here either way — the thunk closes over the handle, which dies
1112
- // with this call.
1113
- return await spendVaultOutputs(w, adminOriginator, amount, reason, () => handle.hd, {
1114
- revaultRemainder: true,
1115
- ...opts
1116
- })
1117
- } finally {
1118
- handle.release()
2496
+ assertVaultScope(scopeToken)
2497
+ const meta = await requireMeta(scopeToken)
2498
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2499
+ const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount, undefined, scopeToken)
2500
+ const want = amount === 'all' ? sel.acc : amount
2501
+ const remainder = sel.acc - want
2502
+ const outputs: VaultSpendPlan['outputs'] = []
2503
+ if (remainder >= VAULT_DEPOSIT_MIN) {
2504
+ // Re-vaulting CREATES a vault output, which the release flag gates (spec
2505
+ // §5.5). Withdrawing pre-existing outputs — 'all' — never is.
2506
+ requireReleased(opts, scopeToken, 'Re-vaulting a remainder')
2507
+ await requirePrivateBackup(opts, 'Re-vaulting a remainder')
2508
+ assertVaultScope(scopeToken)
2509
+ await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, sel.meta, scopeToken)
2510
+ outputs.push(await newVaultOutput(
2511
+ w,
2512
+ adminOriginator,
2513
+ sel.meta,
2514
+ remainder,
2515
+ 'Vault change',
2516
+ sel.saltInventory,
2517
+ scopeToken.chain
2518
+ ))
1119
2519
  }
2520
+ return await spendVaultOutputs(
2521
+ w,
2522
+ adminOriginator,
2523
+ sel,
2524
+ reason,
2525
+ { outputs, labels: ['vault', 'vault-withdraw'], inputDescription: 'Vault withdrawal', description: 'Vault withdrawal' },
2526
+ opts,
2527
+ scopeToken
2528
+ )
2529
+ })
2530
+ }
2531
+
2532
+ // ── re-lock (spec §4.3) ──────────────────────────────────────────────────
2533
+
2534
+ /**
2535
+ * Fee reserve for a re-lock, in the toolbox's own arithmetic (100 sat/kB,
2536
+ * rounded up per kB) plus 10 %.
2537
+ *
2538
+ * size = 10 + inputCount·(41 + 3 + R1C_UNLOCK_LEN) + (3 + lockLen + 8)
2539
+ *
2540
+ * — 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.
2545
+ *
2546
+ * The re-lock output is `acc − this`; the toolbox's real fee is at most this
2547
+ * 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.
2549
+ */
2550
+ export function estimateRelockFee(inputCount: number, lockLen: number, satPerKb = 100): number {
2551
+ const size = 10 + inputCount * (41 + 3 + R1C_UNLOCK_LEN) + (3 + lockLen + 8)
2552
+ const kb = Math.ceil(size / 1000)
2553
+ return Math.ceil((kb * satPerKb * 11) / 10)
1120
2554
  }
1121
2555
 
1122
2556
  /**
1123
- * Recovery for a lost YubiKey: sweep the ENTIRE vault to the default basket,
1124
- * signing with the HD node derived from the main mnemonic + vault passphrase.
2557
+ * Re-lock the vault with the chosen key (spec §4.3): a distinct spend mode,
2558
+ * NOT withdrawFromVault('all') — whose remainder is zero and would sweep the
2559
+ * vault into the hot wallet. Selects exactly as a withdrawal of 'all' does
2560
+ * (filter → sort → cap → commitment check), then creates ONE output of
2561
+ * `acc − estimateRelockFee(...)` committed to the CURRENT key set, and no
2562
+ * withdrawal output. This is how a key added later gains access to old
2563
+ * deposits and how a removed key loses it — on-chain the removed key can still
2564
+ * spend the outputs it was committed to, so the re-lock IS the revocation.
1125
2565
  *
1126
- * The same key the tap would have unwrapped, reached the other way — so this
1127
- * needs no card, no ceremony, and no device-local vault state at all. A
1128
- * mistyped passphrase is caught by prepareSpends, loudly. Returns null when
1129
- * the vault is already empty.
2566
+ * The screen runs one pass per tap while `cappedInputs > 0`, and asks for
2567
+ * another key when only `unreachable` outputs remain.
1130
2568
  */
1131
- export async function sweepVaultWithHD(
2569
+ export async function relockVault(
1132
2570
  w: VaultWallet,
1133
2571
  adminOriginator: string,
1134
- hd: HD,
1135
2572
  reason: string,
2573
+ chosenSerial: string,
1136
2574
  opts?: VaultTransferOptions
1137
- ): Promise<VaultSpendResult | null> {
2575
+ ): Promise<VaultSpendResult> {
2576
+ const scopeToken = vaultStore.captureScopeToken()
2577
+ return await withVaultMutation(async () => {
2578
+ assertVaultScope(scopeToken)
2579
+ requireReleased(opts, scopeToken, 'Re-locking the vault')
1138
2580
  await requireOnline(opts)
2581
+ assertVaultScope(scopeToken)
2582
+ await requirePrivateBackup(opts, 'Re-locking the vault')
2583
+ assertVaultScope(scopeToken)
2584
+ const meta = await requireMeta(scopeToken)
2585
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2586
+ const revokePubkey = opts?.revokePubkey
2587
+ const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, 'all', revokePubkey, scopeToken)
2588
+ if (sel.meta.pendingRemoval && !revokePubkey) {
2589
+ throw new VaultError('relock-required', 'Finish the pending key removal before another re-lock')
2590
+ }
2591
+ if (revokePubkey && sel.chosen.pubkey === revokePubkey) {
2592
+ throw new VaultError('wrong-key', 'The key being revoked cannot authorize its own replacement')
2593
+ }
2594
+ if (revokePubkey && sel.meta.pendingRemoval?.key.pubkey !== revokePubkey) {
2595
+ throw new VaultError('not-enrolled', 'The key being revoked does not match the pending removal')
2596
+ }
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
+ }
2600
+ await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, sel.meta, scopeToken)
2601
+ const fee = estimateRelockFee(sel.selected.length, R1C_LOCK_LEN(sel.keys.length))
2602
+ const relocked = sel.acc - fee
2603
+ if (relocked < VAULT_DEPOSIT_MIN) {
2604
+ throw new VaultError(
2605
+ 'too-small-to-relock',
2606
+ `Re-locking ${sel.acc} satoshis would leave ${relocked} after fees, below the ${VAULT_DEPOSIT_MIN} floor`
2607
+ )
2608
+ }
2609
+ const result = await spendVaultOutputs(
2610
+ w,
2611
+ adminOriginator,
2612
+ sel,
2613
+ reason,
2614
+ {
2615
+ outputs: [await newVaultOutput(
2616
+ w,
2617
+ adminOriginator,
2618
+ sel.meta,
2619
+ relocked,
2620
+ 'Vault re-lock',
2621
+ sel.saltInventory,
2622
+ scopeToken.chain
2623
+ )],
2624
+ labels: ['vault', 'vault-relock'],
2625
+ inputDescription: 'Vault re-lock',
2626
+ // Fixed, like the deposit and withdrawal descriptions (see
2627
+ // VaultSpendPlan): the caller's `reason` is NFC-prompt copy that names
2628
+ // the keys to tap, which read as nonsense in the activity list.
2629
+ description: 'Vault relock'
2630
+ },
2631
+ opts,
2632
+ scopeToken
2633
+ )
2634
+ if (revokePubkey) await vaultStore.markKeyRemovalBroadcast(scopeToken)
2635
+ return result
2636
+ })
2637
+ }
2638
+
2639
+ // ── coverage (spec §3.4 badges) ──────────────────────────────────────────
2640
+
2641
+ /**
2642
+ * How the vault's outputs relate to the CURRENT key list, from each output's
2643
+ * v6 record (the authenticated full key list — sufficient for a badge; the
2644
+ * withdraw path checks the real lock). `stale` counts outputs whose set
2645
+ * differs in EITHER direction; `missingKeys` are the current pubkeys some
2646
+ * output lacks ("{{count}} deposits not yet open to {{nickname}}");
2647
+ * `removedKeyOutputs` are outputs a pubkey no longer in meta can still open
2648
+ * ("still open to a removed key"). Any unreadable candidate fails the whole
2649
+ * authenticated scan rather than disappearing from the safety decision.
2650
+ */
2651
+ export async function getVaultKeyCoverage(w: VaultWallet, adminOriginator: string): Promise<VaultKeyCoverage> {
2652
+ const scopeToken = vaultStore.captureScopeToken()
2653
+ const meta = await vaultStore.getMeta(scopeToken)
2654
+ const current = meta?.keys.map(k => k.pubkey) ?? []
2655
+ const currentSet = new Set(current)
2656
+ const scan = await reduceVerifiedVaultOutputs(
2657
+ w,
2658
+ adminOriginator,
2659
+ () => ({ stale: 0, removedKeyOutputs: 0, missing: new Set<string>() }),
2660
+ (coverage, output) => {
2661
+ const set = new Set(output.ci.keys.map(key => key.pubkey))
2662
+ const same = set.size === currentSet.size && current.every(pk => set.has(pk))
2663
+ if (!same) coverage.stale++
2664
+ for (const pk of current) if (!set.has(pk)) coverage.missing.add(pk)
2665
+ if (output.ci.keys.some(key => !currentSet.has(key.pubkey))) coverage.removedKeyOutputs++
2666
+ },
2667
+ scopeToken
2668
+ )
2669
+ assertVaultScope(scopeToken)
2670
+ return {
2671
+ outputs: scan.outputs,
2672
+ stale: scan.state.stale,
2673
+ missingKeys: current.filter(pk => scan.state.missing.has(pk)), // meta order, each once
2674
+ removedKeyOutputs: scan.state.removedKeyOutputs
2675
+ }
2676
+ }
2677
+
2678
+ /**
2679
+ * How many vault outputs would lose every remaining committed key if `pubkey`
2680
+ * were removed (spec §3.4) — the exact predicate Remove must satisfy: an
2681
+ * output stays spendable after removal only if its baked key set (the
2682
+ * authenticated v6 record — sufficient here, as in getVaultKeyCoverage; the
2683
+ * withdraw path checks the real lock) intersects the CURRENT key list minus
2684
+ * the one being removed. Reads the same strict listOutputs scan as
2685
+ * getVaultKeyCoverage; an unreadable candidate fails closed.
2686
+ */
2687
+ export async function orphanedIfRemoved(w: VaultWallet, adminOriginator: string, pubkey: string): Promise<number> {
2688
+ const scopeToken = vaultStore.captureScopeToken()
2689
+ const meta = await vaultStore.getMeta(scopeToken)
2690
+ const remaining = new Set((meta?.keys.map(k => k.pubkey) ?? []).filter(pk => pk !== pubkey))
2691
+ const { state } = await reduceVerifiedVaultOutputs(
2692
+ w,
2693
+ adminOriginator,
2694
+ () => ({ orphaned: 0 }),
2695
+ (result, output) => {
2696
+ if (!output.ci.keys.some(key => remaining.has(key.pubkey))) result.orphaned++
2697
+ },
2698
+ scopeToken
2699
+ )
2700
+ assertVaultScope(scopeToken)
2701
+ return state.orphaned
2702
+ }
2703
+
2704
+ /**
2705
+ * Start key removal only after a fully authenticated scan proves every current
2706
+ * output remains open to an active key. The store transition is the durable
2707
+ * point of no return for new deposits: it removes the target from active keys
2708
+ * while retaining the full record in pendingRemoval before any createAction.
2709
+ */
2710
+ export async function beginVaultKeyRemoval(
2711
+ w: VaultWallet,
2712
+ adminOriginator: string,
2713
+ serial: string
2714
+ ): Promise<{ complete: boolean; meta: VaultMeta }> {
2715
+ const scopeToken = vaultStore.captureScopeToken()
2716
+ return await withVaultMutation(async () => {
2717
+ assertVaultScope(scopeToken)
2718
+ const meta = await requireMeta(scopeToken)
2719
+ const target = meta.keys.find(key => key.serial === serial)
2720
+ if (!target) throw new VaultError('not-enrolled', `Key ${serial} is not enrolled`)
2721
+ if (meta.keys.length <= VAULT_MIN_KEYS) {
2722
+ throw new VaultError('last-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys`)
2723
+ }
2724
+ await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2725
+ let pendingAction = false
2726
+ await scanVaultActions(
2727
+ w,
2728
+ adminOriginator,
2729
+ { includeLabels: true },
2730
+ // Only an action that has NOT reached the network blocks: it reserves
2731
+ // the very outputs the removal re-lock has to spend. A broadcast one
2732
+ // reserves nothing — its vault output is an ordinary unconfirmed UTXO
2733
+ // the listOutputs scan below authenticates like any other. 'unproven' is
2734
+ // what the activity list shows as "Accepted" and stands until the merkle
2735
+ // proof arrives, so blocking on it refused every removal on a funded
2736
+ // vault and told the user to re-lock — the step this refusal itself
2737
+ // prevented.
2738
+ action => {
2739
+ if (PENDING_ACTION_STATUSES.has(action.status) && !BROADCAST_ACTION_STATUSES.has(action.status)) {
2740
+ pendingAction = true
2741
+ }
2742
+ },
2743
+ scopeToken
2744
+ )
2745
+ if (pendingAction) {
2746
+ throw new VaultError('action-pending', 'Wait for pending vault actions before removing a key')
2747
+ }
2748
+ const remaining = new Set(meta.keys.filter(key => key.serial !== serial).map(key => key.pubkey))
2749
+ const before = await reduceVerifiedVaultOutputs(
2750
+ w,
2751
+ adminOriginator,
2752
+ () => ({ wouldOrphan: false }),
2753
+ (state, output) => {
2754
+ requireOutputMetaConsistency([output], meta)
2755
+ if (!output.ci.keys.some(key => remaining.has(key.pubkey))) state.wouldOrphan = true
2756
+ },
2757
+ scopeToken,
2758
+ 'repair-unsigned'
2759
+ )
2760
+ if (before.state.wouldOrphan) {
2761
+ throw new VaultError('relock-required', 'A vault output would lose every remaining key')
2762
+ }
2763
+ const pending = await vaultStore.beginKeyRemoval(serial, scopeToken)
2764
+ if (before.outputs > 0) return { complete: false, meta: pending }
2765
+
2766
+ // Empty removal has no transaction to prove. Recheck after the metadata
2767
+ // transition because the wallet monitor is outside the process mutex.
2768
+ const after = await reduceVerifiedVaultOutputs(
2769
+ w,
2770
+ adminOriginator,
2771
+ () => undefined,
2772
+ () => {},
2773
+ scopeToken
2774
+ )
2775
+ if (after.outputs > 0) {
2776
+ await vaultStore.cancelUnbroadcastKeyRemoval(scopeToken)
2777
+ throw new VaultError('action-pending', 'A vault output appeared while removing the key')
2778
+ }
2779
+ return { complete: true, meta: await vaultStore.finalizeEmptyKeyRemoval(scopeToken) }
2780
+ })
2781
+ }
2782
+
2783
+ function actionCarriesCurrentRelock(
2784
+ action: VaultActionRow,
2785
+ meta: VaultMeta,
2786
+ expectedChain: VaultScopeToken['chain'],
2787
+ saltInventory?: VaultSaltInventory
2788
+ ): boolean {
2789
+ if (action.status === 'failed' || !action.labels?.includes('vault-relock')) return false
2790
+ const vaultOutputs = (action.outputs ?? []).filter(output => output.basket === VAULT_BASKET)
2791
+ if (vaultOutputs.length !== 1) return false
2792
+ const output = vaultOutputs[0]
2793
+ if (!Number.isSafeInteger(output.satoshis) || output.satoshis < 0) {
2794
+ throw new VaultError('no-transaction', 'Vault re-lock action has an invalid output value')
2795
+ }
2796
+ if (!output.customInstructions || !output.lockingScript) {
2797
+ throw new VaultError('template-invalid', 'Vault re-lock action has unreadable output metadata or script')
2798
+ }
2799
+ const ci = decodeVaultInstructions(output.customInstructions)
2800
+ if (!ci) throw new VaultError('template-invalid', 'Vault re-lock action has invalid recovery metadata')
2801
+ if (ci.chain !== expectedChain) {
2802
+ throw new VaultError('template-invalid', 'Vault re-lock action belongs to a different network')
2803
+ }
2804
+ let lock: LockingScript
1139
2805
  try {
1140
- // The node is the caller's own and no ceremony can revoke it, so the thunk
1141
- // is transparent here — it exists for the withdrawal's handle (see
1142
- // VaultKeySource).
1143
- return await spendVaultOutputs(w, adminOriginator, 'all', reason, () => hd, {
1144
- revaultRemainder: false,
1145
- ...opts
1146
- })
1147
- } catch (e) {
1148
- if (e instanceof VaultError && e.code === 'vault-empty') return null
1149
- throw e
2806
+ lock = LockingScript.fromHex(output.lockingScript)
2807
+ } catch {
2808
+ throw new VaultError('template-invalid', 'Vault re-lock action has a malformed locking script')
2809
+ }
2810
+ verifyInstructionsAgainstLock(ci, lock, `Vault re-lock ${action.txid ?? action.reference ?? ''}`)
2811
+ const carriesCurrentRelock = (
2812
+ ci.vaultId === meta.vaultId &&
2813
+ ci.createdAt === meta.createdAt &&
2814
+ ci.revision === meta.revision &&
2815
+ sameInstructionKeys(meta.keys, ci.keys)
2816
+ )
2817
+ if (carriesCurrentRelock && saltInventory) {
2818
+ rememberVaultSalt(
2819
+ saltInventory,
2820
+ ci,
2821
+ lock,
2822
+ vaultActionOutputId(action, output.outputIndex),
2823
+ expectedChain
2824
+ )
1150
2825
  }
2826
+ return carriesCurrentRelock
2827
+ }
2828
+
2829
+ /** Every source of a removal re-lock must be an exact R1C output that still
2830
+ * authorizes the tombstoned key. This binds action-history evidence to the
2831
+ * authority being revoked rather than trusting a label or replacement alone. */
2832
+ function actionSpendsPendingRemovalKey(
2833
+ action: VaultActionRow,
2834
+ meta: VaultMeta,
2835
+ inventory: VaultSaltInventory
2836
+ ): boolean {
2837
+ const pending = meta.pendingRemoval
2838
+ const inputs = action.inputs ?? []
2839
+ if (!pending || inputs.length === 0) return false
2840
+ return inputs.every(input => {
2841
+ if (!input.sourceOutpoint || !input.sourceLockingScript) return false
2842
+ try {
2843
+ const lock = LockingScript.fromHex(input.sourceLockingScript)
2844
+ bakedCommitments(lock)
2845
+ const record = inventory.outputRecords.get(input.sourceOutpoint.toLowerCase())
2846
+ return record !== undefined &&
2847
+ record.lockingScript === lock.toHex() &&
2848
+ record.pubkeys.has(pending.key.pubkey)
2849
+ } catch {
2850
+ return false
2851
+ }
2852
+ })
2853
+ }
2854
+
2855
+ /** A crash before signAction can leave an unsigned re-lock reserving all of
2856
+ * its sources. It is safe to abort only when the action has no txid, its exact
2857
+ * replacement authenticates against the pending revision, and every input is
2858
+ * a real R1C lock that still authorizes the tombstoned key. Anything less is
2859
+ * an unknown broadcast/source state and remains fail-closed. */
2860
+ function isUnbroadcastPendingRemovalRelock(
2861
+ action: VaultActionRow,
2862
+ meta: VaultMeta,
2863
+ expectedChain: VaultScopeToken['chain'],
2864
+ saltInventory: VaultSaltInventory
2865
+ ): boolean {
2866
+ const pending = meta.pendingRemoval
2867
+ if (!pending || action.status !== 'unsigned' || !!action.txid || !action.reference) return false
2868
+ if (!actionCarriesCurrentRelock(action, meta, expectedChain, saltInventory)) return false
2869
+ return actionSpendsPendingRemovalKey(action, meta, saltInventory)
2870
+ }
2871
+
2872
+ /** Reconcile a durable pending removal. A bounded broadcast marker is inferred
2873
+ * 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. */
2877
+ export async function finalizeVaultKeyRemoval(
2878
+ w: VaultWallet,
2879
+ adminOriginator: string
2880
+ ): Promise<boolean> {
2881
+ const scopeToken = vaultStore.captureScopeToken()
2882
+ return await withVaultMutation(async () => {
2883
+ assertVaultScope(scopeToken)
2884
+ let meta = await requireMeta(scopeToken)
2885
+ const pendingAtStart = meta.pendingRemoval
2886
+ if (!pendingAtStart) return false
2887
+ const first = await reduceVerifiedVaultOutputs(
2888
+ w,
2889
+ adminOriginator,
2890
+ () => ({ authorizesPendingKey: false }),
2891
+ (state, output) => {
2892
+ requireOutputMetaConsistency([output], meta)
2893
+ if (output.ci.keys.some(key => key.pubkey === pendingAtStart.key.pubkey)) {
2894
+ state.authorizesPendingKey = true
2895
+ }
2896
+ },
2897
+ scopeToken,
2898
+ 'allow'
2899
+ )
2900
+
2901
+ const unsignedRelockReferences: string[] = []
2902
+ let invalidCurrentRelock = false
2903
+ let matchingRelock = false
2904
+ let completedMatchingRelock = false
2905
+ let actionStateBlocks = false
2906
+ const actionSaltInventory = emptyVaultSaltInventory()
2907
+ await addHistoricalVaultSaltInventory(w, adminOriginator, actionSaltInventory, meta, scopeToken)
2908
+ await scanVaultActions(w, adminOriginator, {
2909
+ labels: [],
2910
+ includeLabels: true,
2911
+ includeInputs: true,
2912
+ includeInputSourceLockingScripts: true,
2913
+ includeOutputs: true,
2914
+ includeOutputLockingScripts: true
2915
+ }, action => {
2916
+ if (isUnbroadcastPendingRemovalRelock(action, meta, scopeToken.chain, actionSaltInventory)) {
2917
+ unsignedRelockReferences.push(action.reference!)
2918
+ }
2919
+ if (action.txid && actionCarriesCurrentRelock(action, meta, scopeToken.chain, actionSaltInventory)) {
2920
+ if (!actionSpendsPendingRemovalKey(action, meta, actionSaltInventory)) invalidCurrentRelock = true
2921
+ else {
2922
+ matchingRelock = true
2923
+ if (action.status === 'completed') completedMatchingRelock = true
2924
+ }
2925
+ }
2926
+ if (!actionTouchesVault(action)) return
2927
+ if (PENDING_ACTION_STATUSES.has(action.status)) {
2928
+ actionStateBlocks = true
2929
+ } else if (action.status === 'failed') {
2930
+ const labels = new Set(action.labels ?? [])
2931
+ if (!(labels.has('vault-deposit') && !labels.has('vault-withdraw') && !labels.has('vault-relock'))) {
2932
+ actionStateBlocks = true
2933
+ }
2934
+ } else if (action.status !== 'completed') {
2935
+ actionStateBlocks = true
2936
+ }
2937
+ }, scopeToken, true)
2938
+
2939
+ assertVaultScope(scopeToken)
2940
+ await verifyVaultSaltDerivations(w, adminOriginator, actionSaltInventory)
2941
+ assertVaultScope(scopeToken)
2942
+
2943
+ // A process death between createAction and signAction is provably
2944
+ // unbroadcast only in the strict unsigned/no-txid shape above. Release that
2945
+ // reservation, then require an authenticated rescan to show the old locks
2946
+ // again. The pending-removal tombstone stays in place for an explicit retry.
2947
+ let abortedUnsigned = false
2948
+ for (const reference of unsignedRelockReferences) {
2949
+ try {
2950
+ assertVaultScope(scopeToken)
2951
+ await w.abortAction({ reference }, adminOriginator)
2952
+ assertVaultScope(scopeToken)
2953
+ abortedUnsigned = true
2954
+ } catch {
2955
+ return false
2956
+ }
2957
+ }
2958
+ if (abortedUnsigned) {
2959
+ const restored = await reduceVerifiedVaultOutputs(
2960
+ w,
2961
+ adminOriginator,
2962
+ () => ({ authorizesPendingKey: false }),
2963
+ (state, output) => {
2964
+ requireOutputMetaConsistency([output], meta)
2965
+ if (output.ci.keys.some(key => key.pubkey === pendingAtStart.key.pubkey)) {
2966
+ state.authorizesPendingKey = true
2967
+ }
2968
+ },
2969
+ scopeToken,
2970
+ 'allow'
2971
+ )
2972
+ if (!restored.state.authorizesPendingKey) {
2973
+ throw new VaultError('no-transaction', 'Aborted re-lock did not restore its reserved vault sources')
2974
+ }
2975
+ return false
2976
+ }
2977
+
2978
+ if (invalidCurrentRelock) return false
2979
+ if (matchingRelock) await vaultStore.markKeyRemovalBroadcast(scopeToken)
2980
+ meta = await requireMeta(scopeToken)
2981
+ const pending = meta.pendingRemoval
2982
+ if (!pending) return true
2983
+ if (actionStateBlocks) return false
2984
+ if (first.state.authorizesPendingKey) return false
2985
+
2986
+ if (pending.state === 'prepared') {
2987
+ // No output ever needed a re-lock and no matching broadcast was found.
2988
+ const second = await reduceVerifiedVaultOutputs(
2989
+ w,
2990
+ adminOriginator,
2991
+ () => ({ authorizesPendingKey: false }),
2992
+ (state, output) => {
2993
+ requireOutputMetaConsistency([output], meta)
2994
+ if (output.ci.keys.some(key => key.pubkey === pending.key.pubkey)) state.authorizesPendingKey = true
2995
+ },
2996
+ scopeToken,
2997
+ 'allow'
2998
+ )
2999
+ if (second.state.authorizesPendingKey) return false
3000
+ await vaultStore.finalizeEmptyKeyRemoval(scopeToken)
3001
+ return true
3002
+ }
3003
+
3004
+ if (!completedMatchingRelock) return false
3005
+
3006
+ const second = await reduceVerifiedVaultOutputs(
3007
+ w,
3008
+ adminOriginator,
3009
+ () => ({ authorizesPendingKey: false }),
3010
+ (state, output) => {
3011
+ requireOutputMetaConsistency([output], meta)
3012
+ if (output.ci.keys.some(key => key.pubkey === pending.key.pubkey)) state.authorizesPendingKey = true
3013
+ },
3014
+ scopeToken,
3015
+ 'allow'
3016
+ )
3017
+ if (second.state.authorizesPendingKey) return false
3018
+ await vaultStore.finalizeProvenKeyRemoval(scopeToken)
3019
+ return true
3020
+ })
1151
3021
  }