@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
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MandalaTokenModule — the `WalletPermissionsManager` P-module for the
|
|
3
|
+
* `'p mandala'` basket (schemeID `'mandala'`).
|
|
4
|
+
*
|
|
5
|
+
* Mirrors `@bsv/btms-permission-module`'s `BasicTokenModule` shape and file
|
|
6
|
+
* organization exactly (admin pass-through, a 60s session-authorization
|
|
7
|
+
* cache keyed by originator, a JSON-encoded prompt message, a generic
|
|
8
|
+
* fallback that never throws on a decode failure) — but decodes Mandala's
|
|
9
|
+
* own script layout, `<36B assetId><scriptnum amount> OP_2DROP <P2PKH tail>`,
|
|
10
|
+
* via `MandalaToken.decode` from `@bsv/templates`, NOT BTMS's `PushDrop.decode`:
|
|
11
|
+
* the two token formats are unrelated.
|
|
12
|
+
*
|
|
13
|
+
* There is no Mandala equivalent of BTMS's `createSignature`/preimage-binding
|
|
14
|
+
* layer: Mandala's FT protocol (`[2, 'mandala token']`) is not `'p '`-prefixed
|
|
15
|
+
* (renaming it would touch every derivation in the blinding scheme — far too
|
|
16
|
+
* invasive, see offline-settlement-final.md §8.2), so `createSignature` is
|
|
17
|
+
* never routed through this module. Basket-gating alone is the whole gate.
|
|
18
|
+
*
|
|
19
|
+
* Source of truth: offline-settlement-final.md §8.3, plus a set of
|
|
20
|
+
* adversarial-review findings closed here (see the inline notes tagged
|
|
21
|
+
* "adversarial-review finding" throughout this file):
|
|
22
|
+
* 1. [critical] listOutputs no longer lets a paired app read back
|
|
23
|
+
* `customInstructions` (keyID/counterparty/blinding derivation data).
|
|
24
|
+
* 2. [medium/high] createAction that only SPENDS `'p mandala'` INPUTS (no
|
|
25
|
+
* basketed change output) is now gated too — see `anyInputIsTokenCoin`
|
|
26
|
+
* and the `wrapCreateActionForTokenInputs` wrapper below.
|
|
27
|
+
* 3. [medium] listActions is now routed the same as listOutputs.
|
|
28
|
+
* 4. [medium] Prompt amounts are grouped by assetId and decimal-formatted.
|
|
29
|
+
* 5. [low] relinquishOutput is its own authorization class.
|
|
30
|
+
*/
|
|
31
|
+
import { LockingScript, Transaction } from '@bsv/sdk'
|
|
32
|
+
import type { PermissionsModule } from '@bsv/wallet-toolbox-mobile'
|
|
33
|
+
import { MandalaToken } from '@bsv/templates'
|
|
34
|
+
import { MANDALA_BASKET } from './types'
|
|
35
|
+
|
|
36
|
+
const SESSION_TIMEOUT_MS = 60_000
|
|
37
|
+
const SESSION_CLEANUP_INTERVAL_MS = 30_000
|
|
38
|
+
|
|
39
|
+
export interface MandalaAssetMetadata {
|
|
40
|
+
label?: string
|
|
41
|
+
ticker?: string
|
|
42
|
+
/** Base-10 display decimals (e.g. 2 for cents-style tokens). Absent/non-numeric
|
|
43
|
+
* means "unknown" — every amount display falls back to raw base units. */
|
|
44
|
+
decimals?: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface MandalaTokenModuleDeps {
|
|
48
|
+
/** Our own app's originator — calls carrying it pass through with zero prompts. */
|
|
49
|
+
adminOriginator: string
|
|
50
|
+
/** Same shape as BTMS's requestTokenAccess: app id + JSON message -> approved? */
|
|
51
|
+
requestTokenAccess: (app: string, message: string) => Promise<boolean>
|
|
52
|
+
/** Optional friendly name/ticker/decimals for the prompt copy. Never gates anything —
|
|
53
|
+
* a throwing or null-returning resolver just means the raw assetId (in base units) is shown. */
|
|
54
|
+
resolveAssetMetadata: (assetId: string) => Promise<MandalaAssetMetadata | null>
|
|
55
|
+
/**
|
|
56
|
+
* Adversarial-review finding (2): every outpoint (`'txid.vout'`) this
|
|
57
|
+
* wallet currently holds in `MANDALA_BASKET`, via the admin-originator
|
|
58
|
+
* wallet's own `listOutputs({basket: MANDALA_BASKET, ...})` — i.e. a call
|
|
59
|
+
* that itself passes through this module with zero prompts (see the
|
|
60
|
+
* admin pass-through branch in `onRequest`). Used to detect a
|
|
61
|
+
* `createAction` that spends token coins purely through `inputs`, which
|
|
62
|
+
* `WalletPermissionsManager`'s basket-routing (keyed on OUTPUTS only,
|
|
63
|
+
* `collectNonPBaskets`) would otherwise miss entirely. A throwing
|
|
64
|
+
* implementation is treated as "no token inputs found" — this dep can
|
|
65
|
+
* only ever ADD a prompt, never remove one that would otherwise fire from
|
|
66
|
+
* the output-side checks, so a fault here fails toward "no extra info",
|
|
67
|
+
* not toward "silently allow".
|
|
68
|
+
*/
|
|
69
|
+
listTokenOutpoints: () => Promise<Set<string>>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The slice of `CreateActionOutput` this module reads. Structural, not the
|
|
73
|
+
* full SDK type, so a test can pass a plain object. */
|
|
74
|
+
interface MandalaCreateActionOutputLike {
|
|
75
|
+
lockingScript?: string
|
|
76
|
+
basket?: string
|
|
77
|
+
}
|
|
78
|
+
/** The slice of `CreateActionInput` this module reads. */
|
|
79
|
+
interface MandalaCreateActionInputLike {
|
|
80
|
+
outpoint?: string
|
|
81
|
+
}
|
|
82
|
+
interface MandalaCreateActionArgsLike {
|
|
83
|
+
outputs?: MandalaCreateActionOutputLike[]
|
|
84
|
+
inputs?: MandalaCreateActionInputLike[]
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface MandalaInternalizeOutputLike {
|
|
88
|
+
outputIndex: number
|
|
89
|
+
protocol?: string
|
|
90
|
+
insertionRemittance?: { basket?: string }
|
|
91
|
+
}
|
|
92
|
+
interface MandalaInternalizeActionArgsLike {
|
|
93
|
+
/** AtomicBEEF — the SDK type allows either representation; both feed
|
|
94
|
+
* `Transaction.fromAtomicBEEF` directly. */
|
|
95
|
+
tx?: number[] | Uint8Array
|
|
96
|
+
outputs?: MandalaInternalizeOutputLike[]
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The slice of `ListOutputsArgs` this module reads/rewrites. */
|
|
100
|
+
interface MandalaListOutputsArgsLike {
|
|
101
|
+
basket?: string
|
|
102
|
+
includeCustomInstructions?: boolean
|
|
103
|
+
[key: string]: unknown
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface DecodedMandalaOutput {
|
|
107
|
+
assetId: string
|
|
108
|
+
amount: number
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** One asset's send/change totals for a createAction spend prompt. */
|
|
112
|
+
export interface MandalaSpendLine {
|
|
113
|
+
assetId: string
|
|
114
|
+
sendAmount: number
|
|
115
|
+
changeAmount: number
|
|
116
|
+
tokenName?: string
|
|
117
|
+
decimals?: number
|
|
118
|
+
/** Decimal-formatted, e.g. "25.00 USDX"; base units + a short assetId when
|
|
119
|
+
* decimals could not be resolved. */
|
|
120
|
+
display: string
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** One asset's credited total for an internalizeAction credit prompt. */
|
|
124
|
+
export interface MandalaCreditLine {
|
|
125
|
+
assetId: string
|
|
126
|
+
creditAmount: number
|
|
127
|
+
tokenName?: string
|
|
128
|
+
decimals?: number
|
|
129
|
+
display: string
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Decodes one output's locking script as a Mandala token. Never throws:
|
|
134
|
+
* `MandalaToken.decode` throws on anything that isn't its exact 8-chunk
|
|
135
|
+
* shape, and every caller here treats "not a Mandala output" the same way
|
|
136
|
+
* whether the script is empty, foreign, or simply malformed.
|
|
137
|
+
*/
|
|
138
|
+
function tryDecodeMandalaOutput(lockingScriptHex: string | undefined): DecodedMandalaOutput | null {
|
|
139
|
+
if (!lockingScriptHex) return null
|
|
140
|
+
try {
|
|
141
|
+
const script = LockingScript.fromHex(lockingScriptHex)
|
|
142
|
+
const decoded = MandalaToken.decode(script)
|
|
143
|
+
return { assetId: decoded.assetId, amount: decoded.amount }
|
|
144
|
+
} catch {
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A short, human-scannable form of a long `'<64-hex>.<vout>'` assetId. */
|
|
150
|
+
function shortAssetId(assetId: string): string {
|
|
151
|
+
if (!assetId || assetId.length <= 16) return assetId
|
|
152
|
+
return `${assetId.slice(0, 8)}…${assetId.slice(-6)}`
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* "25.00 USDX" when decimals are known (clamped to a sane 0-18 range,
|
|
157
|
+
* mirroring common token-decimals conventions); "2500000 a1b2c3d4…ef01.0"
|
|
158
|
+
* (raw base units + a short assetId form) when they are not — adversarial-
|
|
159
|
+
* review finding (4): never show raw base units next to a resolved ticker,
|
|
160
|
+
* and never guess a decimals value we were not actually given.
|
|
161
|
+
*/
|
|
162
|
+
function formatTokenAmount(
|
|
163
|
+
baseUnits: number,
|
|
164
|
+
decimals: number | undefined,
|
|
165
|
+
tokenName: string | undefined,
|
|
166
|
+
assetId: string
|
|
167
|
+
): string {
|
|
168
|
+
if (typeof decimals === 'number' && Number.isInteger(decimals) && decimals >= 0 && decimals <= 18) {
|
|
169
|
+
const scaled = baseUnits / 10 ** decimals
|
|
170
|
+
const unit = tokenName || shortAssetId(assetId)
|
|
171
|
+
return `${scaled.toFixed(decimals)} ${unit}`
|
|
172
|
+
}
|
|
173
|
+
return `${baseUnits} ${shortAssetId(assetId)}`
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Adversarial-review finding (2): the P-label `WalletPermissionsManager`'s
|
|
178
|
+
* `listActions`/`createAction` label-routing keys on. Two independent uses:
|
|
179
|
+
* - `wrapCreateActionForTokenInputs` (below) injects it onto a createAction
|
|
180
|
+
* call whose INPUTS spend `'p mandala'` coins but whose outputs carry no
|
|
181
|
+
* `'p mandala'`-basket output — the manager's own basket-only routing
|
|
182
|
+
* would otherwise never call `onRequest` for such a call at all.
|
|
183
|
+
* - It also then persists as a real label on the resulting action, so it
|
|
184
|
+
* doubles as the "Mandala action" label finding (3) calls for: apps that
|
|
185
|
+
* build Mandala createAction calls directly (rather than through the
|
|
186
|
+
* wrapper) should add this same label so `listActions({labels:[...]})`
|
|
187
|
+
* P-routes to this module too — label-routing is `listActions`' ONLY
|
|
188
|
+
* signal, `MANDALA_BASKET` alone does not make a listActions call route
|
|
189
|
+
* here. This module cannot enforce that from inside `onRequest` (it never
|
|
190
|
+
* sees the call before the manager decides whether to route it at all);
|
|
191
|
+
* it is a wiring requirement on every Mandala action-creation call site.
|
|
192
|
+
*/
|
|
193
|
+
export const MANDALA_ACTION_LABEL = 'p mandala token-spend'
|
|
194
|
+
|
|
195
|
+
export class MandalaTokenModule implements PermissionsModule {
|
|
196
|
+
private readonly deps: MandalaTokenModuleDeps
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Session-authorization cache — same shape as BasicTokenModule's: a
|
|
200
|
+
* time-limited (60s) grant per originator, refreshed by every prompt this
|
|
201
|
+
* module shows (spend/credit/access alike), consulted only by the
|
|
202
|
+
* once-per-session access checks (`listOutputs`/`listActions`).
|
|
203
|
+
* `relinquishOutput` deliberately does NOT read or write this cache —
|
|
204
|
+
* adversarial-review finding (5): it is its own authorization class.
|
|
205
|
+
*/
|
|
206
|
+
private readonly sessionAuthorizations: Map<string, number> = new Map()
|
|
207
|
+
private readonly cleanupTimer: ReturnType<typeof setInterval>
|
|
208
|
+
|
|
209
|
+
constructor(deps: MandalaTokenModuleDeps) {
|
|
210
|
+
if (!deps || typeof deps.requestTokenAccess !== 'function') {
|
|
211
|
+
throw new Error('requestTokenAccess callback is required')
|
|
212
|
+
}
|
|
213
|
+
if (!deps.adminOriginator || typeof deps.adminOriginator !== 'string') {
|
|
214
|
+
throw new Error('adminOriginator is required')
|
|
215
|
+
}
|
|
216
|
+
this.deps = deps
|
|
217
|
+
this.cleanupTimer = setInterval(() => this.cleanupExpiredSessions(), SESSION_CLEANUP_INTERVAL_MS)
|
|
218
|
+
// Never keep a test runner or RN's timer host alive just for this sweep.
|
|
219
|
+
;(this.cleanupTimer as unknown as { unref?: () => void }).unref?.()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private cleanupExpiredSessions(): void {
|
|
223
|
+
const now = Date.now()
|
|
224
|
+
for (const [originator, timestamp] of this.sessionAuthorizations.entries()) {
|
|
225
|
+
if (now - timestamp > SESSION_TIMEOUT_MS) {
|
|
226
|
+
this.sessionAuthorizations.delete(originator)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private hasSessionAuthorization(originator: string): boolean {
|
|
232
|
+
const timestamp = this.sessionAuthorizations.get(originator)
|
|
233
|
+
if (!timestamp) return false
|
|
234
|
+
if (Date.now() - timestamp > SESSION_TIMEOUT_MS) {
|
|
235
|
+
this.sessionAuthorizations.delete(originator)
|
|
236
|
+
return false
|
|
237
|
+
}
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private grantSessionAuthorization(originator: string): void {
|
|
242
|
+
this.sessionAuthorizations.set(originator, Date.now())
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* THE ONLY MANDALA-SPECIFIC LINE (per spec §8.3): our own app's lib calls
|
|
247
|
+
* always carry `adminOriginator` (the wallet's `withAdminOriginator`
|
|
248
|
+
* wrapper) — auto-approve them with no prompt, preserving "no review
|
|
249
|
+
* screen, the CTA is the confirmation". Everyone else is a paired external
|
|
250
|
+
* caller and is prompted, exactly like BTMS.
|
|
251
|
+
*/
|
|
252
|
+
async onRequest(req: { method: string; args: object; originator: string }): Promise<{ args: object }> {
|
|
253
|
+
const { method, args, originator } = req
|
|
254
|
+
|
|
255
|
+
if (!method || typeof method !== 'string') throw new Error('Invalid method')
|
|
256
|
+
if (!originator || typeof originator !== 'string') throw new Error('Invalid originator')
|
|
257
|
+
if (!args || typeof args !== 'object') throw new Error('Invalid args')
|
|
258
|
+
|
|
259
|
+
if (originator === this.deps.adminOriginator) {
|
|
260
|
+
return { args }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
switch (method) {
|
|
264
|
+
case 'listOutputs': {
|
|
265
|
+
await this.promptOnceForAccess(originator, 'listOutputs')
|
|
266
|
+
// Adversarial-review finding (1): WalletPermissionsManager forwards
|
|
267
|
+
// the ARGS THIS METHOD RETURNS to the underlying listOutputs call
|
|
268
|
+
// (delegateToPModuleIfNeeded), so redacting here genuinely prevents
|
|
269
|
+
// the underlying wallet from ever including customInstructions in
|
|
270
|
+
// its response — this is not merely filtering our own mirror of it
|
|
271
|
+
// afterward, which would be too late for a caller that reads the
|
|
272
|
+
// result directly.
|
|
273
|
+
return { args: this.redactListOutputsArgs(args as MandalaListOutputsArgsLike) }
|
|
274
|
+
}
|
|
275
|
+
case 'listActions':
|
|
276
|
+
// Adversarial-review finding (3): same once-per-session gate as
|
|
277
|
+
// listOutputs. Reaching this handler at all depends on the calling
|
|
278
|
+
// action carrying a 'p mandala ...' label — see MANDALA_ACTION_LABEL's
|
|
279
|
+
// doc above.
|
|
280
|
+
await this.promptOnceForAccess(originator, 'listActions')
|
|
281
|
+
break
|
|
282
|
+
case 'relinquishOutput':
|
|
283
|
+
await this.promptForRelinquish(originator)
|
|
284
|
+
break
|
|
285
|
+
case 'createAction':
|
|
286
|
+
await this.promptForSpend(args as MandalaCreateActionArgsLike, originator)
|
|
287
|
+
break
|
|
288
|
+
case 'internalizeAction':
|
|
289
|
+
await this.promptForCredit(args as MandalaInternalizeActionArgsLike, originator)
|
|
290
|
+
break
|
|
291
|
+
default:
|
|
292
|
+
// No other method is ever routed here (basket-gating only covers
|
|
293
|
+
// these five) — pass through defensively rather than throw on a
|
|
294
|
+
// future manager version that adds one.
|
|
295
|
+
break
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return { args }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Mandala tokens carry no post-hoc metadata to redact and there is no
|
|
303
|
+
* preimage-binding layer here (createSignature is not P-routed for this
|
|
304
|
+
* protocol, see the class doc) — the response passes through unchanged.
|
|
305
|
+
*/
|
|
306
|
+
async onResponse(res: unknown, _context: { method: string; originator: string }): Promise<unknown> {
|
|
307
|
+
return res
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** listOutputs / listActions — once per 60s session, like BTMS's promptForBTMSAccess. */
|
|
311
|
+
private async promptOnceForAccess(originator: string, action: 'listOutputs' | 'listActions'): Promise<void> {
|
|
312
|
+
if (this.hasSessionAuthorization(originator)) return
|
|
313
|
+
|
|
314
|
+
const message = JSON.stringify({ type: 'mandala_access', action })
|
|
315
|
+
const approved = await this.deps.requestTokenAccess(originator, message)
|
|
316
|
+
if (!approved) {
|
|
317
|
+
throw new Error('User denied permission to access Mandala tokens')
|
|
318
|
+
}
|
|
319
|
+
this.grantSessionAuthorization(originator)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Adversarial-review finding (5): relinquishOutput is its own
|
|
324
|
+
* authorization class. It is never satisfied by an existing
|
|
325
|
+
* spend/credit/access session (no `hasSessionAuthorization` check), and it
|
|
326
|
+
* never grants one either (no `grantSessionAuthorization` call) — removing
|
|
327
|
+
* a holding from the wallet is consequential enough that every call must
|
|
328
|
+
* show its own prompt, and approving it must not silently unlock
|
|
329
|
+
* listOutputs/listActions for the rest of the session window.
|
|
330
|
+
*/
|
|
331
|
+
private async promptForRelinquish(originator: string): Promise<void> {
|
|
332
|
+
const message = JSON.stringify({ type: 'mandala_access', action: 'relinquishOutput' })
|
|
333
|
+
const approved = await this.deps.requestTokenAccess(originator, message)
|
|
334
|
+
if (!approved) {
|
|
335
|
+
throw new Error('User denied permission to access Mandala tokens')
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Forces `includeCustomInstructions` off regardless of what the caller
|
|
341
|
+
* asked for. `customInstructions` is where a Mandala coin's `keyID`/
|
|
342
|
+
* `counterparty`/blinding derivation lives (see the module doc) — a paired
|
|
343
|
+
* app has no legitimate use for it, and no other `ListOutputsArgs` field
|
|
344
|
+
* exposes anything equivalent.
|
|
345
|
+
*/
|
|
346
|
+
private redactListOutputsArgs(args: MandalaListOutputsArgsLike): MandalaListOutputsArgsLike {
|
|
347
|
+
return { ...args, includeCustomInstructions: false }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* createAction with an output in `'p mandala'` — always prompts (mirrors
|
|
352
|
+
* BTMS's `handleCreateAction`, which never skips on an existing session;
|
|
353
|
+
* only the access checks above do that), then refreshes the session so a
|
|
354
|
+
* following listOutputs/listActions within the window does not re-prompt.
|
|
355
|
+
*
|
|
356
|
+
* Adversarial-review finding (2): also gates on INPUTS. Basket-routing
|
|
357
|
+
* only ever reaches this method via a `'p mandala'`-basketed/decodable
|
|
358
|
+
* OUTPUT (see `extractOutputAmountsByAsset`) or the `MANDALA_ACTION_LABEL`
|
|
359
|
+
* the `wrapCreateActionForTokenInputs` wrapper injects — a spend with no
|
|
360
|
+
* such output (e.g. a full-balance spend with no change) could otherwise
|
|
361
|
+
* decode to zero here even once routed. `anyInputIsTokenCoin` is a second,
|
|
362
|
+
* independent signal so this method still emits a `'mandala_spend'`
|
|
363
|
+
* prompt (never the fully-generic fallback) whenever any input is a known
|
|
364
|
+
* token coin, even if no output tells us how much.
|
|
365
|
+
*/
|
|
366
|
+
private async promptForSpend(args: MandalaCreateActionArgsLike, originator: string): Promise<void> {
|
|
367
|
+
const totals = this.extractOutputAmountsByAsset(args?.outputs)
|
|
368
|
+
|
|
369
|
+
if (totals.size === 0 && !(await this.anyInputIsTokenCoin(args?.inputs))) {
|
|
370
|
+
// Nothing decodable (every output failed to decode, or none present)
|
|
371
|
+
// and no input is a known token coin either — fall back to a generic
|
|
372
|
+
// prompt rather than guessing. Mirrors BasicTokenModule's
|
|
373
|
+
// promptForGenericAuthorization fallback.
|
|
374
|
+
await this.promptGeneric(originator, 'spend')
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const lines = await this.buildSpendLines(totals)
|
|
379
|
+
// Back-compat top-level fields mirror the FIRST/primary asset (today's
|
|
380
|
+
// single-asset behavior, unchanged); `lines` carries the full,
|
|
381
|
+
// decimal-formatted, one-entry-per-asset breakdown (finding 4).
|
|
382
|
+
// `JSON.stringify` drops `undefined` values, so an empty `lines` array
|
|
383
|
+
// (token-input-only, nothing decodable) naturally omits them.
|
|
384
|
+
const primary = lines[0]
|
|
385
|
+
const message = JSON.stringify({
|
|
386
|
+
type: 'mandala_spend',
|
|
387
|
+
sendAmount: primary?.sendAmount,
|
|
388
|
+
changeAmount: primary?.changeAmount,
|
|
389
|
+
assetId: primary?.assetId,
|
|
390
|
+
tokenName: primary?.tokenName,
|
|
391
|
+
lines
|
|
392
|
+
})
|
|
393
|
+
const approved = await this.deps.requestTokenAccess(originator, message)
|
|
394
|
+
if (!approved) {
|
|
395
|
+
// Exact BTMS wording (spec §8.6): denial "throws the same shape as
|
|
396
|
+
// BTMS ('User denied permission to spend tokens')".
|
|
397
|
+
throw new Error('User denied permission to spend tokens')
|
|
398
|
+
}
|
|
399
|
+
this.grantSessionAuthorization(originator)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** internalizeAction inserting into `'p mandala'` — an app crediting ITSELF. */
|
|
403
|
+
private async promptForCredit(args: MandalaInternalizeActionArgsLike, originator: string): Promise<void> {
|
|
404
|
+
const insertions = (args?.outputs ?? []).filter(
|
|
405
|
+
o => o?.protocol === 'basket insertion' && o?.insertionRemittance?.basket === MANDALA_BASKET
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
const totals = new Map<string, number>()
|
|
409
|
+
if (insertions.length > 0 && args?.tx) {
|
|
410
|
+
try {
|
|
411
|
+
const tx = Transaction.fromAtomicBEEF(args.tx)
|
|
412
|
+
for (const insertion of insertions) {
|
|
413
|
+
const output = tx.outputs[insertion.outputIndex]
|
|
414
|
+
const decoded = output?.lockingScript ? tryDecodeMandalaOutput(output.lockingScript.toHex()) : null
|
|
415
|
+
if (decoded) {
|
|
416
|
+
totals.set(decoded.assetId, (totals.get(decoded.assetId) ?? 0) + decoded.amount)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
} catch {
|
|
420
|
+
// Unparseable AtomicBEEF -- fall through to the zero-amount branch
|
|
421
|
+
// below rather than throw; a decode failure is never fatal here.
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (totals.size === 0) {
|
|
426
|
+
await this.promptGeneric(originator, 'credit')
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const lines = await this.buildCreditLines(totals)
|
|
431
|
+
const primary = lines[0]
|
|
432
|
+
const message = JSON.stringify({
|
|
433
|
+
type: 'mandala_credit',
|
|
434
|
+
creditAmount: primary?.creditAmount,
|
|
435
|
+
assetId: primary?.assetId,
|
|
436
|
+
tokenName: primary?.tokenName,
|
|
437
|
+
lines
|
|
438
|
+
})
|
|
439
|
+
const approved = await this.deps.requestTokenAccess(originator, message)
|
|
440
|
+
if (!approved) {
|
|
441
|
+
throw new Error('User denied permission to credit Mandala tokens')
|
|
442
|
+
}
|
|
443
|
+
this.grantSessionAuthorization(originator)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
private async promptGeneric(originator: string, context: 'spend' | 'credit'): Promise<void> {
|
|
447
|
+
const message = JSON.stringify({ type: 'mandala_generic', context })
|
|
448
|
+
const approved = await this.deps.requestTokenAccess(originator, message)
|
|
449
|
+
if (!approved) {
|
|
450
|
+
throw new Error('User denied permission to spend Mandala tokens')
|
|
451
|
+
}
|
|
452
|
+
this.grantSessionAuthorization(originator)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Sums send vs. change over every Mandala-decodable output, GROUPED BY
|
|
457
|
+
* assetId (adversarial-review finding 4 — a createAction touching more
|
|
458
|
+
* than one asset previously collapsed every asset's amounts into one
|
|
459
|
+
* running total under whichever assetId was seen first). An output that
|
|
460
|
+
* carries the `'p mandala'` basket is change (stays with us); one that
|
|
461
|
+
* does not is the recipient's (Mandala payer outputs are never basketed).
|
|
462
|
+
* A script that fails to decode is silently skipped, not fatal —
|
|
463
|
+
* `tryDecodeMandalaOutput` never throws.
|
|
464
|
+
*/
|
|
465
|
+
private extractOutputAmountsByAsset(
|
|
466
|
+
outputs: MandalaCreateActionOutputLike[] | undefined
|
|
467
|
+
): Map<string, { sendAmount: number; changeAmount: number }> {
|
|
468
|
+
const totals = new Map<string, { sendAmount: number; changeAmount: number }>()
|
|
469
|
+
|
|
470
|
+
for (const output of outputs ?? []) {
|
|
471
|
+
const decoded = tryDecodeMandalaOutput(output?.lockingScript)
|
|
472
|
+
if (!decoded) continue
|
|
473
|
+
const entry = totals.get(decoded.assetId) ?? { sendAmount: 0, changeAmount: 0 }
|
|
474
|
+
if (output.basket === MANDALA_BASKET) {
|
|
475
|
+
entry.changeAmount += decoded.amount
|
|
476
|
+
} else {
|
|
477
|
+
entry.sendAmount += decoded.amount
|
|
478
|
+
}
|
|
479
|
+
totals.set(decoded.assetId, entry)
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return totals
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Adversarial-review finding (2): resolves each input outpoint against
|
|
487
|
+
* `deps.listTokenOutpoints()` (the admin-originator wallet's own
|
|
488
|
+
* `'p mandala'`-basket listing) and reports whether any of them is a
|
|
489
|
+
* token coin this wallet holds. A throwing/failing `listTokenOutpoints`
|
|
490
|
+
* is treated as "no token inputs found" — this is a pure ADD-a-prompt
|
|
491
|
+
* signal on top of the output-side checks, so failing open here never
|
|
492
|
+
* removes a prompt the output side would otherwise have shown.
|
|
493
|
+
*/
|
|
494
|
+
private async anyInputIsTokenCoin(inputs: MandalaCreateActionInputLike[] | undefined): Promise<boolean> {
|
|
495
|
+
if (!inputs || inputs.length === 0) return false
|
|
496
|
+
let tokenOutpoints: Set<string>
|
|
497
|
+
try {
|
|
498
|
+
tokenOutpoints = await this.deps.listTokenOutpoints()
|
|
499
|
+
} catch {
|
|
500
|
+
return false
|
|
501
|
+
}
|
|
502
|
+
return inputs.some(input => !!input?.outpoint && tokenOutpoints.has(input.outpoint))
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private async buildSpendLines(
|
|
506
|
+
totals: Map<string, { sendAmount: number; changeAmount: number }>
|
|
507
|
+
): Promise<MandalaSpendLine[]> {
|
|
508
|
+
const lines: MandalaSpendLine[] = []
|
|
509
|
+
for (const [assetId, { sendAmount, changeAmount }] of totals) {
|
|
510
|
+
const { tokenName, decimals } = await this.resolveAssetDisplay(assetId)
|
|
511
|
+
lines.push({
|
|
512
|
+
assetId,
|
|
513
|
+
sendAmount,
|
|
514
|
+
changeAmount,
|
|
515
|
+
tokenName,
|
|
516
|
+
decimals,
|
|
517
|
+
display: formatTokenAmount(sendAmount, decimals, tokenName, assetId)
|
|
518
|
+
})
|
|
519
|
+
}
|
|
520
|
+
return lines
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private async buildCreditLines(totals: Map<string, number>): Promise<MandalaCreditLine[]> {
|
|
524
|
+
const lines: MandalaCreditLine[] = []
|
|
525
|
+
for (const [assetId, creditAmount] of totals) {
|
|
526
|
+
const { tokenName, decimals } = await this.resolveAssetDisplay(assetId)
|
|
527
|
+
lines.push({
|
|
528
|
+
assetId,
|
|
529
|
+
creditAmount,
|
|
530
|
+
tokenName,
|
|
531
|
+
decimals,
|
|
532
|
+
display: formatTokenAmount(creditAmount, decimals, tokenName, assetId)
|
|
533
|
+
})
|
|
534
|
+
}
|
|
535
|
+
return lines
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private async resolveAssetDisplay(assetId: string | undefined): Promise<{ tokenName?: string; decimals?: number }> {
|
|
539
|
+
if (!assetId) return {}
|
|
540
|
+
try {
|
|
541
|
+
const meta = await this.deps.resolveAssetMetadata(assetId)
|
|
542
|
+
return {
|
|
543
|
+
tokenName: meta?.ticker || meta?.label || undefined,
|
|
544
|
+
decimals: typeof meta?.decimals === 'number' ? meta.decimals : undefined
|
|
545
|
+
}
|
|
546
|
+
} catch {
|
|
547
|
+
// resolveAssetMetadata is caller-injected and may be a stub or may
|
|
548
|
+
// fail (network, missing registry entry) — never let that block or
|
|
549
|
+
// fail a permission prompt; the assetId alone is still shown.
|
|
550
|
+
return {}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Adversarial-review finding (2), second half: `WalletPermissionsManager`
|
|
557
|
+
* only ever routes a `createAction` call through a P-module when the call's
|
|
558
|
+
* OUTPUTS or LABELS name a `'p '`-scheme (`collectNonPBaskets`/
|
|
559
|
+
* `splitLabelsByPermissionModule`, confirmed against
|
|
560
|
+
* `@bsv/wallet-toolbox-mobile`'s `WalletPermissionsManager.js`) — INPUTS are
|
|
561
|
+
* never scanned. A createAction that spends `'p mandala'` inputs with no
|
|
562
|
+
* basketed/decodable Mandala output (e.g. a full-balance spend with no
|
|
563
|
+
* change) therefore never reaches `MandalaTokenModule.onRequest` at all, no
|
|
564
|
+
* matter what that method does internally.
|
|
565
|
+
*
|
|
566
|
+
* This wraps the PUBLISHED `WalletPermissionsManager` (or anything
|
|
567
|
+
* shaped like it) so that a `createAction` call whose inputs reference a
|
|
568
|
+
* known `'p mandala'` outpoint gets `MANDALA_ACTION_LABEL` injected into its
|
|
569
|
+
* `labels` BEFORE the manager's own routing decision runs — which makes the
|
|
570
|
+
* manager's label-routing pick up the module exactly as if the caller had
|
|
571
|
+
* labeled the action itself (see `MANDALA_ACTION_LABEL`'s doc). Every other
|
|
572
|
+
* method/property passes through untouched. `adminOriginator` calls are
|
|
573
|
+
* short-circuited with zero work: the module already grants those a
|
|
574
|
+
* zero-prompt pass-through unconditionally (see the class doc), so injecting
|
|
575
|
+
* the label there would only add a `listTokenOutpoints()` round-trip to
|
|
576
|
+
* EVERY admin createAction call — including the app's own everyday,
|
|
577
|
+
* non-Mandala spends — for no gating benefit at all.
|
|
578
|
+
*
|
|
579
|
+
* WIRING: wrap the RAW `permissionsManager` with this FIRST, THEN apply
|
|
580
|
+
* `guardVaultAccess` around the result — never the other way around.
|
|
581
|
+
* `guardVaultAccess` has its own idempotent-re-wrap dedup
|
|
582
|
+
* (`GUARD_TARGETS`/`GUARDED_PROXIES` in `services/vault/guard.ts`), which
|
|
583
|
+
* several screens rely on (`guardVaultAccess(managers.permissionsManager,
|
|
584
|
+
* ADMIN_ORIGINATOR)` again in e.g. `PairScreen.tsx`/`ConnectionsScreen.tsx`)
|
|
585
|
+
* to avoid creating a second, unsynchronized guard runtime around the same
|
|
586
|
+
* wallet. That dedup only recognizes an object IT previously wrapped —
|
|
587
|
+
* putting this wrapper's Proxy on the OUTSIDE (wrapping an already-guarded
|
|
588
|
+
* manager) would make every such re-application invisible to the dedup and
|
|
589
|
+
* silently double-guard the wallet, splitting its single-flight queue in
|
|
590
|
+
* two. Wrapping the raw manager first, then guarding the result, keeps the
|
|
591
|
+
* publicly published value exactly what `guardVaultAccess` itself produced
|
|
592
|
+
* and expects to see again — in this app that is `WalletContext.tsx`'s
|
|
593
|
+
* `newManagers.permissionsManager = guardVaultAccess(
|
|
594
|
+
* wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints,
|
|
595
|
+
* adminOriginator), adminOriginator)`. A manager constructed anywhere else
|
|
596
|
+
* (a test double, a future second entry point) that skips this wrapper
|
|
597
|
+
* reopens exactly the gap described above.
|
|
598
|
+
*/
|
|
599
|
+
export function wrapCreateActionForTokenInputs<T extends { createAction: (args: any, originator: string) => Promise<unknown> }>(
|
|
600
|
+
manager: T,
|
|
601
|
+
listTokenOutpoints: () => Promise<Set<string>>,
|
|
602
|
+
adminOriginator?: string
|
|
603
|
+
): T {
|
|
604
|
+
return new Proxy(manager, {
|
|
605
|
+
get(target, prop, receiver) {
|
|
606
|
+
if (prop === 'createAction') {
|
|
607
|
+
return async (args: MandalaCreateActionArgsLike & { labels?: string[] }, originator: string) => {
|
|
608
|
+
const routedArgs =
|
|
609
|
+
originator === adminOriginator ? args : await injectMandalaLabelIfTokenInputsPresent(args, listTokenOutpoints)
|
|
610
|
+
return target.createAction(routedArgs, originator)
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const value = Reflect.get(target, prop, receiver)
|
|
614
|
+
return typeof value === 'function' ? value.bind(target) : value
|
|
615
|
+
}
|
|
616
|
+
}) as T
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async function injectMandalaLabelIfTokenInputsPresent(
|
|
620
|
+
args: MandalaCreateActionArgsLike & { labels?: string[] },
|
|
621
|
+
listTokenOutpoints: () => Promise<Set<string>>
|
|
622
|
+
): Promise<MandalaCreateActionArgsLike & { labels?: string[] }> {
|
|
623
|
+
const inputs = args?.inputs
|
|
624
|
+
if (!Array.isArray(inputs) || inputs.length === 0) return args
|
|
625
|
+
|
|
626
|
+
let tokenOutpoints: Set<string>
|
|
627
|
+
try {
|
|
628
|
+
tokenOutpoints = await listTokenOutpoints()
|
|
629
|
+
} catch {
|
|
630
|
+
// Never block a createAction call on a listing fault — the module's own
|
|
631
|
+
// input check (if routing happens to fire some other way) and the
|
|
632
|
+
// output-side gate remain the backstop.
|
|
633
|
+
return args
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const spendsTokenInput = inputs.some(input => !!input?.outpoint && tokenOutpoints.has(input.outpoint))
|
|
637
|
+
if (!spendsTokenInput) return args
|
|
638
|
+
|
|
639
|
+
const labels = Array.isArray(args.labels) ? args.labels : []
|
|
640
|
+
if (labels.includes(MANDALA_ACTION_LABEL)) return args
|
|
641
|
+
return { ...args, labels: [...labels, MANDALA_ACTION_LABEL] }
|
|
642
|
+
}
|