@bsv/expo-wallet-toolbox 0.20.0 → 0.22.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 (85) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/directpay/DirectPayManager.ts +148 -29
  11. package/core/directpay/DirectPayProvider.tsx +11 -2
  12. package/core/directpay/payFlow.ts +10 -1
  13. package/core/directpay/settings.ts +56 -9
  14. package/core/directpay/types.ts +11 -2
  15. package/core/directpay/webrtpay.ts +4 -0
  16. package/core/i18n/translations.tsx +185 -84
  17. package/core/index.ts +55 -37
  18. package/core/localpay/build.ts +110 -569
  19. package/core/localpay/codec.ts +190 -93
  20. package/core/localpay/pending.ts +217 -202
  21. package/core/localpay/session.ts +99 -25
  22. package/core/localpay/types.ts +6 -5
  23. package/core/localpay/verify.ts +118 -173
  24. package/core/mandala/abortGuard.ts +97 -120
  25. package/core/mandala/accessPolicy.ts +133 -0
  26. package/core/mandala/assets.ts +370 -0
  27. package/core/mandala/colorGuard.ts +178 -0
  28. package/core/mandala/colorModule.ts +82 -0
  29. package/core/mandala/createRuntime.ts +483 -2392
  30. package/core/mandala/handle.ts +694 -0
  31. package/core/mandala/kvStore.ts +105 -0
  32. package/core/mandala/nearby.ts +185 -0
  33. package/core/mandala/receipt.ts +121 -0
  34. package/core/mandala/runtime.ts +166 -312
  35. package/core/mandala/settle.ts +540 -0
  36. package/core/mandala/transferJournal.ts +395 -0
  37. package/core/mandala/types.ts +61 -311
  38. package/core/networks.ts +5 -5
  39. package/core/offline/cancelParked.ts +80 -63
  40. package/core/offline/payerHold.ts +52 -118
  41. package/core/parsePeerPayURI.ts +25 -12
  42. package/core/pay/rails/direct.ts +6 -2
  43. package/core/pay/rails/handle.ts +15 -14
  44. package/core/pay/rails/index.ts +5 -3
  45. package/core/pay/rails/nearby.ts +25 -87
  46. package/core/profiles/assertProfileEmpty.ts +19 -10
  47. package/core/services/vault/guard.ts +5 -4
  48. package/core/storage/StorageExpoSQLite.ts +93 -229
  49. package/core/storage/methods/processOfflineActions.ts +86 -136
  50. package/core/storage/schema/createTables.ts +9 -184
  51. package/package.json +6 -5
  52. package/ui/components/pay/AssetPicker.tsx +2 -2
  53. package/ui/components/pay/HandleReceive.tsx +10 -4
  54. package/ui/components/pay/NearbyFlow.tsx +324 -239
  55. package/ui/components/pay/RequestHub.tsx +10 -0
  56. package/ui/components/pay/UniversalSend.tsx +31 -28
  57. package/ui/components/pay/useRecipientInput.ts +2 -2
  58. package/ui/components/ui/PermissionSheet.tsx +94 -160
  59. package/ui/components/ui/colorPrompt.ts +236 -0
  60. package/ui/components/wallet/AmountInput.tsx +9 -6
  61. package/ui/components/wallet/AssetAmount.tsx +6 -6
  62. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  63. package/ui/components/wallet/Balance.tsx +3 -1
  64. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  65. package/ui/components/wallet/tokenEviction.ts +9 -9
  66. package/ui/hooks/useMandala.ts +6 -6
  67. package/ui/hooks/useSpendableBalance.ts +3 -1
  68. package/ui/importDatabases.ts +1 -1
  69. package/ui/screens/PayScreen.tsx +14 -20
  70. package/ui/screens/SettingsScreen.tsx +3 -1
  71. package/ui/screens/WalletCheckScreen.tsx +7 -2
  72. package/ui/screens/WalletHomeScreen.tsx +40 -14
  73. package/ui/screens/tokenRowTitle.ts +28 -15
  74. package/ui/tokenFormat.ts +133 -69
  75. package/ui/tokenStatus.ts +5 -8
  76. package/core/localpay/settlementAck.ts +0 -155
  77. package/core/mandala/basketMigration.ts +0 -166
  78. package/core/mandala/bundle.ts +0 -244
  79. package/core/mandala/drain.ts +0 -754
  80. package/core/mandala/inboxPrehold.ts +0 -193
  81. package/core/mandala/permissionModule.ts +0 -931
  82. package/core/mandala/resendTransfer.ts +0 -178
  83. package/core/mandala/settlementStore.ts +0 -434
  84. package/core/mandala/token.ts +0 -45
  85. package/core/offline/tokenFrames.ts +0 -197
