@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
package/core/localpay/verify.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
|
|
2
2
|
import { MandalaToken } from '@bsv/templates'
|
|
3
3
|
import type { PaymentFrame } from './codec'
|
|
4
|
+
import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
|
|
4
5
|
import { PEERPAY_PROTOCOL_ID } from './pending'
|
|
5
6
|
import { isRequestableAmount } from './session'
|
|
7
|
+
import type { DeclineReason } from './types'
|
|
6
8
|
|
|
7
9
|
// mandala's FT derivation protocol — the payer locks token outputs under it
|
|
8
10
|
// with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
|
|
@@ -10,16 +12,45 @@ export const FT_PROTOCOL_ID: [2, string] = [2, 'mandala token']
|
|
|
10
12
|
|
|
11
13
|
export type VerifiedPayment =
|
|
12
14
|
| { kind: 'bsv'; satoshis: number }
|
|
13
|
-
| {
|
|
15
|
+
| {
|
|
16
|
+
kind: 'token'
|
|
17
|
+
assetId: string
|
|
18
|
+
amount: number
|
|
19
|
+
/**
|
|
20
|
+
* COVER's own answer: the chain transactions that still have to reach the
|
|
21
|
+
* overlay, parents first, tip last. The payee is the party nominally
|
|
22
|
+
* responsible for submitting them (settlement rule 3), so it is handed
|
|
23
|
+
* the list it proved rather than recomputing it later from storage.
|
|
24
|
+
*/
|
|
25
|
+
mustSubmit: string[]
|
|
26
|
+
}
|
|
14
27
|
|
|
15
28
|
/**
|
|
16
29
|
* Why a frame could not be shown to pay this device.
|
|
17
30
|
*
|
|
18
|
-
*
|
|
19
|
-
* transaction are a decode problem the payer can retry from
|
|
20
|
-
*
|
|
31
|
+
* Three kinds, because the payee's decline reason differs: bytes that are not a
|
|
32
|
+
* 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; and a token frame whose
|
|
34
|
+
* 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, and
|
|
36
|
+
* the payer needs to hear which of the three it was.
|
|
37
|
+
*/
|
|
38
|
+
export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered'
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The decline code the payer is told, for each way verification can fail.
|
|
42
|
+
*
|
|
43
|
+
* One mapping, in one place, because it crosses the wire: the payee's screens
|
|
44
|
+
* and the QR path both refuse frames, and two hand-written switches would drift
|
|
45
|
+
* into telling the same payer two different stories about the same failure.
|
|
46
|
+
* Every code here means the payee queued NOTHING, so the payer may safely
|
|
47
|
+
* release the inputs its `noSend` action is holding.
|
|
21
48
|
*/
|
|
22
|
-
export
|
|
49
|
+
export function declineReasonFor(kind: FrameVerifyKind): DeclineReason {
|
|
50
|
+
if (kind === 'not_mine') return 'session_mismatch'
|
|
51
|
+
if (kind === 'not_covered') return 'not_covered'
|
|
52
|
+
return 'decode_failed'
|
|
53
|
+
}
|
|
23
54
|
|
|
24
55
|
export class FrameVerifyError extends Error {
|
|
25
56
|
readonly kind: FrameVerifyKind
|
|
@@ -53,7 +84,35 @@ export interface DerivingWallet {
|
|
|
53
84
|
export async function verifyFramePayment(
|
|
54
85
|
wallet: DerivingWallet,
|
|
55
86
|
frame: PaymentFrame,
|
|
56
|
-
originator: string
|
|
87
|
+
originator: string,
|
|
88
|
+
/**
|
|
89
|
+
* Token frames only. `cover` is the pure COVER walk (spec §1.2), injected
|
|
90
|
+
* because it lives in `@bsv/mandala` beside the overlay's own σ_I digest.
|
|
91
|
+
*
|
|
92
|
+
* Its ABSENCE refuses a token frame rather than crediting one: no verifier
|
|
93
|
+
* is no evidence, and a caller that forgot to wire it must not get a credit
|
|
94
|
+
* indistinguishable from a covered one. The BSV path never reads it.
|
|
95
|
+
*/
|
|
96
|
+
opts?: {
|
|
97
|
+
cover?: CoverVerifier
|
|
98
|
+
/**
|
|
99
|
+
* Token frames only. THIS DEVICE's configured facts about the asset it
|
|
100
|
+
* agreed to be paid in — the session's own `asset` block, which the payee
|
|
101
|
+
* minted and the payer echoed back, not anything read off the frame.
|
|
102
|
+
*
|
|
103
|
+
* Wire contract §9.10: the verifier's trust anchor comes from its own
|
|
104
|
+
* configuration, and the bundle's `overlayIdentityKey` is DATA that must
|
|
105
|
+
* EQUAL it. Without this comparison a frame names its own overlay, and
|
|
106
|
+
* `coverFromFrame` — which builds the COVER bundle straight from
|
|
107
|
+
* `frame.token.overlayIdentityKey` — would happily verify every σ_I in the
|
|
108
|
+
* frame against a key the payer chose. A payer with any keypair could then
|
|
109
|
+
* sign its own admissions and be credited for a coin no issuer ever saw.
|
|
110
|
+
*
|
|
111
|
+
* Its ABSENCE refuses a token frame, exactly as a missing `cover` does: no
|
|
112
|
+
* configured asset is no anchor.
|
|
113
|
+
*/
|
|
114
|
+
asset?: { overlayUrl: string; overlayIdentityKey: string }
|
|
115
|
+
}
|
|
57
116
|
): Promise<VerifiedPayment> {
|
|
58
117
|
let tx: Transaction
|
|
59
118
|
try {
|
|
@@ -130,73 +189,63 @@ export async function verifyFramePayment(
|
|
|
130
189
|
if (!Number.isSafeInteger(decoded.amount) || decoded.amount < 1) {
|
|
131
190
|
throw new FrameVerifyError('not_mine', `the named output carries no usable token amount: ${decoded.amount}`)
|
|
132
191
|
}
|
|
133
|
-
return { kind: 'token', assetId: decoded.assetId, amount: decoded.amount }
|
|
134
|
-
}
|
|
135
192
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
193
|
+
// Coverage runs LAST, and only for an output already proven to be ours.
|
|
194
|
+
// Ownership is the cheaper, more certain check, and running a third party's
|
|
195
|
+
// injected verifier over a stranger's frame would hand it bytes that were
|
|
196
|
+
// never this device's business.
|
|
197
|
+
//
|
|
198
|
+
// This is the whole offline-settlement gate: the coin is credited — spendable
|
|
199
|
+
// immediately, which is what makes chained offline re-spend work — the moment
|
|
200
|
+
// every token ancestor bottoms out at a σ_I this device can verify against
|
|
201
|
+
// THIS session's overlay key, or at bytes it can walk further. Anything else
|
|
202
|
+
// is refused here, before the settle path latches or writes anything, so the
|
|
203
|
+
// refusal stays a provable "queued nothing".
|
|
204
|
+
if (!opts?.cover) {
|
|
205
|
+
throw new FrameVerifyError('not_covered', 'no coverage verifier was supplied for a token frame')
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The trust anchor, BEFORE the walk (wire contract §9.10). `coverFromFrame`
|
|
209
|
+
// takes the bundle's `overlayIdentityKey` from the frame, so this equality is
|
|
210
|
+
// what makes that key the CONFIGURED one rather than the payer's choice —
|
|
211
|
+
// and the overlay URL goes with it, because the linkage payloads this frame
|
|
212
|
+
// carries are the bytes a later `/submit` is aimed at, and aiming them at an
|
|
213
|
+
// attacker's overlay is how a wallet is talked into treating a stranger's
|
|
214
|
+
// "admitted" as the issuer's.
|
|
215
|
+
const asset = opts.asset
|
|
216
|
+
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
|
+
)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const covered = await coverFromFrame(frame, opts.cover)
|
|
224
|
+
if (!covered.ok) {
|
|
225
|
+
throw new FrameVerifyError('not_covered', `the frame’s admission evidence does not cover it: ${covered.reason}`)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { kind: 'token', assetId: decoded.assetId, amount: decoded.amount, mustSubmit: covered.mustSubmit }
|
|
139
229
|
}
|
|
140
230
|
|
|
141
231
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
232
|
+
* Both overlay facts, compared the way each is actually written.
|
|
233
|
+
*
|
|
234
|
+
* The identity key is hex and case-insensitive — a frame writing it uppercase
|
|
235
|
+
* is the same overlay and must not be refused. The URL is compared exactly
|
|
236
|
+
* apart from a trailing slash: anything cleverer (host-only, scheme-agnostic)
|
|
237
|
+
* would start accepting `http://` for `https://`, or a path under the
|
|
238
|
+
* configured origin, which is precisely what this check exists to stop.
|
|
147
239
|
*/
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
try {
|
|
159
|
-
const parsed = JSON.parse(new TextDecoder().decode(recipientLinkage)) as Record<string, unknown>
|
|
160
|
-
if (
|
|
161
|
-
typeof parsed.prover !== 'string' || parsed.prover.length !== 66 ||
|
|
162
|
-
typeof parsed.counterparty !== 'string' || parsed.counterparty.length !== 66 ||
|
|
163
|
-
!Array.isArray(parsed.protocolID) || typeof parsed.keyID !== 'string' ||
|
|
164
|
-
!Array.isArray(parsed.encryptedLinkage)
|
|
165
|
-
) throw new Error('missing linkage fields')
|
|
166
|
-
linkage = parsed as typeof linkage
|
|
167
|
-
} catch (e) {
|
|
168
|
-
throw new FrameVerifyError('unparseable', `recipientLinkage is not a readable SpecificLinkage: ${messageOf(e)}`)
|
|
169
|
-
}
|
|
170
|
-
let plaintext: number[]
|
|
171
|
-
try {
|
|
172
|
-
;({ plaintext } = await wallet.decrypt(
|
|
173
|
-
{
|
|
174
|
-
ciphertext: linkage.encryptedLinkage,
|
|
175
|
-
protocolID: [2, `specific linkage revelation ${linkage.protocolID[0]} ${linkage.protocolID[1]}`],
|
|
176
|
-
keyID: linkage.keyID,
|
|
177
|
-
counterparty: linkage.prover
|
|
178
|
-
},
|
|
179
|
-
originator
|
|
180
|
-
))
|
|
181
|
-
} catch (e) {
|
|
182
|
-
throw new FrameVerifyError('not_mine', `recipientLinkage did not decrypt for this device: ${messageOf(e)}`)
|
|
183
|
-
}
|
|
184
|
-
let derivedPkh: number[]
|
|
185
|
-
try {
|
|
186
|
-
const curve = new Curve()
|
|
187
|
-
const sum = PublicKey.fromString(linkage.counterparty).add(curve.g.mul(new BigNumber(plaintext)))
|
|
188
|
-
derivedPkh = Hash.hash160(Utils.toArray(new PublicKey(sum.x, sum.y).toString(), 'hex'))
|
|
189
|
-
} catch (e) {
|
|
190
|
-
// `linkage.counterparty` is 66 hex chars by the shape check above, but
|
|
191
|
-
// hex-shaped is not curve-valid: hostile JSON can still name a point this
|
|
192
|
-
// library refuses to parse or add. That is a platform Error, not a
|
|
193
|
-
// FrameVerifyError, so it must be caught here to keep this module's
|
|
194
|
-
// every-failure-is-FrameVerifyError contract.
|
|
195
|
-
throw new FrameVerifyError('not_mine', `recipientLinkage counterparty key is unusable: ${messageOf(e)}`)
|
|
196
|
-
}
|
|
197
|
-
const matches = derivedPkh.length === expectedPubKeyHash.length &&
|
|
198
|
-
derivedPkh.every((b, i) => b === expectedPubKeyHash[i])
|
|
199
|
-
if (!matches) throw new FrameVerifyError('not_mine', 'recipientLinkage does not control the paid output')
|
|
240
|
+
function sameOverlay(
|
|
241
|
+
token: { overlayUrl: string; overlayIdentityKey: string },
|
|
242
|
+
asset: { overlayUrl: string; overlayIdentityKey: string }
|
|
243
|
+
): boolean {
|
|
244
|
+
const url = (u: string) => u.trim().replace(/\/+$/, '')
|
|
245
|
+
return (
|
|
246
|
+
token.overlayIdentityKey.toLowerCase() === asset.overlayIdentityKey.toLowerCase() &&
|
|
247
|
+
url(token.overlayUrl) === url(asset.overlayUrl)
|
|
248
|
+
)
|
|
200
249
|
}
|
|
201
250
|
|
|
202
251
|
function messageOf(e: unknown): string {
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard #4: a settled token payment's action may not be aborted.
|
|
3
|
+
*
|
|
4
|
+
* THE 2026-09-15 INCIDENT, in one paragraph. A token transfer is built and
|
|
5
|
+
* signed `noSend`, handed to the payee, and only then submitted to the issuer's
|
|
6
|
+
* overlay — which BROADCASTS on admission. For the window between "signed" and
|
|
7
|
+
* "our own request reaches the network", the only thing holding this device's
|
|
8
|
+
* inputs is a live `noSend` wallet action, and `abortAction(reference)` frees
|
|
9
|
+
* those inputs as spendable. On that day a transfer was admitted (and therefore
|
|
10
|
+
* broadcast by the overlay) and 0.7 s later the wallet aborted its own action:
|
|
11
|
+
* `proven_tx_reqs` went `nosend → abortAction → invalid`, `transactions.status`
|
|
12
|
+
* went `failed`, and the input coin came back spendable although it was spent on
|
|
13
|
+
* chain. The next send reused it and the overlay refused the child with
|
|
14
|
+
* `ERR_INPUT_SPENT` — surfaced to the user as "A payment could not be
|
|
15
|
+
* delivered".
|
|
16
|
+
*
|
|
17
|
+
* The abort came from the lib's own bulk sweep (`reconcileWallet`), which took
|
|
18
|
+
* the action for an abandoned `noSend` because our
|
|
19
|
+
* `StorageExpoSQLite.attemptToPostReqsToNetwork` HOLDS token requests rather
|
|
20
|
+
* than posting them, so the lib's journal entry had been cleared as "broadcast"
|
|
21
|
+
* when nothing had been. Three fixes meet here — the lib no longer clears that
|
|
22
|
+
* entry, `reconcileJournals` no longer runs the sweep at all, and this guard
|
|
23
|
+
* makes the abort itself unreachable from any caller, including one we have
|
|
24
|
+
* not thought of.
|
|
25
|
+
*
|
|
26
|
+
* **The guard is a refusal, not a repair.** It answers `{ aborted: false }`,
|
|
27
|
+
* which is exactly what `abortAction` already returns for an action it will not
|
|
28
|
+
* abort, and every existing caller in this wallet already treats that as a
|
|
29
|
+
* failure to release rather than as a released action (see
|
|
30
|
+
* `finalizeDelivery`'s `queueFailedAbort`). It never throws: a throw from a
|
|
31
|
+
* cleanup path is how a caller ends up abandoning something it was tidying.
|
|
32
|
+
*/
|
|
33
|
+
import type { SettlementStore, TokenSettlementRow, TokenSettlementState } from './types'
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* States in which the bytes are, or may already be, somewhere this device
|
|
37
|
+
* cannot recall them from.
|
|
38
|
+
*
|
|
39
|
+
* `handed_over`/`held` are in the list even though nothing has been submitted
|
|
40
|
+
* yet: the PAYEE holds the frame, and either party may submit it (offline
|
|
41
|
+
* settlement §0.1 — "whoever reconnects first submits"). Releasing the inputs
|
|
42
|
+
* under a payee who is about to submit is the same double spend, only with a
|
|
43
|
+
* longer fuse. `submitting` is a request in flight whose verdict is unknown,
|
|
44
|
+
* and an unknown verdict may be an admission.
|
|
45
|
+
*
|
|
46
|
+
* Everything else is safe to abort, and deliberately so:
|
|
47
|
+
* · `built`/`parked` — the payer's own states (FIX F). The payee has NOT been
|
|
48
|
+
* handed anything, nothing has been submitted, and cancelling a parked
|
|
49
|
+
* payment is a feature (`cancelParkedPayment`) that must keep working.
|
|
50
|
+
* · `refused`/`orphaned` — the overlay's final word. The money never moved and
|
|
51
|
+
* the inputs SHOULD come back.
|
|
52
|
+
*/
|
|
53
|
+
export const ABORT_BLOCKED_SETTLEMENT_STATES: readonly TokenSettlementState[] = [
|
|
54
|
+
'held',
|
|
55
|
+
'handed_over',
|
|
56
|
+
'submitting',
|
|
57
|
+
'admitted',
|
|
58
|
+
'broadcast'
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
export function abortIsBlockedBy(row: TokenSettlementRow | undefined): boolean {
|
|
62
|
+
if (!row) return false
|
|
63
|
+
return ABORT_BLOCKED_SETTLEMENT_STATES.includes(row.state)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The shape this wrapper needs of a manager. Structural, so a test can pass a plain object. */
|
|
67
|
+
export interface AbortableManager {
|
|
68
|
+
abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted: boolean }>
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Where the settlement rows live, read LATE.
|
|
73
|
+
*
|
|
74
|
+
* A function rather than a store, because the wrapper is built once around the
|
|
75
|
+
* published permissions manager while the Mandala runtime is constructed after
|
|
76
|
+
* it — and is replaced wholesale on a network switch or a wallet rebuild.
|
|
77
|
+
* Capturing a store here would guard the departed wallet's tables. Returning
|
|
78
|
+
* `undefined` (no runtime, no database, not a Mandala chain) means "no token
|
|
79
|
+
* payment can be at stake", which is the correct answer, not a failure.
|
|
80
|
+
*/
|
|
81
|
+
export type SettlementStoreLookup = () => Pick<SettlementStore, 'getSettlementByReference'> | undefined
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Wrap `abortAction` so an action that built a token transaction the overlay
|
|
85
|
+
* may already have cannot release its inputs.
|
|
86
|
+
*
|
|
87
|
+
* Same pattern and same placement as `wrapCreateActionForTokenInputs`: it wraps
|
|
88
|
+
* the RAW permissions manager and `guardVaultAccess` is applied to the RESULT,
|
|
89
|
+
* so the published object is still the one the guard's own re-wrap dedup
|
|
90
|
+
* recognises. Every other method and property passes through untouched.
|
|
91
|
+
*
|
|
92
|
+
* **Fails OPEN on a lookup fault.** A database that will not answer is not
|
|
93
|
+
* evidence that a payment is in flight, and refusing every abort in the wallet
|
|
94
|
+
* because one read threw would strand inputs across the whole app — including
|
|
95
|
+
* for plain BSV payments this guard has no business touching. The read is
|
|
96
|
+
* cheap, indexed, and asked only of `abortAction`.
|
|
97
|
+
*/
|
|
98
|
+
export function wrapAbortActionForSettlements<T extends AbortableManager>(
|
|
99
|
+
manager: T,
|
|
100
|
+
settlements: SettlementStoreLookup
|
|
101
|
+
): T {
|
|
102
|
+
return new Proxy(manager, {
|
|
103
|
+
get(target, prop, receiver) {
|
|
104
|
+
if (prop === 'abortAction') {
|
|
105
|
+
return async (args: { reference: string }, originator?: string) => {
|
|
106
|
+
const row = await lookupSettlement(settlements, args?.reference)
|
|
107
|
+
if (abortIsBlockedBy(row)) {
|
|
108
|
+
console.warn(
|
|
109
|
+
`[mandala] refusing to abort ${row!.txid}: its settlement is '${row!.state}', ` +
|
|
110
|
+
'so releasing these inputs would double spend a transaction the overlay may already have'
|
|
111
|
+
)
|
|
112
|
+
return { aborted: false }
|
|
113
|
+
}
|
|
114
|
+
return await target.abortAction(args, originator)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const value = Reflect.get(target, prop, receiver)
|
|
118
|
+
return typeof value === 'function' ? value.bind(target) : value
|
|
119
|
+
}
|
|
120
|
+
}) as T
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function lookupSettlement(
|
|
124
|
+
settlements: SettlementStoreLookup,
|
|
125
|
+
reference: string | undefined
|
|
126
|
+
): Promise<TokenSettlementRow | undefined> {
|
|
127
|
+
if (!reference) return undefined
|
|
128
|
+
try {
|
|
129
|
+
return await settlements()?.getSettlementByReference(reference)
|
|
130
|
+
} catch (e) {
|
|
131
|
+
console.warn('[mandala] could not check the settlement of an aborted action; allowing the abort:', e)
|
|
132
|
+
return undefined
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time migration: rename the Mandala token basket from the old,
|
|
3
|
+
* un-gated `'mandala-tokens'` to the P-routed `MANDALA_BASKET`
|
|
4
|
+
* (`'p mandala'`), per offline-settlement-final.md §8.3.
|
|
5
|
+
*
|
|
6
|
+
* The basket name is persisted per-output (`outputs.basketId` ->
|
|
7
|
+
* `output_baskets.name`), so renaming the constant in code does nothing for
|
|
8
|
+
* a device that already holds tokens under the old name — this migration
|
|
9
|
+
* moves those rows. Guarded by a `key_value_store` marker (the app's
|
|
10
|
+
* existing one-time-migration doctrine, see `ensureOfflineActionsColumns`
|
|
11
|
+
* for the DDL-migration precedent this mirrors for a data migration):
|
|
12
|
+
*
|
|
13
|
+
* - idempotent: once the marker is set, the full (every-user) scan is a
|
|
14
|
+
* no-op read.
|
|
15
|
+
* - a no-op when zero rows carry the old basket name (marks done, moves
|
|
16
|
+
* nothing).
|
|
17
|
+
* - running it twice never double-moves: the marker short-circuits the
|
|
18
|
+
* second full scan entirely, and even without the marker a second pass
|
|
19
|
+
* would find zero outputs left under the old basket id (the UPDATE's own
|
|
20
|
+
* WHERE clause naturally re-converges).
|
|
21
|
+
*
|
|
22
|
+
* "No live builds exist" today (design-v3's Compatibility section), so this
|
|
23
|
+
* has zero live rows to move at ship time — it exists so a later device that
|
|
24
|
+
* *does* hold old-named rows is never left behind.
|
|
25
|
+
*
|
|
26
|
+
* Adversarial-review finding (6): the marker alone is not enough. It marks
|
|
27
|
+
* "the full, every-user scan has run on this device", but a BACKUP RESTORE
|
|
28
|
+
* can reintroduce old-named rows for the device's CURRENT user well after
|
|
29
|
+
* that scan already ran and set the marker (e.g. restoring an older
|
|
30
|
+
* snapshot, or a snapshot from before this rename shipped) — the early
|
|
31
|
+
* return on a set marker would then skip that user's rows forever. Callers
|
|
32
|
+
* that know the current user id should therefore also pass it as
|
|
33
|
+
* `currentUserId`: a cheap, single-user WHERE-based move runs EVERY call
|
|
34
|
+
* regardless of the marker, bounded to just that user's old-basket rows (not
|
|
35
|
+
* a full-table scan), so it is safe to call on every boot. Passing no
|
|
36
|
+
* `currentUserId` reproduces the exact pre-finding-6 behavior (full scan,
|
|
37
|
+
* marker-guarded, nothing else) — every existing caller/test is unaffected.
|
|
38
|
+
*/
|
|
39
|
+
import { MANDALA_BASKET } from './types'
|
|
40
|
+
|
|
41
|
+
/** Old, un-gated basket name this migration moves outputs off of. */
|
|
42
|
+
export const OLD_MANDALA_BASKET_NAME = 'mandala-tokens'
|
|
43
|
+
|
|
44
|
+
/** key_value_store marker key — presence with value 'done' means "never run again". */
|
|
45
|
+
const MIGRATION_MARKER_KEY = 'mandala_basket_migration_v1'
|
|
46
|
+
const MIGRATION_DONE_VALUE = 'done'
|
|
47
|
+
|
|
48
|
+
/** The slice of TableOutputBasket this migration reads. */
|
|
49
|
+
export interface MigrationOutputBasket {
|
|
50
|
+
basketId: number
|
|
51
|
+
userId: number
|
|
52
|
+
isDeleted?: boolean
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The slice of TableOutput this migration reads. */
|
|
56
|
+
export interface MigrationOutput {
|
|
57
|
+
outputId: number
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The slice of `StorageExpoSQLite` this migration needs. Structural, so the
|
|
62
|
+
* real provider and a lightweight test double both satisfy it — same pattern
|
|
63
|
+
* as `core/storage/methods/walletBalanceSql.ts`'s `BalanceStorage`.
|
|
64
|
+
*/
|
|
65
|
+
export interface BasketMigrationStorage {
|
|
66
|
+
getKeyValue(key: string): Promise<string | undefined>
|
|
67
|
+
setKeyValue(key: string, value: string): Promise<void>
|
|
68
|
+
findOutputBaskets(args: { partial: { name: string; userId?: number } }): Promise<MigrationOutputBasket[]>
|
|
69
|
+
/** Finds-or-creates (and un-deletes) the destination basket for one user. */
|
|
70
|
+
findOrInsertOutputBasket(userId: number, name: string): Promise<{ basketId: number }>
|
|
71
|
+
findOutputs(args: { partial: { basketId: number } }): Promise<MigrationOutput[]>
|
|
72
|
+
updateOutput(id: number, update: { basketId: number }): Promise<number>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface BasketMigrationResult {
|
|
76
|
+
/** false when the full scan's marker already showed it had run AND the
|
|
77
|
+
* (optional) single-user pass moved nothing — i.e. nothing was touched. */
|
|
78
|
+
ran: boolean
|
|
79
|
+
/** Baskets (i.e. distinct userIds) that had at least one output moved. */
|
|
80
|
+
basketsMigrated: number
|
|
81
|
+
/** Total output rows moved from the old basket to MANDALA_BASKET. */
|
|
82
|
+
movedOutputs: number
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Moves every output out of one old-named basket into (a find-or-inserted)
|
|
87
|
+
* `MANDALA_BASKET` for that basket's owner. Shared by both the full,
|
|
88
|
+
* every-user scan and the cheap, single-user pass below — the only
|
|
89
|
+
* difference between them is which old baskets they are given to move.
|
|
90
|
+
*/
|
|
91
|
+
async function moveBasketOutputs(
|
|
92
|
+
storage: BasketMigrationStorage,
|
|
93
|
+
oldBasket: MigrationOutputBasket
|
|
94
|
+
): Promise<{ movedOutputs: number }> {
|
|
95
|
+
if (oldBasket.isDeleted) return { movedOutputs: 0 }
|
|
96
|
+
|
|
97
|
+
const outputs = await storage.findOutputs({ partial: { basketId: oldBasket.basketId } })
|
|
98
|
+
if (outputs.length === 0) return { movedOutputs: 0 }
|
|
99
|
+
|
|
100
|
+
const newBasket = await storage.findOrInsertOutputBasket(oldBasket.userId, MANDALA_BASKET)
|
|
101
|
+
for (const output of outputs) {
|
|
102
|
+
await storage.updateOutput(output.outputId, { basketId: newBasket.basketId })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return { movedOutputs: outputs.length }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Runs the migration. Safe to call on every boot — see the idempotency notes
|
|
110
|
+
* above.
|
|
111
|
+
*
|
|
112
|
+
* `currentUserId`, when given, additionally runs the cheap single-user pass
|
|
113
|
+
* (finding 6) on EVERY call, independent of the marker — pass the device's
|
|
114
|
+
* currently-authenticated user id here so a restored backup's old-named rows
|
|
115
|
+
* for that user are always caught, not just on the one device/boot where the
|
|
116
|
+
* full scan happened to run. Omit it to get exactly the original,
|
|
117
|
+
* marker-only behavior.
|
|
118
|
+
*/
|
|
119
|
+
export async function migrateMandalaBasketName(
|
|
120
|
+
storage: BasketMigrationStorage,
|
|
121
|
+
currentUserId?: number
|
|
122
|
+
): Promise<BasketMigrationResult> {
|
|
123
|
+
const marker = await storage.getKeyValue(MIGRATION_MARKER_KEY)
|
|
124
|
+
const fullScanAlreadyRan = marker === MIGRATION_DONE_VALUE
|
|
125
|
+
|
|
126
|
+
let basketsMigrated = 0
|
|
127
|
+
let movedOutputs = 0
|
|
128
|
+
|
|
129
|
+
if (!fullScanAlreadyRan) {
|
|
130
|
+
const oldBaskets = await storage.findOutputBaskets({ partial: { name: OLD_MANDALA_BASKET_NAME } })
|
|
131
|
+
for (const oldBasket of oldBaskets) {
|
|
132
|
+
const moved = await moveBasketOutputs(storage, oldBasket)
|
|
133
|
+
if (moved.movedOutputs > 0) {
|
|
134
|
+
basketsMigrated += 1
|
|
135
|
+
movedOutputs += moved.movedOutputs
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Marked done even when zero rows moved: the point of the marker is
|
|
140
|
+
// "never run the FULL scan again on this device", not "ran and found
|
|
141
|
+
// work" — see the no-op contract in the file doc above. The cheap
|
|
142
|
+
// single-user pass below is unaffected by this marker either way.
|
|
143
|
+
await storage.setKeyValue(MIGRATION_MARKER_KEY, MIGRATION_DONE_VALUE)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (typeof currentUserId === 'number') {
|
|
147
|
+
// Cheap, single-user WHERE-based move — bounded to this one user's
|
|
148
|
+
// old-basket rows (never a full-table scan), so it is safe to run every
|
|
149
|
+
// boot regardless of the marker above. If the full scan above already
|
|
150
|
+
// covered this same user in this same call, this finds zero rows left
|
|
151
|
+
// and is a harmless no-op (the same re-convergence property the file
|
|
152
|
+
// doc describes for a marker-less rerun).
|
|
153
|
+
const oldBaskets = await storage.findOutputBaskets({
|
|
154
|
+
partial: { name: OLD_MANDALA_BASKET_NAME, userId: currentUserId }
|
|
155
|
+
})
|
|
156
|
+
for (const oldBasket of oldBaskets) {
|
|
157
|
+
const moved = await moveBasketOutputs(storage, oldBasket)
|
|
158
|
+
if (moved.movedOutputs > 0) {
|
|
159
|
+
basketsMigrated += 1
|
|
160
|
+
movedOutputs += moved.movedOutputs
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return { ran: !fullScanAlreadyRan || movedOutputs > 0, basketsMigrated, movedOutputs }
|
|
166
|
+
}
|