@bsv/expo-wallet-toolbox 0.10.0 → 0.11.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.
- package/CHANGELOG.md +111 -0
- package/core/backup/restoreOnImport.ts +10 -3
- package/core/context/WalletContext.tsx +18 -5
- package/core/i18n/translations.tsx +109 -36
- package/core/localpay/pendingAbortAuthority.ts +6 -8
- package/core/localpay/pendingAborts.ts +11 -30
- package/core/mandala/permissionModule.ts +10 -8
- package/core/services/vault/VaultKeyService.ts +58 -1
- package/core/services/vault/chainRecovery.ts +188 -37
- package/core/services/vault/guard.ts +75 -139
- package/core/services/vault/transfers.ts +64 -2
- package/core/services/vault/types.ts +3 -0
- package/core/storage/StorageExpoSQLite.ts +33 -11
- package/core/storage/methods/vaultGuardSql.ts +140 -0
- package/core/storage/sqlUpdateValue.ts +4 -1
- package/package.json +1 -1
- package/ui/components/vault/vaultErrorCopy.ts +1 -0
- package/ui/hooks/useExportWalletData.ts +7 -21
- package/ui/screens/VaultScreen.tsx +192 -7
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
* stands; the reference is retried on the next wallet build.
|
|
6
6
|
*/
|
|
7
7
|
import { ADMIN_ORIGINATOR, LEGACY_ADMIN_ORIGINATOR } from '../config'
|
|
8
|
-
import { VAULT_ABORT_REPLAY_MARKER } from '../services/vault/guard'
|
|
9
8
|
import {
|
|
10
9
|
computePendingAbortAuthorityTag,
|
|
11
10
|
verifyPendingAbortAuthorityTag,
|
|
@@ -150,10 +149,7 @@ export interface ReplayPendingAbortsResult {
|
|
|
150
149
|
|
|
151
150
|
export async function replayPendingAborts(args: {
|
|
152
151
|
wallet: {
|
|
153
|
-
abortAction: (
|
|
154
|
-
args: { reference: string; [VAULT_ABORT_REPLAY_MARKER]?: true },
|
|
155
|
-
originator?: string
|
|
156
|
-
) => Promise<{ aborted?: boolean } | void>
|
|
152
|
+
abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
|
|
157
153
|
} & PendingAbortVerifyWallet
|
|
158
154
|
storage: StorageLike
|
|
159
155
|
}): Promise<ReplayPendingAbortsResult> {
|
|
@@ -163,12 +159,9 @@ export async function replayPendingAborts(args: {
|
|
|
163
159
|
const kept: PendingAbort[] = []
|
|
164
160
|
let droppedUntrusted = 0
|
|
165
161
|
for (const item of pending) {
|
|
166
|
-
// XR-102
|
|
167
|
-
//
|
|
168
|
-
//
|
|
169
|
-
// nothing else stops a forged `pending_aborts` entry naming one from
|
|
170
|
-
// being replayed. Authenticate first: an entry this wallet did not
|
|
171
|
-
// itself tag at queue time (queuePendingAbort) is dropped, never
|
|
162
|
+
// XR-102: a forged `pending_aborts` entry would otherwise be replayed
|
|
163
|
+
// with the admin originator. Authenticate first: an entry this wallet
|
|
164
|
+
// did not itself tag at queue time (queuePendingAbort) is dropped, never
|
|
172
165
|
// replayed — fail closed, since the only thing a replay ever does is
|
|
173
166
|
// free a reservation, and a dropped reference stays recoverable through
|
|
174
167
|
// WalletHomeScreen's manual per-row abort.
|
|
@@ -179,25 +172,13 @@ export async function replayPendingAborts(args: {
|
|
|
179
172
|
}
|
|
180
173
|
try {
|
|
181
174
|
// XR-102: the persisted `originator` is never trusted here — this is a
|
|
182
|
-
// raw KV record, writable by anything with local storage access
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
-
//
|
|
188
|
-
|
|
189
|
-
// That alone is not enough: `assertPendingActionOriginator` requires
|
|
190
|
-
// this exact originator for a legitimate replay to succeed at all, and
|
|
191
|
-
// guardVaultAccess treats every admin-originator call as trusted. The
|
|
192
|
-
// marker opts this specific call OUT of that trust and into the same
|
|
193
|
-
// vault-inventory reference check a non-admin caller gets — so a
|
|
194
|
-
// reference an attacker injected that happens to name a Vault action is
|
|
195
|
-
// refused, while an ordinary (and authentically-tagged) localpay/
|
|
196
|
-
// PeerPay reference still replays.
|
|
197
|
-
const result = await args.wallet.abortAction(
|
|
198
|
-
{ reference: item.reference, [VAULT_ABORT_REPLAY_MARKER]: true },
|
|
199
|
-
ADMIN_ORIGINATOR
|
|
200
|
-
)
|
|
175
|
+
// raw KV record, writable by anything with local storage access. The
|
|
176
|
+
// ONLY originator ever used to replay is the real, imported constant
|
|
177
|
+
// every legitimate queued abort was already created under (see
|
|
178
|
+
// queuePendingAbort's call sites — all pass `adminOriginator`), never
|
|
179
|
+
// the field read back off disk; the authority tag above is what makes
|
|
180
|
+
// replaying under it safe.
|
|
181
|
+
const result = await args.wallet.abortAction({ reference: item.reference }, ADMIN_ORIGINATOR)
|
|
201
182
|
if (result && typeof result === 'object' && result.aborted === false) {
|
|
202
183
|
kept.push(item)
|
|
203
184
|
}
|
|
@@ -754,14 +754,16 @@ export class MandalaTokenModule implements PermissionsModule {
|
|
|
754
754
|
* (`GUARD_TARGETS`/`GUARDED_PROXIES` in `services/vault/guard.ts`), which
|
|
755
755
|
* several screens rely on (`guardVaultAccess(managers.permissionsManager,
|
|
756
756
|
* ADMIN_ORIGINATOR)` again in e.g. `PairScreen.tsx`/`ConnectionsScreen.tsx`)
|
|
757
|
-
* to avoid creating a second
|
|
758
|
-
*
|
|
759
|
-
*
|
|
760
|
-
*
|
|
761
|
-
*
|
|
762
|
-
*
|
|
763
|
-
*
|
|
764
|
-
*
|
|
757
|
+
* to avoid creating a second guard runtime around the same wallet. That
|
|
758
|
+
* dedup only recognizes an object IT previously wrapped — putting this
|
|
759
|
+
* wrapper's Proxy on the OUTSIDE (wrapping an already-guarded manager) would
|
|
760
|
+
* make every such re-application invisible to the dedup and silently
|
|
761
|
+
* double-guard the wallet with a second runtime that has no storage lookup
|
|
762
|
+
* (so it refuses every external call naming an outpoint) and its own
|
|
763
|
+
* listActions queue. Wrapping the raw manager first, then guarding the
|
|
764
|
+
* result, keeps the publicly published value exactly what `guardVaultAccess`
|
|
765
|
+
* itself produced and expects to see again — in this app that is
|
|
766
|
+
* `WalletContext.tsx`'s
|
|
765
767
|
* `newManagers.permissionsManager = guardVaultAccess(
|
|
766
768
|
* wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints,
|
|
767
769
|
* adminOriginator), adminOriginator)`. A manager constructed anywhere else
|
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
verifyVaultMetaAuthorityTag,
|
|
31
31
|
type HmacCapableWallet
|
|
32
32
|
} from './metaAuthority'
|
|
33
|
-
import { compressPubkey, type VaultInstructions } from './r1comb'
|
|
33
|
+
import { compressPubkey, type VaultInstructionKey, type VaultInstructions } from './r1comb'
|
|
34
34
|
import { randomBytes } from './random'
|
|
35
35
|
import { withKeySession, VaultSessionGuard } from './session'
|
|
36
36
|
import { VaultError } from './types'
|
|
@@ -919,6 +919,63 @@ export async function adoptVaultKey(args: {
|
|
|
919
919
|
return { ...args.record }
|
|
920
920
|
}
|
|
921
921
|
|
|
922
|
+
/**
|
|
923
|
+
* Find which of `records`' keys the tapped YubiKey actually holds, proving it
|
|
924
|
+
* in the same step: the card signs a fresh random challenge (PIN + touch) and
|
|
925
|
+
* the signature is checked against every key the records list for the
|
|
926
|
+
* card's serial. A reset writes a new key to the same serial, so the serial
|
|
927
|
+
* alone cannot tell setups apart; the signature can.
|
|
928
|
+
*
|
|
929
|
+
* Throws 'key-opens-nothing' when no record names this serial, or none of
|
|
930
|
+
* its keys verifies (the card's key was replaced after those deposits).
|
|
931
|
+
* PIN checks match adoptVaultKey.
|
|
932
|
+
*/
|
|
933
|
+
export async function proveHeldVaultKey(args: {
|
|
934
|
+
records: readonly Pick<VaultInstructions, 'keys'>[]
|
|
935
|
+
onPhase: (p: AdoptPhase) => void
|
|
936
|
+
getPin: () => Promise<string>
|
|
937
|
+
nfcMessage?: string
|
|
938
|
+
}): Promise<VaultInstructionKey> {
|
|
939
|
+
const driver = getVaultDriver()
|
|
940
|
+
if (!driver) throw new VaultError('driver-unavailable')
|
|
941
|
+
|
|
942
|
+
args.onPhase('pin-check')
|
|
943
|
+
const pin = await args.getPin()
|
|
944
|
+
requirePivCode(pin, 'PIN')
|
|
945
|
+
const challenge = randomBytes(32)
|
|
946
|
+
const digest = Utils.toHex(challenge)
|
|
947
|
+
|
|
948
|
+
const held = await withKeySession(
|
|
949
|
+
driver,
|
|
950
|
+
async () => {
|
|
951
|
+
const info = await driver.getKeyInfo()
|
|
952
|
+
const named = new Map<string, VaultInstructionKey>()
|
|
953
|
+
for (const record of args.records) {
|
|
954
|
+
for (const key of record.keys) {
|
|
955
|
+
if (key.serial === info.serial && !named.has(key.pubkey)) named.set(key.pubkey, { ...key })
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
if (named.size === 0) {
|
|
959
|
+
throw new VaultError('key-opens-nothing', 'No vault deposit on the blockchain names this YubiKey')
|
|
960
|
+
}
|
|
961
|
+
if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
|
|
962
|
+
const verified = await driver.verifyPin(info.serial, pin)
|
|
963
|
+
requireVerifiedPin(verified)
|
|
964
|
+
|
|
965
|
+
args.onPhase('challenging')
|
|
966
|
+
const { signature } = await driver.signEcdsa(info.serial, pin, digest)
|
|
967
|
+
for (const key of named.values()) {
|
|
968
|
+
if (signatureProvesKey(key.pubkey, Uint8Array.from(challenge), signature)) return key
|
|
969
|
+
}
|
|
970
|
+
throw new VaultError('key-opens-nothing', 'This YubiKey holds none of the keys its deposits are locked to')
|
|
971
|
+
},
|
|
972
|
+
() => args.onPhase('connecting'),
|
|
973
|
+
{ nfcMessage: args.nfcMessage }
|
|
974
|
+
)
|
|
975
|
+
args.onPhase('done')
|
|
976
|
+
return held
|
|
977
|
+
}
|
|
978
|
+
|
|
922
979
|
export interface VerifiedVaultRecoveryOutput {
|
|
923
980
|
/** Decoded only after baked-salt and exact-lock verification by transfers.
|
|
924
981
|
* v6 or v7 — this function only reads fields common to both shapes
|
|
@@ -25,6 +25,15 @@
|
|
|
25
25
|
* whose transaction the injected lookup reports as not-yet-confirmed is
|
|
26
26
|
* reported back as `pendingConfirmation`, never thrown and never silently
|
|
27
27
|
* dropped, and does not consume a gap-scan slot.
|
|
28
|
+
*
|
|
29
|
+
* KEY FILTER: every setup of the same YubiKeys writes fresh PIV keys (and a
|
|
30
|
+
* new vaultId), yet its deposits still authenticate here — the marker and
|
|
31
|
+
* descriptor derive from the wallet root, not the keys. So a scan also finds
|
|
32
|
+
* deposits from earlier setups that nothing the owner still holds can open.
|
|
33
|
+
* Only candidates sharing a key with the live set are internalized: this
|
|
34
|
+
* device's authenticated key list when it has one, otherwise every key of the
|
|
35
|
+
* newest setup the scan found (latest createdAt). The rest are counted as
|
|
36
|
+
* `unreachable`, never inserted.
|
|
28
37
|
*/
|
|
29
38
|
import { Transaction, Utils } from '@bsv/sdk'
|
|
30
39
|
import {
|
|
@@ -32,12 +41,17 @@ import {
|
|
|
32
41
|
commitment,
|
|
33
42
|
decodeVaultInstructionsV7,
|
|
34
43
|
encodeVaultInstructionsV7,
|
|
44
|
+
type VaultInstructionKey,
|
|
35
45
|
type VaultInstructionsV7,
|
|
36
46
|
type VaultSaltChain
|
|
37
47
|
} from './r1comb'
|
|
38
48
|
import { VaultError } from './types'
|
|
49
|
+
import { vaultStore } from './vaultStore'
|
|
50
|
+
import { verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
|
|
39
51
|
import {
|
|
40
52
|
VAULT_BASKET,
|
|
53
|
+
liveVaultPubkeys,
|
|
54
|
+
opensWithAny,
|
|
41
55
|
deriveVaultMarkerScript,
|
|
42
56
|
deriveVaultSalt,
|
|
43
57
|
decryptVaultDescriptorPlaintext,
|
|
@@ -117,6 +131,9 @@ export interface VaultChainRecoveryProblem {
|
|
|
117
131
|
export interface VaultChainRecoveryResult {
|
|
118
132
|
/** Indices newly inserted into 'admin vault' by this run. */
|
|
119
133
|
found: number
|
|
134
|
+
/** Authenticated, unspent deposits no live key can open (an earlier setup's)
|
|
135
|
+
* — skipped rather than inserted. See this file's KEY FILTER note. */
|
|
136
|
+
unreachable: number
|
|
120
137
|
/** Marker history existed and decrypted to a valid, unspent v7 record, but
|
|
121
138
|
* the lookup could not yet show it as confirmed — the honest zero-conf
|
|
122
139
|
* scope cut (this file's docstring). Not a miss: does not consume a
|
|
@@ -135,17 +152,25 @@ export interface VaultChainRecoveryResult {
|
|
|
135
152
|
scanned: number
|
|
136
153
|
}
|
|
137
154
|
|
|
155
|
+
/** An authenticated, unspent candidate, held until the scan ends so the key
|
|
156
|
+
* filter can see every setup before anything is inserted. */
|
|
157
|
+
export interface RecoverableCandidate {
|
|
158
|
+
index: number
|
|
159
|
+
ci: VaultInstructionsV7
|
|
160
|
+
beef: number[]
|
|
161
|
+
vaultOutputIndex: number
|
|
162
|
+
}
|
|
163
|
+
|
|
138
164
|
type CandidateOutcome =
|
|
139
|
-
| { kind: '
|
|
140
|
-
| { kind: 'pending' }
|
|
165
|
+
| ({ kind: 'ready' } & RecoverableCandidate)
|
|
166
|
+
| { kind: 'pending'; ci: VaultInstructionsV7 }
|
|
141
167
|
| { kind: 'spent' }
|
|
142
168
|
| { kind: 'problem'; reason: string }
|
|
143
169
|
|
|
144
170
|
/**
|
|
145
|
-
* Locate
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
* a miss" contract.
|
|
171
|
+
* Locate and authenticate ONE candidate marker transaction for scan index
|
|
172
|
+
* `k`. Never throws — every failure mode is a distinct, reported outcome, per
|
|
173
|
+
* this module's "found-but-unusable is not a miss" contract.
|
|
149
174
|
*/
|
|
150
175
|
async function recoverOneCandidate(
|
|
151
176
|
w: VaultWallet,
|
|
@@ -228,17 +253,24 @@ async function recoverOneCandidate(
|
|
|
228
253
|
if (status === 'spent') return { kind: 'spent' }
|
|
229
254
|
if (status === 'unknown') return { kind: 'problem', reason: 'could not confirm the vault output is unspent' }
|
|
230
255
|
|
|
231
|
-
if (!entry.confirmed) return { kind: 'pending' }
|
|
256
|
+
if (!entry.confirmed) return { kind: 'pending', ci }
|
|
257
|
+
return { kind: 'ready', index: k, ci, beef: entry.beef, vaultOutputIndex }
|
|
258
|
+
}
|
|
232
259
|
|
|
260
|
+
async function internalizeCandidate(
|
|
261
|
+
w: VaultWallet,
|
|
262
|
+
adminOriginator: string,
|
|
263
|
+
candidate: RecoverableCandidate
|
|
264
|
+
): Promise<string | undefined> {
|
|
233
265
|
try {
|
|
234
266
|
await w.internalizeAction({
|
|
235
|
-
tx:
|
|
267
|
+
tx: candidate.beef,
|
|
236
268
|
outputs: [{
|
|
237
|
-
outputIndex: vaultOutputIndex,
|
|
269
|
+
outputIndex: candidate.vaultOutputIndex,
|
|
238
270
|
protocol: 'basket insertion',
|
|
239
271
|
insertionRemittance: {
|
|
240
272
|
basket: VAULT_BASKET,
|
|
241
|
-
customInstructions: encodeVaultInstructionsV7(ci),
|
|
273
|
+
customInstructions: encodeVaultInstructionsV7(candidate.ci),
|
|
242
274
|
tags: ['vault']
|
|
243
275
|
}
|
|
244
276
|
}],
|
|
@@ -246,9 +278,38 @@ async function recoverOneCandidate(
|
|
|
246
278
|
seekPermission: false
|
|
247
279
|
}, adminOriginator)
|
|
248
280
|
} catch (e) {
|
|
249
|
-
return
|
|
281
|
+
return `could not internalize the recovered output: ${(e as Error)?.message ?? 'unknown error'}`
|
|
282
|
+
}
|
|
283
|
+
return undefined
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The keys a recovered deposit must share one of (KEY FILTER). A local key
|
|
288
|
+
* list counts only when its authority tag verifies: a forged list would
|
|
289
|
+
* otherwise hide every real deposit. Without one, the newest setup found
|
|
290
|
+
* wins — an older setup's PIV keys were replaced by the reset that made it.
|
|
291
|
+
*/
|
|
292
|
+
async function recoveryLiveKeys(
|
|
293
|
+
w: VaultWallet,
|
|
294
|
+
adminOriginator: string,
|
|
295
|
+
records: readonly VaultInstructionsV7[]
|
|
296
|
+
): Promise<ReadonlySet<string>> {
|
|
297
|
+
const scopeToken = vaultStore.captureScopeToken()
|
|
298
|
+
const scope = vaultStore.getScope()
|
|
299
|
+
const meta = await vaultStore.getMeta(scopeToken)
|
|
300
|
+
if (meta && scope) {
|
|
301
|
+
const tag = await vaultStore.getMetaTag(scopeToken)
|
|
302
|
+
if (await verifyVaultMetaAuthorityTag(w as unknown as HmacCapableWallet, adminOriginator, meta, scope, tag)) {
|
|
303
|
+
return liveVaultPubkeys(meta)
|
|
304
|
+
}
|
|
250
305
|
}
|
|
251
|
-
|
|
306
|
+
if (records.length === 0) return new Set()
|
|
307
|
+
const newest = records.reduce((a, b) => (b.createdAt > a.createdAt ? b : a))
|
|
308
|
+
return new Set(
|
|
309
|
+
records
|
|
310
|
+
.filter(r => r.vaultId === newest.vaultId && r.createdAt === newest.createdAt)
|
|
311
|
+
.flatMap(r => r.keys.map(key => key.pubkey))
|
|
312
|
+
)
|
|
252
313
|
}
|
|
253
314
|
|
|
254
315
|
/**
|
|
@@ -271,11 +332,60 @@ export async function recoverVaultFromChain(
|
|
|
271
332
|
chain: VaultSaltChain,
|
|
272
333
|
gap: number = VAULT_RECOVERY_GAP_DEFAULT
|
|
273
334
|
): Promise<VaultChainRecoveryResult> {
|
|
335
|
+
const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
|
|
336
|
+
const live = await recoveryLiveKeys(w, adminOriginator, [...scan.ready.map(c => c.ci), ...scan.pending])
|
|
337
|
+
return await restoreScannedDeposits(w, adminOriginator, scan, live)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Restore with one tapped YubiKey (no local key list needed, and no guessing
|
|
342
|
+
* between setups): scan the chain, let `prove` pick and prove the key the
|
|
343
|
+
* card holds (proveHeldVaultKey), then restore every deposit of the setups
|
|
344
|
+
* that key belongs to. The proven key is marked adopted, so it can withdraw
|
|
345
|
+
* without a second challenge.
|
|
346
|
+
*/
|
|
347
|
+
export async function recoverVaultWithKey(
|
|
348
|
+
w: VaultWallet,
|
|
349
|
+
adminOriginator: string,
|
|
350
|
+
lookup: VaultChainLookup,
|
|
351
|
+
chain: VaultSaltChain,
|
|
352
|
+
prove: (records: readonly VaultInstructionsV7[]) => Promise<VaultInstructionKey>,
|
|
353
|
+
gap: number = VAULT_RECOVERY_GAP_DEFAULT
|
|
354
|
+
): Promise<VaultChainRecoveryResult & { key: VaultInstructionKey }> {
|
|
355
|
+
const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
|
|
356
|
+
const records = [...scan.ready.map(c => c.ci), ...scan.pending]
|
|
357
|
+
const key = await prove(records)
|
|
358
|
+
// Every key of a setup the proven key is part of, so that setup's deposits
|
|
359
|
+
// come back whole and rebuild one consistent key list.
|
|
360
|
+
const live = new Set(
|
|
361
|
+
records.filter(r => r.keys.some(k => k.pubkey === key.pubkey)).flatMap(r => r.keys.map(k => k.pubkey))
|
|
362
|
+
)
|
|
363
|
+
const result = await restoreScannedDeposits(w, adminOriginator, scan, live)
|
|
364
|
+
if (result.found > 0) await vaultStore.markKeyAdopted(key)
|
|
365
|
+
return { ...result, key }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
interface VaultChainScan {
|
|
369
|
+
ready: RecoverableCandidate[]
|
|
370
|
+
pending: VaultInstructionsV7[]
|
|
371
|
+
problems: VaultChainRecoveryProblem[]
|
|
372
|
+
scanned: number
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** The scan half of recovery: find and authenticate every candidate without
|
|
376
|
+
* inserting any. */
|
|
377
|
+
async function scanVaultChain(
|
|
378
|
+
w: VaultWallet,
|
|
379
|
+
adminOriginator: string,
|
|
380
|
+
lookup: VaultChainLookup,
|
|
381
|
+
chain: VaultSaltChain,
|
|
382
|
+
gap: number
|
|
383
|
+
): Promise<VaultChainScan> {
|
|
274
384
|
if (!Number.isSafeInteger(gap) || gap < 1) {
|
|
275
385
|
throw new VaultError('template-invalid', 'Vault recovery gap must be a positive integer')
|
|
276
386
|
}
|
|
277
|
-
|
|
278
|
-
|
|
387
|
+
const ready: RecoverableCandidate[] = []
|
|
388
|
+
const pending: VaultInstructionsV7[] = []
|
|
279
389
|
const problems: VaultChainRecoveryProblem[] = []
|
|
280
390
|
let consecutiveMisses = 0
|
|
281
391
|
// Bounds the loop independently of consecutiveMisses — see
|
|
@@ -344,8 +454,8 @@ export async function recoverVaultFromChain(
|
|
|
344
454
|
}
|
|
345
455
|
inspected++
|
|
346
456
|
const outcome = await recoverOneCandidate(w, adminOriginator, lookup, chain, k, markerScriptHex, txid)
|
|
347
|
-
if (outcome.kind === '
|
|
348
|
-
else if (outcome.kind === 'pending') {
|
|
457
|
+
if (outcome.kind === 'ready') { ready.push(outcome); break }
|
|
458
|
+
else if (outcome.kind === 'pending') { pending.push(outcome.ci); break }
|
|
349
459
|
else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
|
|
350
460
|
// 'spent': a superseded output (already withdrawn or re-locked) —
|
|
351
461
|
// entirely normal, silently skipped; keep inspecting other candidates
|
|
@@ -353,8 +463,34 @@ export async function recoverVaultFromChain(
|
|
|
353
463
|
}
|
|
354
464
|
k++
|
|
355
465
|
}
|
|
466
|
+
return { ready, pending, problems, scanned }
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** The insert half: internalize the scanned deposits `live` can open, count
|
|
470
|
+
* the rest as unreachable, then rebuild local vault metadata. */
|
|
471
|
+
async function restoreScannedDeposits(
|
|
472
|
+
w: VaultWallet,
|
|
473
|
+
adminOriginator: string,
|
|
474
|
+
scan: VaultChainScan,
|
|
475
|
+
live: ReadonlySet<string>
|
|
476
|
+
): Promise<VaultChainRecoveryResult> {
|
|
477
|
+
const { ready, pending, scanned } = scan
|
|
478
|
+
const problems = [...scan.problems]
|
|
479
|
+
let found = 0
|
|
480
|
+
let pendingConfirmation = 0
|
|
481
|
+
let unreachable = 0
|
|
482
|
+
for (const candidate of ready) {
|
|
483
|
+
if (!opensWithAny(candidate.ci, live)) { unreachable++; continue }
|
|
484
|
+
const failure = await internalizeCandidate(w, adminOriginator, candidate)
|
|
485
|
+
if (failure) problems.push({ index: candidate.index, reason: failure })
|
|
486
|
+
else found++
|
|
487
|
+
}
|
|
488
|
+
for (const ci of pending) {
|
|
489
|
+
if (opensWithAny(ci, live)) pendingConfirmation++
|
|
490
|
+
else unreachable++
|
|
491
|
+
}
|
|
356
492
|
await recoverVaultMetaFromOutputs(w, adminOriginator)
|
|
357
|
-
return { found, pendingConfirmation, problems, scanned }
|
|
493
|
+
return { found, pendingConfirmation, unreachable, problems, scanned }
|
|
358
494
|
}
|
|
359
495
|
|
|
360
496
|
// ───────────────────────── default WhatsOnChain implementation ─────────────
|
|
@@ -364,16 +500,11 @@ export async function recoverVaultFromChain(
|
|
|
364
500
|
* patterns already used by core/pay/rails/address.ts (getUtxosForAddress,
|
|
365
501
|
* the `/tx/{txid}/beef` fetch, parseWocBeefBody's response-shape checks).
|
|
366
502
|
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
* `/
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
* of this change (no network access in this environment). This must be
|
|
373
|
-
* smoke-tested against real WhatsOnChain responses (mainnet and testnet)
|
|
374
|
-
* before being relied on in production; recoverVaultFromChain's own logic
|
|
375
|
-
* is unit-tested against an in-memory VaultChainLookup fake and does not
|
|
376
|
-
* depend on these HTTP details being exactly right.
|
|
503
|
+
* Response shapes checked against live mainnet WhatsOnChain on 2026-09-27:
|
|
504
|
+
* `/address/{address}/history` answers `[{tx_hash, height}]`, or 404 "Not
|
|
505
|
+
* Found" for an address with no history; `/tx/{txid}/out/{index}` answers
|
|
506
|
+
* 502 for every output, so spent status comes from `POST /utxos/spent`,
|
|
507
|
+
* which returns one row per outpoint (see outputStatus).
|
|
377
508
|
*/
|
|
378
509
|
export function wocChainLookup(chain: AppChain): VaultChainLookup {
|
|
379
510
|
const woc: WocConfig = wocConfigFor(chain)
|
|
@@ -398,6 +529,9 @@ export function wocChainLookup(chain: AppChain): VaultChainLookup {
|
|
|
398
529
|
throw new Error('wocChainLookup: marker script is not a recognizable P2PKH script')
|
|
399
530
|
}
|
|
400
531
|
const response = await fetch(`${base}/address/${address}/history`)
|
|
532
|
+
// WhatsOnChain's answer for an address that has never been used: a
|
|
533
|
+
// genuine miss, not a failure.
|
|
534
|
+
if (response.status === 404) return []
|
|
401
535
|
if (!response.ok) {
|
|
402
536
|
throw new Error(`wocChainLookup: address history request failed (HTTP ${response.status})`)
|
|
403
537
|
}
|
|
@@ -428,18 +562,35 @@ export function wocChainLookup(chain: AppChain): VaultChainLookup {
|
|
|
428
562
|
|
|
429
563
|
async outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'> {
|
|
430
564
|
// Fail-safe default is 'unknown' (never trusted as unspent — see this
|
|
431
|
-
// file's VaultChainLookup interface doc).
|
|
432
|
-
//
|
|
433
|
-
//
|
|
434
|
-
//
|
|
435
|
-
//
|
|
565
|
+
// file's VaultChainLookup interface doc). The row must be about this
|
|
566
|
+
// exact outpoint. Unspent is a clean row with no `spentIn`; spent is a
|
|
567
|
+
// `spentIn` naming another transaction; an unknown output comes back as
|
|
568
|
+
// `spentIn.status: "Unknown UTXO"` echoing its own txid, which is
|
|
569
|
+
// neither.
|
|
436
570
|
try {
|
|
437
|
-
const response = await fetch(`${base}/
|
|
571
|
+
const response = await fetch(`${base}/utxos/spent`, {
|
|
572
|
+
method: 'POST',
|
|
573
|
+
headers: { 'Content-Type': 'application/json' },
|
|
574
|
+
body: JSON.stringify({ utxos: [{ txid: outpoint.txid, vout: outpoint.vout }] })
|
|
575
|
+
})
|
|
438
576
|
if (!response.ok) return 'unknown'
|
|
439
|
-
const
|
|
440
|
-
|
|
441
|
-
if (
|
|
442
|
-
if (
|
|
577
|
+
const body = await response.json()
|
|
578
|
+
const row = Array.isArray(body) && body.length === 1 ? body[0] : undefined
|
|
579
|
+
if (row === null || typeof row !== 'object') return 'unknown'
|
|
580
|
+
if (row.utxo?.txid !== outpoint.txid || row.utxo?.vout !== outpoint.vout) return 'unknown'
|
|
581
|
+
if (row.error !== '') return 'unknown'
|
|
582
|
+
const spentIn = row.spentIn
|
|
583
|
+
if (spentIn === undefined) return 'unspent'
|
|
584
|
+
if (
|
|
585
|
+
spentIn !== null &&
|
|
586
|
+
typeof spentIn === 'object' &&
|
|
587
|
+
typeof spentIn.txid === 'string' &&
|
|
588
|
+
/^[0-9a-fA-F]{64}$/.test(spentIn.txid) &&
|
|
589
|
+
spentIn.txid.toLowerCase() !== outpoint.txid.toLowerCase() &&
|
|
590
|
+
spentIn.status !== 'Unknown UTXO'
|
|
591
|
+
) {
|
|
592
|
+
return 'spent'
|
|
593
|
+
}
|
|
443
594
|
return 'unknown'
|
|
444
595
|
} catch {
|
|
445
596
|
return 'unknown'
|