@bsv/expo-wallet-toolbox 0.24.3 → 0.25.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.
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The key set a NEW Vault lock may commit (hardening: planted-key).
3
+ *
4
+ * Every output-creating path (deposit, partial-withdrawal remainder, re-lock)
5
+ * calls planLockKeys before any tap and before createAction. A key enters a
6
+ * new lock only when it is proven: by a live tap (a durable adoption pair or a
7
+ * session proof, both bound to serial AND pubkey) or by being the key tapped
8
+ * inside this very operation. A chain record alone never proves a key.
9
+ *
10
+ * - deposit: new funds. Every key of the list must be proven, else
11
+ * `keys-unproven`. The staged key is never part of a deposit.
12
+ * - re-lock / remainder: unproven keys are refused unless the caller accepts
13
+ * dropping them (after a clear warning). The new lock then holds only the
14
+ * proven keys. Fewer than two gives `not-enough-proven-keys`. A full
15
+ * withdrawal creates no lock and never reaches this function, so a lost or
16
+ * planted key cannot close the exit (R1).
17
+ */
18
+ import { VaultError } from './types'
19
+ import { vaultStore, type VaultKeyRecord, type VaultMeta, type VaultScopeToken } from './vaultStore'
20
+
21
+ const MIN_LOCK_KEYS = 2
22
+
23
+ export interface LockKeyPlan {
24
+ /** Keys committed by the new output, in meta order, staged key last. */
25
+ lockKeys: VaultKeyRecord[]
26
+ /** Keys of meta.keys left out because they are unproven. */
27
+ dropped: VaultKeyRecord[]
28
+ /** The staged key being activated, if any. */
29
+ activated?: VaultKeyRecord
30
+ /** Revision to write into the new record. */
31
+ revision: number
32
+ /** True when meta must be updated after success. */
33
+ changesKeySet: boolean
34
+ }
35
+
36
+ const pairKey = (k: Pick<VaultKeyRecord, 'serial' | 'pubkey'>): string => `${k.serial}:${k.pubkey}`
37
+
38
+ export function planLockKeys(args: {
39
+ meta: VaultMeta
40
+ scopeToken: VaultScopeToken
41
+ chosenSerial: string
42
+ purpose: 'deposit' | 'relock' | 'remainder'
43
+ /** Serial; must equal meta.staged?.serial. */
44
+ activateStagedKey?: string
45
+ acceptDroppingUnproven?: boolean
46
+ }): LockKeyPlan {
47
+ const { meta, scopeToken, chosenSerial, purpose } = args
48
+ const chosen = meta.keys.find(k => k.serial === chosenSerial)
49
+ if (!chosen) throw new VaultError('not-enrolled', `Key ${chosenSerial} is not one of this vault's keys`)
50
+ if (args.activateStagedKey !== undefined && args.activateStagedKey !== meta.staged?.serial) {
51
+ throw new VaultError('not-enrolled', 'The staged key does not match the key to activate')
52
+ }
53
+ // A deposit never takes the staged key: it is committed only by a re-lock
54
+ // signed by an existing key.
55
+ const activated = purpose !== 'deposit' && args.activateStagedKey !== undefined ? meta.staged : undefined
56
+
57
+ const proven = new Set(vaultStore.provenKeyRecords(meta, scopeToken).map(pairKey))
58
+ // The chosen key is tapped (a fresh signature is verified) before any funds
59
+ // move; a staged key passed its own live challenge as a ready draft.
60
+ proven.add(pairKey(chosen))
61
+ if (activated) proven.add(pairKey(activated))
62
+
63
+ const candidates = [...meta.keys, ...(activated ? [activated] : [])]
64
+ const unproven = candidates.filter(k => !proven.has(pairKey(k)))
65
+
66
+ if (purpose === 'deposit') {
67
+ if (unproven.length > 0) throw keysUnproven(unproven)
68
+ return { lockKeys: [...meta.keys], dropped: [], revision: meta.revision, changesKeySet: false }
69
+ }
70
+
71
+ if (unproven.length > 0 && args.acceptDroppingUnproven !== true) throw keysUnproven(unproven)
72
+ const lockKeys = candidates.filter(k => proven.has(pairKey(k)))
73
+ if (lockKeys.length < MIN_LOCK_KEYS) {
74
+ throw new VaultError(
75
+ 'not-enough-proven-keys',
76
+ `A new vault lock needs at least ${MIN_LOCK_KEYS} keys checked by a tap; ${lockKeys.length} available`,
77
+ undefined,
78
+ { proven: lockKeys.length }
79
+ )
80
+ }
81
+ const sameAsList =
82
+ activated === undefined &&
83
+ lockKeys.length === meta.keys.length &&
84
+ lockKeys.every((k, i) => pairKey(k) === pairKey(meta.keys[i]))
85
+ return {
86
+ lockKeys,
87
+ dropped: meta.keys.filter(k => !proven.has(pairKey(k))),
88
+ ...(activated ? { activated } : {}),
89
+ revision: sameAsList ? meta.revision : meta.revision + 1,
90
+ changesKeySet: !sameAsList
91
+ }
92
+ }
93
+
94
+ function keysUnproven(unproven: VaultKeyRecord[]): VaultError {
95
+ return new VaultError(
96
+ 'keys-unproven',
97
+ 'A new vault lock cannot include keys that have not been checked by a tap on this phone',
98
+ undefined,
99
+ { serials: unproven.map(k => k.serial).join(',') }
100
+ )
101
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * One chain lookup with three results (hardening constraints 1 and 5).
3
+ *
4
+ * Salt allocation, the chain scan and the reset gate all ask the same
5
+ * question: "does this marker script have any history?". The answer is found,
6
+ * none or unknown. "unknown" (lookup failed, rate limit, truncated window)
7
+ * must fail closed: callers never read it as "no funds" and never allow a
8
+ * salt index on it.
9
+ */
10
+ import type { AppChain } from '../../config'
11
+ import { wocChainLookup } from './wocLookup'
12
+
13
+ /** Smallest Vault output a scan will internalize. Frozen at the value that
14
+ * applied when the first v7 marker was committed (every v7 output was created
15
+ * under it). It never follows VAULT_DEPOSIT_MIN downward: lowering the
16
+ * deposit floor requires a new scan rule. */
17
+ export const VAULT_SCAN_MIN_SATS = 100_000
18
+
19
+ export type MarkerUnknownReason = 'request-failed' | 'rate-limited' | 'malformed' | 'window-full'
20
+
21
+ export type MarkerHistory =
22
+ | { status: 'none' }
23
+ | { status: 'found'; txids: string[] }
24
+ /** txids = rows read before the problem, may be empty. */
25
+ | { status: 'unknown'; reason: MarkerUnknownReason; txids: string[] }
26
+
27
+ /**
28
+ * Injected chain lookup: the only network/indexer dependency of the scan.
29
+ * Unit-tested against an in-memory fake; wocLookup.ts is the production
30
+ * WhatsOnChain implementation.
31
+ */
32
+ export interface VaultChainLookup {
33
+ /** Every txid whose output list includes an output with exactly this
34
+ * locking script, from address history and/or the current unspent set.
35
+ * An empty result is a genuine "no marker at this index" miss. Legacy
36
+ * contract, unchanged. */
37
+ transactionsForLockingScript(lockingScriptHex: string): Promise<string[]>
38
+ /** AtomicBEEF-decodable bytes for `txid` (a plain raw-tx-only BEEF is
39
+ * fine: recoverOneCandidate only reads `tx.outputs` from it locally; the
40
+ * bytes handed to `wallet.internalizeAction` are these same bytes, and ITS
41
+ * OWN chain-tracker validation is the actual SPV gate), plus whether this
42
+ * lookup can currently show the transaction as confirmed. `null` means the
43
+ * lookup could not produce usable bytes at all (reported as a problem, not
44
+ * a miss). `confirmed: false` is the explicit zero-conf boundary:
45
+ * recoverOneCandidate reports it as `pendingConfirmation` rather than
46
+ * attempting `internalizeAction`. */
47
+ transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null>
48
+ /** Spent/unspent/unknown for one outpoint. 'unknown' is never trusted as
49
+ * unspent. */
50
+ outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'>
51
+ /** One lookup, three results. Optional so existing fakes keep working. */
52
+ markerHistory?(lockingScriptHex: string): Promise<MarkerHistory>
53
+ /** Base58 address of a P2PKH marker script, for display. */
54
+ markerAddress?(lockingScriptHex: string): string | undefined
55
+ }
56
+
57
+ /** Ask the one question. Uses `markerHistory` when the lookup has it, else
58
+ * falls back to the legacy `transactionsForLockingScript`: a throw is
59
+ * unknown, an empty list is none, rows are found. */
60
+ export async function lookupMarker(lookup: VaultChainLookup, lockingScriptHex: string): Promise<MarkerHistory> {
61
+ if (lookup.markerHistory) return lookup.markerHistory(lockingScriptHex)
62
+ let txids: string[]
63
+ try {
64
+ txids = await lookup.transactionsForLockingScript(lockingScriptHex)
65
+ } catch {
66
+ return { status: 'unknown', reason: 'request-failed', txids: [] }
67
+ }
68
+ return txids.length === 0 ? { status: 'none' } : { status: 'found', txids }
69
+ }
70
+
71
+ let injectedLookup: VaultChainLookup | null = null
72
+
73
+ /** Test seam. A no-op outside __DEV__ (same gate as setMockDriver), so a
74
+ * release build can never swap the chain lookup. */
75
+ export function setVaultChainLookup(lookup: VaultChainLookup | null): void {
76
+ if (!__DEV__) return
77
+ injectedLookup = lookup
78
+ }
79
+
80
+ /** The injected lookup, else WhatsOnChain. `wocChainLookup` throws for a
81
+ * chain without WhatsOnChain, so a misrouted call fails closed. */
82
+ export function getVaultChainLookup(chain: AppChain): VaultChainLookup {
83
+ return injectedLookup ?? wocChainLookup(chain)
84
+ }
85
+
86
+ const saltFloors = new Map<string, number>()
87
+
88
+ /** In-memory hint: the highest salt index already used for `storageKey` in
89
+ * this session. It only raises. */
90
+ export function noteSaltFloor(storageKey: string, index: number): void {
91
+ if (index > (saltFloors.get(storageKey) ?? 0)) saltFloors.set(storageKey, index)
92
+ }
93
+
94
+ /** 0 when unset. */
95
+ export function saltFloorFor(storageKey: string): number {
96
+ return saltFloors.get(storageKey) ?? 0
97
+ }
98
+
99
+ /** Test seam, same __DEV__ gate as setVaultChainLookup: forget the in-memory
100
+ * floor hints so one test's allocations do not move the next test's start. */
101
+ export function resetSaltFloors(): void {
102
+ if (!__DEV__) return
103
+ saltFloors.clear()
104
+ }
@@ -28,16 +28,18 @@
28
28
  * `requireReadyEnrollmentDrafts`/`resumeEnrollmentDraft` trust a `ready`
29
29
  * draft (VaultKeyService.ts).
30
30
  *
31
- * WHY THESE FIELDS AND NOT OTHERS. The tagged meta payload is exactly
32
- * `vaultId`, `revision`, `createdAt`, the ordered key list (serial/slot/
33
- * pubkey) and `pendingRemoval` — the fields `newVaultOutput` bakes into a
34
- * new R1C lock, or that gate a two-phase key removal. Cosmetic/local-only
35
- * fields (`nickname`, `enrolledAt`, `lastUsedAt`/`lastUsedSerial`,
36
- * `recovery.adoptedSerials`) are deliberately EXCLUDED: they never feed a
37
- * new output's lock, and including them would force a fresh tag on every
38
- * rename/last-use/adoption write in addition to every revision-bumping one,
39
- * without closing any additional attack surface (see vaultStore.ts's
40
- * markKeyAdopted/noteLastUsed/renameKey for where this matters).
31
+ * WHY THESE FIELDS AND NOT OTHERS. The tagged meta payload is `vaultId`,
32
+ * `revision`, `createdAt`, the ordered key list (serial/slot/pubkey),
33
+ * `pendingRemoval`, the staged key and the adopted (serial, pubkey) pairs.
34
+ * The first five are what `newVaultOutput` bakes into a new R1C lock or what
35
+ * gates a two-phase key removal. The staged key and the adopted pairs decide
36
+ * which keys a new lock may commit (vaultStore.provenKeyRecords), so a
37
+ * store-only attacker must not be able to add either. Cosmetic/local-only
38
+ * fields (`nickname`, `enrolledAt`, `lastUsedAt`/`lastUsedSerial`, the legacy
39
+ * `recovery.adoptedSerials`) stay EXCLUDED: they never feed a lock, and
40
+ * covering them would force a fresh tag on every rename/last-use write (see
41
+ * vaultStore.ts's noteLastUsed/renameKey). Session proofs are in memory and
42
+ * never tagged.
41
43
  */
42
44
  import type { WalletInterface } from '@bsv/sdk'
43
45
  import type { VaultKeyRecord, VaultMeta, VaultPendingRemoval, VaultStoreScope } from './vaultStore'
@@ -53,7 +55,10 @@ export const VAULT_META_PROTOCOL_ID = [2, 'vault meta'] as const
53
55
  * trusted rather than refusing it. */
54
56
  export type HmacCapableWallet = Pick<WalletInterface, 'createHmac' | 'verifyHmac'>
55
57
 
56
- type TaggedMetaFields = Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'pendingRemoval'>
58
+ type TaggedMetaFields = Pick<
59
+ VaultMeta,
60
+ 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'pendingRemoval' | 'staged' | 'recovery'
61
+ >
57
62
 
58
63
  function canonicalKeyFields(k: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>) {
59
64
  return { serial: k.serial, slot: k.slot, pubkey: k.pubkey }
@@ -79,7 +84,14 @@ function vaultMetaAuthorityMessage(meta: TaggedMetaFields, scope: VaultStoreScop
79
84
  revision: meta.revision,
80
85
  createdAt: meta.createdAt,
81
86
  keys: meta.keys.map(canonicalKeyFields),
82
- pendingRemoval: canonicalPendingRemoval(meta.pendingRemoval)
87
+ pendingRemoval: canonicalPendingRemoval(meta.pendingRemoval),
88
+ // Added conditionally and last, so the tag of a meta with no staged key and
89
+ // no recovery state is byte-identical to the one computed before these
90
+ // fields were covered.
91
+ ...(meta.staged ? { staged: canonicalKeyFields(meta.staged) } : {}),
92
+ ...(meta.recovery?.required
93
+ ? { adopted: [...(meta.recovery.adopted ?? [])].map(p => `${p.serial}:${p.pubkey}`).sort() }
94
+ : {})
83
95
  })
84
96
  }
85
97
 
@@ -46,7 +46,52 @@ export async function requireVaultOutputKeyPossession(
46
46
  'utf8'
47
47
  )
48
48
  )
