@bsv/expo-wallet-toolbox 0.14.0 → 0.15.1

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 CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.1
4
+
5
+ ### Fixed
6
+
7
+ - **Connected apps can issue and send Mandala tokens.** `MandalaTokenModule`
8
+ forced `includeCustomInstructions` off on every `listOutputs` call from a
9
+ connected app, but the Mandala lib finds the issuer's admin assets and the
10
+ coins it can spend by the `keyID`/`counterparty` stored there, so the
11
+ console found nothing to issue from or send. After the token access prompt
12
+ the instructions are now returned as asked. The redaction dates from before
13
+ `createSignature` was bound to approved transactions; knowing a coin's
14
+ derivation no longer lets an app spend it.
15
+
16
+ ## 0.15.0
17
+
18
+ ### Changed
19
+
20
+ - **Breaking: Mandala token keys derive under `[2, 'p mandala token']`.**
21
+ Requires `@bsv/mandala` 0.4.0, which renamed `FT_PROTOCOL` from
22
+ `[2, 'mandala token']`. Every token key derivation changes; tokens held
23
+ under the old protocol are not migrated.
24
+ - **Mandala token keys are gated by the `mandala` permission module, not the
25
+ vault guard.** The `'p '` prefix makes `WalletPermissionsManager` route
26
+ every call under the token protocol to `MandalaTokenModule`, the way
27
+ `[0, 'p btms']` reaches the BTMS module. The vault guard no longer reserves
28
+ the namespace, so a connected app (such as the Mandala console) can issue
29
+ tokens and send to itself. For a connected app:
30
+ - `getPublicKey` and `verifySignature` pass through, for any counterparty.
31
+ - `createSignature` passes without a prompt when it signs the BIP-143
32
+ sighash of an input of a transaction the user approved through the
33
+ module's `createAction` prompt within the last 60 seconds. Any other
34
+ signature gets its own `mandala_signature` prompt, and approving it does
35
+ not cover later signatures.
36
+ - `encrypt`, `decrypt`, `createHmac` and `verifyHmac` are refused.
37
+ - `revealSpecificKeyLinkage` is no longer refused and is not prompted.
38
+ - Privileged calls are still refused.
39
+
3
40
  ## 0.14.0
4
41
 
5
42
  ### Fixed
@@ -17,7 +17,7 @@ const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
17
17
  const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
18
18
 