@@ -1,155 +0,0 @@
1
- /**
2
- * The settlement ack (offline-settlement spec §4.8, rule 5).
3
- *
4
- * When the recipient's drain gets σ_I for the tip, it tells the payer — so the
5
- * payer's screen can say "settled" instead of "settling", and its own
6
- * reconciliation pass can stop chasing a transaction that is already admitted.
7
- *
8
- * No new channel is introduced. The payload rides the string slot the existing
9
- * confirm channel already has (`confirmFrame(accepted, reason)` →
10
- * `Ack.error`), behind a prefix so it can never be mistaken for a
11
- * `DeclineReason`; over the handle rail it rides the `'mandala-payments'`
12
- * MessageBox instead. Same bytes either way.
13
- *
14
- * FIX H is the whole reason this module has a verification step at all. The
15
- * payload is COUNTERPARTY-SUPPLIED: it arrives from the other device, which
16
- * may be lying, broken, or replaying. So:
17
- *
18
- * · it is verified against THIS session's overlay key before it is allowed
19
- * to mean anything;
20
- * · a payload that fails verification is treated as ABSENT — never as a
21
- * decline, never as proof. The drain then runs its own `postTokenStep` as
22
- * if no ack had arrived, which is exactly what it would do for a payer
23
- * whose counterparty said nothing at all.
24
- *
25
- * That asymmetry is deliberate: a forged ack can only ever cost the payer a
26
- * redundant idempotent `/submit`, whereas treating a forged ack as a decline
27
- * would let any counterparty unwind a payment it had already accepted.
28
- */
29
- import type { AdmissionEntryWire } from '../mandala/types'
30
- import type { Ack } from './types'
31
-
32
- /** Distinguishes a settlement payload from a `DeclineReason` in the same slot. */
33
- export const SETTLEMENT_ACK_PREFIX = 'msa1:'
34
-
35
- /** What the recipient tells the payer once the overlay has admitted the tip. */
36
- export interface SettlementAck {
37
- txid: string
38
- /** Sorted ascending, exactly as the overlay signed them. */
39
- outputsToAdmit: number[]
40
- /** σ_I over `admissionDigestV3(topic, txid, outputsToAdmit)`, DER hex. */
41
- admissionSignature: string
42
- }
43
-
44
- /**
45
- * Verifies one admission entry against the overlay that is supposed to have
46
- * signed it. Injected: the σ_I digest is the overlay's own and lives in
47
- * `@bsv/mandala`, so wallet and overlay cannot disagree about what is signed.
48
- */
49
- export type VerifyAdmissionFn = (entry: AdmissionEntryWire, overlayIdentityKey: string) => boolean | Promise<boolean>
50
-
51
- export function encodeSettlementAck(ack: SettlementAck): string {
52
- return SETTLEMENT_ACK_PREFIX + JSON.stringify(ack)
53
- }
54
-
55
- /**
56
- * Reads a settlement payload out of the confirm channel's string slot.
57
- *
58
- * Returns undefined for anything that is not one — including a plain decline
59
- * code, an empty string, and a payload whose shape is wrong. Never throws: this
60
- * runs on bytes a counterparty chose, on a path where an exception would
61
- * abort a screen that has already taken real money.
62
- */
63
- export function decodeSettlementAck(raw: unknown): SettlementAck | undefined {
64
- if (typeof raw !== 'string' || !raw.startsWith(SETTLEMENT_ACK_PREFIX)) return undefined
65
- let parsed: unknown
66
- try {
67
- parsed = JSON.parse(raw.slice(SETTLEMENT_ACK_PREFIX.length))
68
- } catch {
69
- return undefined
70
- }
71
- if (typeof parsed !== 'object' || parsed === null) return undefined
72
- const { txid, outputsToAdmit, admissionSignature } = parsed as Record<string, unknown>
73
- if (typeof txid !== 'string' || txid.length !== 64 || !/^[0-9a-f]+$/i.test(txid)) return undefined
74
- if (typeof admissionSignature !== 'string' || admissionSignature.length === 0) return undefined
75
- if (admissionSignature.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(admissionSignature)) return undefined
76
- if (!Array.isArray(outputsToAdmit)) return undefined
77
- const outs: number[] = []
78
- for (const v of outputsToAdmit) {
79
- if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) return undefined
80
- outs.push(v)
81
- }
82
- return { txid: txid.toLowerCase(), outputsToAdmit: outs, admissionSignature: admissionSignature.toLowerCase() }
83
- }
84
-
85
- function hexToBytes(hex: string): Uint8Array {
86
- const out = new Uint8Array(hex.length / 2)
87
- for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
88
- return out
89
- }
90
-
91
- /**
92
- * The admission a positive ack carries, IF it carries one that verifies.
93
- *
94
- * Undefined means "no evidence arrived", for every reason there is: a decline,
95
- * an ordinary positive ack with nothing on it, a malformed payload, a payload
96
- * signed by somebody other than this session's overlay, a verifier that said
97
- * no, or a verifier that threw. The caller's next move is the same in all of
98
- * them — let the drain do its own submit — which is why they collapse to one
99
- * value rather than a taxonomy nobody would branch on.
100
- *
101
- * `expectTxid` binds the payload to the transaction actually handed over: an
102
- * ack naming a DIFFERENT txid is somebody else's admission, replayed. It
103
- * verifies perfectly and proves nothing about this payment.
104
- *
105
- * `expectVout` binds it further, to the payee's OWN output on that
106
- * transaction (XR-093): the overlay signs `outputsToAdmit` as a set, so a
107
- * genuine admission of a sibling output on the same tip — the payer's own
108
- * token change, say — verifies just as well as one that actually covers the
109
- * payee's output. Without this check the two are indistinguishable and the
110
- * payer's screen could claim 'sent-settled' for a payment the overlay never
111
- * admitted.
112
- */
113
- export async function readSettlementAck(
114
- ack: Ack,
115
- args: { overlayIdentityKey: string; expectTxid?: string; expectVout: number; verify: VerifyAdmissionFn }
116
- ): Promise<AdmissionEntryWire | undefined> {
117
- if (!ack.ok) return undefined
118
- const payload = decodeSettlementAck(ack.error)
119
- if (!payload) return undefined
120
- if (args.expectTxid !== undefined && payload.txid !== args.expectTxid.toLowerCase()) return undefined
121
- if (!payload.outputsToAdmit.includes(args.expectVout)) return undefined
122
-
123
- const entry: AdmissionEntryWire = {
124
- txid: payload.txid,
125
- outputsToAdmit: payload.outputsToAdmit,
126
- signature: hexToBytes(payload.admissionSignature),
127
- signerKey: args.overlayIdentityKey
128
- }
129
- try {
130
- return (await args.verify(entry, args.overlayIdentityKey)) ? entry : undefined
131
- } catch {
132
- return undefined
133
- }
134
- }
135
-
136
- /**
137
- * What the payer's success screen says after a token hand-over (spec §9 step 7).
138
- *
139
- * Only two states, because guard #1 means a token `finalizeDelivery` ALWAYS
140
- * returns `broadcast: 'pending'` — there is no third, greener outcome it could
141
- * report on its own. The difference is whether a verified σ_I for this
142
- * transaction has come back yet:
143
- *
144
- * 'sent-settling' → "Sent. Settling with {{issuer}} — you'll see it confirm
145
- * once you or {{payee}} reconnect."
146
- * 'sent-settled' → "Sent · settled with {{issuer}}"
147
- *
148
- * Takes the already-VERIFIED admission, not a raw ack, so a screen cannot turn
149
- * green on a payload nobody checked.
150
- */
151
- export type TokenSendState = 'sent-settling' | 'sent-settled'
152
-
153
- export function tokenSendState(admission?: AdmissionEntryWire): TokenSendState {
154
- return admission ? 'sent-settled' : 'sent-settling'
155
- }
@@ -1,166 +0,0 @@
1
- /**
2
- * One-time migration: rename the Mandala token basket from the old,
3
- * un-gated `'mandala-tokens'` to the P-routed `MANDALA_BASKET`
4
- * (`'p mandala'`), per offline-settlement-final.md §8.3.
5
- *
6
- * The basket name is persisted per-output (`outputs.basketId` ->
7
- * `output_baskets.name`), so renaming the constant in code does nothing for
8
- * a device that already holds tokens under the old name — this migration
9
- * moves those rows. Guarded by a `key_value_store` marker (the app's
10
- * existing one-time-migration doctrine, see `ensureOfflineActionsColumns`
11
- * for the DDL-migration precedent this mirrors for a data migration):
12
- *
13
- * - idempotent: once the marker is set, the full (every-user) scan is a
14
- * no-op read.
15
- * - a no-op when zero rows carry the old basket name (marks done, moves
16
- * nothing).
17
- * - running it twice never double-moves: the marker short-circuits the
18
- * second full scan entirely, and even without the marker a second pass
19
- * would find zero outputs left under the old basket id (the UPDATE's own
20
- * WHERE clause naturally re-converges).
21
- *
22
- * "No live builds exist" today (design-v3's Compatibility section), so this
23
- * has zero live rows to move at ship time — it exists so a later device that
24
- * *does* hold old-named rows is never left behind.
25
- *
26
- * Adversarial-review finding (6): the marker alone is not enough. It marks
27
- * "the full, every-user scan has run on this device", but a BACKUP RESTORE
28
- * can reintroduce old-named rows for the device's CURRENT user well after
29
- * that scan already ran and set the marker (e.g. restoring an older
30
- * snapshot, or a snapshot from before this rename shipped) — the early
31
- * return on a set marker would then skip that user's rows forever. Callers
32
- * that know the current user id should therefore also pass it as
33
- * `currentUserId`: a cheap, single-user WHERE-based move runs EVERY call
34
- * regardless of the marker, bounded to just that user's old-basket rows (not
35
- * a full-table scan), so it is safe to call on every boot. Passing no
36
- * `currentUserId` reproduces the exact pre-finding-6 behavior (full scan,
37
- * marker-guarded, nothing else) — every existing caller/test is unaffected.
38
- */
39
- import { MANDALA_BASKET } from './types'
40
-
41
- /** Old, un-gated basket name this migration moves outputs off of. */
42
- export const OLD_MANDALA_BASKET_NAME = 'mandala-tokens'
43
-
44
- /** key_value_store marker key — presence with value 'done' means "never run again". */
45
- const MIGRATION_MARKER_KEY = 'mandala_basket_migration_v1'
46
- const MIGRATION_DONE_VALUE = 'done'
47
-
48
- /** The slice of TableOutputBasket this migration reads. */
49
- export interface MigrationOutputBasket {
50
- basketId: number
51
- userId: number
52
- isDeleted?: boolean
53
- }
54
-
55
- /** The slice of TableOutput this migration reads. */
56
- export interface MigrationOutput {
57
- outputId: number
58
- }
59
-
60
- /**
61
- * The slice of `StorageExpoSQLite` this migration needs. Structural, so the
62
- * real provider and a lightweight test double both satisfy it — same pattern
63
- * as `core/storage/methods/walletBalanceSql.ts`'s `BalanceStorage`.
64
- */
65
- export interface BasketMigrationStorage {
66
- getKeyValue(key: string): Promise<string | undefined>
67
- setKeyValue(key: string, value: string): Promise<void>
68
- findOutputBaskets(args: { partial: { name: string; userId?: number } }): Promise<MigrationOutputBasket[]>
69
- /** Finds-or-creates (and un-deletes) the destination basket for one user. */
70
- findOrInsertOutputBasket(userId: number, name: string): Promise<{ basketId: number }>
71
- findOutputs(args: { partial: { basketId: number } }): Promise<MigrationOutput[]>
72
- updateOutput(id: number, update: { basketId: number }): Promise<number>
73
- }
74
-
75
- export interface BasketMigrationResult {
76
- /** false when the full scan's marker already showed it had run AND the
77
- * (optional) single-user pass moved nothing — i.e. nothing was touched. */
78
- ran: boolean
79
- /** Baskets (i.e. distinct userIds) that had at least one output moved. */
80
- basketsMigrated: number
81
- /** Total output rows moved from the old basket to MANDALA_BASKET. */
82
- movedOutputs: number
83
- }
84
-
85
- /**
86
- * Moves every output out of one old-named basket into (a find-or-inserted)
87
- * `MANDALA_BASKET` for that basket's owner. Shared by both the full,
88
- * every-user scan and the cheap, single-user pass below — the only
89
- * difference between them is which old baskets they are given to move.
90
- */
91
- async function moveBasketOutputs(
92
- storage: BasketMigrationStorage,
93
- oldBasket: MigrationOutputBasket
94
- ): Promise<{ movedOutputs: number }> {
95
- if (oldBasket.isDeleted) return { movedOutputs: 0 }
96
-
97
- const outputs = await storage.findOutputs({ partial: { basketId: oldBasket.basketId } })
98
- if (outputs.length === 0) return { movedOutputs: 0 }
99
-
100
- const newBasket = await storage.findOrInsertOutputBasket(oldBasket.userId, MANDALA_BASKET)
101
- for (const output of outputs) {
102
- await storage.updateOutput(output.outputId, { basketId: newBasket.basketId })
103
- }
104
-
105
- return { movedOutputs: outputs.length }
106
- }
107
-
108
- /**
109
- * Runs the migration. Safe to call on every boot — see the idempotency notes
110
- * above.
111
- *
112
- * `currentUserId`, when given, additionally runs the cheap single-user pass
113
- * (finding 6) on EVERY call, independent of the marker — pass the device's
114
- * currently-authenticated user id here so a restored backup's old-named rows
115
- * for that user are always caught, not just on the one device/boot where the
116
- * full scan happened to run. Omit it to get exactly the original,
117
- * marker-only behavior.
118
- */
119
- export async function migrateMandalaBasketName(
120
- storage: BasketMigrationStorage,
121
- currentUserId?: number
122
- ): Promise<BasketMigrationResult> {
123
- const marker = await storage.getKeyValue(MIGRATION_MARKER_KEY)
124
- const fullScanAlreadyRan = marker === MIGRATION_DONE_VALUE
125
-
126
- let basketsMigrated = 0
127
- let movedOutputs = 0
128
-
129
- if (!fullScanAlreadyRan) {
130
- const oldBaskets = await storage.findOutputBaskets({ partial: { name: OLD_MANDALA_BASKET_NAME } })
131
- for (const oldBasket of oldBaskets) {
132
- const moved = await moveBasketOutputs(storage, oldBasket)
133
- if (moved.movedOutputs > 0) {
134
- basketsMigrated += 1
135
- movedOutputs += moved.movedOutputs
136
- }
137
- }
138
-
139
- // Marked done even when zero rows moved: the point of the marker is
140
- // "never run the FULL scan again on this device", not "ran and found
141
- // work" — see the no-op contract in the file doc above. The cheap
142
- // single-user pass below is unaffected by this marker either way.
143
- await storage.setKeyValue(MIGRATION_MARKER_KEY, MIGRATION_DONE_VALUE)
144
- }
145
-
146
- if (typeof currentUserId === 'number') {
147
- // Cheap, single-user WHERE-based move — bounded to this one user's
148
- // old-basket rows (never a full-table scan), so it is safe to run every
149
- // boot regardless of the marker above. If the full scan above already
150
- // covered this same user in this same call, this finds zero rows left
151
- // and is a harmless no-op (the same re-convergence property the file
152
- // doc describes for a marker-less rerun).
153
- const oldBaskets = await storage.findOutputBaskets({
154
- partial: { name: OLD_MANDALA_BASKET_NAME, userId: currentUserId }
155
- })
156
- for (const oldBasket of oldBaskets) {
157
- const moved = await moveBasketOutputs(storage, oldBasket)
158
- if (moved.movedOutputs > 0) {
159
- basketsMigrated += 1
160
- movedOutputs += moved.movedOutputs
161
- }
162
- }
163
- }
164
-
165
- return { ran: !fullScanAlreadyRan || movedOutputs > 0, basketsMigrated, movedOutputs }
166
- }
@@ -1,244 +0,0 @@
1
- /**
2
- * The AdmissionBundle: the evidence a token payment carries with it.
3
- *
4
- * Offline settlement turns on one question the recipient must answer with no
5
- * network: *is every token ancestor of this transaction either already
6
- * admitted by the issuer's overlay, or present in bytes I can walk further?*
7
- * The bundle is what makes that question answerable — σ_I signatures for the
8
- * ancestors that bottom out, linkage payloads for the ones that do not (so
9
- * whoever reconnects first can submit them), and the tip's own AtomicBEEF for
10
- * everything in between.
11
- *
12
- * Two halves live here, and they are deliberately separate:
13
- *
14
- * · `assembleBundle` — the PAYER's side. Walks the transaction it just built
15
- * and collects, from this device's own settlement tables, the evidence the
16
- * recipient will need. Storage-facing, async, and best-effort: it never
17
- * decides whether the result is sufficient.
18
- *
19
- * · `coverFromFrame` — the PAYEE's side. Rebuilds an in-memory bundle from a
20
- * decoded frame and hands it to an injected pure verifier. The verdict is
21
- * the verifier's, never this module's.
22
- *
23
- * The COVER walk itself (spec §1.2) is pure and belongs in `@bsv/mandala`,
24
- * where the overlay's own σ_I digest lives beside it — one implementation, one
25
- * set of test vectors, no chance of the wallet and the overlay disagreeing
26
- * about what a signature covers. This package does not depend on it yet, so
27
- * the verifier is INJECTED and its types are declared here to match
28
- * `CoverResult` in `./types`. When the dependency lands, the injection site
29
- * becomes a one-line import and nothing else here changes.
30
- */
31
- import { Beef, Transaction } from '@bsv/sdk'
32
- import { MandalaToken } from './token'
33
- import type { PaymentFrame } from '../localpay/codec'
34
- import type { AdmissionEntryWire, CoverResult, SettlementStore } from './types'
35
-
36
- export { MANDALA_ACTION_LABEL, MANDALA_BASKET } from './types'
37
-
38
- /**
39
- * The read side of the settlement store this walk needs.
40
- *
41
- * Narrowed from `SettlementStore` on purpose: the walk reads cached evidence
42
- * and writes nothing, and a builder holding the full store could advance a
43
- * settlement row halfway through assembling a frame.
44
- */
45
- export type BundleStore = Pick<SettlementStore, 'getAdmission' | 'getLinkage'>
46
-
47
- /** The evidence a payer collected for one tip, ready to go onto the wire. */
48
- export interface AdmissionBundle {
49
- tipTxid: string
50
- assetId: string
51
- overlayIdentityKey: string
52
- /** Frontier ancestors: unadmitted, so somebody must still submit them. */
53
- linkage: Array<{ txid: string; payload: Uint8Array }>
54
- /** Bottoms: ancestors this device holds the overlay's own σ_I for. */
55
- admissions: AdmissionEntryWire[]
56
- }
57
-
58
- /** The tip the verifier is asked about. */
59
- export interface CoverTip {
60
- txid: string
61
- tx: Transaction
62
- }
63
-
64
- /**
65
- * Everything the pure COVER walk reads, as maps — the in-memory shape of
66
- * §1.1's AdmissionBundle. Mirrors `@bsv/mandala`'s own input type; declared
67
- * locally only until this package depends on it.
68
- */
69
- export interface CoverBundle {
70
- assetId: string
71
- overlayIdentityKey: string
72
- /** Every transaction carried in the tip's AtomicBEEF, keyed by txid. */
73
- beef: Map<string, Transaction>
74
- linkage: Map<string, Uint8Array>
75
- admissions: Map<string, AdmissionEntryWire>
76
- }
77
-
78
- /** The injected pure verifier: `cover(tip, bundle)` (spec §1.2). */
79
- export type CoverVerifier = (tip: CoverTip, bundle: CoverBundle) => CoverResult | Promise<CoverResult>
80
-
81
- /**
82
- * The token inputs of `tx` for `assetId` — FIX K.
83
- *
84
- * Only inputs whose SOURCE OUTPUT decodes as a MandalaToken of this asset
85
- * count. A fresh unconfirmed BSV output funding the fee is not a token
86
- * ancestor: the payer's own change routinely funds the next offline payment
87
- * (`allocateChangeInput` accepts `unproven`), and a walk that treated it as an
88
- * ancestor with no σ_I would refuse the single most ordinary case there is.
89
- * It is an ordinary broadcast-only parent, handled by the release engine.
90
- *
91
- * Returns the parent transactions, deduplicated by txid — a transaction with
92
- * two inputs from the same parent is one ancestor, not two.
93
- */
94
- export function tokenParentsOf(tx: Transaction, assetId: string): Transaction[] {
95
- const seen = new Set<string>()
96
- const parents: Transaction[] = []
97
- for (const input of tx.inputs) {
98
- const source = input.sourceTransaction
99
- if (!source) continue // txid-only ancestor: a hole for COVER, nothing to walk here
100
- const output = source.outputs[input.sourceOutputIndex]
101
- if (!output?.lockingScript) continue
102
- let decoded: { assetId: string }
103
- try {
104
- decoded = MandalaToken.decode(output.lockingScript)
105
- } catch {
106
- continue // not a token script — a fee parent, per FIX K
107
- }
108
- if (decoded.assetId !== assetId) continue // another issuer's coin riding along
109
- const txid = source.id('hex')
110
- if (seen.has(txid)) continue
111
- seen.add(txid)
112
- parents.push(source)
113
- }
114
- return parents
115
- }
116
-
117
- function hexToBytes(hex: string): Uint8Array {
118
- const clean = hex.length % 2 === 0 ? hex : ''
119
- const out = new Uint8Array(clean.length / 2)
120
- for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16) || 0
121
- return out
122
- }
123
-
124
- /**
125
- * Collects the evidence for `tipTx`'s token ancestry (spec §1.1).
126
- *
127
- * One decision per ancestor, and it is the whole algorithm:
128
- *
129
- * · a cached admission signed by THIS session's overlay is a BOTTOM — emit an
130
- * admissions entry and stop. The recipient can verify it offline and will
131
- * never need to submit that transaction, so forwarding its linkage would be
132
- * dead weight on the wire.
133
- * · anything else is a FRONTIER — emit the stored linkage payload if this
134
- * device holds one, then walk that ancestor's OWN token inputs. Forwarding
135
- * linkage verbatim hop by hop is what lets whoever reconnects first settle
136
- * a whole chain of offline hands.
137
- *
138
- * An admission signed by any other key is treated as ABSENT, not as a
139
- * refusal (FIX H): it is not evidence for this overlay, and the ancestor is
140
- * walked exactly as if the cache had been empty.
141
- *
142
- * A frontier this device holds no linkage for still emits nothing and is still
143
- * walked. That is not a silent failure — the recipient's own COVER decides
144
- * whether what arrived is sufficient, and inventing a payload here would put a
145
- * guess where the overlay expects exact bytes.
146
- *
147
- * The tip's own linkage is NOT collected: the payer mints it as part of
148
- * building the transfer and adds it at the call site, because only the builder
149
- * knows which outputs it just created.
150
- */
151
- export async function assembleBundle(args: {
152
- tipTx: Transaction
153
- assetId: string
154
- overlayIdentityKey: string
155
- store: BundleStore
156
- }): Promise<AdmissionBundle> {
157
- const { tipTx, assetId, overlayIdentityKey, store } = args
158
- const linkage: Array<{ txid: string; payload: Uint8Array }> = []
159
- const admissions: AdmissionEntryWire[] = []
160
- const visited = new Set<string>()
161
-
162
- // Iterative, not recursive: a hostile or merely deep BEEF must not be able to
163
- // blow the JS stack on a device. Termination is structural — a txid is the
164
- // hash of its own bytes, so the spend graph is acyclic — and `visited` bounds
165
- // the work at one expansion per distinct transaction regardless.
166
- const queue: Transaction[] = [tipTx]
167
- while (queue.length > 0) {
168
- const tx = queue.shift() as Transaction
169
- for (const parent of tokenParentsOf(tx, assetId)) {
170
- const txid = parent.id('hex')
171
- if (visited.has(txid)) continue
172
- visited.add(txid)
173
-
174
- const cached = await store.getAdmission(txid)
175
- if (cached && cached.signerKey === overlayIdentityKey) {
176
- admissions.push({
177
- txid,
178
- outputsToAdmit: [...cached.outputsToAdmit],
179
- signature: hexToBytes(cached.signatureHex),
180
- signerKey: cached.signerKey
181
- })
182
- continue
183
- }
184
-
185
- const stored = await store.getLinkage(txid)
186
- if (stored && stored.payloadBytes.length > 0) linkage.push({ txid, payload: new Uint8Array(stored.payloadBytes) })
187
- queue.push(parent)
188
- }
189
- }
190
-
191
- return { tipTxid: tipTx.id('hex'), assetId, overlayIdentityKey, linkage, admissions }
192
- }
193
-
194
- /**
195
- * Runs COVER for a delivered frame.
196
- *
197
- * A thin adapter, on purpose: it turns the frame's wire arrays into the maps
198
- * the pure walk reads, and makes exactly no judgement of its own about whether
199
- * the evidence is sufficient. Every verdict below that is not the verifier's
200
- * own is a SHAPE refusal — there was nothing coherent to ask about:
201
- *
202
- * · not a token frame, or a token frame with no token block;
203
- * · transaction bytes that are not readable AtomicBEEF;
204
- * · a verifier that threw. The verifier is injected and may be a third
205
- * party's; an exception escaping into the settle path would abort a credit
206
- * somewhere between "refused" and "accepted", which is the one outcome a
207
- * money path may never have.
208
- */
209
- export async function coverFromFrame(frame: PaymentFrame, cover: CoverVerifier): Promise<CoverResult> {
210
- if (frame.kind !== 'token' || !frame.token) return { ok: false, reason: 'shape' }
211
-
212
- let beef: Beef
213
- let tipTxid: string
214
- try {
215
- beef = Beef.fromBinary(Array.from(frame.transaction))
216
- const atomic = beef.atomicTxid
217
- const tx = Transaction.fromAtomicBEEF(Array.from(frame.transaction))
218
- tipTxid = atomic ?? tx.id('hex')
219
- } catch {
220
- return { ok: false, reason: 'shape' }
221
- }
222
-
223
- const txs = new Map<string, Transaction>()
224
- for (const btx of beef.txs) {
225
- const tx = btx.tx
226
- if (tx) txs.set(btx.txid, tx)
227
- }
228
- const tip = txs.get(tipTxid)
229
- if (!tip) return { ok: false, reason: 'shape' }
230
-
231
- const bundle: CoverBundle = {
232
- assetId: frame.token.assetId,
233
- overlayIdentityKey: frame.token.overlayIdentityKey,
234
- beef: txs,
235
- linkage: new Map(frame.token.linkage.map(l => [l.txid, l.payload])),
236
- admissions: new Map(frame.token.admissions.map(a => [a.txid, a]))
237
- }
238
-
239
- try {
240
- return await cover({ txid: tipTxid, tx: tip }, bundle)
241
- } catch {
242
- return { ok: false, reason: 'shape' }
243
- }
244
- }