@bsv/expo-wallet-toolbox 0.24.3 → 0.25.1

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.
@@ -72,8 +72,10 @@ import { VaultError } from './types'
72
72
  import { metaFromVerifiedOutputs, VAULT_MAX_KEYS, VAULT_MIN_KEYS } from './VaultKeyService'
73
73
  import { vaultStore, VaultKeyRecord, VaultMeta, type VaultScopeToken, type VaultStoreScope } from './vaultStore'
74
74
  import { computeVaultMetaAuthorityTag, verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
75
- import { requireVaultOutputKeyPossession } from './outputAuthority'
75
+ import { requireVaultKeyChallenge, requireVaultOutputKeyPossession } from './outputAuthority'
76
+ import { planLockKeys, type LockKeyPlan } from './lockKeys'
76
77
  import { forgetSerialsNoLongerEnrolledForIdentity } from './enrolledSerialRegistry'
78
+ import { getVaultChainLookup, lookupMarker, noteSaltFloor, saltFloorFor, type VaultChainLookup } from './markerLookup'
77
79
 
78
80
  export const VAULT_BASKET = 'admin vault'
79
81
  /** Wallet HMAC domain used only for Vault output salts. */
@@ -249,6 +251,13 @@ export interface VaultTransferOptions {
249
251
  * pubkey and write replacements under the remaining active keys. A durable
250
252
  * pendingRemoval tombstone must already retain the revoked key record. */
251
253
  revokePubkey?: string
254
+ /** Re-lock or partial-withdrawal remainder: allow the new lock to leave out
255
+ * keys that no tap on this phone has proven (after a clear warning). Without
256
+ * it such a lock is refused with `keys-unproven`. Never used by deposits. */
257
+ acceptDroppingUnproven?: boolean
258
+ /** Re-lock or remainder: serial of the staged key to commit into the new
259
+ * lock. Must equal `meta.staged.serial`. */
260
+ activateStagedKey?: string
252
261
  }
253
262
 
254
263
  export interface VaultSpendResult {
@@ -522,6 +531,26 @@ async function scanVaultOutputPages(
522
531
  return offset
523
532
  }
524
533
 
534
+ /** Every outpoint already in the Vault basket, as lowercase `txid.vout`. The
535
+ * scan uses it to merge by outpoint, so a second run adds only what is new. */
536
+ export async function listVaultBasketOutpoints(
537
+ w: VaultWallet,
538
+ adminOriginator: string,
539
+ scopeToken?: VaultScopeToken
540
+ ): Promise<Set<string>> {
541
+ const outpoints = new Set<string>()
542
+ await scanVaultOutputPages(
543
+ w,
544
+ adminOriginator,
545
+ 'locking scripts',
546
+ outputs => {
547
+ for (const output of outputs) outpoints.add(output.outpoint.toLowerCase())
548
+ },
549
+ scopeToken
550
+ )
551
+ return outpoints
552
+ }
553
+
525
554
  /** An empty-basket safety decision needs one authoritative row, not every
526
555
  * locking script in the basket. A contradictory total still fails closed. */
527
556
  async function vaultHasOutputs(
@@ -1795,6 +1824,92 @@ function recoveredSupersedesExisting(existing: VaultMeta, recovered: VaultMeta):
1795
1824
  return true
1796
1825
  }
1797
1826
 
1827
+ /** Whether `keys` names a key (serial AND pubkey) that `meta` does not know:
1828
+ * not among its keys, its staged key or its pending-removal key. A scan uses it
1829
+ * to keep a planted higher revision from adding a key to existing local meta. */
1830
+ export function introducesUnknownKey(
1831
+ meta: Pick<VaultMeta, 'keys' | 'staged' | 'pendingRemoval'>,
1832
+ keys: readonly Pick<VaultKeyRecord, 'serial' | 'pubkey'>[]
1833
+ ): boolean {
1834
+ const known = [
1835
+ ...meta.keys,
1836
+ ...(meta.staged ? [meta.staged] : []),
1837
+ ...(meta.pendingRemoval ? [meta.pendingRemoval.key] : [])
1838
+ ]
1839
+ return keys.some(key => !known.some(k => k.serial === key.serial && k.pubkey === key.pubkey))
1840
+ }
1841
+
1842
+ /** The group a restore chose: meta is rebuilt from its records only. */
1843
+ export interface VaultMetaGroup {
1844
+ vaultId: string
1845
+ createdAt: number
1846
+ /** Highest revision of the group. */
1847
+ revision: number
1848
+ /** Key list at that revision. */
1849
+ keys: readonly Pick<VaultKeyRecord, 'serial' | 'pubkey'>[]
1850
+ }
1851
+
1852
+ const sameSerialPubkeys = (
1853
+ a: readonly Pick<VaultKeyRecord, 'serial' | 'pubkey'>[],
1854
+ b: readonly Pick<VaultKeyRecord, 'serial' | 'pubkey'>[]
1855
+ ): boolean => a.length === b.length && a.every((k, i) => k.serial === b[i].serial && k.pubkey === b[i].pubkey)
1856
+
1857
+ /**
1858
+ * Pick the records metaFromVerifiedOutputs may see, or null when nothing can be
1859
+ * chosen without guessing (the caller then keeps the existing meta). The
1860
+ * validator throws on disagreement, and a mnemonic-only attacker can plant a
1861
+ * disagreeing record, so a disagreement is resolved here, never thrown:
1862
+ * - `only` (a restore chose one group): that group's top-revision records.
1863
+ * - existing meta: its own lineage, at its revision or higher, naming no
1864
+ * unknown key; older records cannot supersede it. One key list at the top.
1865
+ * - neither: one lineage and one key list at its top revision, else null.
1866
+ */
1867
+ function selectMetaRecords(
1868
+ records: readonly { instructions: VaultInstructions; txid: string }[],
1869
+ existing: VaultMeta | null,
1870
+ only?: VaultMetaGroup
1871
+ ): { instructions: VaultInstructions; txid: string }[] | null {
1872
+ let pool = [...records]
1873
+ if (only) {
1874
+ pool = pool.filter(
1875
+ r =>
1876
+ r.instructions.vaultId === only.vaultId &&
1877
+ r.instructions.createdAt === only.createdAt &&
1878
+ r.instructions.revision === only.revision &&
1879
+ sameSerialPubkeys(r.instructions.keys, only.keys)
1880
+ )
1881
+ }
1882
+ if (existing) {
1883
+ pool = pool.filter(
1884
+ r =>
1885
+ r.instructions.vaultId === existing.vaultId &&
1886
+ r.instructions.createdAt === existing.createdAt &&
1887
+ r.instructions.revision >= existing.revision &&
1888
+ !introducesUnknownKey(existing, r.instructions.keys)
1889
+ )
1890
+ }
1891
+ if (pool.length === 0) return null
1892
+ // Without a chosen group or an existing meta, two lineages cannot be ranked.
1893
+ const lineage = pool[0].instructions
1894
+ if (pool.some(r => r.instructions.vaultId !== lineage.vaultId || r.instructions.createdAt !== lineage.createdAt)) {
1895
+ return null
1896
+ }
1897
+ const top = Math.max(...pool.map(r => r.instructions.revision))
1898
+ const atTop = pool.filter(r => r.instructions.revision === top)
1899
+ const first = atTop[0].instructions
1900
+ if (
1901
+ atTop.some(
1902
+ r =>
1903
+ r.instructions.vaultId !== first.vaultId ||
1904
+ r.instructions.createdAt !== first.createdAt ||
1905
+ !sameSerialPubkeys(r.instructions.keys, first.keys)
1906
+ )
1907
+ ) {
1908
+ return null
1909
+ }
1910
+ return atTop
1911
+ }
1912
+
1798
1913
  /** Restore a missing scoped cache only from currently spendable outputs whose
1799
1914
  * real source values, exact R1C locks, salted commitments, v6 recovery records, and
1800
1915
  * wallet salt-key derivations all authenticate. Conflict selection belongs to
@@ -1808,7 +1923,11 @@ function recoveredSupersedesExisting(existing: VaultMeta, recovered: VaultMeta):
1808
1923
  * always runs; the existing record is kept only when it is not superseded
1809
1924
  * (recoveredSupersedesExisting), and restored the same way — through
1810
1925
  * vaultStore.restoreVerifiedMeta — when it is. */
1811
- export async function recoverVaultMetaFromOutputs(w: VaultWallet, adminOriginator: string): Promise<VaultMeta | null> {
1926
+ export async function recoverVaultMetaFromOutputs(
1927
+ w: VaultWallet,
1928
+ adminOriginator: string,
1929
+ only?: VaultMetaGroup
1930
+ ): Promise<VaultMeta | null> {
1812
1931
  const scopeToken = vaultStore.captureScopeToken()
1813
1932
  return await withVaultMutation(async () => {
1814
1933
  assertVaultScope(scopeToken)
@@ -1826,7 +1945,16 @@ export async function recoverVaultMetaFromOutputs(w: VaultWallet, adminOriginato
1826
1945
  )
1827
1946
  if (scan.outputs === 0) return existing
1828
1947
  await verifyVaultSaltDerivations(w, adminOriginator, scan.inventory)
1829
- const recovered = metaFromVerifiedOutputs(scan.state)
1948
+ // Build meta only from records that agree with each other and with the
1949
+ // chosen group or the existing meta, so a planted record never reaches a
1950
+ // metaFromVerifiedOutputs throw (restore must not wedge, R1).
1951
+ const records = selectMetaRecords(scan.state, existing, only)
1952
+ if (!records) return existing
1953
+ const recovered = metaFromVerifiedOutputs(records)
1954
+ // A scan never adds a key to existing local meta: a recovered record that
1955
+ // names a key local meta does not know (a planted higher revision) is
1956
+ // ignored. The crash-recovery case (every key known) still supersedes.
1957
+ if (existing && introducesUnknownKey(existing, recovered.keys)) return existing
1830
1958
  if (existing && !recoveredSupersedesExisting(existing, recovered)) return existing
1831
1959
  const scope = vaultStore.getScope()
1832
1960
  await vaultStore.restoreVerifiedMeta(
@@ -2086,10 +2214,104 @@ function requireLockableKeyCount(count: number): void {
2086
2214
  }
2087
2215
  }
2088
2216
 
2217
+ /**
2218
+ * Pick the salt index for a new Vault output (hardening: salt-reuse).
2219
+ *
2220
+ * The local inventory only knows the indexes this phone has seen. After a
2221
+ * full withdrawal (the witness publishes the salt) and a wiped phone the
2222
+ * local floor is 0 again, so the old rule re-derived an index whose salt was
2223
+ * already public. Every candidate index is therefore looked up on its marker
2224
+ * address first. Any history at all (confirmed, unconfirmed, dust, a
2225
+ * truncated window with rows) means the index is used and is skipped. A
2226
+ * lookup that fails with no rows fails closed: nothing is allocated, and the
2227
+ * caller has not asked for a tap yet.
2228
+ */
2229
+ export async function allocateSaltIndex(args: {
2230
+ w: VaultWallet
2231
+ adminOriginator: string
2232
+ chain: VaultScopeToken['chain']
2233
+ storageKey: string
2234
+ lookup: VaultChainLookup
2235
+ /** inventory.maxKeyIndex */
2236
+ floor: number
2237
+ /** default 64 */
2238
+ maxProbe?: number
2239
+ }): Promise<number> {
2240
+ const { w, adminOriginator, chain, storageKey, lookup } = args
2241
+ const maxProbe = args.maxProbe ?? 64
2242
+ const start = Math.max(args.floor, saltFloorFor(storageKey)) + 1
2243
+ for (let k = start; k < start + maxProbe; k++) {
2244
+ const script = (await deriveVaultMarkerScript(w, adminOriginator, chain, String(k))).toHex()
2245
+ let history: Awaited<ReturnType<typeof lookupMarker>>
2246
+ try {
2247
+ history = await lookupMarker(lookup, script)
2248
+ } catch (e) {
2249
+ if (e instanceof VaultError) throw e
2250
+ // A raw lookup error is unknown, never "free": fail closed.
2251
+ throw new VaultError(
2252
+ 'lookup-unknown',
2253
+ `Could not check whether Vault salt index ${k} is already used (${e instanceof Error ? e.message : 'lookup failed'})`,
2254
+ undefined,
2255
+ { reason: 'request-failed', index: k }
2256
+ )
2257
+ }
2258
+ if (history.status === 'none') {
2259
+ noteSaltFloor(storageKey, k - 1)
2260
+ return k
2261
+ }
2262
+ if (history.status === 'found' || history.txids.length > 0) continue
2263
+ throw new VaultError(
2264
+ 'lookup-unknown',
2265
+ `Could not check whether Vault salt index ${k} is already used (${history.reason})`,
2266
+ undefined,
2267
+ { reason: history.reason, index: k }
2268
+ )
2269
+ }
2270
+ throw new VaultError(
2271
+ 'lookup-unknown',
2272
+ `Every one of the next ${maxProbe} Vault salt indexes is already used`,
2273
+ undefined,
2274
+ { reason: 'probe-limit', index: start + maxProbe - 1 }
2275
+ )
2276
+ }
2277
+
2278
+ /** The record a new output is built from: the plan's keys and revision. */
2279
+ function lockMeta(
2280
+ meta: Pick<VaultMeta, 'vaultId' | 'createdAt'>,
2281
+ plan: LockKeyPlan
2282
+ ): Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt'> & { keys: VaultKeyRecord[] } {
2283
+ return { vaultId: meta.vaultId, createdAt: meta.createdAt, revision: plan.revision, keys: plan.lockKeys }
2284
+ }
2285
+
2286
+ /** After a spend whose lock used a different key set than the list: one tagged
2287
+ * write of keys and revision. Re-reads and re-authenticates meta first. */
2288
+ async function commitPlannedKeySet(
2289
+ w: VaultWallet,
2290
+ adminOriginator: string,
2291
+ scopeToken: VaultScopeToken,
2292
+ plan: LockKeyPlan
2293
+ ): Promise<void> {
2294
+ assertVaultScope(scopeToken)
2295
+ const scope = vaultStore.getScope()
2296
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
2297
+ const currentMeta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
2298
+ await vaultStore.commitLockKeySet(
2299
+ {
2300
+ keys: plan.lockKeys,
2301
+ revision: plan.revision,
2302
+ clearStaged: plan.activated !== undefined,
2303
+ ...(plan.activated ? { activated: plan.activated } : {})
2304
+ },
2305
+ scopeToken,
2306
+ next => computeVaultMetaAuthorityTag(asHmacWallet(w), adminOriginator, next, scope),
2307
+ currentMeta
2308
+ )
2309
+ }
2310
+
2089
2311
  async function newVaultOutput(
2090
2312
  w: VaultWallet,
2091
2313
  adminOriginator: string,
2092
- meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys'>,
2314
+ meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt'> & { keys: VaultKeyRecord[] },
2093
2315
  satoshis: number,
2094
2316
  outputDescription: string,
2095
2317
  inventory: VaultSaltInventory,
@@ -2103,7 +2325,16 @@ async function newVaultOutput(
2103
2325
  requireLockableKeyCount(meta.keys.length)
2104
2326
  const { chain } = scopeToken
2105
2327
  const pubkeys = meta.keys.map(k => k.pubkey)
2106
- const keyIndex = inventory.maxKeyIndex + 1
2328
+ // The chain, not only local history, decides which salt index is free. This
2329
+ // runs before requireVaultOutputKeyPossession, so a refusal costs no tap.
2330
+ const keyIndex = await allocateSaltIndex({
2331
+ w,
2332
+ adminOriginator,
2333
+ chain,
2334
+ storageKey: scopeToken.storageKey,
2335
+ lookup: getVaultChainLookup(chain),
2336
+ floor: inventory.maxKeyIndex
2337
+ })
2107
2338
  if (!Number.isSafeInteger(keyIndex)) {
2108
2339
  throw new VaultError('template-invalid', 'Vault salt key index is exhausted')
2109
2340
  }
@@ -2378,12 +2609,16 @@ export async function depositToVault(
2378
2609
  // XR-002: authenticate meta BEFORE it is used to build a new output.
2379
2610
  const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
2380
2611
  if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal before depositing')
2381
- if (meta.recovery?.required) {
2382
- const adopted = new Set(meta.recovery.adoptedSerials)
2383
- if (meta.keys.filter(key => adopted.has(key.serial)).length < VAULT_MIN_KEYS) {
2384
- throw new VaultError('key-not-adopted', 'Verify at least two recovered YubiKeys before depositing new funds')
2385
- }
2386
- }
2612
+ // planted-key: new funds are locked only to keys a tap has proven. Refused
2613
+ // here, before the salt lookup, any tap and createAction.
2614
+ const depositKeySerial =
2615
+ opts?.outputKeySerial ?? (meta.keys.find(k => k.serial === meta.lastUsedSerial) ?? meta.keys[0]).serial
2616
+ const depositPlan = planLockKeys({
2617
+ meta,
2618
+ scopeToken,
2619
+ chosenSerial: depositKeySerial,
2620
+ purpose: 'deposit'
2621
+ })
2387
2622
  await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
2388
2623
  const existing = await reduceVerifiedVaultOutputs(
2389
2624
  w,
@@ -2399,12 +2634,12 @@ export async function depositToVault(
2399
2634
  const output = await newVaultOutput(
2400
2635
  w,
2401
2636
  adminOriginator,
2402
- meta,
2637
+ lockMeta(meta, depositPlan),
2403
2638
  satoshis,
2404
2639
  'Vault deposit',
2405
2640
  saltInventory,
2406
2641
  scopeToken,
2407
- opts?.outputKeySerial
2642
+ depositKeySerial
2408
2643
  )
2409
2644
  let reference: string | undefined
2410
2645
  let heldTxid: string | undefined
@@ -2506,6 +2741,11 @@ interface VaultSelection {
2506
2741
  beef?: number[]
2507
2742
  /** Salts, derivation IDs and script hashes already present in authenticated history. */
2508
2743
  saltInventory: VaultSaltInventory
2744
+ /** The first record that disagrees with local meta (another enrollment, a
2745
+ * newer revision, other keys at the active revision). Selection does not throw
2746
+ * it: only an operation that creates a new output refuses on it, so a full
2747
+ * withdrawal stays open (R1). */
2748
+ consistencyError?: VaultError
2509
2749
  }
2510
2750
 
2511
2751
  /**
@@ -2575,6 +2815,7 @@ async function selectVaultInputs(
2575
2815
  unreachableSatoshis: number
2576
2816
  otherPubkeys: Set<string>
2577
2817
  selected: Candidate[]
2818
+ consistencyError?: VaultError
2578
2819
  }
2579
2820
  const add = (current: number, value: number, where: string): number => {
2580
2821
  const next = current + value
@@ -2596,7 +2837,12 @@ async function selectVaultInputs(
2596
2837
  selected: []
2597
2838
  }),
2598
2839
  (state, output, sources) => {
2599
- requireOutputMetaConsistency([output], meta)
2840
+ try {
2841
+ requireOutputMetaConsistency([output], meta)
2842
+ } catch (error) {
2843
+ if (!(error instanceof VaultError)) throw error
2844
+ state.consistencyError ??= error
2845
+ }
2600
2846
  if (requiredPubkey && !hasPubkey(output, requiredPubkey)) return
2601
2847
  state.decodable++
2602
2848
  state.total = add(state.total, output.satoshis, 'Vault selection')
@@ -2681,7 +2927,8 @@ async function selectVaultInputs(
2681
2927
  cappedInputs,
2682
2928
  unreachable,
2683
2929
  beef: sourceBeef.toBinary(),
2684
- saltInventory: verified.inventory
2930
+ saltInventory: verified.inventory,
2931
+ consistencyError: scan.consistencyError
2685
2932
  }
2686
2933
  }
2687
2934
 
@@ -3159,6 +3406,50 @@ function requireWithdrawalAmount(amount: number | 'all'): void {
3159
3406
  }
3160
3407
  }
3161
3408
 
3409
+ /** What a withdrawal's new lock would hold (see previewVaultWithdrawal). */
3410
+ export interface VaultLockPlanPreview {
3411
+ /** A remainder at or above the floor would create a new lock. */
3412
+ needsRelock: boolean
3413
+ provenSerials: string[]
3414
+ unprovenSerials: string[]
3415
+ /** Fewer than two keys could be locked. */
3416
+ blocked?: 'not-enough-proven-keys'
3417
+ }
3418
+
3419
+ function previewLockPlan(
3420
+ meta: VaultMeta,
3421
+ scopeToken: VaultScopeToken,
3422
+ chosenSerial: string,
3423
+ needsRelock: boolean
3424
+ ): VaultLockPlanPreview | undefined {
3425
+ try {
3426
+ const plan = planLockKeys({
3427
+ meta,
3428
+ scopeToken,
3429
+ chosenSerial,
3430
+ purpose: 'remainder',
3431
+ acceptDroppingUnproven: true
3432
+ })
3433
+ return {
3434
+ needsRelock,
3435
+ provenSerials: plan.lockKeys.map(k => k.serial),
3436
+ unprovenSerials: plan.dropped.map(k => k.serial)
3437
+ }
3438
+ } catch (error) {
3439
+ if (error instanceof VaultError && error.code === 'not-enough-proven-keys') {
3440
+ const proven = new Set(vaultStore.provenKeyRecords(meta, scopeToken).map(k => k.serial))
3441
+ proven.add(chosenSerial)
3442
+ return {
3443
+ needsRelock,
3444
+ provenSerials: meta.keys.filter(k => proven.has(k.serial)).map(k => k.serial),
3445
+ unprovenSerials: meta.keys.filter(k => !proven.has(k.serial)).map(k => k.serial),
3446
+ blocked: 'not-enough-proven-keys'
3447
+ }
3448
+ }
3449
+ return undefined
3450
+ }
3451
+ }
3452
+
3162
3453
  /**
3163
3454
  * What a withdrawal with the CHOSEN key would select, without reserving,
3164
3455
  * tapping or signing anything (spec §4.2 step 4 needs it BEFORE the tap).
@@ -3179,7 +3470,12 @@ export async function previewVaultWithdrawal(
3179
3470
  adminOriginator: string,
3180
3471
  chosenSerial: string,
3181
3472
  amount: number | 'all'
3182
- ): Promise<{ selectedTotal: number; cappedInputs: number; unreachable: VaultSpendResult['unreachable'] }> {
3473
+ ): Promise<{
3474
+ selectedTotal: number
3475
+ cappedInputs: number
3476
+ unreachable: VaultSpendResult['unreachable']
3477
+ lockPlan?: VaultLockPlanPreview
3478
+ }> {
3183
3479
  requireWithdrawalAmount(amount)
3184
3480
  const scopeToken = vaultStore.captureScopeToken()
3185
3481
  return await withVaultMutation(async () => {
@@ -3188,7 +3484,13 @@ export async function previewVaultWithdrawal(
3188
3484
  // from a past crash is still cleaned up by the next real withdraw/re-lock
3189
3485
  // (see selectVaultInputs' `repair` param and the P1 fix note there).
3190
3486
  const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, amount, undefined, scopeToken, false)
3191
- return { selectedTotal: sel.acc, cappedInputs: sel.cappedInputs, unreachable: sel.unreachable }
3487
+ const needsRelock = amount !== 'all' && sel.acc - amount >= VAULT_DEPOSIT_MIN
3488
+ return {
3489
+ selectedTotal: sel.acc,
3490
+ cappedInputs: sel.cappedInputs,
3491
+ unreachable: sel.unreachable,
3492
+ lockPlan: previewLockPlan(sel.meta, scopeToken, chosenSerial, needsRelock)
3493
+ }
3192
3494
  })
3193
3495
  }
3194
3496
 
@@ -3225,7 +3527,11 @@ export async function withdrawFromVault(
3225
3527
  const want = amount === 'all' ? sel.acc : amount
3226
3528
  const remainder = sel.acc - want
3227
3529
  const outputs: VaultSpendPlan['outputs'] = []
3530
+ let remainderPlan: LockKeyPlan | undefined
3228
3531
  if (remainder >= VAULT_DEPOSIT_MIN) {
3532
+ // A new output would be created next to a record that disagrees with
3533
+ // local meta: refuse. A full withdrawal creates none and stays open.
3534
+ if (sel.consistencyError) throw sel.consistencyError
3229
3535
  // P2-774: reconcileHeldVaultDeposits' gate exists only to protect
3230
3536
  // salt-index-allocation integrity for a call that is about to allocate a
3231
3537
  // NEW one (spec's high-water-mark check) — a full-balance withdrawal
@@ -3243,12 +3549,21 @@ export async function withdrawFromVault(
3243
3549
  // blocks a plain 'all' withdrawal, whose authority is its spent outputs'
3244
3550
  // own real locks, never local meta (see requireAuthenticatedMeta).
3245
3551
  const authenticatedMeta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, sel.meta)
3552
+ // planted-key: the remainder is a new lock. Refused before any tap.
3553
+ remainderPlan = planLockKeys({
3554
+ meta: authenticatedMeta,
3555
+ scopeToken,
3556
+ chosenSerial,
3557
+ purpose: 'remainder',
3558
+ activateStagedKey: opts?.activateStagedKey,
3559
+ acceptDroppingUnproven: opts?.acceptDroppingUnproven
3560
+ })
3246
3561
  await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, authenticatedMeta, scopeToken)
3247
3562
  outputs.push(
3248
3563
  ...(await newVaultOutput(
3249
3564
  w,
3250
3565
  adminOriginator,
3251
- authenticatedMeta,
3566
+ lockMeta(authenticatedMeta, remainderPlan),
3252
3567
  remainder,
3253
3568
  'Vault change',
3254
3569
  sel.saltInventory,
@@ -3257,7 +3572,7 @@ export async function withdrawFromVault(
3257
3572
  ))
3258
3573
  )
3259
3574
  }
3260
- return await spendVaultOutputs(
3575
+ const result = await spendVaultOutputs(
3261
3576
  w,
3262
3577
  adminOriginator,
3263
3578
  sel,
@@ -3271,6 +3586,8 @@ export async function withdrawFromVault(
3271
3586
  opts,
3272
3587
  scopeToken
3273
3588
  )
3589
+ if (remainderPlan?.changesKeySet) await commitPlannedKeySet(w, adminOriginator, scopeToken, remainderPlan)
3590
+ return result
3274
3591
  })
3275
3592
  }
3276
3593
 
@@ -3357,6 +3674,9 @@ export async function relockVault(
3357
3674
  await reconcileHeldVaultDeposits(w, adminOriginator, meta, scopeToken)
3358
3675
  const revokePubkey = opts?.revokePubkey
3359
3676
  const sel = await selectVaultInputs(w, adminOriginator, chosenSerial, 'all', revokePubkey, scopeToken)
3677
+ // A re-lock always creates a new output, so it refuses on a record that
3678
+ // disagrees with local meta.
3679
+ if (sel.consistencyError) throw sel.consistencyError
3360
3680
  if (sel.meta.pendingRemoval && !revokePubkey) {
3361
3681
  throw new VaultError('relock-required', 'Finish the pending key removal before another re-lock')
3362
3682
  }
@@ -3366,10 +3686,19 @@ export async function relockVault(
3366
3686
  if (revokePubkey && sel.meta.pendingRemoval?.key.pubkey !== revokePubkey) {
3367
3687
  throw new VaultError('not-enrolled', 'The key being revoked does not match the pending removal')
3368
3688
  }
3689
+ // planted-key: the new lock holds only proven keys. Refused before any tap.
3690
+ const plan = planLockKeys({
3691
+ meta: sel.meta,
3692
+ scopeToken,
3693
+ chosenSerial,
3694
+ purpose: 'relock',
3695
+ activateStagedKey: opts?.activateStagedKey,
3696
+ acceptDroppingUnproven: opts?.acceptDroppingUnproven
3697
+ })
3369
3698
  // Before the fee estimate below, which cannot size a lock outside 2..5.
3370
- requireLockableKeyCount(sel.keys.length)
3699
+ requireLockableKeyCount(plan.lockKeys.length)
3371
3700
  await addHistoricalVaultSaltInventory(w, adminOriginator, sel.saltInventory, sel.meta, scopeToken)
3372
- const fee = estimateRelockFee(sel.selected.length, R1C_LOCK_LEN(sel.keys.length))
3701
+ const fee = estimateRelockFee(sel.selected.length, R1C_LOCK_LEN(plan.lockKeys.length))
3373
3702
  const relocked = sel.acc - fee
3374
3703
  if (relocked < VAULT_DEPOSIT_MIN) {
3375
3704
  throw new VaultError(
@@ -3386,7 +3715,7 @@ export async function relockVault(
3386
3715
  outputs: await newVaultOutput(
3387
3716
  w,
3388
3717
  adminOriginator,
3389
- sel.meta,
3718
+ lockMeta(sel.meta, plan),
3390
3719
  relocked,
3391
3720
  'Vault re-lock',
3392
3721
  sel.saltInventory,
@@ -3417,10 +3746,102 @@ export async function relockVault(
3417
3746
  currentMeta
3418
3747
  )
3419
3748
  }
3749
+ if (plan.changesKeySet) await commitPlannedKeySet(w, adminOriginator, scopeToken, plan)
3420
3750
  return result
3421
3751
  })
3422
3752
  }
3423
3753
 
3754
+ /**
3755
+ * Promote the staged key when the Vault holds no output (add-key, late-key).
3756
+ *
3757
+ * With funds the key is activated by a re-lock (relockVault with
3758
+ * `activateStagedKey`). With none there is nothing to re-lock, so the proof is
3759
+ * a fresh PIN and touch challenge from an existing proven key that binds the
3760
+ * vault, the staged pubkey and the new revision (requireVaultKeyChallenge). A
3761
+ * phone-only attacker cannot give it. Refuses with `relock-required` as soon as
3762
+ * an output exists, and with `action-pending` while a vault action is pending.
3763
+ *
3764
+ * A phone that has not scanned the chain may show no outputs while deposits
3765
+ * exist. The promotion still needs the tap, and such deposits only lack the new
3766
+ * key until a re-lock (the coverage badge shows it); no spend authority is
3767
+ * gained by anyone.
3768
+ */
3769
+ export async function activateStagedKeyWithoutOutputs(
3770
+ w: VaultWallet,
3771
+ adminOriginator: string,
3772
+ chosenSerial: string,
3773
+ opts?: VaultTransferOptions
3774
+ ): Promise<VaultMeta> {
3775
+ const scopeToken = vaultStore.captureScopeToken()
3776
+ return await withVaultMutation(async () => {
3777
+ assertVaultScope(scopeToken)
3778
+ requireReleased(opts, scopeToken, 'Adding a key')
3779
+ await requireOnline(opts)
3780
+ assertVaultScope(scopeToken)
3781
+ const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
3782
+ if (!meta.staged) throw new VaultError('not-enrolled', 'No key is waiting to be added')
3783
+ if (meta.pendingRemoval) {
3784
+ throw new VaultError('relock-required', 'Finish the pending key removal first')
3785
+ }
3786
+ const { state: found } = await reduceVerifiedVaultOutputs(
3787
+ w,
3788
+ adminOriginator,
3789
+ () => ({ outputs: 0 }),
3790
+ state => {
3791
+ state.outputs++
3792
+ },
3793
+ scopeToken,
3794
+ 'block'
3795
+ )
3796
+ if (found.outputs > 0) {
3797
+ throw new VaultError('relock-required', 'This vault holds funds: add the key with a re-lock')
3798
+ }
3799
+ let pendingAction = false
3800
+ await scanVaultActions(
3801
+ w,
3802
+ adminOriginator,
3803
+ { includeLabels: true },
3804
+ action => {
3805
+ if (PENDING_ACTION_STATUSES.has(action.status) && !BROADCAST_ACTION_STATUSES.has(action.status)) {
3806
+ pendingAction = true
3807
+ }
3808
+ },
3809
+ scopeToken
3810
+ )
3811
+ if (pendingAction) {
3812
+ throw new VaultError('action-pending', 'Wait for pending vault actions before adding a key')
3813
+ }
3814
+ if (!meta.keys.some(k => k.serial === chosenSerial)) {
3815
+ throw new VaultError('not-enrolled', `Key ${chosenSerial} is not one of this vault's keys`)
3816
+ }
3817
+ if (!vaultStore.provenKeyRecords(meta, scopeToken).some(k => k.serial === chosenSerial)) {
3818
+ throw new VaultError('keys-unproven', 'This key has not been checked by a tap on this phone', undefined, {
3819
+ serials: chosenSerial
3820
+ })
3821
+ }
3822
+ // Every refusal that needs no tap comes first (limit of five keys per lock,
3823
+ // unproven other keys).
3824
+ const plan = planLockKeys({
3825
+ meta,
3826
+ scopeToken,
3827
+ chosenSerial,
3828
+ purpose: 'relock',
3829
+ activateStagedKey: meta.staged.serial,
3830
+ acceptDroppingUnproven: opts?.acceptDroppingUnproven
3831
+ })
3832
+ requireLockableKeyCount(plan.lockKeys.length)
3833
+ await requireVaultKeyChallenge(
3834
+ meta,
3835
+ scopeToken,
3836
+ { kind: 'vault-add-key', stagedPubkey: meta.staged.pubkey, newRevision: meta.revision + 1 },
3837
+ chosenSerial
3838
+ )
3839
+ assertVaultScope(scopeToken)
3840
+ await commitPlannedKeySet(w, adminOriginator, scopeToken, plan)
3841
+ return await requireMeta(scopeToken)
3842
+ })
3843
+ }
3844
+
3424
3845
  // ── coverage (spec §3.4 badges) ──────────────────────────────────────────
3425
3846
 
3426
3847
  /**
@@ -3517,6 +3938,42 @@ export async function forgetUnreachableVaultOutputs(
3517
3938
  })
3518
3939
  }
3519
3940
 
3941
+ /**
3942
+ * The exit for a phone stuck with conflicting or planted local rows: relinquish
3943
+ * every local Vault output and forget the local setup (meta, tag, session
3944
+ * proofs), so a fresh scan or a tapped restore starts clean. It reads the raw
3945
+ * basket (no authentication, so conflicting rows cannot block it) and never
3946
+ * touches the chain: the funds stay where they are and a scan finds them again.
3947
+ * Refuses while any Vault action is pending.
3948
+ */
3949
+ export async function forgetVaultSetup(w: VaultWallet, adminOriginator: string): Promise<{ forgottenOutputs: number }> {
3950
+ const scopeToken = vaultStore.captureScopeToken()
3951
+ return await withVaultMutation(async () => {
3952
+ assertVaultScope(scopeToken)
3953
+ let pendingAction = false
3954
+ await scanVaultActions(
3955
+ w,
3956
+ adminOriginator,
3957
+ { includeLabels: true },
3958
+ action => {
3959
+ if (PENDING_ACTION_STATUSES.has(action.status)) pendingAction = true
3960
+ },
3961
+ scopeToken
3962
+ )
3963
+ if (pendingAction) {
3964
+ throw new VaultError('action-pending', 'Wait for pending vault actions before forgetting this setup')
3965
+ }
3966
+ const outpoints = await listVaultBasketOutpoints(w, adminOriginator, scopeToken)
3967
+ for (const outpoint of outpoints) {
3968
+ assertVaultScope(scopeToken)
3969
+ await w.relinquishOutput({ basket: VAULT_BASKET, output: outpoint }, adminOriginator)
3970
+ }
3971
+ assertVaultScope(scopeToken)
3972
+ await vaultStore.forgetSetup(scopeToken)
3973
+ return { forgottenOutputs: outpoints.size }
3974
+ })
3975
+ }
3976
+
3520
3977
  /**
3521
3978
  * How many vault outputs would lose every remaining committed key if `pubkey`
3522
3979
  * were removed (spec §3.4) — the exact predicate Remove must satisfy: an
@@ -3559,7 +4016,7 @@ export async function beginVaultKeyRemoval(
3559
4016
  assertVaultScope(scopeToken)
3560
4017
  // XR-002: this is a meta-mutating write (beginKeyRemoval), not an
3561
4018
  // output-creating one, but its own `next` must still be tagged from an
3562
- // already-trustworthy `meta` — see vaultStore.addKey's laundering
4019
+ // already-trustworthy `meta` — see vaultStore.stageKey's laundering
3563
4020
  // caveat, which applies identically here.
3564
4021
  const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, await requireMeta(scopeToken))
3565
4022
  const scope = vaultStore.getScope()