49
- const signer = await requestVaultSigner('Verify vault key for new funds', chosen.serial)
49
+ await proveKeyPossession(scope, chosen, digest, 'Verify vault key for new funds')
50
+ }
51
+
52
+ /** Fresh hardware authority to promote a staged key (add-key, late-key) when
53
+ * no funded output exists to re-lock. Same flow as requireVaultOutputKeyPossession:
54
+ * the chosen existing key signs a digest that binds the vault, its current
55
+ * revision and key list, the staged pubkey, the new revision and a nonce. */
56
+ export async function requireVaultKeyChallenge(
57
+ meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'lastUsedSerial'>,
58
+ scope: VaultScopeToken,
59
+ challenge: { kind: 'vault-add-key'; stagedPubkey: string; newRevision: number },
60
+ chosenSerial: string
61
+ ): Promise<void> {
62
+ vaultStore.assertScopeToken(scope)
63
+ const chosen = meta.keys.find(key => key.serial === chosenSerial)
64
+ if (!chosen) throw new VaultError('not-enrolled', 'Choose a key that is already part of the vault')
65
+ const digest = Hash.sha256(
66
+ Utils.toArray(
67
+ JSON.stringify({
68
+ v: 1,
69
+ kind: challenge.kind,
70
+ walletScope: scope.storageKey,
71
+ chain: scope.chain,
72
+ vaultId: meta.vaultId,
73
+ revision: meta.revision,
74
+ createdAt: meta.createdAt,
75
+ keys: meta.keys.map(key => ({ serial: key.serial, slot: key.slot, pubkey: key.pubkey })),
76
+ stagedPubkey: challenge.stagedPubkey,
77
+ newRevision: challenge.newRevision,
78
+ nonce: Utils.toHex(randomBytes(32))
79
+ }),
80
+ 'utf8'
81
+ )
82
+ )
83
+ await proveKeyPossession(scope, chosen, digest, 'Verify vault key to add a new key')
84
+ }
85
+
86
+ /** Ask the chosen key's card to sign `digest` and verify the P-256 signature
87
+ * against the stored pubkey. */
88
+ async function proveKeyPossession(
89
+ scope: VaultScopeToken,
90
+ chosen: VaultMeta['keys'][number],
91
+ digest: number[],
92
+ reason: string
93
+ ): Promise<void> {
94
+ const signer = await requestVaultSigner(reason, chosen.serial)
50
95
  try {
51
96
  vaultStore.assertScopeToken(scope)
52
97
  if (signer.serial !== chosen.serial || signer.pubkey !== chosen.pubkey) {
@@ -59,6 +59,7 @@
59
59
  import { getVaultDriver } from './driver'
60
60
  import { enrolledSerialRegistry } from './enrolledSerialRegistry'
61
61
  import { withKeySession, VaultSessionGuard } from './session'
62
+ import { requireFundsGate, type VaultResetClearance } from './resetClearance'
62
63
  import { VaultError } from './types'
63
64
  import { isVaultSerial, vaultStore, type VaultScopeToken } from './vaultStore'
64
65
 
@@ -90,6 +91,15 @@ export async function resetPivApplication(args: {
90
91
  * to no vault this device can see — an abandoned vault, or one enrolled under
91
92
  * another wallet identity. Never a way past the enrolled-serial refusal. */
92
93
  acknowledgeUnrecognizedVaultKey?: true
94
+ /** The result of `checkVaultCardFunds` for this serial: a complete chain scan
95
+ * found no Vault record that names this card. Without it, a reset needs
96
+ * `acknowledgeFundsLoss`. */
97
+ fundsClearance?: VaultResetClearance
98
+ /** The owner's explicit affirmation that any earlier funds this key opens are
99
+ * lost for good. The only way to reset without a clearance (for example when
100
+ * the chain check could not finish). Never a way past the enrolled-serial
101
+ * refusal. */
102
+ acknowledgeFundsLoss?: true
93
103
  scopeToken?: VaultScopeToken
94
104
  nfcMessage?: string
95
105
  onPhase?: (p: PivResetPhase) => void
@@ -104,6 +114,12 @@ export async function resetPivApplication(args: {
104
114
  }
105
115
  const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
106
116
 
117
+ // The chain gate (reset-new-phone). The local guards below read local data
118
+ // only, which is empty on a restored phone. Runs first, before any card
119
+ // contact and before `refuse()`, and again inside the session.
120
+ const requireChainCheck = () => requireFundsGate(args, scopeToken, args.serial)
121
+ requireChainCheck()
122
+
107
123
  const refuse = async () => {
108
124
  // Across every chain, and including a key mid-removal. See the header.
109
125
  const enrolled = new Set<string>([
@@ -138,6 +154,8 @@ export async function resetPivApplication(args: {
138
154
  chosen: args.serial
139
155
  })
140
156
  }
157
+ // The clearance can expire while the user fetches the card.
158
+ requireChainCheck()
141
159
  // Guard 2: re-read inside the session. Meta can change between the
142
160
  // first check and the tap, and this is the last chance before an
143
161
  // irreversible destruction.
@@ -0,0 +1,66 @@
1
+ import { VaultError } from './types'
2
+
3
+ /** Issued only by `checkVaultCardFunds` (through `issueResetClearance`). */
4
+ export interface VaultResetClearance {
5
+ readonly serial: string
6
+ readonly storageKey: string
7
+ readonly issuedAt: number
8
+ }
9
+
10
+ /** How long a clearance stays valid. */
11
+ export const VAULT_RESET_CLEARANCE_MS = 10 * 60 * 1000
12
+
13
+ // Membership proves the object came from issueResetClearance. A hand-made object with the same fields is not in the set.
14
+ const issued = new WeakSet<object>()
15
+
16
+ export function issueResetClearance(serial: string, storageKey: string, now: number = Date.now()): VaultResetClearance {
17
+ const clearance: VaultResetClearance = Object.freeze({ serial, storageKey, issuedAt: now })
18
+ issued.add(clearance)
19
+ return clearance
20
+ }
21
+
22
+ // The one validity test. `serial` undefined means "the serial is not known yet": it is then not compared.
23
+ function clearanceMatches(
24
+ clearance: VaultResetClearance | undefined,
25
+ serial: string | undefined,
26
+ storageKey: string,
27
+ now: number
28
+ ): boolean {
29
+ if (!clearance || !issued.has(clearance)) return false
30
+ if (clearance.storageKey !== storageKey) return false
31
+ if (serial !== undefined && clearance.serial !== serial) return false
32
+ const age = now - clearance.issuedAt
33
+ return age >= 0 && age <= VAULT_RESET_CLEARANCE_MS
34
+ }
35
+
36
+ export function isValidResetClearance(
37
+ clearance: VaultResetClearance | undefined,
38
+ serial: string,
39
+ storageKey: string,
40
+ now: number = Date.now()
41
+ ): boolean {
42
+ return clearanceMatches(clearance, serial, storageKey, now)
43
+ }
44
+
45
+ /**
46
+ * The one gate in front of every operation that destroys the key in a YubiKey's Vault slot (a PIV reset, and
47
+ * enrollKey with replaceOccupiedVaultSlot). Passes with the owner's affirmation (`acknowledgeFundsLoss: true`)
48
+ * or an issued, fresh clearance for this wallet. With `serial` undefined (before the card is read) the
49
+ * clearance's own serial is not compared; the caller checks again with the tapped serial.
50
+ */
51
+ export function requireFundsGate(
52
+ args: { fundsClearance?: VaultResetClearance; acknowledgeFundsLoss?: true },
53
+ scope: { storageKey: string },
54
+ serial: string | undefined,
55
+ now: number = Date.now()
56
+ ): void {
57
+ if (args.acknowledgeFundsLoss === true) return
58
+ if (!clearanceMatches(args.fundsClearance, serial, scope.storageKey, now)) {
59
+ throw new VaultError(
60
+ 'chain-check-required',
61
+ 'Check the chain for funds on this YubiKey before resetting it',
62
+ undefined,
63
+ serial === undefined ? undefined : { serial }
64
+ )
65
+ }
66
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The chain check that runs before any YubiKey PIV reset (audit finding
3
+ * reset-new-phone).
4
+ *
5
+ * The guards in pivReset.ts read local data only. On a phone that was restored
6
+ * from the mnemonic they are all empty, so a card that already opens Vault
7
+ * funds could be reset and its key destroyed. `checkVaultCardFunds` scans the
8
+ * chain (read-only) and answers one of three things:
9
+ *
10
+ * - `clear`: a complete scan found no record that names this card. It carries
11
+ * a short-lived clearance that `resetPivApplication` accepts.
12
+ * - `funds`: some record names this card. The app adopts the key
13
+ * (recoverVaultWithKey) and does not offer the reset.
14
+ * - `unknown`: the scan could not finish. This is never read as "no funds".
15
+ *
16
+ * A reset is still possible without a clearance, only with an explicit
17
+ * `acknowledgeFundsLoss: true` from the owner.
18
+ */
19
+ import { VAULT_RECOVERY_GAP_DEFAULT, scanVaultRecords, vaultGroupsOf, type VaultRecoveryGroup } from './chainRecovery'
20
+ import type { VaultChainLookup } from './markerLookup'
21
+ import type { VaultSaltChain } from './r1comb'
22
+ import type { VaultWallet } from './transfers'
23
+ import { issueResetClearance, type VaultResetClearance } from './resetClearance'
24
+ import { VaultError } from './types'
25
+ import { vaultStore } from './vaultStore'
26
+
27
+ export { VAULT_RESET_CLEARANCE_MS, isValidResetClearance, type VaultResetClearance } from './resetClearance'
28
+
29
+ export type VaultCardFunds =
30
+ | { kind: 'clear'; serial: string; clearance: VaultResetClearance }
31
+ | { kind: 'funds'; serial: string; deposits: number; satoshis: number; vaults: VaultRecoveryGroup[] }
32
+ | { kind: 'unknown'; serial: string; reason: string; problems: number }
33
+
34
+ export async function checkVaultCardFunds(
35
+ w: VaultWallet,
36
+ adminOriginator: string,
37
+ lookup: VaultChainLookup,
38
+ chain: VaultSaltChain,
39
+ serial: string,
40
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT
41
+ ): Promise<VaultCardFunds> {
42
+ // Captured before the scan, so a wallet switch during it cannot be cleared.
43
+ const storageKey = vaultStore.captureScopeToken().storageKey
44
+ let scan: Awaited<ReturnType<typeof scanVaultRecords>>
45
+ try {
46
+ scan = await scanVaultRecords(w, adminOriginator, lookup, chain, gap)
47
+ } catch (error) {
48
+ const code = error instanceof VaultError ? error.code : 'chain-scan-failed'
49
+ return { kind: 'unknown', serial, reason: code, problems: 0 }
50
+ }
51
+ if (scan.unknownIndexes.length > 0 || scan.problems.length > 0) {
52
+ return {
53
+ kind: 'unknown',
54
+ serial,
55
+ reason: scan.problems[0]?.reason ?? `lookup incomplete at index ${scan.unknownIndexes[0]}`,
56
+ problems: scan.problems.length
57
+ }
58
+ }
59
+ // Serial only: a reset changes the card's public key, the card stays the same.
60
+ const names = (keys: readonly { serial: string }[]) => keys.some(k => k.serial === serial)
61
+ const ready = scan.ready.filter(c => names(c.ci.keys))
62
+ const pending = scan.pending.filter(ci => names(ci.keys))
63
+ if (ready.length + pending.length > 0) {
64
+ return {
65
+ kind: 'funds',
66
+ serial,
67
+ deposits: ready.length + pending.length,
68
+ satoshis: ready.reduce((sum, c) => sum + c.satoshis, 0),
69
+ vaults: vaultGroupsOf(ready, pending)
70
+ }
71
+ }
72
+ const clearance = issueResetClearance(serial, storageKey)
73
+ return { kind: 'clear', serial, clearance }
74
+ }