@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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.
Files changed (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -1,7 +1,18 @@
1
1
  import { SymmetricKey } from '@bsv/sdk'
2
- import type { AdmissionEntryWire } from '../mandala/types'
3
2
 
4
- export const FRAME_VERSION = 5
3
+ /**
4
+ * 7 (IC §7.3, design §9 B7): the token block carries exactly the members of
5
+ * the v4 MessageBox hand-over body (IC §7.2) that the frame does not already
6
+ * carry: `assetId`, `amount` (canonical decimal string), `senderMode`, the
7
+ * optional tip `admission`, the ancestor `admissions[]` (σ) and `linkage[]`
8
+ * (one envelope per unadmitted transaction, the tip included), plus the
9
+ * unchanged opaque `certificates`. The frame's own sender key, remittance
10
+ * strings, output index, note and AtomicBEEF are the body's other members.
11
+ * The payee rebuilds the body and runs the lib's recipient path on it with
12
+ * its own configured overlay. Frame 6 (BRC-207 receipt `profileData`) and
13
+ * older are refused outright; there is no back-compat.
14
+ */
15
+ export const FRAME_VERSION = 7
5
16
 
6
17
  export class CodecError extends Error {
7
18
  constructor(message: string) {
@@ -12,33 +23,53 @@ export class CodecError extends Error {
12
23
 
13
24
  export type FrameKind = 'bsv' | 'token'
14
25
 
26
+ /**
27
+ * Ceiling on the token block's evidence JSON (`admission`, `admissions`,
28
+ * `linkage`). The lib caps each list at 1000 rows; a 1000-hop chain of
29
+ * envelopes stays well inside this.
30
+ */
31
+ export const MAX_EVIDENCE_BYTES = 16_777_216
32
+
33
+ /** The lib's per-list row ceiling (`receive.ts` MAX_EVIDENCE_ROWS). */
34
+ const MAX_EVIDENCE_ROWS = 1000
35
+
36
+ /** Asset ids are `<64 lowercase hex>_0` (IC §0, Mandala policy). */
37
+ const ASSET_ID_RE = /^[0-9a-f]{64}_0$/
38
+ const DECIMAL_RE = /^(0|[1-9][0-9]*)$/
39
+ const TXID_RE = /^[0-9a-f]{64}$/
40
+ const KEY_RE = /^0[23][0-9a-f]{64}$/
41
+ const EVEN_HEX_RE = /^(?:[0-9a-f]{2})+$/
42
+ const MAX_UINT32 = 4294967295
43
+
44
+ /** One σ row: the BRC-207 JSON attestation shape (IC §3, §7.2). */
45
+ export interface FrameAttestation {
46
+ txid: string
47
+ outputs: number[]
48
+ signer: string
49
+ signature: string
50
+ }
51
+
52
+ /** One envelope row: the off-chain values `txid` is submitted with, lowercase hex. */
53
+ export interface FrameLinkage {
54
+ txid: string
55
+ offChainValues: string
56
+ }
57
+
15
58
  export interface TokenPayment {
16
- assetId: string // "<64-hex txid>.<vout>"
17
- overlayUrl: string
18
- overlayIdentityKey: string // 66-hex compressed pubkey
19
- certificates: Uint8Array[] // opaque serialized VerifiableCertificates
20
- linkage: Array<{ txid: string; payload: Uint8Array }> // per-txid MandalaLinkagePayload bytes, whole chain
21
- /**
22
- * σ_I evidence for the ancestors this frame's chain bottoms out at — the
23
- * AdmissionBundle's `admissions` map, flattened (offline-settlement spec
24
- * §1.1/§2.1). One entry per COVERED ancestor: the overlay's own signature
25
- * over `(txid, outputsToAdmit)`, which the payee verifies against the
26
- * session's `overlayIdentityKey` before crediting.
27
- *
28
- * REPLACES v3's `recipientLinkage`. A payee-decryptable linkage is
29
- * impossible under D2 sender blinding without leaking the payer's real
30
- * identity key (BRC-72 decryption by the named verifier requires
31
- * `counterparty: prover`), and σ_I bound to the admitted output set is
32
- * strictly stronger evidence at roughly a tenth the size: it is the
33
- * OVERLAY's assertion, not the payer's assertion about their own honesty.
34
- * Removed, not renamed — a v3 decoder cannot read a v4 frame at all.
35
- *
36
- * `linkage` and `admissions` are keyed by disjoint txid sets in a
37
- * well-formed bundle: a txid with σ_I needs no linkage forwarded (nobody
38
- * will submit it again); a txid without σ_I needs linkage (so whoever
39
- * reconnects first can build its /submit body) and is walked further.
40
- */
41
- admissions: AdmissionEntryWire[]
59
+ /** `<64 lowercase hex>_0` — the underscore id form, never the dot outpoint form. */
60
+ assetId: string
61
+ /** Exact token units of the named output, canonical decimal string (IC §0). */
62
+ amount: string
63
+ /** `blinded` when the sender key is A′, `identity` when it is A. */
64
+ senderMode: 'blinded' | 'identity'
65
+ /** σ of the tip, when the payer already holds it. */
66
+ admission?: FrameAttestation
67
+ /** σ per admitted ancestor (terminates the payee's COVER walk). */
68
+ admissions: FrameAttestation[]
69
+ /** Envelope per unadmitted transaction, the tip included. */
70
+ linkage: FrameLinkage[]
71
+ /** Opaque serialized VerifiableCertificates. */
72
+ certificates: Uint8Array[]
42
73
  }
43
74
 
44
75
  export interface PaymentFrame {
@@ -59,12 +90,9 @@ export interface PaymentFrame {
59
90
  derivationPrefix: string
60
91
  derivationSuffix: string
61
92
  /**
62
- * Present iff kind === 'token'. Carried opaquely: the codec validates
63
- * shapes and lengths, never parses linkage payloads or certificates.
64
- * `linkage` maps EVERY unbroadcast token transaction in `transaction`'s
65
- * ancestry to the exact offChainValues bytes its issuer overlay consumes —
66
- * forwarded verbatim on chained re-spends so whoever reconnects first can
67
- * submit the whole chain.
93
+ * Present iff kind === 'token'. The codec validates shapes and lengths
94
+ * (decimal amount, attestation and envelope row shapes); it verifies no
95
+ * signature and no envelope. The payee's lib does (IC §7.2).
68
96
  */
69
97
  token?: TokenPayment
70
98
  /**
@@ -114,8 +142,10 @@ function putBytes(out: number[], bytes: Uint8Array): void {
114
142
  for (const byte of bytes) out.push(byte)
115
143
  }
116
144
 
117
- function getBytes(b: Uint8Array, pos: { i: number }): Uint8Array {
145
+ function getBytes(b: Uint8Array, pos: { i: number }, max?: { bytes: number; what: string }): Uint8Array {
118
146
  const len = getVarint(b, pos)
147
+ // A hostile length prefix is refused before anything is sliced.
148
+ if (max !== undefined && len > max.bytes) throw new CodecError(`${max.what} too large`)
119
149
  if (pos.i + len > b.length) throw new CodecError('truncated byte field')
120
150
  const slice = b.slice(pos.i, pos.i + len)
121
151
  pos.i += len
@@ -148,6 +178,100 @@ function bytesToHex(b: Uint8Array): string {
148
178
  return Array.from(b, x => x.toString(16).padStart(2, '0')).join('')
149
179
  }
150
180
 
181
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
182
+ typeof v === 'object' && v !== null && !Array.isArray(v)
183
+
184
+ function readAttestation(v: unknown, what: string): FrameAttestation {
185
+ if (!isPlainObject(v)) throw new CodecError(`${what} is not an object`)
186
+ const keys = Object.keys(v)
187
+ if (keys.length !== 4 || !['txid', 'outputs', 'signer', 'signature'].every(k => keys.includes(k))) {
188
+ throw new CodecError(`${what} members must be exactly txid, outputs, signer, signature`)
189
+ }
190
+ if (typeof v.txid !== 'string' || !TXID_RE.test(v.txid)) throw new CodecError(`${what}.txid is not a txid`)
191
+ if (
192
+ !Array.isArray(v.outputs) ||
193
+ v.outputs.length === 0 ||
194
+ v.outputs.some(o => typeof o !== 'number' || !Number.isInteger(o) || o < 0 || o > MAX_UINT32)
195
+ ) {
196
+ throw new CodecError(`${what}.outputs is not a non-empty uint32 list`)
197
+ }
198
+ if (typeof v.signer !== 'string' || !KEY_RE.test(v.signer)) throw new CodecError(`${what}.signer is not a key`)
199
+ if (typeof v.signature !== 'string' || !EVEN_HEX_RE.test(v.signature)) {
200
+ throw new CodecError(`${what}.signature is not hex`)
201
+ }
202
+ return { txid: v.txid, outputs: [...(v.outputs as number[])], signer: v.signer, signature: v.signature }
203
+ }
204
+
205
+ function readLinkage(v: unknown, what: string): FrameLinkage {
206
+ if (!isPlainObject(v) || Object.keys(v).length !== 2) {
207
+ throw new CodecError(`${what} must be exactly {txid, offChainValues}`)
208
+ }
209
+ if (typeof v.txid !== 'string' || !TXID_RE.test(v.txid)) throw new CodecError(`${what}.txid is not a txid`)
210
+ if (typeof v.offChainValues !== 'string' || !EVEN_HEX_RE.test(v.offChainValues)) {
211
+ throw new CodecError(`${what}.offChainValues is not hex`)
212
+ }
213
+ return { txid: v.txid, offChainValues: v.offChainValues }
214
+ }
215
+
216
+ interface Evidence {
217
+ admission?: FrameAttestation
218
+ admissions: FrameAttestation[]
219
+ linkage: FrameLinkage[]
220
+ }
221
+
222
+ /** The evidence members, checked and normalised; the same rules at encode and decode. */
223
+ function checkEvidence(v: unknown): Evidence {
224
+ if (!isPlainObject(v)) throw new CodecError('token evidence is not a JSON object')
225
+ for (const k of Object.keys(v)) {
226
+ if (k !== 'admission' && k !== 'admissions' && k !== 'linkage') {
227
+ throw new CodecError(`token evidence has an unexpected member ${JSON.stringify(k)}`)
228
+ }
229
+ }
230
+ if (!Array.isArray(v.admissions) || v.admissions.length > MAX_EVIDENCE_ROWS) {
231
+ throw new CodecError('token admissions is not a list')
232
+ }
233
+ if (!Array.isArray(v.linkage) || v.linkage.length > MAX_EVIDENCE_ROWS) {
234
+ throw new CodecError('token linkage is not a list')
235
+ }
236
+ const linkage = v.linkage.map((l, i) => readLinkage(l, `token linkage[${i}]`))
237
+ if (new Set(linkage.map(l => l.txid)).size !== linkage.length)
238
+ throw new CodecError('token linkage names a txid twice')
239
+ return {
240
+ ...(v.admission !== undefined ? { admission: readAttestation(v.admission, 'token admission') } : {}),
241
+ admissions: v.admissions.map((a, i) => readAttestation(a, `token admissions[${i}]`)),
242
+ linkage
243
+ }
244
+ }
245
+
246
+ function checkTokenScalars(t: { assetId: unknown; amount: unknown; senderMode: unknown }): void {
247
+ if (typeof t.assetId !== 'string' || !ASSET_ID_RE.test(t.assetId)) throw new CodecError('bad token assetId')
248
+ if (typeof t.amount !== 'string' || !DECIMAL_RE.test(t.amount) || t.amount === '0') {
249
+ throw new CodecError('token amount is not a positive canonical decimal string')
250
+ }
251
+ if (BigInt(t.amount) > (1n << 64n) - 1n) throw new CodecError('token amount exceeds 2^64-1')
252
+ if (t.senderMode !== 'blinded' && t.senderMode !== 'identity') {
253
+ throw new CodecError('token senderMode must be blinded or identity')
254
+ }
255
+ }
256
+
257
+ const SENDER_MODE_BYTE = { identity: 0x00, blinded: 0x01 } as const
258
+
259
+ /**
260
+ * Strict UTF-8 decode, independent of whether the platform TextDecoder
261
+ * honours `fatal`: a lenient decode would silently rewrite invalid bytes to
262
+ * U+FFFD, so the carrier the payee hands on would differ from what was sent.
263
+ * Valid UTF-8 is exactly the bytes that re-encode to themselves.
264
+ */
265
+ function decodeUtf8Strict(bytes: Uint8Array, what: string): string {
266
+ const text = dec.decode(bytes)
267
+ const again = enc.encode(text)
268
+ if (again.length !== bytes.length) throw new CodecError(`${what} is not valid UTF-8`)
269
+ for (let i = 0; i < again.length; i++) {
270
+ if (again[i] !== bytes[i]) throw new CodecError(`${what} is not valid UTF-8`)
271
+ }
272
+ return text
273
+ }
274
+
151
275
  // ── frame ──
152
276
 
153
277
  const KIND_BYTE: Record<FrameKind, number> = { bsv: 0x01, token: 0x02 }
@@ -167,37 +291,22 @@ export function encodeFrame(f: PaymentFrame): Uint8Array {
167
291
  putStr(out, f.derivationSuffix)
168
292
  if (f.token) {
169
293
  const t = f.token
170
- if (t.overlayIdentityKey.length !== 66) {
171
- throw new CodecError(`overlayIdentityKey must be 66 hex chars, got ${t.overlayIdentityKey.length}`)
172
- }
294
+ // Checked at encode as well as decode: fail where there is still a payer
295
+ // to tell, rather than ship a frame every payee will refuse.
296
+ checkTokenScalars(t)
297
+ const evidence = checkEvidence({
298
+ ...(t.admission !== undefined ? { admission: t.admission } : {}),
299
+ admissions: t.admissions,
300
+ linkage: t.linkage
301
+ })
302
+ const evidenceBytes = enc.encode(JSON.stringify(evidence))
303
+ if (evidenceBytes.length > MAX_EVIDENCE_BYTES) throw new CodecError('token evidence too large')
173
304
  putStr(out, t.assetId)
174
- putStr(out, t.overlayUrl)
175
- for (const byte of hexToBytes(t.overlayIdentityKey.toLowerCase())) out.push(byte)
305
+ putStr(out, t.amount)
306
+ out.push(SENDER_MODE_BYTE[t.senderMode])
176
307
  putVarint(out, t.certificates.length)
177
308
  for (const cert of t.certificates) putBytes(out, cert)
178
- putVarint(out, t.linkage.length)
179
- for (const entry of t.linkage) {
180
- if (entry.txid.length !== 64) throw new CodecError(`linkage txid must be 64 hex chars, got ${entry.txid.length}`)
181
- for (const byte of hexToBytes(entry.txid.toLowerCase())) out.push(byte)
182
- putBytes(out, entry.payload)
183
- }
184
- putVarint(out, t.admissions.length)
185
- for (const entry of t.admissions) {
186
- if (entry.txid.length !== 64)
187
- throw new CodecError(`admission txid must be 64 hex chars, got ${entry.txid.length}`)
188
- // Same shape check the overlay key already gets: a signerKey that is not
189
- // a 33-byte compressed point can never verify, and one that is silently
190
- // truncated on the wire would verify against a DIFFERENT key on the far
191
- // side. Fail at encode, where there is still a payer to tell.
192
- if (entry.signerKey.length !== 66) {
193
- throw new CodecError(`admission signerKey must be 66 hex chars, got ${entry.signerKey.length}`)
194
- }
195
- for (const byte of hexToBytes(entry.txid.toLowerCase())) out.push(byte)
196
- putVarint(out, entry.outputsToAdmit.length)
197
- for (const vout of entry.outputsToAdmit) putVarint(out, vout)
198
- putBytes(out, entry.signature)
199
- for (const byte of hexToBytes(entry.signerKey.toLowerCase())) out.push(byte)
200
- }
309
+ putBytes(out, evidenceBytes)
201
310
  }
202
311
  putStr(out, f.note ?? '')
203
312
  putBytes(out, f.transaction)
@@ -220,40 +329,28 @@ export function decodeFrame(b: Uint8Array): PaymentFrame {
220
329
  let token: TokenPayment | undefined
221
330
  if (kind === 'token') {
222
331
  const assetId = getStr(b, pos)
223
- const overlayUrl = getStr(b, pos)
224
- if (pos.i + 33 > b.length) throw new CodecError('truncated overlayIdentityKey')
225
- const overlayIdentityKey = bytesToHex(b.slice(pos.i, pos.i + 33))
226
- pos.i += 33
332
+ const amount = getStr(b, pos)
333
+ if (pos.i >= b.length) throw new CodecError('truncated token senderMode')
334
+ const modeByte = b[pos.i++]
335
+ const senderMode = modeByte === 0x00 ? 'identity' : modeByte === 0x01 ? 'blinded' : undefined
336
+ if (senderMode === undefined) throw new CodecError(`unsupported token senderMode ${modeByte}`)
337
+ checkTokenScalars({ assetId, amount, senderMode })
227
338
  const certificates: Uint8Array[] = []
339
+ // Each certificate consumes bytes and bounds-checks first, so a hostile
340
+ // count cannot make this loop spin: it throws the moment the buffer runs out.
228
341
  const certCount = getVarint(b, pos)
229
342
  for (let c = 0; c < certCount; c++) certificates.push(getBytes(b, pos))
230
- const linkage: Array<{ txid: string; payload: Uint8Array }> = []
231
- const linkCount = getVarint(b, pos)
232
- for (let l = 0; l < linkCount; l++) {
233
- if (pos.i + 32 > b.length) throw new CodecError('truncated linkage txid')
234
- const txid = bytesToHex(b.slice(pos.i, pos.i + 32))
235
- pos.i += 32
236
- linkage.push({ txid, payload: getBytes(b, pos) })
237
- }
238
- const admissions: AdmissionEntryWire[] = []
239
- const admissionCount = getVarint(b, pos)
240
- for (let a = 0; a < admissionCount; a++) {
241
- // Every field below consumes bytes and bounds-checks first, so a hostile
242
- // count cannot make this loop spin: it throws the moment the buffer runs
243
- // out, on the first entry that does not fit.
244
- if (pos.i + 32 > b.length) throw new CodecError('truncated admission txid')
245
- const txid = bytesToHex(b.slice(pos.i, pos.i + 32))
246
- pos.i += 32
247
- const voutCount = getVarint(b, pos)
248
- const outputsToAdmit: number[] = []
249
- for (let v = 0; v < voutCount; v++) outputsToAdmit.push(getVarint(b, pos))
250
- const signature = getBytes(b, pos)
251
- if (pos.i + 33 > b.length) throw new CodecError('truncated admission signerKey')
252
- const signerKey = bytesToHex(b.slice(pos.i, pos.i + 33))
253
- pos.i += 33
254
- admissions.push({ txid, outputsToAdmit, signature, signerKey })
343
+ const evidenceText = decodeUtf8Strict(
344
+ getBytes(b, pos, { bytes: MAX_EVIDENCE_BYTES, what: 'token evidence' }),
345
+ 'token evidence'
346
+ )
347
+ let parsed: unknown
348
+ try {
349
+ parsed = JSON.parse(evidenceText)
350
+ } catch {
351
+ throw new CodecError('token evidence is not JSON')
255
352
  }
256
- token = { assetId, overlayUrl, overlayIdentityKey, certificates, linkage, admissions }
353
+ token = { assetId, amount, senderMode, ...checkEvidence(parsed), certificates }
257
354
  }
258
355
  const note = getStr(b, pos)
259
356
  const transaction = getBytes(b, pos)