19
19
  export const DEMO_USD: TokenAssetInfo = {
20
- assetId: 'd0'.repeat(32) + '.0',
20
+ assetId: 'd0'.repeat(32) + '_0',
21
21
  label: 'Acme Dollar',
22
22
  ticker: 'USDX',
23
23
  decimals: 2,
@@ -27,7 +27,7 @@ export const DEMO_USD: TokenAssetInfo = {
27
27
  }
28
28
 
29
29
  export const DEMO_CHF: TokenAssetInfo = {
30
- assetId: 'cf'.repeat(32) + '.0',
30
+ assetId: 'cf'.repeat(32) + '_0',
31
31
  label: 'Helvetia Franc',
32
32
  ticker: 'CHFX',
33
33
  decimals: 2,
@@ -9,7 +9,7 @@ import {
9
9
  UnlockingScript,
10
10
  Utils
11
11
  } from '@bsv/sdk'
12
- import { MandalaToken } from '@bsv/templates'
12
+ import { MandalaToken } from '../mandala/token'
13
13
  import { FRAME_VERSION, type PaymentFrame } from './codec'
14
14
  import { isRequestableAmount, type Session } from './session'
15
15
  import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
@@ -503,7 +503,7 @@ const SETTLEMENT_PREWRITE_FAILURE = 'could not record the settlement row before
503
503
  * derivation field to undefined, and this is the only slot that survives to
504
504
  * the day the coin is spent.
505
505
  */
506
- const FT_PROTOCOL_ID: [number, string] = [2, 'mandala token']
506
+ const FT_PROTOCOL_ID: [number, string] = [2, 'p mandala token']
507
507
 
508
508
  /** What `internalizeAction` is told about one frame's output. */
509
509
  function internalizeOutput(frame: PaymentFrame): Record<string, unknown> {
@@ -252,7 +252,7 @@ export function decodeSession(text: string): Session {
252
252
  if (t !== undefined) {
253
253
  if (typeof t !== 'object' || t === null) throw new CodecError('bad asset block')
254
254
  const { i: ai, n, s: tick, d, u, k: ok } = t as Record<string, unknown>
255
- if (typeof ai !== 'string' || !/^[0-9a-f]{64}\.\d+$/.test(ai)) throw new CodecError('bad assetId')
255
+ if (typeof ai !== 'string' || !/^[0-9a-f]{64}_0$/.test(ai)) throw new CodecError('bad assetId')
256
256
  if (typeof u !== 'string' || u.length === 0) throw new CodecError('bad overlayUrl')
257
257
  if (typeof ok !== 'string' || ok.length !== 66) throw new CodecError('bad overlayIdentityKey')
258
258
  if (n !== undefined && typeof n !== 'string') throw new CodecError('bad asset label')
@@ -37,7 +37,7 @@ export interface SettlementAck {
37
37
  txid: string
38
38
  /** Sorted ascending, exactly as the overlay signed them. */
39
39
  outputsToAdmit: number[]
40
- /** σ_I over `admissionDigestV2(txid, outputsToAdmit)`, DER hex. */
40
+ /** σ_I over `admissionDigestV3(topic, txid, outputsToAdmit)`, DER hex. */
41
41
  admissionSignature: string
42
42
  }
43
43
 
@@ -1,6 +1,6 @@
1
1
  import { Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
2
2
  import type { ChainTracker } from '@bsv/sdk'
3
- import { MandalaToken } from '@bsv/templates'
3
+ import { MandalaToken } from '../mandala/token'
4
4
  import type { PaymentFrame } from './codec'
5
5
  import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
6
6
  import { PEERPAY_PROTOCOL_ID } from './pending'
@@ -9,7 +9,7 @@ import type { DeclineReason } from './types'
9
9
 
10
10
  // mandala's FT derivation protocol — the payer locks token outputs under it
11
11
  // with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
12
- export const FT_PROTOCOL_ID: [2, string] = [2, 'mandala token']
12
+ export const FT_PROTOCOL_ID: [2, string] = [2, 'p mandala token']
13
13
 
14
14
  export type VerifiedPayment =
15
15
  | { kind: 'bsv'; satoshis: number }
@@ -29,7 +29,7 @@
29
29
  * becomes a one-line import and nothing else here changes.
30
30
  */
31
31
  import { Beef, Transaction } from '@bsv/sdk'
32
- import { MandalaToken } from '@bsv/templates'
32
+ import { MandalaToken } from './token'
33
33
  import type { PaymentFrame } from '../localpay/codec'
34
34
  import type { AdmissionEntryWire, CoverResult, SettlementStore } from './types'
35
35
 
@@ -22,13 +22,15 @@
22
22
  * with the bytes and the evidence the local tables hold.
23
23
  */
24
24
  import { Beef, Transaction, Utils, type WalletInterface } from '@bsv/sdk'
25
- import { MandalaToken } from '@bsv/templates'
25
+ import { MandalaToken } from './token'
26
26
  import {
27
27
  blindingCommit,
28
28
  blindingGet,
29
29
  blindingPruneReserved,
30
30
  blindingReserve,
31
31
  cover as coverWalk,
32
+ decodeToken,
33
+ decodeValue,
32
34
  createOverlayFacilitator,
33
35
  fetchAdmission as libFetchAdmission,
34
36
  fetchRegistry,
@@ -45,6 +47,7 @@ import {
45
47
  registryIsLive,
46
48
  resolveAssetMetadata,
47
49
  submitToOverlay,
50
+ tokenTopic,
48
51
  transferTokens,
49
52
  verifyAdmission as libVerifyAdmission,
50
53
  verifyFetchedAdmission,
@@ -718,19 +721,18 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
718
721
  const vout = Number(voutText)
719
722
  const script = beef.findTxid(txid)?.tx?.outputs[vout]?.lockingScript
720
723
  if (!script) continue
721
- try {
722
- const decoded = MandalaToken.decode(script)
723
- out.push({
724
- outpoint: output.outpoint,
725
- txid,
726
- vout,
727
- assetId: decoded.assetId,
728
- amount: decoded.amount,
729
- spendable: output.spendable !== false
730
- })
731
- } catch {
732
- // A stray non-token output in the basket is not this asset's coin.
733
- }
724
+ // BRC-162: only value-role outputs are coins; a stray non-token (or
725
+ // deploy/authority) output in the basket is not this asset's coin.
726
+ const decoded = decodeValue(script)
727
+ if (decoded == null) continue
728
+ out.push({
729
+ outpoint: output.outpoint,
730
+ txid,
731
+ vout,
732
+ assetId: decoded.tokenId,
733
+ amount: decoded.amount,
734
+ spendable: output.spendable !== false
735
+ })
734
736
  }
735
737
  return out
736
738
  }
@@ -847,12 +849,48 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
847
849
  )
848
850
  )
849
851
 
852
+ /**
853
+ * BRC-162: the σI topic of a token transaction is `tokenTopic(tokenId)` of its
854
+ * token outputs (value or authority). Undefined when no token output decodes.
855
+ */
856
+ const topicOfTx = (tx: Transaction | undefined): string | undefined => {
857
+ for (const o of tx?.outputs ?? []) {
858
+ const d = o.lockingScript != null ? decodeToken(o.lockingScript) : null
859
+ if (d?.tokenId != null) {
860
+ try {
861
+ return tokenTopic(d.tokenId)
862
+ } catch {
863
+ continue
864
+ }
865
+ }
866
+ }
867
+ return undefined
868
+ }
869
+ const topicCache = new Map<string, string>()
870
+ const topicOfTxid = async (txid: string): Promise<string | undefined> => {
871
+ const hit = topicCache.get(txid)
872
+ if (hit !== undefined) return hit
873
+ let topic: string | undefined
874
+ try {
875
+ topic = topicOfTx((await loadBeefContaining(txid))?.findTxid(txid)?.tx)
876
+ } catch (e) {
877
+ devLog(`[mandala] could not derive the token topic of ${txid}:`, e)
878
+ }
879
+ if (topic !== undefined) topicCache.set(txid, topic)
880
+ return topic
881
+ }
882
+
850
883
  /** FIX H, in one function: an entry proves nothing unless THIS overlay signed it. */
851
- const verifyAdmissionEntry: VerifyAdmissionFn = (entry, key) => {
884
+ const verifyAdmissionEntry: VerifyAdmissionFn = async (entry, key) => {
852
885
  if (entry.signerKey.toLowerCase() !== key.toLowerCase()) return false
886
+ // σI v3 binds the token topic. An entry that does not name it (a cached
887
+ // row, an older frame) gets it from the transaction's own token outputs.
888
+ const topic = entry.topic ?? (await topicOfTxid(entry.txid))
889
+ if (topic === undefined) return false
853
890
  try {
854
891
  return libVerifyAdmission({
855
892
  txid: entry.txid,
893
+ topic,
856
894
  outputsToAdmit: entry.outputsToAdmit,
857
895
  signature: Array.from(entry.signature),
858
896
  signerKey: entry.signerKey
@@ -1030,11 +1068,18 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1030
1068
  } catch (e) {
1031
1069
  devLog(`[mandala] could not read the linkage payload of ${txid}:`, e)
1032
1070
  }
1071
+ const topic = topicOfTx(own)
1072
+ if (topic === undefined) {
1073
+ devLog(`[mandala] ${txid} carries no BRC-162 token output; nothing to submit`)
1074
+ return { kind: 'unavailable', code: 'ERR_LOCAL_BYTES', retryable: true }
1075
+ }
1076
+ topicCache.set(txid, topic)
1033
1077
  try {
1034
1078
  const admitted = await submitToOverlay(
1035
1079
  bytes,
1036
1080
  linkage && linkage.payloadBytes.length > 0 ? Array.from(linkage.payloadBytes) : undefined,
1037
- facilitator()
1081
+ facilitator(),
1082
+ [topic]
1038
1083
  )
1039
1084
  // The lib already refuses an unsigned or unverifiable answer
1040
1085
  // (ERR_NO_ADMISSION / ERR_BAD_ADMISSION); this is the wallet's own
@@ -1050,6 +1095,7 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1050
1095
  }
1051
1096
  const trusted = await verifyAdmission({
1052
1097
  txid,
1098
+ topic: admitted.topic ?? topic,
1053
1099
  outputsToAdmit: admitted.outputsToAdmit,
1054
1100
  signature: hexToBytes(signatureHex),
1055
1101
  signerKey
@@ -26,8 +26,8 @@
26
26
  * dependency and is unit-testable against an in-memory SQLite.
27
27
  */
28
28
  import { Beef, Utils } from '@bsv/sdk'
29
- import { MandalaToken } from '@bsv/templates'
30
- import { payloadHash } from '@bsv/mandala'
29
+ import { MandalaToken } from './token'
30
+ import { payloadHash, tokenTopicOrEmpty } from '@bsv/mandala'
31
31
  import type { PostOutcome } from '../offline/plan'
32
32
  import { devLog } from '../logging'
33
33
  import {
@@ -196,7 +196,8 @@ export async function populateEvidenceFromFrame(
196
196
  const at = (opts.now?.() ?? new Date()).toISOString()
197
197
 
198
198
  for (const entry of token.admissions ?? []) {
199
- if (!(await entryIsTrustworthy(entry, opts))) {
199
+ // BRC-162: σI v3 binds the token topic; the frame's asset names it.
200
+ if (!(await entryIsTrustworthy({ ...entry, topic: entry.topic ?? tokenTopicOrEmpty(token.assetId) }, opts))) {
200
201
  result.admissionsDropped++
201
202
  continue
202
203
  }
@@ -390,7 +391,8 @@ export interface TokenStepDeps extends EvidenceTrustAnchor {
390
391
  async function admissionStandsIn(
391
392
  row: TokenAdmissionRow | undefined,
392
393
  anchor: EvidenceTrustAnchor,
393
- requiredVouts: readonly number[]
394
+ requiredVouts: readonly number[],
395
+ assetId?: string
394
396
  ): Promise<boolean> {
395
397
  if (row === undefined) return false
396
398
  if (row.signatureHex.length === 0 || row.outputsToAdmit.length === 0) return false
@@ -398,6 +400,7 @@ async function admissionStandsIn(
398
400
  return await entryIsTrustworthy(
399
401
  {
400
402
  txid: row.txid,
403
+ ...(assetId !== undefined ? { topic: tokenTopicOrEmpty(assetId) } : {}),
401
404
  outputsToAdmit: row.outputsToAdmit,
402
405
  signature: hexToBytes(row.signatureHex),
403
406
  signerKey: row.signerKey
@@ -496,7 +499,7 @@ export async function postTokenStep(
496
499
  // bytes this device does not hold) left an already-admitted tip at
497
500
  // `admitted` on every tick, never broadcast (2026-09-16).
498
501
  const tipAdmission = await store.getAdmission(tip)
499
- if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts)) {
502
+ if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts, settlement.assetId)) {
500
503
  await store.advanceSettlement(tip, PRE_ADMIT_STATES, 'admitted', {
501
504
  admissionOutputs: tipAdmission?.outputsToAdmit,
502
505
  admissionSignatureHex: tipAdmission?.signatureHex
@@ -544,7 +547,7 @@ export async function postTokenStep(
544
547
  // vout(s) of it something still in this walk actually spends.
545
548
  const requiredVouts =
546
549
  ancestorTxid === tip ? tipRequiredVouts : await requiredVoutsOfAncestor(store, ancestorTxid, cover.mustSubmit)
547
- if (await admissionStandsIn(cached, deps, requiredVouts)) {
550
+ if (await admissionStandsIn(cached, deps, requiredVouts, settlement.assetId)) {
548
551
  await store.advanceSettlement(ancestorTxid, PRE_ADMIT_STATES, 'admitted', {
549
552
  admissionOutputs: cached?.outputsToAdmit,
550
553
  admissionSignatureHex: cached?.signatureHex
@@ -74,6 +74,7 @@ interface RawInboxMessage {
74
74
  /** What one decoded hand-over needs from `settle` — the exact shape `SettleArgs` wants. */
75
75
  interface DecodedHandover {
76
76
  tip: Transaction
77
+ assetId: string
77
78
  mustSubmit: string[]
78
79
  bytesFor: (txid: string) => { beef: number[]; offChainValues: number[] } | undefined
79
80
  }
@@ -128,6 +129,7 @@ function decodeHandover(body: RawHandoverBody, cover: PreHoldCoverFn): DecodedHa
128
129
 
129
130
  return {
130
131
  tip,
132
+ assetId: body.assetId,
131
133
  mustSubmit: result.mustSubmit,
132
134
  bytesFor: (id: string) => {
133
135
  const found = beef.findAtomicTransaction(id)
@@ -172,7 +174,12 @@ export async function preHoldInboxSettlements(deps: PreHoldInboxDeps): Promise<S
172
174
  if (!decoded) continue // COVER refused it — acceptOne will reach the same refusal before internalizing
173
175
 
174
176
  try {
175
- await deps.settle({ txid: decoded.tip.id('hex'), mustSubmit: decoded.mustSubmit, bytesFor: decoded.bytesFor })
177
+ await deps.settle({
178
+ txid: decoded.tip.id('hex'),
179
+ mustSubmit: decoded.mustSubmit,
180
+ assetId: decoded.assetId,
181
+ bytesFor: decoded.bytesFor
182
+ })
176
183
  } catch (e) {
177
184
  devLog(
178
185
  `[mandala] inbox pre-hold could not write the settlement row for message ${raw.messageId}; holding it back this pass:`,
@@ -10,17 +10,30 @@
10
10
  * via `MandalaToken.decode` from `@bsv/templates`, NOT BTMS's `PushDrop.decode`:
11
11
  * the two token formats are unrelated.
12
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.
13
+ * Mandala's FT protocol is `[2, 'p mandala token']` (@bsv/mandala 0.4.0), so
14
+ * `WalletPermissionsManager` also routes every wallet call keyed on that
15
+ * protocol here, the same way BTMS's `[0, 'p btms']` reaches
16
+ * `BasicTokenModule`. For a connected app:
17
+ * - `getPublicKey`/`verifySignature` pass through. A public key cannot
18
+ * spend, and issuing or sending to yourself needs keys toward `self`/
19
+ * your own identity key.
20
+ * - `createSignature` passes only when the digest it signs is the BIP-143
21
+ * sighash of an input of a transaction this module saw the user approve
22
+ * (the `createAction` response, captured in `onResponse`). Any other
23
+ * signature gets its own prompt and never grants a session.
24
+ * - `encrypt`/`decrypt`/`createHmac`/`verifyHmac` are refused: nothing in
25
+ * the Mandala lib uses them under the token protocol.
18
26
  *
19
27
  * Source of truth: offline-settlement-final.md §8.3, plus a set of
20
28
  * adversarial-review findings closed here (see the inline notes tagged
21
29
  * "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).
30
+ * 1. [critical] listOutputs used to withhold `customInstructions`
31
+ * (keyID/counterparty/blinding derivation data), because knowing a
32
+ * coin's derivation was enough to sign a spend of it. Reverted: the
33
+ * Mandala lib finds admin assets and spendable coins by those
34
+ * instructions, so withholding them broke issuing and sending from a
35
+ * connected app, and `createSignature` is now bound to approved
36
+ * transactions (see above), so the derivation alone no longer spends.
24
37
  * 2. [medium/high] createAction that only SPENDS `'p mandala'` INPUTS (no
25
38
  * basketed change output) is now gated too — see `anyInputIsTokenCoin`
26
39
  * and the `wrapCreateActionForTokenInputs` wrapper below.
@@ -28,13 +41,62 @@
28
41
  * 4. [medium] Prompt amounts are grouped by assetId and decimal-formatted.
29
42
  * 5. [low] relinquishOutput is its own authorization class.
30
43
  */
31
- import { LockingScript, Transaction } from '@bsv/sdk'
44
+ import { Hash, LockingScript, Transaction, Utils } from '@bsv/sdk'
32
45
  import type { PermissionsModule } from '@bsv/wallet-toolbox-mobile'
33
- import { MandalaToken } from '@bsv/templates'
46
+ import { MandalaToken } from './token'
34
47
  import { MANDALA_BASKET } from './types'
35
48
 
36
49
  const SESSION_TIMEOUT_MS = 60_000
37
50
  const SESSION_CLEANUP_INTERVAL_MS = 30_000
51
+ /** Approved transactions remembered per originator. A token send signs right
52
+ * after its createAction, so a handful covers any honest app; the cap keeps
53
+ * a looping one from growing the map without bound. */
54
+ const MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR = 8
55
+
56
+ /** Token-protocol methods the Mandala lib never calls: refused outright. */
57
+ const REFUSED_KEY_METHODS = new Set(['encrypt', 'decrypt', 'createHmac', 'verifyHmac'])
58
+
59
+ /**
60
+ * The digest a `createSignature` call will actually sign: `hashToDirectlySign`
61
+ * as given, otherwise SHA-256 of `data` (what ProtoWallet does). Undefined
62
+ * for anything malformed, which the caller then refuses.
63
+ */
64
+ export function signedDigestHex(args: unknown): string | undefined {
65
+ if (args === null || typeof args !== 'object') return undefined
66
+ const { hashToDirectlySign, data } = args as { hashToDirectlySign?: unknown; data?: unknown }
67
+ const bytes = (value: unknown): number[] | undefined => {
68
+ if (!Array.isArray(value) && !(value instanceof Uint8Array)) return undefined
69
+ const out = Array.from(value as ArrayLike<unknown>)
70
+ return out.every(b => Number.isInteger(b) && (b as number) >= 0 && (b as number) <= 255)
71
+ ? (out as number[])
72
+ : undefined
73
+ }
74
+ if (hashToDirectlySign !== undefined) {
75
+ const hash = bytes(hashToDirectlySign)
76
+ return hash !== undefined && hash.length === 32 ? Utils.toHex(hash) : undefined
77
+ }
78
+ const payload = bytes(data)
79
+ return payload !== undefined ? Utils.toHex(Hash.sha256(payload)) : undefined
80
+ }
81
+
82
+ /**
83
+ * The BIP-143 sighash (SIGHASH_ALL|FORKID, what `walletMandalaUnlock` signs
84
+ * by default) of every input of a signable transaction. An input whose
85
+ * source is not in the BEEF cannot be hashed and is skipped: it is not one
86
+ * the wallet can be asked to sign for anyway.
87
+ */
88
+ export function authorizedSighashes(atomicBEEF: number[] | Uint8Array): Set<string> {
89
+ const tx = Transaction.fromAtomicBEEF(Array.from(atomicBEEF))
90
+ const digests = new Set<string>()
91
+ for (let i = 0; i < tx.inputs.length; i++) {
92
+ try {
93
+ digests.add(Utils.toHex(Hash.hash256(tx.preimage(i))))
94
+ } catch {
95
+ // No source transaction for this input.
96
+ }
97
+ }
98
+ return digests
99
+ }
38
100
 
39
101
  /**
40
102
  * Normalises an outpoint the same way the SDK's own `Number(...)` coercion
@@ -186,13 +248,6 @@ interface MandalaInternalizeActionArgsLike {
186
248
  outputs?: MandalaInternalizeOutputLike[]
187
249
  }
188
250
 
189
- /** The slice of `ListOutputsArgs` this module reads/rewrites. */
190
- interface MandalaListOutputsArgsLike {
191
- basket?: string
192
- includeCustomInstructions?: boolean
193
- [key: string]: unknown
194
- }
195
-
196
251
  export interface DecodedMandalaOutput {
197
252
  assetId: string
198
253
  amount: number
@@ -345,6 +400,9 @@ export class MandalaTokenModule implements PermissionsModule {
345
400
  * adversarial-review finding (5): it is its own authorization class.
346
401
  */
347
402
  private readonly sessionAuthorizations: Map<string, number> = new Map()
403
+ /** Per originator: the input sighashes of each transaction the user
404
+ * approved through `promptForSpend`/`promptGeneric`, newest last. */
405
+ private readonly authorizedTransactions: Map<string, { digests: Set<string>; timestamp: number }[]> = new Map()
348
406
  private readonly cleanupTimer: ReturnType<typeof setInterval>
349
407
 
350
408
  constructor(deps: MandalaTokenModuleDeps) {
@@ -367,6 +425,16 @@ export class MandalaTokenModule implements PermissionsModule {
367
425
  this.sessionAuthorizations.delete(originator)
368
426
  }
369
427
  }
428
+ for (const originator of this.authorizedTransactions.keys()) this.liveAuthorizedTransactions(originator)
429
+ }
430
+
431
+ /** This originator's unexpired approved transactions; prunes the rest. */
432
+ private liveAuthorizedTransactions(originator: string): { digests: Set<string>; timestamp: number }[] {
433
+ const now = Date.now()
434
+ const live = (this.authorizedTransactions.get(originator) ?? []).filter(t => now - t.timestamp <= SESSION_TIMEOUT_MS)
435
+ if (live.length === 0) this.authorizedTransactions.delete(originator)
436
+ else this.authorizedTransactions.set(originator, live)
437
+ return live
370
438
  }
371
439
 
372
440
  private hasSessionAuthorization(originator: string): boolean {
@@ -403,15 +471,9 @@ export class MandalaTokenModule implements PermissionsModule {
403
471
 
404
472
  switch (method) {
405
473
  case 'listOutputs': {
474
+ // customInstructions come back when asked for: see finding (1).
406
475
  await this.promptOnceForAccess(originator, 'listOutputs')
407
- // Adversarial-review finding (1): WalletPermissionsManager forwards
408
- // the ARGS THIS METHOD RETURNS to the underlying listOutputs call
409
- // (delegateToPModuleIfNeeded), so redacting here genuinely prevents
410
- // the underlying wallet from ever including customInstructions in
411
- // its response — this is not merely filtering our own mirror of it
412
- // afterward, which would be too late for a caller that reads the
413
- // result directly.
414
- return { args: this.redactListOutputsArgs(args as MandalaListOutputsArgsLike) }
476
+ break
415
477
  }
416
478
  case 'listActions':
417
479
  // Adversarial-review finding (3): same once-per-session gate as
@@ -429,10 +491,15 @@ export class MandalaTokenModule implements PermissionsModule {
429
491
  case 'internalizeAction':
430
492
  await this.promptForCredit(args as MandalaInternalizeActionArgsLike, originator)
431
493
  break
494
+ case 'createSignature':
495
+ await this.authorizeSignature(args, originator)
496
+ break
432
497
  default:
433
- // No other method is ever routed here (basket-gating only covers
434
- // these five) — pass through defensively rather than throw on a
435
- // future manager version that adds one.
498
+ if (REFUSED_KEY_METHODS.has(method)) {
499
+ throw new Error(`Mandala token keys cannot be used for ${method}`)
500
+ }
501
+ // getPublicKey/verifySignature, and any method a future manager
502
+ // version routes here, pass through.
436
503
  break
437
504
  }
438
505
 
@@ -440,14 +507,45 @@ export class MandalaTokenModule implements PermissionsModule {
440
507
  }
441
508
 
442
509
  /**
443
- * Mandala tokens carry no post-hoc metadata to redact and there is no
444
- * preimage-binding layer here (createSignature is not P-routed for this
445
- * protocol, see the class doc) — the response passes through unchanged.
510
+ * After an approved `createAction` (`onRequest` threw otherwise), remembers
511
+ * the input sighashes of the transaction the wallet built, so the app's
512
+ * `createSignature` calls for exactly that transaction need no second
513
+ * prompt. A response that cannot be hashed is passed on unchanged and
514
+ * simply leaves those signatures to `authorizeSignature`'s own prompt.
446
515
  */
447
- async onResponse(res: unknown, _context: { method: string; originator: string }): Promise<unknown> {
516
+ async onResponse(res: unknown, context: { method: string; originator: string }): Promise<unknown> {
517
+ if (context.method !== 'createAction' || context.originator === this.deps.adminOriginator) return res
518
+ const tx = (res as { signableTransaction?: { tx?: number[] | Uint8Array } } | null)?.signableTransaction?.tx
519
+ if (tx === undefined) return res
520
+ let digests: Set<string>
521
+ try {
522
+ digests = authorizedSighashes(tx)
523
+ } catch {
524
+ return res
525
+ }
526
+ const live = this.liveAuthorizedTransactions(context.originator)
527
+ live.push({ digests, timestamp: Date.now() })
528
+ this.authorizedTransactions.set(context.originator, live.slice(-MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR))
448
529
  return res
449
530
  }
450
531
 
532
+ /**
533
+ * `createSignature` under the token protocol from a connected app. Signing
534
+ * an input of a transaction the user just approved goes ahead; anything
535
+ * else (an unrouted createAction, an expired approval, a digest that is not
536
+ * one of that transaction's) is asked about on its own. The prompt never
537
+ * grants a session: one approval is one signature.
538
+ */
539
+ private async authorizeSignature(args: object, originator: string): Promise<void> {
540
+ const digest = signedDigestHex(args)
541
+ if (digest === undefined) throw new Error('Invalid createSignature args')
542
+ if (this.liveAuthorizedTransactions(originator).some(t => t.digests.has(digest))) return
543
+ const approved = await this.deps.requestTokenAccess(originator, JSON.stringify({ type: 'mandala_signature' }))
544
+ if (!approved) {
545
+ throw new Error('User denied permission to sign with a Mandala token key')
546
+ }
547
+ }
548
+
451
549
  /** listOutputs / listActions — once per 60s session, like BTMS's promptForBTMSAccess. */
452
550
  private async promptOnceForAccess(originator: string, action: 'listOutputs' | 'listActions'): Promise<void> {
453
551
  if (this.hasSessionAuthorization(originator)) return
@@ -505,16 +603,6 @@ export class MandalaTokenModule implements PermissionsModule {
505
603
  }
506
604
  }
507
605
 
508
- /**
509
- * Forces `includeCustomInstructions` off regardless of what the caller
510
- * asked for. `customInstructions` is where a Mandala coin's `keyID`/
511
- * `counterparty`/blinding derivation lives (see the module doc) — a paired
512
- * app has no legitimate use for it, and no other `ListOutputsArgs` field
513
- * exposes anything equivalent.
514
- */
515
- private redactListOutputsArgs(args: MandalaListOutputsArgsLike): MandalaListOutputsArgsLike {
516
- return { ...args, includeCustomInstructions: false }
517
- }
518
606
 
519
607
  /**
520
608
  * createAction with an output in `'p mandala'` — always prompts (mirrors
@@ -27,14 +27,14 @@
27
27
  * transaction's own status: a resend is a delivery, not a payment.
28
28
  */
29
29
  import { Transaction } from '@bsv/sdk'
30
- import { MandalaToken } from '@bsv/templates'
30
+ import { MandalaToken } from './token'
31
31
  import { isDuplicateMessageError } from '../peerpay/control'
32
32
 
33
33
  /** The recipient-side inbox `receiveTokens` drains (`@bsv/mandala` `MESSAGEBOX`). */
34
34
  export const MANDALA_MESSAGE_BOX = 'mandala-payments'
35
35
 
36
36
  /** The FT derivation protocol, as the lib's `FT_PROTOCOL`. */
37
- const FT_PROTOCOL: [number, string] = [2, 'mandala token']
37
+ const FT_PROTOCOL: [number, string] = [2, 'p mandala token']
38
38
 
39
39
  export type TokenResendFailure = 'no_record' | 'no_transaction'
40
40
  export type TokenResendOutcome = { ok: true } | { ok: false; reason: TokenResendFailure }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * BRC-162 token-script boundary for the wallet.
3
+ *
4
+ * A drop-in for the old `MandalaToken` (8-chunk PushDrop) from `@bsv/templates`
5
+ * 1.x, over `Bsv21Binary` from `@bsv/templates` 2.x. `decode` yields
6
+ * `{ assetId, amount, pubKeyHash }` for a VALUE-role output only (deploy and
7
+ * authority outputs are not coins) and throws on anything else, exactly as the
8
+ * old decoder did, so every call site keeps its `try/catch` shape.
9
+ */
10
+ import { LockingScript, type WalletCounterparty, type WalletInterface, type WalletProtocol } from '@bsv/sdk'
11
+ import { Bsv21Binary, tokenIdToString } from '@bsv/templates'
12
+
13
+ export class MandalaToken {
14
+ private readonly inner: Bsv21Binary
15
+
16
+ constructor(wallet?: WalletInterface, originator?: string) {
17
+ this.inner = new Bsv21Binary(wallet, originator)
18
+ }
19
+
20
+ static decode(script: LockingScript | string): { assetId: string; amount: number; pubKeyHash: number[] } {
21
+ const ls = LockingScript.fromHex(typeof script === 'string' ? script : script.toHex())
22
+ const d = Bsv21Binary.decode(ls)
23
+ if (d.role !== 'value' || d.tokenId == null) throw new Error(`not a BRC-162 value output (role ${d.role})`)
24
+ if (d.restPubKeyHash == null) throw new Error('BRC-162 output is not P2PKH-locked')
25
+ if (d.amount > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('BRC-162 amount exceeds 2^53-1')
26
+ return { assetId: tokenIdToString(d.tokenId), amount: Number(d.amount), pubKeyHash: d.restPubKeyHash }
27
+ }
28
+
29
+ /** A value coin of `assetId` locked to `pubKeyHash`. */
30
+ lock(assetId: string, amount: number, pubKeyHash: readonly number[]): LockingScript {
31
+ return LockingScript.fromHex(this.inner.lock(assetId, BigInt(amount), pubKeyHash).toHex())
32
+ }
33
+
34
+ /** A value coin locked to hash160 of the wallet-derived (BRC-29 style) key. */
35
+ async lockBRC29(
36
+ assetId: string,
37
+ amount: number,
38
+ protocolID: WalletProtocol,
39
+ keyID: string,
40
+ counterparty: WalletCounterparty
41
+ ): Promise<LockingScript> {
42
+ const s = await this.inner.lockBRC29(assetId, BigInt(amount), protocolID, keyID, counterparty)
43
+ return LockingScript.fromHex(s.toHex())
44
+ }
45
+ }
@@ -120,6 +120,11 @@ export type OverlayVerdict =
120
120
  /** An AdmissionEntry as carried on the wire (frame v4 `admissions[]`). */
121
121
  export interface AdmissionEntryWire {
122
122
  txid: string
123
+ /**
124
+ * BRC-162 σI v3 topic (`tokenTopic(assetId)`). Optional: when absent the
125
+ * verifier derives it from the transaction's own token outputs.
126
+ */
127
+ topic?: string
123
128
  outputsToAdmit: number[]
124
129
  signature: Uint8Array
125
130
  signerKey: string
@@ -27,7 +27,7 @@
27
27
  * an explicit `refused`/`orphaned` verdict from the overlay.
28
28
  */
29
29
  import { Beef, Transaction } from '@bsv/sdk'
30
- import { MandalaToken } from '@bsv/templates'
30
+ import { MandalaToken } from '../mandala/token'
31
31
  import type { EvidenceFrame, TokenFrameSource } from '../mandala/drain'
32
32
  import type { OfflineActionRow } from '../storage/methods/offlineActions'
33
33
  import { frameBytesFromQr, unsealFrame } from '../localpay/codec'
@@ -54,8 +54,8 @@ export function peerPayHasErrors(result: PeerPayValidationResult): boolean {
54
54
 
55
55
  const PEERPAY_SCHEME = 'peerpay:'
56
56
  const COMPRESSED_PUBLIC_KEY_REGEX = /^0[23][0-9a-fA-F]{64}$/
57
- /** A genesis outpoint: 32-byte txid in hex, a dot, a decimal output index. */
58
- const ASSET_OUTPOINT_REGEX = /^[0-9a-fA-F]{64}\.(0|[1-9][0-9]*)$/
57
+ /** A BRC-162 token id: the 32-byte deploy txid in hex, then `_0`. */
58
+ const ASSET_OUTPOINT_REGEX = /^[0-9a-fA-F]{64}_0$/
59
59
  /** A whole non-negative figure with no sign, point or leading zero. */
60
60
  const WHOLE_FIGURE_REGEX = /^(0|[1-9][0-9]*)$/
61
61
  /**
@@ -29,8 +29,6 @@
29
29
  */
30
30
  import {
31
31
  LockingScript,
32
- PrivateKey,
33
- PublicKey,
34
32
  Transaction,
35
33
  Utils,
36
34
  Validation,
@@ -122,14 +120,10 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
122
120
  * own vault code ever reaches it. */
123
121
  const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
124
122
 
125
- /** Protocol namespace this package's OWN internal, fund-controlling FT/
126
- * mandala-token rail derives under (localpay/verify.ts's FT_PROTOCOL_ID,
127
- * `[2, 'mandala token']`). It is not Vault state, but core/localpay/build.ts
128
- * proves createSignature+getPublicKey over it is sufficient to construct a
129
- * valid spend -- so a connected origin must not be able to mint either
130
- * primitive under it itself, exactly as for Vault's own namespaces. The one
131
- * exception is getPublicKey toward another party's identity key (see
132
- * derivesTowardAnotherParty).
123
+ /** Mandala's token protocol (`[2, 'p mandala token']`) is not reserved here:
124
+ * its `'p '` prefix routes every call under it to MandalaTokenModule
125
+ * (core/mandala/permissionModule.ts), which binds connected-app signatures to
126
+ * transactions the user approved.
133
127
  *
134
128
  * BRC-29 (`[2, '3241645161d8']`) was reserved here too (XR-020) and is not any
135
129
  * more: it is the standard BRC-100 payment protocol, and refusing it broke
@@ -137,7 +131,6 @@ const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'va
137
131
  * goes through the permissions manager's protocol prompt instead
138
132
  * (seekProtocolPermissionsForSigning in WalletContext.tsx), except for the
139
133
  * address rail's own key IDs, which stay refused (isAddressRailKeyID). */
140
- const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['mandala token'])
141
134
 
142
135
  /** base64('legacy'), the suffix every address-rail key ID ends in
143
136
  * (pay/rails/address.ts's LEGACY_DERIVATION_SUFFIX). */
@@ -173,46 +166,6 @@ function requestsAddressRailKey(args: unknown): boolean {
173
166
  )
174
167
  }
175
168
 
176
- /** The BRC-42 'anyone' counterparty (1·G), in canonical form. */
177
- const ANYONE_PUBLIC_KEY = new PrivateKey(1).toPublicKey().toString()
178
-
179
- /** Canonical (compressed) hex of a counterparty given as a public key;
180
- * undefined for 'self', 'anyone', a non-string, or anything that is not a
181
- * point on the curve. Parsing and re-encoding means another encoding of the
182
- * same point cannot pass a comparison its canonical form would fail. */
183
- function counterpartyPublicKey(counterparty: unknown): string | undefined {
184
- if (typeof counterparty !== 'string') return undefined
185
- try {
186
- return PublicKey.fromString(counterparty).toString()
187
- } catch {
188
- return undefined
189
- }
190
- }
191
-
192
- /** getPublicKey under a reserved rail namespace toward another party's
193
- * identity key is the ordinary FT payer (forSelf false) and payee
194
- * (forSelf true) step every payment dApp takes. ECDH is symmetric, so that
195
- * party can compute the same public key itself: revealing it neither signs
196
- * nor tells anyone anything new. createSignature and the other private-key
197
- * methods stay reserved, as do the two counterparties this wallet's own funds
198
- * are locked to where a site could guess the keyID: 'anyone' and the
199
- * wallet's own identity key (FT change). Any
200
- * failure to read the identity key counts as a match, so the call is refused. */
201
- async function derivesTowardAnotherParty(
202
- getPublicKey: (args: any, originator?: string) => Promise<{ publicKey: string }>,
203
- args: any,
204
- adminOriginator: string
205
- ): Promise<boolean> {
206
- const counterparty = counterpartyPublicKey(args?.counterparty)
207
- if (counterparty === undefined || counterparty === ANYONE_PUBLIC_KEY) return false
208
- try {
209
- const own = counterpartyPublicKey((await getPublicKey({ identityKey: true }, adminOriginator))?.publicKey)
210
- return own !== undefined && counterparty !== own
211
- } catch {
212
- return false
213
- }
214
- }
215
-
216
169
  /** XR-027: protocol namespace this package's own saved-pairing authority tag
217
170
  * is derived under. A saved connection's approved (origin, topic, protocolID,
218
171
  * backendIdentityKey) tuple is MAC'd with the admin-scoped wallet at approval
@@ -253,10 +206,6 @@ function requestsVaultProtocol(args: unknown): boolean {
253
206
  return matchesProtocolNamespace(args, VAULT_PROTOCOL_NAMES)
254
207
  }
255
208
 
256
- function requestsReservedRailProtocol(args: unknown): boolean {
257
- return matchesProtocolNamespace(args, RESERVED_RAIL_PROTOCOL_NAMES)
258
- }
259
-
260
209
  function requestsConnectionAuthorityProtocol(args: unknown): boolean {
261
210
  return matchesProtocolNamespace(args, CONNECTION_AUTHORITY_PROTOCOL_NAMES)
262
211
  }
@@ -745,29 +694,15 @@ export function guardVaultAccess<T extends WalletInterface>(
745
694
 
746
695
  if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
747
696
 
748
- return async (rawArgs: any, originator?: string) => {
749
- if (originator === adminOriginator) return await bound(rawArgs, originator)
750
- // The reserved-rail getPublicKey check awaits before deriving. Decide
751
- // on, and derive from, one plain copy so an accessor on the caller's
752
- // object cannot answer the check with one counterparty and the
753
- // derivation with another.
754
- let args = rawArgs
755
- if (method === 'getPublicKey' && rawArgs !== null && typeof rawArgs === 'object') {
756
- try {
757
- args = JSON.parse(JSON.stringify(rawArgs))
758
- } catch {
759
- return deny(String(method), originator)
760
- }
761
- }
697
+ return async (args: any, originator?: string) => {
698
+ if (originator === adminOriginator) return await bound(args, originator)
762
699
  if (
763
700
  PRIVILEGED_CAPABLE.has(method) &&
764
701
  (args?.privileged ||
765
702
  requestsVaultProtocol(args) ||
766
703
  requestsConnectionAuthorityProtocol(args) ||
767
704
  requestsPendingAbortAuthorityProtocol(args) ||
768
- requestsAddressRailKey(args) ||
769
- (requestsReservedRailProtocol(args) &&
770
- !(method === 'getPublicKey' && (await derivesTowardAnotherParty(bound, args, adminOriginator)))))
705
+ requestsAddressRailKey(args))
771
706
  ) {
772
707
  return deny(String(method), originator)
773
708
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
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",
@@ -32,11 +32,11 @@
32
32
  "@bsv/air-gap": "^0.1.3",
33
33
  "@bsv/backup-cache-client": "^0.1.0",
34
34
  "@bsv/btms-permission-module": "^1.2.1",
35
- "@bsv/mandala": "^0.2.0",
35
+ "@bsv/mandala": "^0.4.0",
36
36
  "@bsv/message-box-client": "^2.5.3",
37
37
  "@bsv/react-native-localpay-transport": "*",
38
- "@bsv/sdk": "^2.8.2",
39
- "@bsv/templates": "^1.10.3",
38
+ "@bsv/sdk": "^2.8.11",
39
+ "@bsv/templates": "^2.0.0",
40
40
  "@bsv/wallet-toolbox-mobile": "^2.14.3",
41
41
  "@expo/vector-icons": "^15.0.3",
42
42
  "@noble/curves": "^2.3.0",
@@ -379,6 +379,8 @@ export function deriveActive(
379
379
  description = 'wants to remove a Mandala token holding from your wallet'
380
380
  } else if (promptData.type === 'mandala_access') {
381
381
  description = 'wants to see your Mandala token balance'
382
+ } else if (promptData.type === 'mandala_signature') {
383
+ description = 'wants to sign with one of your token keys. Only approve if you just asked this app to move tokens'
382
384
  } else {
383
385
  description = 'wants to access Mandala tokens'
384
386
  }