@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.
- package/CHANGELOG.md +292 -0
- package/README.md +0 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +9 -1
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +409 -20
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +97 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +112 -1
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +38 -16
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- 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
|
|
3
|
+
* and the `admin vault` basket, over 1-of-N P-256 comb-verifier outputs
|
|
4
|
+
* (r1comb.ts, spec §2).
|
|
4
5
|
*
|
|
5
|
-
* Deposit:
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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:
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
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
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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:
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
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,
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
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
|
-
|
|
52
|
-
|
|
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
|
-
|
|
56
|
-
|
|
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
|
|
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
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
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 =
|
|
161
|
+
export const VAULT_DEPOSIT_MIN = 100_000
|
|
155
162
|
|
|
156
163
|
/**
|
|
157
164
|
* Vault inputs per withdrawal.
|
|
158
165
|
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
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<{
|
|
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
|
-
|
|
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
|
-
|
|
217
|
-
|
|
218
|
-
*
|
|
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
|
-
*
|
|
226
|
-
*
|
|
227
|
-
*
|
|
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
|
-
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
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
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
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
|
-
|
|
243
|
-
|
|
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
|
-
|
|
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 (
|
|
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 (
|
|
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(
|
|
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.
|
|
405
|
-
|
|
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
|
|
437
|
-
*
|
|
438
|
-
*
|
|
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
|
|
451
|
-
|
|
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
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
|
|
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
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
)
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
-
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
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
|
-
*
|
|
525
|
-
*
|
|
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
|
|
1326
|
+
export async function disableVaultWhenSafe(
|
|
533
1327
|
w: VaultWallet,
|
|
534
1328
|
adminOriginator: string,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
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
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
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
|
-
// ──
|
|
1432
|
+
// ── vault outputs ────────────────────────────────────────────────────────
|
|
574
1433
|
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
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
|
-
*
|
|
595
|
-
*
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
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
|
-
*
|
|
601
|
-
*
|
|
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
|
|
1667
|
+
export async function depositToVault(
|
|
604
1668
|
w: VaultWallet,
|
|
605
1669
|
adminOriginator: string,
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
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
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
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
|
|
691
|
-
|
|
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
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
const
|
|
716
|
-
{
|
|
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
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
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
|
-
//
|
|
753
|
-
//
|
|
754
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
772
|
-
*
|
|
773
|
-
*
|
|
774
|
-
*
|
|
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
|
-
*
|
|
779
|
-
*
|
|
780
|
-
*
|
|
781
|
-
*
|
|
782
|
-
* (
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
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
|
-
*
|
|
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
|
|
821
|
-
*
|
|
822
|
-
*
|
|
823
|
-
*
|
|
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
|
-
*
|
|
826
|
-
*
|
|
827
|
-
* the
|
|
828
|
-
*
|
|
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
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
)
|
|
835
|
-
|
|
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
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2157
|
+
sel: VaultSelection,
|
|
866
2158
|
reason: string,
|
|
867
|
-
|
|
868
|
-
opts
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
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
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
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
|
-
|
|
917
|
-
|
|
918
|
-
|
|
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
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
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
|
-
|
|
945
|
-
|
|
946
|
-
|
|
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
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
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
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
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 {
|
|
1018
|
-
let builtSpends: Record<number, { unlockingScript: string }>
|
|
2304
|
+
const unlocks: { inputIndex: number; unlockingScript: UnlockingScript }[] = []
|
|
1019
2305
|
try {
|
|
1020
|
-
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1023
|
-
//
|
|
1024
|
-
//
|
|
1025
|
-
//
|
|
1026
|
-
//
|
|
1027
|
-
//
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
1056
|
-
// vault UTXO stays spendable=false and the next
|
|
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
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
//
|
|
1066
|
-
//
|
|
1067
|
-
//
|
|
1068
|
-
//
|
|
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
|
-
//
|
|
1071
|
-
//
|
|
1072
|
-
//
|
|
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
|
-
{
|
|
2384
|
+
{
|
|
2385
|
+
reference,
|
|
2386
|
+
spends,
|
|
2387
|
+
options: createsVaultOutput ? { noSend: true } : { acceptDelayedBroadcast: false }
|
|
2388
|
+
},
|
|
1078
2389
|
adminOriginator
|
|
1079
2390
|
)
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
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
|
|
1087
|
-
*
|
|
1088
|
-
*
|
|
1089
|
-
*
|
|
1090
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
//
|
|
1110
|
-
//
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
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
|
-
*
|
|
1124
|
-
*
|
|
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
|
|
1127
|
-
*
|
|
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
|
|
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
|
|
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
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
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
|
}
|