@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 +1790 -0
- package/README.md +54 -1
- package/core/amountFormatHelpers.ts +20 -2
- package/core/backup/RemoteSyncReader.ts +131 -19
- package/core/backup/appData.ts +157 -0
- package/core/backup/client.ts +15 -1
- package/core/backup/codec.ts +147 -9
- package/core/backup/constants.ts +30 -1
- package/core/backup/cursor.ts +31 -2
- package/core/backup/push.ts +70 -4
- package/core/backup/restore.ts +104 -16
- package/core/backup/restoreOnImport.ts +94 -30
- package/core/backup/status.ts +13 -8
- package/core/constants.ts +14 -1
- package/core/context/ExchangeRateContext.tsx +34 -27
- package/core/context/LocalStorageProvider.tsx +43 -40
- package/core/context/UserContext.tsx +18 -7
- package/core/context/VaultContext.tsx +49 -2
- package/core/context/WalletConnectionContext.tsx +203 -11
- package/core/context/WalletContext.tsx +653 -175
- package/core/headers/OfflineFirstChaintracks.ts +48 -4
- package/core/headers/headerStore.ts +26 -4
- package/core/headers/headerSyncTriggers.ts +65 -0
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +1001 -25
- package/core/identity/handleRegistry/client.ts +31 -2
- package/core/identity/handleRegistry/keyPinStore.ts +70 -0
- package/core/identity/handleRegistry/resolver.ts +71 -3
- package/core/index.ts +33 -3
- package/core/localpay/build.ts +225 -24
- package/core/localpay/pending.ts +110 -7
- package/core/localpay/pendingAbortAuthority.ts +95 -0
- package/core/localpay/pendingAborts.ts +264 -28
- package/core/localpay/session.ts +42 -17
- package/core/localpay/settlementAck.ts +10 -1
- package/core/localpay/transport/socket.ts +52 -3
- package/core/localpay/types.ts +9 -1
- package/core/localpay/verify.ts +143 -16
- package/core/mandala/abortGuard.ts +96 -20
- package/core/mandala/createRuntime.ts +206 -33
- package/core/mandala/drain.ts +89 -11
- package/core/mandala/inboxPrehold.ts +186 -0
- package/core/mandala/permissionModule.ts +202 -20
- package/core/mandala/settlementStore.ts +24 -2
- package/core/mandala/types.ts +40 -5
- package/core/monitor/TaskBackupPush.ts +14 -0
- package/core/monitor/TaskDrainOutbox.ts +14 -0
- package/core/monitor/TaskSendOffline.ts +14 -0
- package/core/net/publicDestination.ts +91 -0
- package/core/net/validateArcUrl.ts +22 -0
- package/core/offline/cancelParked.ts +134 -13
- package/core/offline/payerHold.ts +100 -24
- package/core/offline/plan.ts +36 -7
- package/core/pay/beefRepair.ts +6 -2
- package/core/pay/damagedInbox.ts +24 -0
- package/core/pay/rails/address.ts +107 -12
- package/core/pay/rails/handle.ts +117 -22
- package/core/pay/rails/index.ts +45 -7
- package/core/pay/rails/nativeIntent.ts +61 -0
- package/core/pay/rails/nearby.ts +1 -0
- package/core/pay/receiveHistory.ts +93 -0
- package/core/pay/recordProof.ts +19 -1
- package/core/pay/refreshProofGuard.ts +42 -1
- package/core/pay/watchlist.ts +5 -2
- package/core/peerpay/control.ts +17 -18
- package/core/peerpay/handleResendRequests.ts +58 -4
- package/core/peerpay/outbox.ts +3 -1
- package/core/recovery/backupMaterial.ts +61 -0
- package/core/recovery/createWallet.ts +95 -0
- package/core/recovery/recoverWallet.ts +120 -0
- package/core/recovery/restoreWallet.ts +170 -0
- package/core/recovery/secret.ts +92 -0
- package/core/recovery/shareCollector.ts +71 -0
- package/core/recovery/shareParsing.ts +87 -0
- package/core/recovery/shares.ts +116 -0
- package/core/recovery/useRecoveryDeps.ts +70 -0
- package/core/services/arcTokenStorage.ts +52 -0
- package/core/services/arcadeBroadcastProvider.ts +232 -48
- package/core/services/autoApprovePolicy.ts +105 -0
- package/core/services/callbackToken.ts +19 -0
- package/core/services/capWalletArgs.ts +14 -2
- package/core/services/connectionAuthority.ts +98 -0
- package/core/services/exchangeRate.ts +35 -12
- package/core/services/externalOrigin.ts +11 -0
- package/core/services/secrets/kek.ts +126 -29
- package/core/services/secrets/migration.ts +16 -4
- package/core/services/secrets/store.ts +42 -14
- package/core/services/vault/VaultKeyService.ts +228 -45
- package/core/services/vault/chainRecovery.ts +483 -0
- package/core/services/vault/driver.ts +9 -1
- package/core/services/vault/enrolledSerialRegistry.ts +150 -0
- package/core/services/vault/guard.ts +218 -32
- package/core/services/vault/hardwareLease.ts +19 -0
- package/core/services/vault/metaAuthority.ts +210 -0
- package/core/services/vault/pivReset.ts +64 -23
- package/core/services/vault/r1comb.ts +139 -3
- package/core/services/vault/session.ts +25 -4
- package/core/services/vault/transfers.ts +866 -170
- package/core/services/vault/types.ts +19 -4
- package/core/services/vault/vaultStore.ts +256 -29
- package/core/services/walletArgLimits.ts +45 -2
- package/core/services/walletConnectionValidation.ts +76 -6
- package/core/services/walletServiceConfig.ts +10 -8
- package/core/storage/StorageExpoSQLite.ts +47 -13
- package/core/storage/methods/findSql.ts +21 -2
- package/core/storage/methods/offlineActions.ts +10 -1
- package/core/storage/methods/processOfflineActions.ts +116 -23
- package/core/storage/schema/createTables.ts +126 -2
- package/core/stores/ConnectionStore.ts +34 -0
- package/core/toolboxConfig.ts +45 -11
- package/core/walletDbRegistry.ts +63 -0
- package/core/walletMonitor.ts +17 -1
- package/core/walletRepair/releaseStuckReservations.ts +72 -0
- package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
- package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
- package/package.json +2 -2
- package/ui/backupShares.ts +26 -169
- package/ui/components/pay/AddressReceive.tsx +13 -6
- package/ui/components/pay/AssetPicker.tsx +30 -9
- package/ui/components/pay/MessageBoxConfig.tsx +16 -0
- package/ui/components/pay/NearbyFlow.tsx +511 -251
- package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
- package/ui/components/pay/UniversalSend.tsx +167 -73
- package/ui/components/ui/AlertCard.tsx +38 -5
- package/ui/components/ui/PermissionSheet.tsx +197 -66
- package/ui/components/vault/EnrollWizard.tsx +61 -13
- package/ui/components/vault/vaultErrorCopy.ts +3 -1
- package/ui/components/wallet/ActivityRow.tsx +5 -3
- package/ui/components/wallet/AmountInput.tsx +8 -2
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
- package/ui/components/wallet/Balance.tsx +42 -23
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
- package/ui/exportTransactions.ts +36 -4
- package/ui/hooks/useExportWalletData.ts +25 -2
- package/ui/importDatabases.ts +339 -24
- package/ui/index.ts +9 -3
- package/ui/isImageUrl.ts +6 -0
- package/ui/printRecoveryShares.ts +9 -10
- package/ui/recoveryPrompts.ts +91 -0
- package/ui/resolveIdentity.ts +31 -9
- package/ui/screens/ConnectionsScreen.tsx +86 -19
- package/ui/screens/IdentifierScreen.tsx +30 -8
- package/ui/screens/PairScreen.tsx +74 -2
- package/ui/screens/SettingsScreen.tsx +10 -4
- package/ui/screens/TrustScreen.tsx +99 -4
- package/ui/screens/VaultScreen.tsx +410 -61
- package/ui/screens/VaultTransferScreen.tsx +59 -7
- package/ui/screens/WalletCheckScreen.tsx +17 -6
- package/ui/screens/WalletConfigScreen.tsx +82 -28
- package/ui/screens/WalletHomeScreen.tsx +179 -88
- package/ui/screens/detailActionKeys.ts +55 -0
- package/ui/tokenFormat.ts +44 -4
- package/ui/txStatus.ts +5 -0
- package/core/storage/LocalStorageAdapter.ts +0 -58
package/core/localpay/verify.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
|
|
2
|
+
import type { ChainTracker } from '@bsv/sdk'
|
|
2
3
|
import { MandalaToken } from '@bsv/templates'
|
|
3
4
|
import type { PaymentFrame } from './codec'
|
|
4
5
|
import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
|
|
@@ -28,14 +29,17 @@ export type VerifiedPayment =
|
|
|
28
29
|
/**
|
|
29
30
|
* Why a frame could not be shown to pay this device.
|
|
30
31
|
*
|
|
31
|
-
*
|
|
32
|
+
* Four kinds, because the payee's decline reason differs: bytes that are not a
|
|
32
33
|
* transaction are a decode problem the payer can retry from; a transaction that
|
|
33
|
-
* pays someone else is a frame that was never for us;
|
|
34
|
+
* pays someone else is a frame that was never for us; a token frame whose
|
|
34
35
|
* evidence does not COVER its own ancestry is a frame that pays us with a coin
|
|
35
|
-
* the issuer's overlay has never vouched for — retrying it will not help
|
|
36
|
-
*
|
|
36
|
+
* the issuer's overlay has never vouched for — retrying it will not help; and
|
|
37
|
+
* a transaction whose ancestry ends at a block root this device could not
|
|
38
|
+
* confirm, which is what an offline payee with no header for that block sees.
|
|
39
|
+
* That last one is fixed by the PAYEE getting online briefly, so the payer
|
|
40
|
+
* needs to hear which of the four it was.
|
|
37
41
|
*/
|
|
38
|
-
export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered'
|
|
42
|
+
export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered' | 'root_unverified'
|
|
39
43
|
|
|
40
44
|
/**
|
|
41
45
|
* The decline code the payer is told, for each way verification can fail.
|
|
@@ -49,6 +53,7 @@ export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered'
|
|
|
49
53
|
export function declineReasonFor(kind: FrameVerifyKind): DeclineReason {
|
|
50
54
|
if (kind === 'not_mine') return 'session_mismatch'
|
|
51
55
|
if (kind === 'not_covered') return 'not_covered'
|
|
56
|
+
if (kind === 'root_unverified') return 'root_unverified'
|
|
52
57
|
return 'decode_failed'
|
|
53
58
|
}
|
|
54
59
|
|
|
@@ -61,11 +66,31 @@ export class FrameVerifyError extends Error {
|
|
|
61
66
|
}
|
|
62
67
|
}
|
|
63
68
|
|
|
64
|
-
/** The one wallet capability this module needs: BRC-42 derivation.
|
|
69
|
+
/** The one wallet capability this module needs: BRC-42 derivation. The
|
|
70
|
+
* permissions manager satisfies it as is. */
|
|
65
71
|
export interface DerivingWallet {
|
|
66
72
|
getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
|
|
67
73
|
}
|
|
68
74
|
|
|
75
|
+
/**
|
|
76
|
+
* What `verifyFramePayment` needs from this device, as two separate
|
|
77
|
+
* dependencies rather than one object that must happen to provide both: the
|
|
78
|
+
* permissions manager derives keys but holds no chain services, and a single
|
|
79
|
+
* "wallet" parameter asking for both is how a missing `getServices()` once
|
|
80
|
+
* reached production as a TypeError on every Nearby BSV payment.
|
|
81
|
+
*/
|
|
82
|
+
export interface FrameVerifyDeps {
|
|
83
|
+
wallet: DerivingWallet
|
|
84
|
+
/**
|
|
85
|
+
* The chain tracker the BSV branch's SPV check walks merkle paths against —
|
|
86
|
+
* the same one `internalizeAction` consults, i.e.
|
|
87
|
+
* `storage.getServices().getChainTracker()`. In the app that is the
|
|
88
|
+
* offline-first tracker over the local header window, so an offline payee
|
|
89
|
+
* can still verify. Not read for a token frame.
|
|
90
|
+
*/
|
|
91
|
+
chainTracker: ChainTracker
|
|
92
|
+
}
|
|
93
|
+
|
|
69
94
|
/**
|
|
70
95
|
* The satoshis a delivered frame actually pays this device.
|
|
71
96
|
*
|
|
@@ -78,11 +103,11 @@ export interface DerivingWallet {
|
|
|
78
103
|
*
|
|
79
104
|
* Throws on every failure and returns on none, so a caller cannot mistake a
|
|
80
105
|
* refusal for a zero-value payment. MUST be called before the settle path
|
|
81
|
-
* latches or writes anything: every throw here has to remain
|
|
82
|
-
* "queued nothing" decline.
|
|
106
|
+
* latches or writes anything: every throw here has to remain an invariant
|
|
107
|
+
* this module enforces on itself — a "queued nothing" decline, by construction.
|
|
83
108
|
*/
|
|
84
109
|
export async function verifyFramePayment(
|
|
85
|
-
wallet:
|
|
110
|
+
{ wallet, chainTracker }: FrameVerifyDeps,
|
|
86
111
|
frame: PaymentFrame,
|
|
87
112
|
originator: string,
|
|
88
113
|
/**
|
|
@@ -159,6 +184,57 @@ export async function verifyFramePayment(
|
|
|
159
184
|
throw new FrameVerifyError('not_mine', `the named output carries no usable satoshi value: ${output.satoshis}`)
|
|
160
185
|
}
|
|
161
186
|
|
|
187
|
+
// The ownership/amount checks above are cheap and certain, but they say
|
|
188
|
+
// nothing about the REST of the transaction: `internalizeAction`'s own
|
|
189
|
+
// gate (toolbox `validateAtomicBeef` -> SDK `Beef.verify`) is a pure
|
|
190
|
+
// AtomicBEEF-structure/SPV check with no script interpreter step, so
|
|
191
|
+
// without this call a payer could spend a real mined UTXO it does not
|
|
192
|
+
// own, with a garbage unlockingScript, into an output that locks to us,
|
|
193
|
+
// for any amount, and have it accepted here.
|
|
194
|
+
//
|
|
195
|
+
// `tx.verify(chainTracker)` does the whole job in one pass: it walks
|
|
196
|
+
// every ancestor's merkle path against this device's own offline-capable
|
|
197
|
+
// chain tracker, runs the per-input script check against each ancestor's
|
|
198
|
+
// real locking script (defeating the garbage-unlockingScript attack), and
|
|
199
|
+
// checks sum(outputs) <= sum(inputs) (defeating an inflated-output
|
|
200
|
+
// attack) — and it FAILS CLOSED: it throws when an input's ancestor is
|
|
201
|
+
// present only as a txid (no raw bytes, e.g. a mined ancestor the payer's
|
|
202
|
+
// BEEF only proved by merkle path) rather than silently skipping that
|
|
203
|
+
// input, which is the desired refusal for an ancestor this device cannot
|
|
204
|
+
// actually verify. No feeModel is passed, so a legitimate low-fee frame
|
|
205
|
+
// is never refused on fee grounds — only on SPV/script/value grounds.
|
|
206
|
+
//
|
|
207
|
+
// The tracker is wrapped only to notice a refused merkle root, so that
|
|
208
|
+
// refusal can be told apart from a bad script or value: `tx.verify`
|
|
209
|
+
// returns false for both. A refused root is what an offline payee sees
|
|
210
|
+
// for a block its header window does not reach yet (and what anyone sees
|
|
211
|
+
// for a forged proof), and the remedy — the payee going online — is
|
|
212
|
+
// different from a malformed transaction's.
|
|
213
|
+
let rootRefused = false
|
|
214
|
+
const observed: ChainTracker = {
|
|
215
|
+
isValidRootForHeight: async (root, height) => {
|
|
216
|
+
const ok = await chainTracker.isValidRootForHeight(root, height)
|
|
217
|
+
if (!ok) rootRefused = true
|
|
218
|
+
return ok
|
|
219
|
+
},
|
|
220
|
+
currentHeight: async () => await chainTracker.currentHeight()
|
|
221
|
+
}
|
|
222
|
+
// A refused root surfaces as a throw ("Invalid merkle path"), so both exits
|
|
223
|
+
// check the flag.
|
|
224
|
+
const rootUnverified = () =>
|
|
225
|
+
new FrameVerifyError('root_unverified', 'a merkle root in the frame could not be confirmed on this device')
|
|
226
|
+
let verified: boolean
|
|
227
|
+
try {
|
|
228
|
+
verified = await tx.verify(observed)
|
|
229
|
+
} catch (e) {
|
|
230
|
+
if (rootRefused) throw rootUnverified()
|
|
231
|
+
throw new FrameVerifyError('unparseable', `transaction failed SPV/script verification: ${messageOf(e)}`)
|
|
232
|
+
}
|
|
233
|
+
if (!verified) {
|
|
234
|
+
if (rootRefused) throw rootUnverified()
|
|
235
|
+
throw new FrameVerifyError('unparseable', 'transaction failed SPV/script verification')
|
|
236
|
+
}
|
|
237
|
+
|
|
162
238
|
return { kind: 'bsv', satoshis: output.satoshis }
|
|
163
239
|
}
|
|
164
240
|
|
|
@@ -183,13 +259,22 @@ export async function verifyFramePayment(
|
|
|
183
259
|
originator
|
|
184
260
|
)
|
|
185
261
|
const expectedPkh = Hash.hash160(Utils.toArray(publicKey, 'hex'))
|
|
186
|
-
const mine =
|
|
187
|
-
decoded.pubKeyHash.every((b, i) => b === expectedPkh[i])
|
|
262
|
+
const mine =
|
|
263
|
+
decoded.pubKeyHash.length === expectedPkh.length && decoded.pubKeyHash.every((b, i) => b === expectedPkh[i])
|
|
188
264
|
if (!mine) throw new FrameVerifyError('not_mine', 'the named token output does not pay this device')
|
|
189
265
|
if (!Number.isSafeInteger(decoded.amount) || decoded.amount < 1) {
|
|
190
266
|
throw new FrameVerifyError('not_mine', `the named output carries no usable token amount: ${decoded.amount}`)
|
|
191
267
|
}
|
|
192
268
|
|
|
269
|
+
// XR-099. COVER proves ancestry admission, never value: nothing before this
|
|
270
|
+
// point sums a token input against a token output, so a payer could spend a
|
|
271
|
+
// real, small admitted coin into an output naming any larger amount it
|
|
272
|
+
// likes and have it accepted. Cheap and certain, like the ownership checks
|
|
273
|
+
// above it, so it runs before the COVER walk below.
|
|
274
|
+
if (!tokenConservationHolds(tx, frame.token.assetId)) {
|
|
275
|
+
throw new FrameVerifyError('not_covered', 'the frame’s admission evidence does not cover it: conservation')
|
|
276
|
+
}
|
|
277
|
+
|
|
193
278
|
// Coverage runs LAST, and only for an output already proven to be ours.
|
|
194
279
|
// Ownership is the cheaper, more certain check, and running a third party's
|
|
195
280
|
// injected verifier over a stranger's frame would hand it bytes that were
|
|
@@ -200,7 +285,7 @@ export async function verifyFramePayment(
|
|
|
200
285
|
// every token ancestor bottoms out at a σ_I this device can verify against
|
|
201
286
|
// THIS session's overlay key, or at bytes it can walk further. Anything else
|
|
202
287
|
// is refused here, before the settle path latches or writes anything, so the
|
|
203
|
-
// refusal stays
|
|
288
|
+
// refusal stays an unlatched "queued nothing" by construction.
|
|
204
289
|
if (!opts?.cover) {
|
|
205
290
|
throw new FrameVerifyError('not_covered', 'no coverage verifier was supplied for a token frame')
|
|
206
291
|
}
|
|
@@ -214,10 +299,7 @@ export async function verifyFramePayment(
|
|
|
214
299
|
// "admitted" as the issuer's.
|
|
215
300
|
const asset = opts.asset
|
|
216
301
|
if (!asset || !sameOverlay(frame.token, asset)) {
|
|
217
|
-
throw new FrameVerifyError(
|
|
218
|
-
'not_covered',
|
|
219
|
-
`the frame’s admission evidence does not cover it: unsafe_asset`
|
|
220
|
-
)
|
|
302
|
+
throw new FrameVerifyError('not_covered', `the frame’s admission evidence does not cover it: unsafe_asset`)
|
|
221
303
|
}
|
|
222
304
|
|
|
223
305
|
const covered = await coverFromFrame(frame, opts.cover)
|
|
@@ -251,3 +333,48 @@ function sameOverlay(
|
|
|
251
333
|
function messageOf(e: unknown): string {
|
|
252
334
|
return e instanceof Error ? e.message : String(e)
|
|
253
335
|
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* XR-099. Sums `tip`'s own decodable token inputs and outputs for `assetId`
|
|
339
|
+
* and reports whether the outputs are actually covered by the inputs.
|
|
340
|
+
*
|
|
341
|
+
* Deliberately scoped to the tip's OWN direct inputs, not the whole ancestor
|
|
342
|
+
* tree COVER walks: a direct input's previous output is always present in the
|
|
343
|
+
* frame's AtomicBEEF regardless (the payer needs its locking script to build
|
|
344
|
+
* and sign against it), so this is real evidence, not an assumption. An input
|
|
345
|
+
* whose `sourceTransaction` is absent, or whose source output is not a
|
|
346
|
+
* MandalaToken of this asset at all (an ordinary BSV fee input, most
|
|
347
|
+
* commonly), contributes nothing to `inputSum` — which only ever makes this
|
|
348
|
+
* check MORE likely to refuse, never less: there is no way to under-count an
|
|
349
|
+
* output or over-count an input by omission, so this cannot be defeated by a
|
|
350
|
+
* payer hiding a real input behind a hole.
|
|
351
|
+
*/
|
|
352
|
+
function tokenConservationHolds(tip: Transaction, assetId: string): boolean {
|
|
353
|
+
let inputSum = 0
|
|
354
|
+
for (const input of tip.inputs) {
|
|
355
|
+
const source = input.sourceTransaction
|
|
356
|
+
const output = source?.outputs[input.sourceOutputIndex]
|
|
357
|
+
if (!output?.lockingScript) continue
|
|
358
|
+
try {
|
|
359
|
+
const decoded = MandalaToken.decode(output.lockingScript)
|
|
360
|
+
if (decoded.assetId === assetId && Number.isSafeInteger(decoded.amount) && decoded.amount > 0) {
|
|
361
|
+
inputSum += decoded.amount
|
|
362
|
+
}
|
|
363
|
+
} catch {
|
|
364
|
+
// Not a token script — an ordinary fee input, per FIX K (see
|
|
365
|
+
// core/mandala/bundle.ts's `tokenParentsOf`).
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
let outputSum = 0
|
|
369
|
+
for (const output of tip.outputs) {
|
|
370
|
+
try {
|
|
371
|
+
const decoded = MandalaToken.decode(output.lockingScript)
|
|
372
|
+
if (decoded.assetId === assetId && Number.isSafeInteger(decoded.amount) && decoded.amount > 0) {
|
|
373
|
+
outputSum += decoded.amount
|
|
374
|
+
}
|
|
375
|
+
} catch {
|
|
376
|
+
// Not a token output of this asset.
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return outputSum <= inputSum
|
|
380
|
+
}
|
|
@@ -78,7 +78,36 @@ export interface AbortableManager {
|
|
|
78
78
|
* `undefined` (no runtime, no database, not a Mandala chain) means "no token
|
|
79
79
|
* payment can be at stake", which is the correct answer, not a failure.
|
|
80
80
|
*/
|
|
81
|
-
export type SettlementStoreLookup = () =>
|
|
81
|
+
export type SettlementStoreLookup = () =>
|
|
82
|
+
| Pick<SettlementStore, 'getSettlementByReference' | 'hasUnresolvedLegacyBlockedRows'>
|
|
83
|
+
| undefined
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Whether a token payment could exist on THIS wallet build at all — read LATE,
|
|
87
|
+
* for the same reason `settlements` is, and answering ONLY the question of
|
|
88
|
+
* whether the current chain's configuration could ever have written a
|
|
89
|
+
* `token_settlements` row.
|
|
90
|
+
*
|
|
91
|
+
* XR-034 (SEC1-024 / SEC2-038). `settlements()` answering `undefined` is not
|
|
92
|
+
* one fact. WalletContext.tsx wires it to `() => mandalaRef.current?.store`,
|
|
93
|
+
* and `mandalaRef.current` reads `undefined` in situations that mean opposite
|
|
94
|
+
* things for safety:
|
|
95
|
+
* 1. This chain has no Mandala endpoints at all — `createRuntime.ts`'s
|
|
96
|
+
* `available` (`endpoints !== undefined && db !== undefined`) is false by
|
|
97
|
+
* construction, so no token action has ever existed here, or ever can.
|
|
98
|
+
* 2. `createMandalaRuntime` THREW while endpoints exist (WalletContext.tsx's
|
|
99
|
+
* catch around the construction), or a network switch/rebuild has
|
|
100
|
+
* cleared the ref ahead of the new build's runtime replacing it. Either
|
|
101
|
+
* way the chain's own storage may still carry a `handed_over`/`held`/
|
|
102
|
+
* `submitting`/`admitted`/`broadcast` row from a previous build; this
|
|
103
|
+
* call simply cannot see it right now.
|
|
104
|
+
*
|
|
105
|
+
* Only case 1 licenses treating `undefined` as "no row, safe". WalletContext.tsx
|
|
106
|
+
* wires this to `() => mandalaEndpoints !== undefined` — a static fact of the
|
|
107
|
+
* chain's own configuration that does not fluctuate with runtime construction,
|
|
108
|
+
* build failures, or rebuild timing the way `mandalaRef.current` does.
|
|
109
|
+
*/
|
|
110
|
+
export type TokenSettlementPossible = () => boolean
|
|
82
111
|
|
|
83
112
|
/**
|
|
84
113
|
* Wrap `abortAction` so an action that built a token transaction the overlay
|
|
@@ -89,26 +118,72 @@ export type SettlementStoreLookup = () => Pick<SettlementStore, 'getSettlementBy
|
|
|
89
118
|
* so the published object is still the one the guard's own re-wrap dedup
|
|
90
119
|
* recognises. Every other method and property passes through untouched.
|
|
91
120
|
*
|
|
92
|
-
* **
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
121
|
+
* **XR-034: fails CLOSED on anything but a definitive "no".** A database that
|
|
122
|
+
* will not answer, a settlement runtime that has not been built yet, and one
|
|
123
|
+
* mid-rebuild are all indistinguishable from "a payment is in flight" — they
|
|
124
|
+
* are exactly the moments this device can least tell, which is the opposite of
|
|
125
|
+
* evidence that releasing inputs is safe. Refusing the abort in that window
|
|
126
|
+
* costs a retry (every caller already treats `{ aborted: false }` as "did not
|
|
127
|
+
* release, try again" — see `queueFailedAbort`); wrongly granting it costs a
|
|
128
|
+
* double spend. The one shape that still passes through when `settlements()`
|
|
129
|
+
* answers `undefined` is `tokenSettlementPossible()` reporting false: a chain
|
|
130
|
+
* with no Mandala configuration at all, where a blocking row could never have
|
|
131
|
+
* been written and refusing every plain BSV abort forever would be its own
|
|
132
|
+
* outage.
|
|
133
|
+
*
|
|
134
|
+
* **XR-033, a second and coarser check.** A row that predates the `reference`
|
|
135
|
+
* column (or whose backfill at migration time could not resolve one — see
|
|
136
|
+
* `createTables.ts`'s `ensureTokenSettlementColumns`) reads back with
|
|
137
|
+
* `reference === undefined` forever, which the lookup above can never match
|
|
138
|
+
* against ANY reference — so a legacy row stuck in a blocked state is
|
|
139
|
+
* invisible to it no matter which action is being aborted. `hasUnresolvedLegacyBlockedRows`
|
|
140
|
+
* asks the coarser question instead: does ANY such row exist at all. It only
|
|
141
|
+
* ever narrows an abort from allowed to refused, never the reverse, and (like
|
|
142
|
+
* the lookup above) now fails CLOSED on its own read fault, for the same
|
|
143
|
+
* reason.
|
|
97
144
|
*/
|
|
98
145
|
export function wrapAbortActionForSettlements<T extends AbortableManager>(
|
|
99
146
|
manager: T,
|
|
100
|
-
settlements: SettlementStoreLookup
|
|
147
|
+
settlements: SettlementStoreLookup,
|
|
148
|
+
tokenSettlementPossible: TokenSettlementPossible
|
|
101
149
|
): T {
|
|
102
150
|
return new Proxy(manager, {
|
|
103
151
|
get(target, prop, receiver) {
|
|
104
152
|
if (prop === 'abortAction') {
|
|
105
153
|
return async (args: { reference: string }, originator?: string) => {
|
|
106
|
-
const
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
'
|
|
111
|
-
|
|
154
|
+
const store = settlements()
|
|
155
|
+
if (!store) {
|
|
156
|
+
if (tokenSettlementPossible()) {
|
|
157
|
+
console.warn(
|
|
158
|
+
'[mandala] refusing to abort: token settlement state is unavailable right now ' +
|
|
159
|
+
'(the runtime is not built, is rebuilding, or its store could not be reached) and this ' +
|
|
160
|
+
'chain can carry token payments — releasing inputs could double spend one the overlay already has'
|
|
161
|
+
)
|
|
162
|
+
return { aborted: false }
|
|
163
|
+
}
|
|
164
|
+
// No Mandala endpoints on this chain: a blocking row could never
|
|
165
|
+
// have been written, so this is a plain BSV abort like any other.
|
|
166
|
+
return await target.abortAction(args, originator)
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
const row = await lookupSettlement(store, args?.reference)
|
|
170
|
+
if (abortIsBlockedBy(row)) {
|
|
171
|
+
console.warn(
|
|
172
|
+
`[mandala] refusing to abort ${row!.txid}: its settlement is '${row!.state}', ` +
|
|
173
|
+
'so releasing these inputs would double spend a transaction the overlay may already have'
|
|
174
|
+
)
|
|
175
|
+
return { aborted: false }
|
|
176
|
+
}
|
|
177
|
+
if (await hasUnresolvedLegacyBlockedRow(store)) {
|
|
178
|
+
console.warn(
|
|
179
|
+
'[mandala] refusing to abort: an unresolved legacy settlement row exists with no reference to ' +
|
|
180
|
+
'match against — releasing any inputs while it is unresolved risks double spending a token ' +
|
|
181
|
+
'payment that row already has a claim on'
|
|
182
|
+
)
|
|
183
|
+
return { aborted: false }
|
|
184
|
+
}
|
|
185
|
+
} catch (e) {
|
|
186
|
+
console.warn('[mandala] refusing to abort: could not read this action\'s settlement state:', e)
|
|
112
187
|
return { aborted: false }
|
|
113
188
|
}
|
|
114
189
|
return await target.abortAction(args, originator)
|
|
@@ -121,14 +196,15 @@ export function wrapAbortActionForSettlements<T extends AbortableManager>(
|
|
|
121
196
|
}
|
|
122
197
|
|
|
123
198
|
async function lookupSettlement(
|
|
124
|
-
|
|
199
|
+
store: Pick<SettlementStore, 'getSettlementByReference'>,
|
|
125
200
|
reference: string | undefined
|
|
126
201
|
): Promise<TokenSettlementRow | undefined> {
|
|
127
202
|
if (!reference) return undefined
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
203
|
+
return await store.getSettlementByReference(reference)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function hasUnresolvedLegacyBlockedRow(
|
|
207
|
+
store: Pick<SettlementStore, 'hasUnresolvedLegacyBlockedRows'>
|
|
208
|
+
): Promise<boolean> {
|
|
209
|
+
return await store.hasUnresolvedLegacyBlockedRows()
|
|
134
210
|
}
|