@bsv/expo-wallet-toolbox 0.11.4 → 0.11.6
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 +59 -0
- package/core/context/WalletContext.tsx +3 -0
- package/core/services/conformWalletResults.ts +4 -0
- package/core/services/vault/guard.ts +90 -16
- package/core/storage/StorageExpoSQLite.ts +55 -18
- package/core/storage/methods/vaultGuardSql.ts +83 -20
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,64 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.6
|
|
4
|
+
|
|
5
|
+
### External wallet guard: a site's own actions
|
|
6
|
+
|
|
7
|
+
`WalletPermissionsManager` labels every action it creates
|
|
8
|
+
`admin originator <origin>` and `admin month YYYY-MM`, to total each site's
|
|
9
|
+
spending against its monthly allowance. The guard's point lookups (0.11.0)
|
|
10
|
+
counted any `admin*` label as Vault/admin state, so every unbasketed output of
|
|
11
|
+
a site's own action, and the action itself, was admin state to that same site:
|
|
12
|
+
|
|
13
|
+
- `internalizeAction` of a payment the site had just funded from this wallet was
|
|
14
|
+
refused ('Wallet operation "internalizeAction" is not permitted for origin
|
|
15
|
+
"…"'; fast.brc.dev conformance card 21).
|
|
16
|
+
- `sendWith` of the site's own no-send actions was refused, which broke the
|
|
17
|
+
no-send batch pattern.
|
|
18
|
+
- Spending an unbasketed output of the site's own earlier action as a
|
|
19
|
+
`createAction` input was refused, by the guard and by the storage backstop.
|
|
20
|
+
|
|
21
|
+
Month labels and the caller's own originator label no longer count. Everything
|
|
22
|
+
else still does: a `vault` tag or label, an admin-prefixed basket (created or
|
|
23
|
+
spent), any other admin label, and another originator's label, the admin's
|
|
24
|
+
included. A caller whose label storage would keep as the admin's (`ADMIN.COM`
|
|
25
|
+
when the admin is `admin.com`) gets no exemption. The storage backstop takes the
|
|
26
|
+
caller from the action's own `admin originator` label, only when there is
|
|
27
|
+
exactly one, and needs the host to call `setVaultAdminOriginator` (the wallet
|
|
28
|
+
builder does); until then it counts every originator label.
|
|
29
|
+
|
|
30
|
+
### Discovery shim with a toolbox that pages
|
|
31
|
+
|
|
32
|
+
`conformWalletResults` no longer re-slices a discovery result that is already
|
|
33
|
+
a page (fewer certificates than `totalCertificates`), which dropped results at
|
|
34
|
+
any offset past 0 once `@bsv/wallet-toolbox-mobile` 2.14.4 pages discovery
|
|
35
|
+
itself.
|
|
36
|
+
|
|
37
|
+
## 0.11.5
|
|
38
|
+
|
|
39
|
+
### External wallet guard: BRC-29 and FT payments to another party
|
|
40
|
+
|
|
41
|
+
The guard refused every external call under the wallet's own payment-rail
|
|
42
|
+
namespaces (`[2,'3241645161d8']` for BRC-29/PeerPay and `[2,'mandala token']`
|
|
43
|
+
for the FT rail), including `getPublicKey`. That blocked the first step of
|
|
44
|
+
every BRC-29 payment a dApp makes (fast.brc.dev "Pay to Identity",
|
|
45
|
+
`@bsv/sdk` `BasicBRC29` / PeerPay settlements) with 'Wallet operation
|
|
46
|
+
"getPublicKey" is not permitted for origin "…"'.
|
|
47
|
+
|
|
48
|
+
- `getPublicKey` under those namespaces is now allowed when `counterparty` is
|
|
49
|
+
another party's identity key, with `forSelf` either way: the payer and payee
|
|
50
|
+
steps of a BRC-29 or FT payment. ECDH is symmetric, so that party can compute
|
|
51
|
+
the same public key itself.
|
|
52
|
+
- Still refused: `counterparty` `'anyone'` (the address rail, whose keyIDs are
|
|
53
|
+
guessable dates) or the wallet's own identity key (FT change), in any valid
|
|
54
|
+
encoding; `privileged` calls; any call if the wallet's identity key cannot be
|
|
55
|
+
read; and `createSignature`, `encrypt`, `decrypt`, `createHmac`,
|
|
56
|
+
`verifyHmac`, `verifySignature` and the key-linkage methods under these
|
|
57
|
+
namespaces, which are what could spend or expose the wallet's own funds.
|
|
58
|
+
- External `getPublicKey` arguments are now checked and used as one plain
|
|
59
|
+
copy, so a caller's object cannot present different values to the check and
|
|
60
|
+
to the derivation.
|
|
61
|
+
|
|
3
62
|
## 0.11.4
|
|
4
63
|
|
|
5
64
|
### dApp results the SDK rejected: noSend actions and identity discovery
|
|
@@ -1420,6 +1420,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1420
1420
|
databaseName: selectedDb
|
|
1421
1421
|
})
|
|
1422
1422
|
phoneStorage.setServices(services)
|
|
1423
|
+
// Lets the createAction input backstop tell a site's own earlier
|
|
1424
|
+
// actions from the admin's (see validateResolvedActionInput).
|
|
1425
|
+
phoneStorage.setVaultAdminOriginator(adminOriginator)
|
|
1423
1426
|
await phoneStorage.migrate('bsv-wallet', identityKey)
|
|
1424
1427
|
|
|
1425
1428
|
console.log('[WalletContext] Local SQLite storage initialized successfully')
|
|
@@ -45,6 +45,10 @@ function noSendChangeOnTxid<R>(result: R): R {
|
|
|
45
45
|
function discoveryPage<R>(result: R, args: { limit?: number; offset?: number } | undefined): R {
|
|
46
46
|
const r = result as DiscoveryResultLike | undefined
|
|
47
47
|
if (!r || !Array.isArray(r.certificates)) return result
|
|
48
|
+
// A toolbox that pages itself (2.14.4+) returns fewer certificates than it
|
|
49
|
+
// counts whenever paging changed anything; slicing that page again would
|
|
50
|
+
// drop results at any offset past 0.
|
|
51
|
+
if (r.certificates.length !== r.totalCertificates) return result
|
|
48
52
|
const offset = args?.offset ?? 0
|
|
49
53
|
const limit = args?.limit ?? DEFAULT_DISCOVERY_LIMIT
|
|
50
54
|
return { ...r, certificates: r.certificates.slice(offset, offset + limit) } as R
|
|
@@ -18,12 +18,19 @@
|
|
|
18
18
|
* is a Vault or admin transaction, so a held Vault transaction cannot be
|
|
19
19
|
* broadcast by someone else.
|
|
20
20
|
*
|
|
21
|
+
* WalletPermissionsManager labels every action with its originator and month
|
|
22
|
+
* (`admin originator <o>`, `admin month YYYY-MM`) for spend tracking. Those
|
|
23
|
+
* labels make another originator's action admin state, but not the caller's
|
|
24
|
+
* own, so a site can internalize, spend and sendWith what it created itself.
|
|
25
|
+
*
|
|
21
26
|
* The admin originator (this app's own code) passes straight through. R1C
|
|
22
27
|
* locking scripts are not special here: an app may create and spend R1C
|
|
23
28
|
* outputs in its own baskets.
|
|
24
29
|
*/
|
|
25
30
|
import {
|
|
26
31
|
LockingScript,
|
|
32
|
+
PrivateKey,
|
|
33
|
+
PublicKey,
|
|
27
34
|
Transaction,
|
|
28
35
|
Validation,
|
|
29
36
|
type ListActionsArgs,
|
|
@@ -32,6 +39,7 @@ import {
|
|
|
32
39
|
type WalletAction,
|
|
33
40
|
type WalletInterface
|
|
34
41
|
} from '@bsv/sdk'
|
|
42
|
+
import { ownOriginatorLabel } from '../../storage/methods/vaultGuardSql'
|
|
35
43
|
import { bakedCommitments, R1C_LOCK_LEN, R1C_MAX_KEYS } from './r1comb'
|
|
36
44
|
|
|
37
45
|
const VAULT_LABEL = 'vault'
|
|
@@ -121,9 +129,50 @@ const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'va
|
|
|
121
129
|
* core/localpay/build.ts proves createSignature+getPublicKey over them is
|
|
122
130
|
* sufficient to construct a valid spend -- so a connected origin must not be
|
|
123
131
|
* able to mint either primitive under these namespaces itself, exactly as
|
|
124
|
-
* for Vault's own namespaces.
|
|
132
|
+
* for Vault's own namespaces. The one exception is getPublicKey toward
|
|
133
|
+
* another party's identity key (see derivesTowardAnotherParty). */
|
|
125
134
|
const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['3241645161d8', 'mandala token'])
|
|
126
135
|
|
|
136
|
+
/** The BRC-42 'anyone' counterparty (1·G), in canonical form. */
|
|
137
|
+
const ANYONE_PUBLIC_KEY = new PrivateKey(1).toPublicKey().toString()
|
|
138
|
+
|
|
139
|
+
/** Canonical (compressed) hex of a counterparty given as a public key;
|
|
140
|
+
* undefined for 'self', 'anyone', a non-string, or anything that is not a
|
|
141
|
+
* point on the curve. Parsing and re-encoding means another encoding of the
|
|
142
|
+
* same point cannot pass a comparison its canonical form would fail. */
|
|
143
|
+
function counterpartyPublicKey(counterparty: unknown): string | undefined {
|
|
144
|
+
if (typeof counterparty !== 'string') return undefined
|
|
145
|
+
try {
|
|
146
|
+
return PublicKey.fromString(counterparty).toString()
|
|
147
|
+
} catch {
|
|
148
|
+
return undefined
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** getPublicKey under a reserved rail namespace toward another party's
|
|
153
|
+
* identity key is the ordinary BRC-29 / FT payer (forSelf false) and payee
|
|
154
|
+
* (forSelf true) step every payment dApp takes. ECDH is symmetric, so that
|
|
155
|
+
* party can compute the same public key itself: revealing it neither signs
|
|
156
|
+
* nor tells anyone anything new. createSignature and the other private-key
|
|
157
|
+
* methods stay reserved, as do the two counterparties this wallet's own funds
|
|
158
|
+
* are locked to where a site could guess the keyID: 'anyone' (the address
|
|
159
|
+
* rail's date keyIDs) and the wallet's own identity key (FT change). Any
|
|
160
|
+
* failure to read the identity key counts as a match, so the call is refused. */
|
|
161
|
+
async function derivesTowardAnotherParty(
|
|
162
|
+
getPublicKey: (args: any, originator?: string) => Promise<{ publicKey: string }>,
|
|
163
|
+
args: any,
|
|
164
|
+
adminOriginator: string
|
|
165
|
+
): Promise<boolean> {
|
|
166
|
+
const counterparty = counterpartyPublicKey(args?.counterparty)
|
|
167
|
+
if (counterparty === undefined || counterparty === ANYONE_PUBLIC_KEY) return false
|
|
168
|
+
try {
|
|
169
|
+
const own = counterpartyPublicKey((await getPublicKey({ identityKey: true }, adminOriginator))?.publicKey)
|
|
170
|
+
return own !== undefined && counterparty !== own
|
|
171
|
+
} catch {
|
|
172
|
+
return false
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
127
176
|
/** XR-027: protocol namespace this package's own saved-pairing authority tag
|
|
128
177
|
* is derived under. A saved connection's approved (origin, topic, protocolID,
|
|
129
178
|
* backendIdentityKey) tuple is MAC'd with the admin-scoped wallet at approval
|
|
@@ -194,11 +243,14 @@ const OUTPUT_NAMING = new Set<keyof WalletInterface>([
|
|
|
194
243
|
export interface VaultGuardLookup {
|
|
195
244
|
/** True when any canonical `txid.vout` is held in an `admin`-prefixed
|
|
196
245
|
* basket, or has no basket but is tagged `vault` or was created by a
|
|
197
|
-
* `vault
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
246
|
+
* transaction labelled `vault` or with an admin label other than a month
|
|
247
|
+
* label or `ownLabel` (a relinquished Vault output, or another originator's
|
|
248
|
+
* action). `ownLabel` is the caller's own originator label, or null. */
|
|
249
|
+
anyAdminOutpoint(outpoints: string[], ownLabel: string | null): Promise<boolean>
|
|
250
|
+
/** True when any lowercase txid is labelled `vault` or with an admin label
|
|
251
|
+
* other than a month label or `ownLabel`, or creates or spends an output in
|
|
252
|
+
* an `admin`-prefixed basket. */
|
|
253
|
+
anyAdminTransaction(txids: string[], ownLabel: string | null): Promise<boolean>
|
|
202
254
|
}
|
|
203
255
|
|
|
204
256
|
export interface GuardVaultAccessOptions {
|
|
@@ -547,18 +599,27 @@ function requestedOutpoints(method: keyof WalletInterface, args: any): string[]
|
|
|
547
599
|
}
|
|
548
600
|
|
|
549
601
|
/** Whether an external output-naming call names an admin-state outpoint or a
|
|
550
|
-
* Vault/admin transaction.
|
|
551
|
-
*
|
|
552
|
-
|
|
602
|
+
* Vault/admin transaction. The caller's own actions do not count merely for
|
|
603
|
+
* the originator and month labels WalletPermissionsManager gave them (see
|
|
604
|
+
* ownOriginatorLabel). Unparseable arguments, a missing lookup and a failed
|
|
605
|
+
* lookup all count as yes. */
|
|
606
|
+
async function namesAdminState(
|
|
607
|
+
runtime: GuardRuntime,
|
|
608
|
+
method: keyof WalletInterface,
|
|
609
|
+
args: any,
|
|
610
|
+
originator: string | undefined,
|
|
611
|
+
adminOriginator: string
|
|
612
|
+
): Promise<boolean> {
|
|
553
613
|
const outpoints = requestedOutpoints(method, args)
|
|
554
614
|
const sendWith = requestedSendWithTxids(method, args)
|
|
555
615
|
if (outpoints === undefined || sendWith === undefined) return true
|
|
556
616
|
if (outpoints.length === 0 && sendWith.length === 0) return false
|
|
557
617
|
const lookup = runtime.lookup
|
|
558
618
|
if (!lookup) return true
|
|
619
|
+
const ownLabel = ownOriginatorLabel(originator, adminOriginator)
|
|
559
620
|
try {
|
|
560
|
-
if (outpoints.length > 0 && (await lookup.anyAdminOutpoint(outpoints))) return true
|
|
561
|
-
return sendWith.length > 0 && (await lookup.anyAdminTransaction(sendWith))
|
|
621
|
+
if (outpoints.length > 0 && (await lookup.anyAdminOutpoint(outpoints, ownLabel))) return true
|
|
622
|
+
return sendWith.length > 0 && (await lookup.anyAdminTransaction(sendWith, ownLabel))
|
|
562
623
|
} catch {
|
|
563
624
|
return true
|
|
564
625
|
}
|
|
@@ -644,19 +705,32 @@ export function guardVaultAccess<T extends WalletInterface>(
|
|
|
644
705
|
|
|
645
706
|
if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
|
|
646
707
|
|
|
647
|
-
return async (
|
|
648
|
-
if (originator === adminOriginator) return await bound(
|
|
708
|
+
return async (rawArgs: any, originator?: string) => {
|
|
709
|
+
if (originator === adminOriginator) return await bound(rawArgs, originator)
|
|
710
|
+
// The reserved-rail getPublicKey check awaits before deriving. Decide
|
|
711
|
+
// on, and derive from, one plain copy so an accessor on the caller's
|
|
712
|
+
// object cannot answer the check with one counterparty and the
|
|
713
|
+
// derivation with another.
|
|
714
|
+
let args = rawArgs
|
|
715
|
+
if (method === 'getPublicKey' && rawArgs !== null && typeof rawArgs === 'object') {
|
|
716
|
+
try {
|
|
717
|
+
args = JSON.parse(JSON.stringify(rawArgs))
|
|
718
|
+
} catch {
|
|
719
|
+
return deny(String(method), originator)
|
|
720
|
+
}
|
|
721
|
+
}
|
|
649
722
|
if (
|
|
650
723
|
PRIVILEGED_CAPABLE.has(method) &&
|
|
651
724
|
(args?.privileged ||
|
|
652
725
|
requestsVaultProtocol(args) ||
|
|
653
|
-
requestsReservedRailProtocol(args) ||
|
|
654
726
|
requestsConnectionAuthorityProtocol(args) ||
|
|
655
|
-
requestsPendingAbortAuthorityProtocol(args)
|
|
727
|
+
requestsPendingAbortAuthorityProtocol(args) ||
|
|
728
|
+
(requestsReservedRailProtocol(args) &&
|
|
729
|
+
!(method === 'getPublicKey' && (await derivesTowardAnotherParty(bound, args, adminOriginator)))))
|
|
656
730
|
) {
|
|
657
731
|
return deny(String(method), originator)
|
|
658
732
|
}
|
|
659
|
-
if (OUTPUT_NAMING.has(method) && (await namesAdminState(runtime, method, args))) {
|
|
733
|
+
if (OUTPUT_NAMING.has(method) && (await namesAdminState(runtime, method, args, originator, adminOriginator))) {
|
|
660
734
|
return deny(String(method), originator)
|
|
661
735
|
}
|
|
662
736
|
return await bound(args, originator)
|
|
@@ -66,7 +66,13 @@ import {
|
|
|
66
66
|
import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
|
|
67
67
|
import { getOnline } from '../net/online'
|
|
68
68
|
import { TaskSendOffline } from '../monitor/TaskSendOffline'
|
|
69
|
-
import {
|
|
69
|
+
import {
|
|
70
|
+
anyAdminOutpoint,
|
|
71
|
+
anyAdminTransaction,
|
|
72
|
+
isAdminOutput,
|
|
73
|
+
ORIGINATOR_LABEL_PREFIX,
|
|
74
|
+
ownOriginatorLabel
|
|
75
|
+
} from './methods/vaultGuardSql'
|
|
70
76
|
import type {
|
|
71
77
|
AuthId,
|
|
72
78
|
FindCertificateFieldsArgs,
|
|
@@ -159,39 +165,70 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
159
165
|
* The toolbox calls this after it has resolved each input's source from
|
|
160
166
|
* authenticated local storage (`input.output`) or verified BEEF. A stored
|
|
161
167
|
* output that is admin state — held in an `admin`-prefixed basket (the
|
|
162
|
-
* Vault's `admin vault`), or created by a
|
|
163
|
-
*
|
|
164
|
-
* unreachable deposits" — can be named
|
|
165
|
-
* admin originator, which the patched
|
|
166
|
-
* `__bsvVaultAdminAuthorized`.
|
|
167
|
-
*
|
|
168
|
+
* Vault's `admin vault`), or unbasketed and created by a transaction labelled
|
|
169
|
+
* `vault` or with another originator's admin labels, which still covers a
|
|
170
|
+
* Vault output relinquished by "forget unreachable deposits" — can be named
|
|
171
|
+
* as an input only by the app's own admin originator, which the patched
|
|
172
|
+
* Wallet.createAction records as `__bsvVaultAdminAuthorized`. A site may
|
|
173
|
+
* name an unbasketed output of its own earlier action (see
|
|
174
|
+
* actionOriginatorLabel). Running inside createAction, this also covers a
|
|
175
|
+
* caller that reaches the wallet without going through guardVaultAccess.
|
|
168
176
|
*
|
|
169
177
|
* The locking script does not decide: an app may hold and spend R1C outputs
|
|
170
178
|
* of its own.
|
|
171
179
|
*/
|
|
172
180
|
async validateResolvedActionInput(
|
|
173
|
-
vargs: { __bsvVaultAdminAuthorized?: boolean },
|
|
181
|
+
vargs: { __bsvVaultAdminAuthorized?: boolean; labels?: unknown },
|
|
174
182
|
input: { output?: { outputId?: number } }
|
|
175
183
|
): Promise<void> {
|
|
176
184
|
if (vargs.__bsvVaultAdminAuthorized === true) return
|
|
177
185
|
const outputId = input.output?.outputId
|
|
178
186
|
if (outputId == null) return
|
|
179
|
-
if (await isAdminOutput(this.getDB(), outputId)) {
|
|
187
|
+
if (await isAdminOutput(this.getDB(), outputId, this.actionOriginatorLabel(vargs.labels))) {
|
|
180
188
|
throw new Error('Inputs holding admin or Vault state require internal wallet authorization')
|
|
181
189
|
}
|
|
182
190
|
}
|
|
183
191
|
|
|
184
|
-
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
|
|
188
|
-
|
|
192
|
+
/**
|
|
193
|
+
* The admin originator, set once by the host where the wallet is built.
|
|
194
|
+
* Until it is set, validateResolvedActionInput counts every originator label
|
|
195
|
+
* as admin state.
|
|
196
|
+
*/
|
|
197
|
+
private vaultAdminOriginator?: string
|
|
198
|
+
|
|
199
|
+
setVaultAdminOriginator(adminOriginator: string): void {
|
|
200
|
+
if (this.vaultAdminOriginator !== undefined) throw new Error('The Vault admin originator is already set')
|
|
201
|
+
this.vaultAdminOriginator = adminOriginator
|
|
189
202
|
}
|
|
190
203
|
|
|
191
|
-
/**
|
|
192
|
-
*
|
|
193
|
-
|
|
194
|
-
|
|
204
|
+
/**
|
|
205
|
+
* The creating originator's label on the action being built, for
|
|
206
|
+
* validateResolvedActionInput to ignore. WalletPermissionsManager appends it,
|
|
207
|
+
* and a site cannot set an admin label itself, so it is taken only when
|
|
208
|
+
* there is exactly one and it is not the admin's.
|
|
209
|
+
*/
|
|
210
|
+
private actionOriginatorLabel(labels: unknown): string | null {
|
|
211
|
+
if (!Array.isArray(labels)) return null
|
|
212
|
+
const found = labels.filter(
|
|
213
|
+
(label): label is string => typeof label === 'string' && label.startsWith(ORIGINATOR_LABEL_PREFIX)
|
|
214
|
+
)
|
|
215
|
+
if (found.length !== 1) return null
|
|
216
|
+
return ownOriginatorLabel(found[0].slice(ORIGINATOR_LABEL_PREFIX.length), this.vaultAdminOriginator)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** guardVaultAccess lookup: is any `txid.vout` admin state (admin-prefixed
|
|
220
|
+
* basket, or a Vault/admin transaction's output) to the caller whose own
|
|
221
|
+
* originator label is `ownLabel`? Reads basket names and labels only (see
|
|
222
|
+
* methods/vaultGuardSql.ts). */
|
|
223
|
+
async anyAdminOutpoint(outpoints: string[], ownLabel: string | null = null): Promise<boolean> {
|
|
224
|
+
return await anyAdminOutpoint(this.getDB(), outpoints, ownLabel)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** guardVaultAccess lookup: is any txid a Vault or admin transaction to the
|
|
228
|
+
* caller whose own originator label is `ownLabel`? Reads labels and basket
|
|
229
|
+
* names only (see methods/vaultGuardSql.ts). */
|
|
230
|
+
async anyAdminTransaction(txids: string[], ownLabel: string | null = null): Promise<boolean> {
|
|
231
|
+
return await anyAdminTransaction(this.getDB(), txids, ownLabel)
|
|
195
232
|
}
|
|
196
233
|
|
|
197
234
|
// ============================================================================
|
|
@@ -23,6 +23,41 @@ export const VAULT_ACTION_LABEL = 'vault'
|
|
|
23
23
|
* recovery alike. Chain recovery internalizes without a `vault` label. */
|
|
24
24
|
export const VAULT_OUTPUT_TAG = 'vault'
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* WalletPermissionsManager appends `admin originator <originator>` and
|
|
28
|
+
* `admin month YYYY-MM` to every action it creates, the admin's included, and
|
|
29
|
+
* sums them per site for monthly spending authorization. They are admin labels
|
|
30
|
+
* a site cannot set, but they mark whose action it is, not Vault or admin
|
|
31
|
+
* state. Counting them made every unbasketed output of a site's own action
|
|
32
|
+
* admin state to that same site, which refused internalizing a payment it had
|
|
33
|
+
* just funded and `sendWith` of its own no-send actions.
|
|
34
|
+
*
|
|
35
|
+
* So the admin-state rule ignores every month label and the caller's own
|
|
36
|
+
* originator label. Another originator's label, the admin's included, still
|
|
37
|
+
* counts.
|
|
38
|
+
*/
|
|
39
|
+
export const ORIGINATOR_LABEL_PREFIX = 'admin originator '
|
|
40
|
+
export const MONTH_LABEL_PREFIX = 'admin month '
|
|
41
|
+
|
|
42
|
+
/** The originator label WalletPermissionsManager writes for `originator`, as
|
|
43
|
+
* storage keeps it (the SDK's label validation trims and lowercases). */
|
|
44
|
+
export function originatorLabel(originator: string): string {
|
|
45
|
+
return `${ORIGINATOR_LABEL_PREFIX}${originator}`.trim().toLowerCase()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The caller's own originator label for the admin-state rule to ignore, or
|
|
50
|
+
* null to ignore none: no originator, no known admin originator, or a caller
|
|
51
|
+
* whose label is the admin's (`Admin.example` stores the same label as
|
|
52
|
+
* `admin.example`).
|
|
53
|
+
*/
|
|
54
|
+
export function ownOriginatorLabel(originator: unknown, adminOriginator: string | undefined): string | null {
|
|
55
|
+
if (typeof originator !== 'string' || originator.trim() === '') return null
|
|
56
|
+
if (typeof adminOriginator !== 'string' || adminOriginator.trim() === '') return null
|
|
57
|
+
const own = originatorLabel(originator)
|
|
58
|
+
return own === originatorLabel(adminOriginator) ? null : own
|
|
59
|
+
}
|
|
60
|
+
|
|
26
61
|
/** Placeholders per statement, kept under the lowest SQLITE_MAX_VARIABLE_NUMBER
|
|
27
62
|
* a shipped SQLite still enforces (999). */
|
|
28
63
|
const MAX_BOUND_VARIABLES = 998
|
|
@@ -30,12 +65,15 @@ const MAX_BOUND_VARIABLES = 998
|
|
|
30
65
|
const IS_ADMIN_BASKET = `substr("b"."name", 1, ${ADMIN_PREFIX.length}) = '${ADMIN_PREFIX}'`
|
|
31
66
|
|
|
32
67
|
/** The transaction whose id is `transactionIdSql` carries the `vault` label or
|
|
33
|
-
* an `admin*` label
|
|
68
|
+
* an `admin*` label other than a month label or the caller's own originator
|
|
69
|
+
* label. Takes one bound parameter: that label, or NULL to ignore none. */
|
|
34
70
|
function hasAdminLabel(transactionIdSql: string): string {
|
|
35
71
|
return (
|
|
36
72
|
'EXISTS (SELECT 1 FROM "tx_labels_map" "m" JOIN "tx_labels" "l" ON "l"."txLabelId" = "m"."txLabelId" ' +
|
|
37
73
|
`WHERE "m"."transactionId" = ${transactionIdSql} AND ("l"."label" = '${VAULT_ACTION_LABEL}' ` +
|
|
38
|
-
`OR substr("l"."label", 1, ${ADMIN_PREFIX.length}) = '${ADMIN_PREFIX}'
|
|
74
|
+
`OR (substr("l"."label", 1, ${ADMIN_PREFIX.length}) = '${ADMIN_PREFIX}' ` +
|
|
75
|
+
`AND substr("l"."label", 1, ${MONTH_LABEL_PREFIX.length}) <> '${MONTH_LABEL_PREFIX}' ` +
|
|
76
|
+
'AND "l"."label" IS NOT ?)))'
|
|
39
77
|
)
|
|
40
78
|
}
|
|
41
79
|
|
|
@@ -48,9 +86,11 @@ const HAS_VAULT_TAG =
|
|
|
48
86
|
* An output row `o` (with its basket LEFT JOINed as `b`) is admin state when it
|
|
49
87
|
* sits in an `admin`-prefixed basket, or when it has no basket (relinquished,
|
|
50
88
|
* e.g. by "forget unreachable deposits") and is still recognisably a Vault or
|
|
51
|
-
* admin output: tagged `vault`, or created by a `vault
|
|
52
|
-
*
|
|
53
|
-
*
|
|
89
|
+
* admin output: tagged `vault`, or created by a transaction labelled `vault` or
|
|
90
|
+
* with an admin label that is not a month label or the caller's own
|
|
91
|
+
* originator label (see ORIGINATOR_LABEL_PREFIX). The label and tag count only
|
|
92
|
+
* for an unbasketed row, so an app's own basketed outputs never collide with
|
|
93
|
+
* them. Takes one bound parameter, the caller's own originator label or NULL.
|
|
54
94
|
*
|
|
55
95
|
* `default` is deliberately not included: an app retrying internalizeAction
|
|
56
96
|
* for a payment the wallet already holds as change names a `default` output,
|
|
@@ -63,7 +103,8 @@ const IS_ADMIN_OUTPUT =
|
|
|
63
103
|
const OUTPUT_WITH_BASKET = 'FROM "outputs" "o" LEFT JOIN "output_baskets" "b" ON "b"."basketId" = "o"."basketId" '
|
|
64
104
|
|
|
65
105
|
/**
|
|
66
|
-
* Hit when any named outpoint is admin state (see IS_ADMIN_OUTPUT).
|
|
106
|
+
* Hit when any named outpoint is admin state (see IS_ADMIN_OUTPUT). Bound as
|
|
107
|
+
* each `txid`, `vout` pair, then the caller's own originator label.
|
|
67
108
|
*
|
|
68
109
|
* One OR-group per outpoint rather than a row-value IN, so the query works on
|
|
69
110
|
* any SQLite build (same shape as `spendingReferencesSql`).
|
|
@@ -73,12 +114,15 @@ export function adminOutpointsSql(pairCount: number): string {
|
|
|
73
114
|
return `SELECT 1 AS hit ${OUTPUT_WITH_BASKET}WHERE (${groups}) AND ${IS_ADMIN_OUTPUT} LIMIT 1`
|
|
74
115
|
}
|
|
75
116
|
|
|
76
|
-
/** Hit when the output with this `outputId` is admin state.
|
|
117
|
+
/** Hit when the output with this `outputId` is admin state. Bound as the
|
|
118
|
+
* `outputId`, then the caller's own originator label. */
|
|
77
119
|
export const ADMIN_OUTPUT_BY_ID_SQL = `SELECT 1 AS hit ${OUTPUT_WITH_BASKET}WHERE "o"."outputId" = ? AND ${IS_ADMIN_OUTPUT} LIMIT 1`
|
|
78
120
|
|
|
79
121
|
/**
|
|
80
|
-
* Hit when any named txid is a Vault or admin transaction: labelled `vault
|
|
81
|
-
*
|
|
122
|
+
* Hit when any named txid is a Vault or admin transaction: labelled `vault`,
|
|
123
|
+
* carrying an admin label other than a month label or the caller's own
|
|
124
|
+
* originator label, or creating or spending an output in an admin-prefixed
|
|
125
|
+
* basket. Bound as each txid, then the caller's own originator label.
|
|
82
126
|
*
|
|
83
127
|
* Spending is matched through `outputs.spentBy`, which the toolbox sets when
|
|
84
128
|
* an action reserves its inputs, so a signed-but-held withdrawal is caught
|
|
@@ -100,11 +144,19 @@ export function adminTransactionsSql(txidCount: number): string {
|
|
|
100
144
|
|
|
101
145
|
/** The slice of an expo-sqlite handle these lookups use. */
|
|
102
146
|
export interface GuardSqlDb {
|
|
103
|
-
getFirstAsync(sql: string, params: (string | number)[]): Promise<unknown>
|
|
147
|
+
getFirstAsync(sql: string, params: (string | number | null)[]): Promise<unknown>
|
|
104
148
|
}
|
|
105
149
|
|
|
106
|
-
/**
|
|
107
|
-
|
|
150
|
+
/**
|
|
151
|
+
* `txid.vout` pairs, as the guard canonicalizes them (lowercase txid).
|
|
152
|
+
* `ownLabel` is the caller's own originator label (see ownOriginatorLabel),
|
|
153
|
+
* or null to treat every originator label as admin state.
|
|
154
|
+
*/
|
|
155
|
+
export async function anyAdminOutpoint(
|
|
156
|
+
db: GuardSqlDb,
|
|
157
|
+
outpoints: string[],
|
|
158
|
+
ownLabel: string | null = null
|
|
159
|
+
): Promise<boolean> {
|
|
108
160
|
const pairs = outpoints.map(outpoint => {
|
|
109
161
|
const dot = outpoint.lastIndexOf('.')
|
|
110
162
|
const txid = outpoint.slice(0, dot).toLowerCase()
|
|
@@ -114,27 +166,38 @@ export async function anyAdminOutpoint(db: GuardSqlDb, outpoints: string[]): Pro
|
|
|
114
166
|
}
|
|
115
167
|
return [txid, vout] as const
|
|
116
168
|
})
|
|
117
|
-
|
|
169
|
+
// One placeholder is the label.
|
|
170
|
+
const perStatement = Math.floor((MAX_BOUND_VARIABLES - 1) / 2)
|
|
118
171
|
for (let i = 0; i < pairs.length; i += perStatement) {
|
|
119
172
|
const chunk = pairs.slice(i, i + perStatement)
|
|
120
|
-
if (await db.getFirstAsync(adminOutpointsSql(chunk.length), chunk.flat())) return true
|
|
173
|
+
if (await db.getFirstAsync(adminOutpointsSql(chunk.length), [...chunk.flat(), ownLabel])) return true
|
|
121
174
|
}
|
|
122
175
|
return false
|
|
123
176
|
}
|
|
124
177
|
|
|
125
|
-
export async function anyAdminTransaction(
|
|
178
|
+
export async function anyAdminTransaction(
|
|
179
|
+
db: GuardSqlDb,
|
|
180
|
+
txids: string[],
|
|
181
|
+
ownLabel: string | null = null
|
|
182
|
+
): Promise<boolean> {
|
|
126
183
|
const normalized = txids.map(txid => {
|
|
127
184
|
const lower = txid.toLowerCase()
|
|
128
185
|
if (!/^[0-9a-f]{64}$/.test(lower)) throw new Error(`Invalid txid ${txid}`)
|
|
129
186
|
return lower
|
|
130
187
|
})
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
188
|
+
// One placeholder is the label.
|
|
189
|
+
const perStatement = MAX_BOUND_VARIABLES - 1
|
|
190
|
+
for (let i = 0; i < normalized.length; i += perStatement) {
|
|
191
|
+
const chunk = normalized.slice(i, i + perStatement)
|
|
192
|
+
if (await db.getFirstAsync(adminTransactionsSql(chunk.length), [...chunk, ownLabel])) return true
|
|
134
193
|
}
|
|
135
194
|
return false
|
|
136
195
|
}
|
|
137
196
|
|
|
138
|
-
export async function isAdminOutput(
|
|
139
|
-
|
|
197
|
+
export async function isAdminOutput(
|
|
198
|
+
db: GuardSqlDb,
|
|
199
|
+
outputId: number,
|
|
200
|
+
ownLabel: string | null = null
|
|
201
|
+
): Promise<boolean> {
|
|
202
|
+
return !!(await db.getFirstAsync(ADMIN_OUTPUT_BY_ID_SQL, [outputId, ownLabel]))
|
|
140
203
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bsv/expo-wallet-toolbox",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.6",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.txt",
|