@qntx/wallet-engine 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/idb.d.mts +28 -0
- package/dist/idb.mjs +134 -0
- package/dist/idb.mjs.map +1 -0
- package/dist/index.d.mts +758 -0
- package/dist/index.mjs +3420 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +68 -4
- package/README.md +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["NAME_MAX","isNonNegativeInt","KNOWN_GROUP_KEYS","KNOWN_WALLET_KEYS","PUBKEY_RE","isObject","isObject","runPay"],"sources":["../src/controller.ts","../src/events.ts","../src/errors.ts","../src/store/guard.ts","../src/store/memory.ts","../src/accounts/errors.ts","../src/accounts/controller.ts","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../src/backup/errors.ts","../src/backup/controller.ts","../src/meta/doc.ts","../src/meta/errors.ts","../src/meta/controller.ts","../src/payments/parse.ts","../src/spark/errors.ts","../src/payments/errors.ts","../src/payments/pay.ts","../src/payments/resolve.ts","../src/payments/zap.ts","../src/spark/notes.ts","../src/spark/exit-chain-codec.ts","../src/spark/store.ts","../src/spark/controller.ts","../src/engine.ts","../src/backup/memory.ts"],"sourcesContent":["import { createStore } from \"zustand/vanilla\";\nimport type { StoreApi } from \"zustand/vanilla\";\n\nexport type ControllerOptions<S> = {\n readonly name: string;\n readonly defaultState: () => S;\n};\n\n/**\n * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must\n * return a NEW state object; returning the same reference is a no-op (no set, no notification).\n * Persistence and migrations layer on later — this package carries only what its first user needs.\n */\nexport abstract class Controller<S extends Record<string, unknown>> {\n readonly name: string;\n readonly store: StoreApi<S>;\n\n protected constructor(options: ControllerOptions<S>) {\n this.name = options.name;\n this.store = createStore<S>(options.defaultState);\n }\n\n getState(): S {\n return this.store.getState();\n }\n\n protected update(recipe: (state: S) => S): void {\n this.store.setState((state) => recipe(state));\n }\n\n abstract init(): Promise<void>;\n abstract destroy(): Promise<void>;\n}\n","/** Log port: listener failures are reported here and never reach the emitter or peers. */\nexport type EngineLogger = {\n readonly warn: (message: string, error?: unknown) => void;\n};\n\nexport type EventBus<E> = {\n /** Synchronous dispatch to every current listener in registration order. */\n emit: <K extends keyof E>(type: K, payload: E[K]) => void;\n on: <K extends keyof E>(type: K, listener: (payload: E[K]) => void) => () => void;\n};\n\nexport function createEventBus<E>(logger: EngineLogger): EventBus<E> {\n const listeners = new Map<keyof E, Set<(payload: unknown) => void>>();\n return {\n emit<K extends keyof E>(type: K, payload: E[K]): void {\n const set = listeners.get(type);\n if (set === undefined) {\n return;\n }\n for (const listener of set) {\n try {\n listener(payload);\n } catch (error) {\n logger.warn(\"event listener threw\", error);\n }\n }\n },\n on<K extends keyof E>(type: K, listener: (payload: E[K]) => void): () => void {\n let set = listeners.get(type);\n if (set === undefined) {\n set = new Set();\n listeners.set(type, set);\n }\n // The set is keyed by event type, so each listener only ever receives its own payload.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const stored = listener as (payload: unknown) => void;\n set.add(stored);\n return () => {\n set.delete(stored);\n };\n },\n };\n}\n","export type EngineErrorCode = \"closed\" | \"integrity\" | \"invalid-input\";\n\n/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */\nexport class EngineStoreError extends Error {\n readonly code: EngineErrorCode;\n\n constructor(code: EngineErrorCode, message: string) {\n super(message);\n this.name = \"EngineStoreError\";\n this.code = code;\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\n\n/** NUL is the composite-key/AAD separator — a name or key containing it collides. */\nexport function checkName(kind: \"collection\" | \"key\", value: string): void {\n if (value.includes(\"\\u0000\")) {\n throw new EngineStoreError(\"invalid-input\", `${kind} must not contain NUL`);\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\nimport { checkName } from \"./guard.ts\";\nimport type { EngineCollection, EngineStore } from \"./port.ts\";\n\n/** In-memory EngineStore: the Node/test implementation — same contract, no durability. */\nexport function createMemoryEngineStore(backing?: {\n readonly collections?: Map<string, Map<string, Uint8Array>>;\n}): EngineStore {\n const collections = backing?.collections ?? new Map<string, Map<string, Uint8Array>>();\n let closed = false;\n const guard = (): void => {\n if (closed) {\n throw new EngineStoreError(\"closed\", \"engine store is closed\");\n }\n };\n return {\n collection(name: string): EngineCollection {\n checkName(\"collection\", name);\n let table = collections.get(name);\n if (table === undefined) {\n table = new Map();\n collections.set(name, table);\n }\n return {\n get: async (key) => {\n guard();\n checkName(\"key\", key);\n const value = table.get(key);\n return value === undefined ? undefined : new Uint8Array(value);\n },\n put: async (key, bytes) => {\n guard();\n checkName(\"key\", key);\n table.set(key, new Uint8Array(bytes));\n },\n delete: async (key) => {\n guard();\n checkName(\"key\", key);\n table.delete(key);\n },\n list: async () => {\n guard();\n return [...table.keys()];\n },\n };\n },\n close: async () => {\n closed = true;\n collections.clear();\n },\n };\n}\n","/** Account-tree error categories — messages never carry secrets. */\nexport type AccountTreeErrorCategory = \"invalid-input\" | \"rejected\" | \"not-found\" | \"locked\";\n\nexport class AccountTreeError extends Error {\n readonly category: AccountTreeErrorCategory;\n\n constructor(category: AccountTreeErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"AccountTreeError\";\n this.category = category;\n }\n}\n","import type { SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { MetaDoc, MetaDocGroup } from \"../meta/doc.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\nimport { AccountTreeError } from \"./errors.ts\";\n\nexport type AccountGroup = {\n readonly walletId: string;\n readonly index: number;\n readonly name?: string;\n readonly hidden: boolean;\n /** A social identity (64 lowercase hex) bound to this group; one identity binds one group. */\n readonly boundPubkey?: string;\n /** Last local modification time (ms); reconcile-created entries start at 0. */\n readonly updatedAt: number;\n};\n\nexport type AccountTreeState = {\n readonly status: \"locked\" | \"ready\";\n readonly wallets: ReadonlyArray<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }>;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- spec shape: no wallets → null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\nexport type AccountTreeControllerOptions = {\n readonly wallet: Wallet;\n readonly spark: SparkController;\n readonly sparkNetwork: SparkNetwork;\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\ntype PersistedTree = {\n readonly wallets: Readonly<\n Record<string, { readonly name?: string; readonly updatedAt: number }>\n >;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: selected may be null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\nconst EMPTY_TREE: PersistedTree = { wallets: {}, groups: {}, selected: null, totals: {} };\n\nconst TOTAL_KEY = (walletId: string, index: number): string => `${walletId}:${index}`;\n\nconst withoutBinding = (g: AccountGroup): AccountGroup => {\n const { boundPubkey: _removed, ...rest } = g;\n void _removed;\n return rest;\n};\n\nconst NAME_MAX = 24;\nconst TOTALS_DEBOUNCE_MS = 1000;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst own = (o: Record<string, unknown>, k: string): boolean => Object.hasOwn(o, k);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nfunction validateName(v: unknown): string | undefined {\n if (v === undefined) {\n return undefined;\n }\n if (typeof v !== \"string\") {\n return undefined;\n }\n const name = v.trim();\n return name.length > 0 && name.length <= NAME_MAX ? name : undefined;\n}\n\nconst KNOWN_GROUP_KEYS = new Set([\n \"walletId\",\n \"index\",\n \"name\",\n \"hidden\",\n \"boundPubkey\",\n \"updatedAt\",\n]);\nconst KNOWN_TOP_KEYS = new Set([\"wallets\", \"groups\", \"selected\", \"totals\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_SELECTED_KEYS = new Set([\"walletId\", \"groupIndex\"]);\n\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\n\n/** Strict decode — any malformed shape or unknown key returns `undefined`. */\nfunction decodeTree(bytes: Uint8Array): PersistedTree | undefined {\n try {\n const text = new TextDecoder().decode(bytes);\n const raw: unknown = JSON.parse(text);\n if (!isPlainObject(raw)) {\n return undefined;\n }\n for (const k of Object.keys(raw)) {\n if (!KNOWN_TOP_KEYS.has(k)) {\n return undefined;\n }\n }\n const rawWallets = raw[\"wallets\"];\n const rawGroups = raw[\"groups\"];\n const rawSelected = raw[\"selected\"];\n const rawTotals = raw[\"totals\"];\n if (!isPlainObject(rawWallets) || !isPlainObject(rawGroups) || !isPlainObject(rawTotals)) {\n return undefined;\n }\n const wallets: Record<string, { name?: string; updatedAt: number }> = {};\n for (const [walletId, w] of Object.entries(rawWallets)) {\n if (!isPlainObject(w) || walletId.length === 0) {\n return undefined;\n }\n for (const k of Object.keys(w)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n const name = validateName(w[\"name\"]);\n if (w[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = w;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n wallets[walletId] = { updatedAt, ...(name === undefined ? {} : { name }) };\n }\n const groups: Record<string, AccountGroup[]> = {};\n for (const [walletId, arr] of Object.entries(rawGroups)) {\n if (!Array.isArray(arr)) {\n return undefined;\n }\n const seen = new Set<number>();\n const list: AccountGroup[] = [];\n for (const item of arr) {\n if (!isPlainObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n if (item[\"walletId\"] !== walletId || !isNonNegativeInt(item[\"index\"])) {\n return undefined;\n }\n const { index } = item;\n if (seen.has(index) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n seen.add(index);\n const name = validateName(item[\"name\"]);\n if (item[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = item;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n list.push({\n walletId,\n index,\n hidden: item[\"hidden\"],\n updatedAt,\n ...(name === undefined ? {} : { name }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n list.sort((a, b) => a.index - b.index);\n groups[walletId] = list;\n }\n let selected: PersistedTree[\"selected\"] = null;\n if (rawSelected !== undefined && rawSelected !== null) {\n if (!isPlainObject(rawSelected)) {\n return undefined;\n }\n for (const k of Object.keys(rawSelected)) {\n if (!KNOWN_SELECTED_KEYS.has(k)) {\n return undefined;\n }\n }\n const { walletId } = rawSelected;\n const { groupIndex } = rawSelected;\n if (typeof walletId !== \"string\" || walletId.length === 0 || !isNonNegativeInt(groupIndex)) {\n return undefined;\n }\n selected = { walletId, groupIndex };\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(rawTotals)) {\n if (!own(rawTotals, k) || !isNonNegativeInt(v)) {\n return undefined;\n }\n totals[k] = v;\n }\n return { wallets, groups, selected, totals };\n } catch {\n return undefined;\n }\n}\n\nfunction encodeTree(tree: PersistedTree): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(tree));\n}\n\n/**\n * Declarative account tree: wallets come from the Wallet snapshot (reconciled on unlock and on\n * every snapshot change while unlocked), groups/names/hidden/selected/totals persist to the engine\n * store under `accounts/tree`. The controller drives `spark.setAccounts` with the selected group\n * only — an unselected group needs no live client (incoming transfers are claimed whenever it is\n * selected again). The active account's `balanceSats` feeds `totals`, debounced 1 s before\n * persist.\n */\nexport class AccountTreeController extends Controller<AccountTreeState> {\n private readonly options: AccountTreeControllerOptions;\n private col: EngineCollection | undefined;\n private sparkUnsubscribe: (() => void) | undefined;\n private totalsTimer: ReturnType<typeof setTimeout> | undefined;\n private persistChain: Promise<void> = Promise.resolve();\n\n constructor(options: AccountTreeControllerOptions) {\n super({\n name: \"accounts\",\n defaultState: () => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }),\n });\n this.options = options;\n }\n\n setStore(store: EngineStore | undefined): void {\n this.col = store === undefined ? undefined : store.collection(\"accounts\");\n }\n\n /** Load persisted state, reconcile with the snapshot, start driving Spark. */\n async init(): Promise<void> {\n const persisted = await this.load();\n this.update(() => ({ status: \"ready\", ...persistedToState(persisted) }));\n this.reconcile();\n // First drive: the reconciled selection always starts a client for it.\n this.driveSpark(this.getState().selected);\n this.sparkUnsubscribe = this.options.spark.store.subscribe((state) => {\n this.onSparkState(state.accounts);\n });\n }\n\n async destroy(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n await this.lock();\n }\n\n /** Locked: stop every Spark client, flush pending persists, then drop to the empty state. */\n async lock(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n this.options.spark.setAccounts([]);\n // Flush while the real state is still visible — updating first would persist empties over\n // names, groups, hidden flags and the selection.\n await this.flushTotals();\n this.col = undefined;\n this.update(() => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }));\n await Promise.resolve();\n }\n\n /** Reconcile groups/names/selected with `wallet.getSnapshot().wallets`; persists on change. */\n reconcile(): void {\n if (this.getState().status !== \"ready\") {\n return;\n }\n const snapshot = this.options.wallet.getSnapshot();\n const live = snapshot.wallets.map((w) => w.walletId);\n const liveSet = new Set(live);\n const state = this.getState();\n const entriesById = new Map(state.wallets.map((w) => [w.walletId, w]));\n const wallets = live.map((walletId) => {\n const existing = entriesById.get(walletId);\n return existing ?? { walletId, updatedAt: 0 };\n });\n const groups: Record<string, ReadonlyArray<AccountGroup>> = {};\n for (const walletId of live) {\n const existing = state.groups[walletId] ?? [];\n groups[walletId] =\n existing.length > 0 ? existing : [{ walletId, index: 0, hidden: false, updatedAt: 0 }];\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(state.totals)) {\n const walletId = k.slice(0, Math.max(0, k.lastIndexOf(\":\")));\n if (liveSet.has(walletId)) {\n totals[k] = v;\n }\n }\n const selected = this.validSelection(groups, live, state.selected);\n const changed =\n JSON.stringify(wallets) !== JSON.stringify(state.wallets) ||\n JSON.stringify(groups) !== JSON.stringify(state.groups) ||\n JSON.stringify(totals) !== JSON.stringify(state.totals) ||\n JSON.stringify(selected) !== JSON.stringify(state.selected);\n if (changed) {\n this.update((s) => ({ ...s, wallets, groups, totals, selected }));\n this.persist();\n // Drive only on effective change — an unchanged reconcile must not stomp a caller-set\n // setAccounts (e.g. tests running two accounts at once).\n this.driveSpark(selected);\n }\n }\n\n addGroup(walletId: string): number {\n this.mustWallet(walletId);\n const groups = this.getState().groups[walletId] ?? [];\n let index = 0;\n for (const g of groups) {\n index = Math.max(index, g.index + 1);\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) => [...list, { walletId, index, hidden: false, updatedAt }]);\n return index;\n }\n\n addGroups(walletId: string, indices: ReadonlyArray<number>): void {\n this.mustWallet(walletId);\n this.mutateGroups(walletId, (list) => {\n const have = new Set(list.map((g) => g.index));\n const added: AccountGroup[] = [];\n const updatedAt = this.options.now();\n for (const i of indices) {\n if (Number.isSafeInteger(i) && i >= 0 && !have.has(i)) {\n have.add(i);\n added.push({ walletId, index: i, hidden: false, updatedAt });\n }\n }\n return [...list, ...added].sort((a, b) => a.index - b.index);\n });\n }\n\n renameWallet(walletId: string, name: string): void {\n this.mustWallet(walletId);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n wallets: s.wallets.map((w) =>\n w.walletId === walletId ? { walletId, name: trimmed, updatedAt } : w,\n ),\n }));\n this.persist();\n }\n\n renameGroup(walletId: string, index: number, name: string): void {\n this.mustGroup(walletId, index);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, name: trimmed, updatedAt } : g)),\n );\n }\n\n setHidden(walletId: string, index: number, hidden: boolean): void {\n const state = this.getState();\n this.mustGroup(walletId, index);\n const visible = this.visibleGroups(state).filter(\n (g) => !(g.walletId === walletId && g.index === index),\n );\n if (hidden && visible.length === 0) {\n throw new AccountTreeError(\"rejected\", \"cannot hide every account group\");\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, hidden, updatedAt } : g)),\n );\n const sel = state.selected;\n if (sel !== null && sel.walletId === walletId && sel.groupIndex === index && hidden) {\n this.selectFallback();\n }\n }\n\n select(walletId: string, index: number): void {\n const state = this.getState();\n const group = (state.groups[walletId] ?? []).find((g) => g.index === index);\n if (group === undefined) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n if (group.hidden) {\n throw new AccountTreeError(\"rejected\", \"cannot select a hidden account group\");\n }\n if (state.selected?.walletId === walletId && state.selected.groupIndex === index) {\n return;\n }\n this.update((s) => ({ ...s, selected: { walletId, groupIndex: index } }));\n this.persist();\n this.driveSpark(this.getState().selected);\n }\n\n /**\n * Binds a social identity to one group. The identity is unique across the whole tree — every\n * group in every wallet carrying it loses the binding (each entry re-stamped).\n */\n bind(walletId: string, index: number, pubkey: string): void {\n this.mustGroup(walletId, index);\n if (!PUBKEY_RE.test(pubkey)) {\n throw new AccountTreeError(\"invalid-input\", \"boundPubkey must be 64 lowercase hex\");\n }\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n groups: Object.fromEntries(\n Object.entries(s.groups).map(([wid, list]) => [\n wid,\n list.map((g) => {\n if (wid === walletId && g.index === index) {\n return { ...g, boundPubkey: pubkey, updatedAt };\n }\n if (g.boundPubkey === pubkey) {\n return { ...withoutBinding(g), updatedAt };\n }\n return g;\n }),\n ]),\n ),\n }));\n this.persist();\n }\n\n unbind(walletId: string, index: number): void {\n this.mustGroup(walletId, index);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...withoutBinding(g), updatedAt } : g)),\n );\n }\n\n /**\n * Which group currently holds a pubkey — merges can leave the same identity on groups in two\n * wallets; the newest `updatedAt` wins, ties resolve by snapshot wallet order then lower index.\n */\n bindingOf(pubkey: string): { walletId: string; groupIndex: number } | undefined {\n const s = this.getState();\n let best:\n | { walletId: string; groupIndex: number; updatedAt: number; walletPos: number }\n | undefined;\n let walletPos = -1;\n for (const w of s.wallets) {\n walletPos += 1;\n for (const g of s.groups[w.walletId] ?? []) {\n if (g.boundPubkey !== pubkey) {\n continue;\n }\n if (\n best === undefined ||\n g.updatedAt > best.updatedAt ||\n (g.updatedAt === best.updatedAt &&\n (walletPos < best.walletPos ||\n (walletPos === best.walletPos && g.index < best.groupIndex)))\n ) {\n best = { walletId: w.walletId, groupIndex: g.index, updatedAt: g.updatedAt, walletPos };\n }\n }\n }\n return best === undefined\n ? undefined\n : { walletId: best.walletId, groupIndex: best.groupIndex };\n }\n\n /** The wallet's metadata document — every group, hidden included. */\n exportMeta(walletId: string): MetaDoc {\n this.mustWallet(walletId);\n const s = this.getState();\n const w = s.wallets.find((x) => x.walletId === walletId);\n const wallet: MetaDoc[\"wallet\"] = {\n updatedAt: w?.updatedAt ?? 0,\n ...(w?.name === undefined ? {} : { name: w.name }),\n };\n const groups: MetaDocGroup[] = [];\n for (const g of s.groups[walletId] ?? []) {\n groups.push({\n index: g.index,\n hidden: g.hidden,\n updatedAt: g.updatedAt,\n ...(g.name === undefined ? {} : { name: g.name }),\n ...(g.boundPubkey === undefined ? {} : { boundPubkey: g.boundPubkey }),\n });\n }\n return { v: 1, wallet, groups };\n }\n\n /**\n * Entry-level last-writer-wins merge: a newer remote `updatedAt` replaces the local entry, a tie\n * keeps local; remote-only groups are added. `selected`/hidden rules are re-validated — if the\n * merge hides the selected group it is re-selected, and a merge may never leave every group\n * hidden (the selected one stays visible and is re-stamped so the fix propagates).\n */\n mergeMeta(walletId: string, doc: MetaDoc): { changed: boolean; localNewer: boolean } {\n this.mustWallet(walletId);\n let changed = false;\n let localNewer = false;\n const s = this.getState();\n const localWallet = s.wallets.find((w) => w.walletId === walletId);\n const walletUpdatedAt = localWallet?.updatedAt ?? 0;\n let wallet = localWallet ?? { walletId, updatedAt: 0 };\n if (doc.wallet.updatedAt > walletUpdatedAt) {\n wallet = {\n walletId,\n updatedAt: doc.wallet.updatedAt,\n ...(doc.wallet.name === undefined ? {} : { name: doc.wallet.name }),\n };\n changed = true;\n } else if (walletUpdatedAt > doc.wallet.updatedAt) {\n localNewer = true;\n }\n const localByIndex = new Map((s.groups[walletId] ?? []).map((g) => [g.index, g]));\n const groups = [...(s.groups[walletId] ?? [])];\n for (const remote of doc.groups) {\n const local = localByIndex.get(remote.index);\n if (local === undefined) {\n groups.push({\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n });\n changed = true;\n continue;\n }\n if (remote.updatedAt > local.updatedAt) {\n const replaced: AccountGroup = {\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n };\n const at = groups.findIndex((g) => g.index === remote.index);\n groups[at] = replaced;\n changed = true;\n } else if (local.updatedAt > remote.updatedAt) {\n localNewer = true;\n }\n }\n for (const g of groups) {\n if (!doc.groups.some((r) => r.index === g.index) && g.updatedAt > 0) {\n localNewer = true;\n }\n }\n groups.sort((a, b) => a.index - b.index);\n // Re-validate selection: merge may have hidden the selected group or every group.\n const walletOrder = s.wallets.map((w) => w.walletId);\n let selected = this.validSelection(\n { ...s.groups, [walletId]: groups },\n walletOrder,\n s.selected,\n );\n const visible = groups.some((g) => !g.hidden);\n if (!visible && groups.length > 0) {\n // A merge must never hide every group — keep the selected (or first) one visible and\n // stamp it so the local correction wins the next merge too.\n const keep = selected ?? { walletId, groupIndex: groups[0]?.index ?? 0 };\n const now = this.options.now();\n for (const [i, g] of groups.entries()) {\n if (g.index === keep.groupIndex) {\n groups[i] = { ...g, hidden: false, updatedAt: now };\n }\n }\n selected = keep;\n changed = true;\n localNewer = true;\n }\n if (\n selected?.walletId !== s.selected?.walletId ||\n selected?.groupIndex !== s.selected?.groupIndex\n ) {\n changed = true;\n }\n if (changed) {\n this.update((st) => ({\n ...st,\n wallets: st.wallets.map((w) => (w.walletId === walletId ? wallet : w)),\n groups: { ...st.groups, [walletId]: groups },\n selected,\n }));\n this.persist();\n this.driveSpark(selected);\n }\n return { changed, localNewer };\n }\n\n /** Sequential inspect from 0 upward; index 0 always included; stop after 2 consecutive unused. */\n async discoverSpark(walletId: string): Promise<number[]> {\n this.mustWallet(walletId);\n const found: number[] = [0];\n let index = 0;\n let unused = 0;\n while (found.length < 65) {\n const ref = { walletId, groupIndex: index, network: this.options.sparkNetwork } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- discovery is sequential per spec\n const { used } = await this.options.spark.inspect(ref);\n if (used) {\n if (index !== 0) {\n found.push(index);\n }\n unused = 0;\n } else {\n unused += 1;\n if (index !== 0 && unused >= 2) {\n break;\n }\n }\n index += 1;\n }\n return found;\n }\n\n /** Refresh `totals` for every other visible group; per-group failures are logged and skipped. */\n async refreshTotals(): Promise<void> {\n const state = this.getState();\n const sel = state.selected;\n const targets = this.visibleGroups(state).filter(\n (g) => !(sel !== null && g.walletId === sel.walletId && g.index === sel.groupIndex),\n );\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < targets.length) {\n const group = targets[cursor];\n cursor += 1;\n if (group === undefined) {\n return;\n }\n try {\n const ref = {\n walletId: group.walletId,\n groupIndex: group.index,\n network: this.options.sparkNetwork,\n } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- workers drain a shared cursor\n const { balanceSats } = await this.options.spark.inspect(ref);\n this.setTotal(group.walletId, group.index, balanceSats);\n } catch (error) {\n this.options.logger.warn(\n `refreshTotals failed for ${group.walletId}:${group.index}`,\n error,\n );\n }\n }\n };\n await Promise.all([worker(), worker()]);\n }\n\n private onSparkState(\n accounts: Readonly<Record<string, { readonly balanceSats?: number }>>,\n ): void {\n const sel = this.getState().selected;\n if (sel === null) {\n return;\n }\n const accountKey = `${sel.walletId}:${sel.groupIndex}:${this.options.sparkNetwork}`;\n const balance = accounts[accountKey]?.balanceSats;\n if (balance !== undefined) {\n this.setTotal(sel.walletId, sel.groupIndex, balance);\n }\n }\n\n private setTotal(walletId: string, index: number, balanceSats: number): void {\n const k = TOTAL_KEY(walletId, index);\n if (this.getState().totals[k] === balanceSats) {\n return;\n }\n this.update((s) => ({ ...s, totals: { ...s.totals, [k]: balanceSats } }));\n this.scheduleTotalsPersist();\n }\n\n private driveSpark(selected: AccountTreeState[\"selected\"]): void {\n this.options.spark.setAccounts(\n selected === null ? [] : [{ ...selected, network: this.options.sparkNetwork }],\n );\n }\n\n private visibleGroups(state: AccountTreeState): AccountGroup[] {\n const out: AccountGroup[] = [];\n for (const w of state.wallets) {\n for (const g of state.groups[w.walletId] ?? []) {\n if (!g.hidden) {\n out.push(g);\n }\n }\n }\n return out;\n }\n\n private validSelection(\n groups: Record<string, ReadonlyArray<AccountGroup>>,\n walletOrder: ReadonlyArray<string>,\n current: AccountTreeState[\"selected\"],\n ): AccountTreeState[\"selected\"] {\n if (current !== null) {\n const g = (groups[current.walletId] ?? []).find((x) => x.index === current.groupIndex);\n if (g !== undefined && !g.hidden) {\n return current;\n }\n }\n for (const walletId of walletOrder) {\n for (const g of groups[walletId] ?? []) {\n if (!g.hidden) {\n return { walletId, groupIndex: g.index };\n }\n }\n }\n return null;\n }\n\n private selectFallback(): void {\n const state = this.getState();\n const next = this.validSelection(\n state.groups,\n state.wallets.map((w) => w.walletId),\n null,\n );\n this.update((s) => ({ ...s, selected: next }));\n this.persist();\n this.driveSpark(next);\n }\n\n private mutateGroups(\n walletId: string,\n fn: (list: ReadonlyArray<AccountGroup>) => ReadonlyArray<AccountGroup>,\n ): void {\n this.update((s) => ({\n ...s,\n groups: { ...s.groups, [walletId]: fn(s.groups[walletId] ?? []) },\n }));\n this.persist();\n }\n\n private mustWallet(walletId: string): void {\n if (this.getState().status !== \"ready\") {\n throw new AccountTreeError(\"locked\", \"account tree is locked\");\n }\n if (!this.getState().wallets.some((w) => w.walletId === walletId)) {\n throw new AccountTreeError(\"not-found\", \"wallet does not exist\");\n }\n }\n\n private mustGroup(walletId: string, index: number): void {\n this.mustWallet(walletId);\n if (!(this.getState().groups[walletId] ?? []).some((g) => g.index === index)) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n }\n\n private checkedName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > NAME_MAX) {\n throw new AccountTreeError(\"invalid-input\", \"name must be 1-24 characters\");\n }\n return trimmed;\n }\n\n private async load(): Promise<PersistedTree> {\n if (this.col === undefined) {\n return EMPTY_TREE;\n }\n const bytes = await this.col.get(\"tree\");\n if (bytes === undefined) {\n return EMPTY_TREE;\n }\n const tree = decodeTree(bytes);\n if (tree === undefined) {\n this.options.logger.warn(\"invalid persisted account tree — starting empty\");\n return EMPTY_TREE;\n }\n return tree;\n }\n\n /** Queues a store write behind the previous one — the last queued write always lands last. */\n private persist(): void {\n const { col } = this;\n if (col === undefined) {\n return;\n }\n const previous = this.persistChain;\n this.persistChain = (async () => {\n try {\n await previous;\n const s = this.getState();\n const tree: PersistedTree = {\n wallets: Object.fromEntries(\n s.wallets.map((w) => [\n w.walletId,\n { updatedAt: w.updatedAt, ...(w.name === undefined ? {} : { name: w.name }) },\n ]),\n ),\n groups: s.groups,\n selected: s.selected,\n totals: s.totals,\n };\n await col.put(\"tree\", encodeTree(tree));\n } catch (error) {\n this.options.logger.warn(\"account tree persist failed\", error);\n }\n })();\n }\n\n private scheduleTotalsPersist(): void {\n if (this.totalsTimer !== undefined) {\n return;\n }\n this.totalsTimer = setTimeout(() => {\n this.totalsTimer = undefined;\n this.persist();\n }, TOTALS_DEBOUNCE_MS);\n }\n\n private async flushTotals(): Promise<void> {\n if (this.totalsTimer !== undefined) {\n clearTimeout(this.totalsTimer);\n this.totalsTimer = undefined;\n this.persist();\n }\n await this.persistChain;\n }\n}\n\nfunction persistedToState(tree: PersistedTree): Omit<AccountTreeState, \"status\"> {\n const wallets: Array<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }> = [];\n for (const [walletId, w] of Object.entries(tree.wallets)) {\n if (w.name === undefined) {\n wallets.push({ walletId, updatedAt: w.updatedAt });\n } else {\n wallets.push({ walletId, name: w.name, updatedAt: w.updatedAt });\n }\n }\n return {\n wallets,\n groups: tree.groups,\n selected: tree.selected,\n totals: tree.totals,\n };\n}\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/** BackupController error categories — never carry file contents, digests or secrets. */\nexport type BackupErrorCategory = \"cloud\" | \"conflict\" | \"unavailable\";\n\nexport class BackupControllerError extends Error {\n readonly category: BackupErrorCategory;\n\n constructor(category: BackupErrorCategory, message: string) {\n super(message);\n this.name = \"BackupControllerError\";\n this.category = category;\n }\n}\n","/**\n * The backup reconcile loop (design/backup.mdx \"同步\"): keeps the cloud file\n * `qntx-wallet-backup-<id>.json` in step with the vault. Single-flight — a trigger during a run\n * schedules exactly one rerun; `lock()` bumps a generation so a stale run never writes state, store\n * or cloud after that point.\n *\n * Security shape: the engine only ever moves ciphertext. The BEK stays in the enclave; the local\n * record is a digest/coverage baseline, not a key.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport type {\n Wallet,\n BackupHeader,\n BackupInfo,\n WalletInfo,\n WalletSnapshot,\n UnlockFactor,\n InitialFactor,\n} from \"@qntx/wallet\";\nimport { parseBackupHeader } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { BackupControllerError } from \"./errors.ts\";\nimport type { BackupErrorCategory } from \"./errors.ts\";\nimport type { CloudStore } from \"./port.ts\";\n\nexport type BackupControllerState = {\n readonly status: \"locked\" | \"unavailable\" | \"off\" | \"syncing\" | \"synced\" | \"conflict\" | \"error\";\n /** The retained backup key's public summary from the wallet snapshot. */\n // oxlint-disable-next-line typescript/no-restricted-types -- the snapshot contract is `null`\n readonly backup: BackupInfo | null;\n readonly uploadedAt: number | undefined;\n readonly unprotected: {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n };\n readonly error: BackupErrorCategory | undefined;\n};\n\n/** The EngineStore `backup/state` record — a baseline, never a key. */\ntype BackupRecord = {\n readonly id: string;\n readonly digest: string | undefined;\n readonly uploadedAt: number | undefined;\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n};\n\nconst COLLECTION = \"backup\";\nconst RECORD_KEY = \"state\";\nconst FILE_PREFIX = \"qntx-wallet-backup-\";\nconst FILE_SUFFIX = \".json\";\n\nfunction fileName(id: string): string {\n return `${FILE_PREFIX}${id}${FILE_SUFFIX}`;\n}\n\nfunction digestOf(text: string): string {\n return bytesToHex(sha256(utf8ToBytes(text)));\n}\n\nfunction sorted(values: Iterable<string>): ReadonlyArray<string> {\n return [...values].sort();\n}\n\nfunction sameSet(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst isStringArray = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every((e) => typeof e === \"string\");\n\n/** Strict record validation — anything malformed reads as absent (and is logged). */\nfunction parseRecord(bytes: Uint8Array | undefined): BackupRecord | undefined {\n if (bytes === undefined) {\n return undefined;\n }\n try {\n const value: unknown = JSON.parse(new TextDecoder().decode(bytes));\n if (!isObject(value)) {\n return undefined;\n }\n const o = value;\n const { id } = o;\n const { digest } = o;\n const { uploadedAt } = o;\n const { walletIds } = o;\n const { nostrKeyIds } = o;\n if (typeof id !== \"string\" || !/^[0-9a-f]{32}$/.test(id)) {\n return undefined;\n }\n if (digest !== undefined && (typeof digest !== \"string\" || !/^[0-9a-f]{64}$/.test(digest))) {\n return undefined;\n }\n if (\n uploadedAt !== undefined &&\n (typeof uploadedAt !== \"number\" || !Number.isSafeInteger(uploadedAt))\n ) {\n return undefined;\n }\n if (!isStringArray(walletIds) || !isStringArray(nostrKeyIds)) {\n return undefined;\n }\n return { id, digest, uploadedAt, walletIds, nostrKeyIds };\n } catch {\n return undefined;\n }\n}\n\nexport type BackupControllerOptions = {\n readonly wallet: Wallet;\n readonly cloud: CloudStore | undefined;\n readonly now: () => number;\n readonly logger: EngineLogger;\n};\n\nexport class BackupController extends Controller<BackupControllerState> {\n private readonly wallet: Wallet;\n private readonly cloud: CloudStore | undefined;\n private readonly now: () => number;\n private readonly logger: EngineLogger;\n\n private engineStore: EngineStore | undefined;\n private generation = 0;\n private current: Promise<void> | undefined;\n private rerun = false;\n /** Set by restore() before the store opens — written as a record on the first reconcile. */\n private pendingAdoption: { readonly id: string; readonly digest: string } | undefined;\n\n constructor(options: BackupControllerOptions) {\n super({ name: \"backup\", defaultState: () => defaultState() });\n this.wallet = options.wallet;\n this.cloud = options.cloud;\n this.now = options.now;\n this.logger = options.logger;\n }\n\n async init(): Promise<void> {\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n this.generation += 1;\n await Promise.resolve();\n }\n\n /** The engine hands over the store on unlock and takes it back on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /** Bumps the generation: an in-flight reconcile writes nothing after this point. */\n lock(): void {\n this.generation += 1;\n this.engineStore = undefined;\n this.update(() => defaultState());\n }\n\n trigger(): void {\n void this.triggerAsync();\n }\n\n private async triggerAsync(): Promise<void> {\n try {\n await this.reconcile();\n } catch (error) {\n this.logger.warn(\"backup reconcile trigger failed\", error);\n }\n }\n\n /** Explicit sync — awaits the run so callers see its outcome. */\n async sync(): Promise<void> {\n await this.reconcile();\n }\n\n async enable(options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> {\n // Check before the ceremony: the user must not verify and retain a BEK when there is\n // nowhere to upload it.\n if (this.cloud === undefined || !(await this.cloud.available())) {\n throw new BackupControllerError(\"unavailable\", \"the cloud store is unavailable\");\n }\n await this.wallet.backup.enable(options);\n await this.reconcileOrThrow();\n }\n\n async disable(): Promise<void> {\n await this.wallet.backup.disable();\n await this.reconcileOrThrow();\n }\n\n /** Files under our prefix with a parseable header. */\n async list(): Promise<ReadonlyArray<{ readonly name: string; readonly header: BackupHeader }>> {\n if (this.cloud === undefined) {\n return [];\n }\n const all = await this.cloud.list();\n const names = all.filter((n) => n.startsWith(FILE_PREFIX) && n.endsWith(FILE_SUFFIX));\n const { cloud } = this;\n const texts = await Promise.all(names.map(async (name) => cloud.read(name)));\n const out: Array<{ name: string; header: BackupHeader }> = [];\n for (const [index, name] of names.entries()) {\n const text = texts[index];\n if (text === undefined) {\n continue;\n }\n try {\n out.push({ name, header: parseBackupHeader(text) });\n } catch {\n this.logger.warn(\"backup file failed to parse\", new Error(name));\n }\n }\n return out;\n }\n\n async restore(options: {\n readonly name: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> {\n if (this.cloud === undefined) {\n throw new BackupControllerError(\"cloud\", \"no cloud store configured\");\n }\n const text = await this.cloud.read(options.name);\n if (text === undefined) {\n throw new BackupControllerError(\"cloud\", \"backup file not found\");\n }\n const id = idFromName(options.name);\n if (id === undefined) {\n throw new BackupControllerError(\"cloud\", \"unrecognized backup file name\");\n }\n const wasUninitialized = this.wallet.getSnapshot().vault === \"uninitialized\";\n if (wasUninitialized) {\n // Set before the kernel restore: the commit's status event can already trigger the\n // first reconcile once the engine store opens.\n this.pendingAdoption = { id, digest: digestOf(text) };\n }\n let wallets: ReadonlyArray<WalletInfo>;\n try {\n wallets = await this.wallet.backup.restore({\n envelope: text,\n backupFactor: options.backupFactor,\n ...(options.factor === undefined ? {} : { factor: options.factor }),\n });\n } catch (error) {\n this.pendingAdoption = undefined;\n throw error;\n }\n const { backup } = this.wallet.getSnapshot();\n if (!wasUninitialized && backup !== null && backup.id === id) {\n // Own-lineage merge: baseline to this file's digest, empty coverage forces the next\n // sync to upload the merged superset.\n const previous = await this.readRecord();\n await this.writeRecord({\n id,\n digest: digestOf(text),\n uploadedAt: previous?.uploadedAt,\n walletIds: [],\n nostrKeyIds: [],\n });\n }\n // Converge now — the commit's snapshot trigger may have run before the baseline landed.\n // Restore already succeeded, so a failed reconcile only leaves its status behind.\n try {\n await this.reconcile();\n } catch {\n /* state carries the outcome */\n }\n return wallets;\n }\n\n private async reconcileOrThrow(): Promise<void> {\n await this.reconcile();\n const { status, error } = this.getState();\n if (status === \"error\" || status === \"conflict\" || status === \"unavailable\") {\n throw new BackupControllerError(error ?? \"cloud\", `backup sync failed: ${status}`);\n }\n }\n\n private async readRecord(): Promise<BackupRecord | undefined> {\n const bytes = await this.engineStore?.collection(COLLECTION).get(RECORD_KEY);\n const record = parseRecord(bytes);\n if (bytes !== undefined && record === undefined) {\n this.logger.warn(\"backup record failed to parse — treating as absent\", new Error(COLLECTION));\n }\n return record;\n }\n\n private async writeRecord(record: BackupRecord): Promise<void> {\n await this.engineStore\n ?.collection(COLLECTION)\n .put(RECORD_KEY, new TextEncoder().encode(JSON.stringify(record)));\n }\n\n private async deleteRecord(): Promise<void> {\n await this.engineStore?.collection(COLLECTION).delete(RECORD_KEY);\n }\n\n private snapshot(): WalletSnapshot {\n return this.wallet.getSnapshot();\n }\n\n private unprotected(snapshot: WalletSnapshot, record: BackupRecord | undefined) {\n const covered =\n snapshot.backup !== null &&\n record !== undefined &&\n record.id === snapshot.backup.id &&\n record.digest !== undefined;\n const wallets = snapshot.wallets.filter((w) => w.backup !== \"mnemonic\");\n const keys = snapshot.nostr.keys.filter(\n (k) => k.ref.kind === \"standalone\" && k.backedUp === false,\n );\n const walletIds = wallets\n .map((w) => w.walletId)\n .filter((id) => !covered || !record.walletIds.includes(id));\n const nostrKeyIds = keys\n .map((k) => k.publicKey)\n .filter((id) => !covered || !record.nostrKeyIds.includes(id));\n return { walletIds: sorted(walletIds), nostrKeyIds: sorted(nostrKeyIds) };\n }\n\n private coverage(snapshot: WalletSnapshot): {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n } {\n return {\n walletIds: sorted(snapshot.wallets.map((w) => w.walletId)),\n nostrKeyIds: sorted(\n snapshot.nostr.keys.filter((k) => k.ref.kind === \"standalone\").map((k) => k.publicKey),\n ),\n };\n }\n\n private setStatus(\n generation: number,\n status: BackupControllerState[\"status\"],\n error?: BackupErrorCategory,\n record?: BackupRecord,\n ): void {\n if (generation !== this.generation) {\n return;\n }\n const snapshot = this.snapshot();\n this.update((state) => ({\n ...state,\n status,\n backup: snapshot.backup,\n uploadedAt: record?.uploadedAt,\n error,\n unprotected: this.unprotected(snapshot, record),\n }));\n }\n\n /**\n * Single-flight: a trigger during a run flags exactly one rerun inside the same promise, so\n * `sync()`/`enable()` await real convergence instead of a mid-run snapshot.\n */\n private async reconcile(): Promise<void> {\n if (this.current !== undefined) {\n this.rerun = true;\n return this.current;\n }\n this.current = (async () => {\n try {\n do {\n this.rerun = false;\n // The generation is read per pass: a lock invalidates the current pass, and a\n // trigger flagged under it still earns a fresh pass after unlock.\n // oxlint-disable-next-line eslint/no-await-in-loop -- passes must serialize: one rerun flag, one pass at a time\n await this.pass(this.generation);\n } while (this.rerun);\n } finally {\n this.current = undefined;\n }\n })();\n return this.current;\n }\n\n private async pass(generation: number): Promise<void> {\n const snapshot = this.snapshot();\n if (snapshot.vault !== \"unlocked\" || this.engineStore === undefined) {\n return;\n }\n let record = await this.readRecord();\n if (this.cloud === undefined || !(await this.cloud.available())) {\n this.setStatus(generation, \"unavailable\", undefined, record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n\n // Pending adoption lands once — and only when the vault's backup key is the file's key.\n const adoption = this.pendingAdoption;\n if (adoption !== undefined) {\n this.pendingAdoption = undefined;\n if (snapshot.backup?.id === adoption.id) {\n record = {\n id: adoption.id,\n digest: adoption.digest,\n uploadedAt: undefined,\n walletIds: [],\n nostrKeyIds: [],\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(record);\n } else {\n this.logger.warn(\n \"backup adoption dropped — the vault's backup key is not the file's\",\n new Error(adoption.id),\n );\n }\n }\n\n const { backup } = snapshot;\n if (backup === null) {\n // Backup off in the vault: remove our file + record, then report off.\n if (record !== undefined) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n if (generation !== this.generation) {\n return;\n }\n await this.deleteRecord();\n } catch (error) {\n this.logger.warn(\"backup cloud delete failed — retrying next reconcile\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n }\n this.setStatus(generation, \"off\", undefined, undefined);\n return;\n }\n\n const baseline = record !== undefined && record.id === backup.id ? record.digest : undefined;\n const cov = this.coverage(snapshot);\n if (\n baseline !== undefined &&\n record !== undefined &&\n sameSet(cov.walletIds, record.walletIds) &&\n sameSet(cov.nostrKeyIds, record.nostrKeyIds)\n ) {\n this.setStatus(generation, \"synced\", undefined, record);\n return;\n }\n\n this.setStatus(generation, \"syncing\", undefined, record);\n try {\n const envelope = await this.wallet.backup.update();\n if (generation !== this.generation) {\n return;\n }\n const name = fileName(backup.id);\n const remote = await this.cloud.read(name);\n const digest = digestOf(envelope);\n if (remote !== undefined && digestOf(remote) !== baseline) {\n this.setStatus(generation, \"conflict\", \"conflict\", record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.write(name, envelope);\n const readBack = await this.cloud.read(name);\n if (readBack !== envelope) {\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n const next: BackupRecord = {\n id: backup.id,\n digest,\n uploadedAt: this.now(),\n walletIds: cov.walletIds,\n nostrKeyIds: cov.nostrKeyIds,\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(next);\n if (record !== undefined && record.id !== backup.id) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n } catch (error) {\n this.logger.warn(\"stale backup file delete failed\", error);\n }\n }\n this.setStatus(generation, \"synced\", undefined, next);\n } catch (error) {\n if (generation !== this.generation) {\n return;\n }\n this.logger.warn(\"backup reconcile failed\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n }\n }\n}\n\nfunction defaultState(): BackupControllerState {\n return {\n status: \"locked\",\n backup: null,\n uploadedAt: undefined,\n unprotected: { walletIds: [], nostrKeyIds: [] },\n error: undefined,\n };\n}\n\nfunction idFromName(name: string): string | undefined {\n if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) {\n return undefined;\n }\n const id = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);\n return /^[0-9a-f]{32}$/.test(id) ? id : undefined;\n}\n","/**\n * Wallet metadata document — the plaintext exchanged over kind-30078 events between this wallet's\n * own devices. One document per wallet; entry-level last-writer-wins on `updatedAt`.\n */\n\nexport type MetaDocWallet = {\n readonly name?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDocGroup = {\n readonly index: number;\n readonly name?: string;\n readonly hidden: boolean;\n readonly boundPubkey?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDoc = {\n readonly v: 1;\n readonly wallet: MetaDocWallet;\n readonly groups: ReadonlyArray<MetaDocGroup>;\n};\n\nexport const META_DOC_MAX_BYTES = 65536;\n\nconst NAME_MAX = 24;\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\nconst KNOWN_DOC_KEYS = new Set([\"v\", \"wallet\", \"groups\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_GROUP_KEYS = new Set([\"index\", \"name\", \"hidden\", \"boundPubkey\", \"updatedAt\"]);\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nconst validName = (v: unknown): boolean =>\n v === undefined || (typeof v === \"string\" && v.trim().length > 0 && v.trim().length <= NAME_MAX);\n\nconst trimmedName = (v: unknown): string | undefined =>\n typeof v === \"string\" ? v.trim() : undefined;\n\n/** Strict decode — any malformed shape, unknown key or duplicate index returns `undefined`. */\nexport function decodeMetaDoc(value: unknown): MetaDoc | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const k of Object.keys(value)) {\n if (!KNOWN_DOC_KEYS.has(k)) {\n return undefined;\n }\n }\n if (value[\"v\"] !== 1) {\n return undefined;\n }\n const { wallet } = value;\n if (!isObject(wallet)) {\n return undefined;\n }\n for (const k of Object.keys(wallet)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n if (!validName(wallet[\"name\"]) || !isNonNegativeInt(wallet[\"updatedAt\"])) {\n return undefined;\n }\n const { groups } = value;\n if (!Array.isArray(groups)) {\n return undefined;\n }\n const seen = new Set<number>();\n const out: MetaDocGroup[] = [];\n for (const item of groups) {\n if (!isObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n const { index } = item;\n if (!isNonNegativeInt(index) || seen.has(index)) {\n return undefined;\n }\n seen.add(index);\n if (!validName(item[\"name\"]) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n if (!isNonNegativeInt(item[\"updatedAt\"])) {\n return undefined;\n }\n const gName = trimmedName(item[\"name\"]);\n out.push({\n index,\n hidden: item[\"hidden\"],\n updatedAt: item[\"updatedAt\"],\n ...(gName === undefined ? {} : { name: gName }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n out.sort((a, b) => a.index - b.index);\n const name = trimmedName(wallet[\"name\"]);\n return {\n v: 1,\n wallet: {\n updatedAt: wallet[\"updatedAt\"],\n ...(name === undefined ? {} : { name }),\n },\n groups: out,\n };\n}\n\n/** UTF-8 JSON — `undefined` when the document exceeds the 64 KB limit. */\nexport function encodeMetaDoc(doc: MetaDoc): Uint8Array | undefined {\n const bytes = new TextEncoder().encode(JSON.stringify(doc));\n return bytes.byteLength <= META_DOC_MAX_BYTES ? bytes : undefined;\n}\n\nexport function decodeMetaDocBytes(bytes: Uint8Array): MetaDoc | undefined {\n if (bytes.byteLength > META_DOC_MAX_BYTES) {\n return undefined;\n }\n try {\n return decodeMetaDoc(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n return undefined;\n }\n}\n","/** Meta-sync error categories — messages never carry event or document content. */\nexport type MetaSyncErrorCategory = \"network\" | \"internal\" | \"unsupported\" | \"corrupt\";\n\nexport class MetaSyncError extends Error {\n readonly category: MetaSyncErrorCategory;\n\n constructor(category: MetaSyncErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"MetaSyncError\";\n this.category = category;\n }\n}\n","import type { Event, Filter } from \"@qntx/nostr\";\nimport { verifyEvent } from \"@qntx/nostr\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport type { NostrKeyRef, WalletSigner } from \"@qntx/wallet/nostr\";\n\nimport type { AccountTreeController } from \"../accounts/controller.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport { decodeMetaDocBytes, encodeMetaDoc } from \"./doc.ts\";\nimport type { MetaSyncErrorCategory } from \"./errors.ts\";\nimport { MetaSyncError } from \"./errors.ts\";\n\nexport const META_SYNC_KIND = 30078;\nconst PUBLISH_DEBOUNCE_MS = 2000;\n\nexport type MetaSyncRelayPort = {\n readonly fetch: (filter: Filter) => Promise<ReadonlyArray<Event>>;\n readonly publish: (event: Event) => Promise<void>;\n};\n\nexport type MetaSyncConfig = {\n /** The `d` tag that names this wallet's metadata document. */\n readonly tag: string;\n readonly relays: MetaSyncRelayPort;\n};\n\nexport type MetaSyncWalletStatus = {\n readonly status: \"unavailable\" | \"syncing\" | \"synced\" | \"error\";\n readonly error?: MetaSyncErrorCategory;\n};\n\nexport type MetaSyncState = {\n readonly wallets: Readonly<Record<string, MetaSyncWalletStatus>>;\n};\n\nexport type MetaSyncControllerOptions = {\n readonly wallet: Wallet;\n readonly accounts: AccountTreeController;\n /** `nostr(wallet)` — the signer is requested per wallet for its group-0 derived key. */\n readonly nostr: { readonly signer: (ref: NostrKeyRef) => WalletSigner };\n readonly metaSync: MetaSyncConfig | undefined;\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\n/**\n * Wallet-metadata sync over kind-30078 addressable events: one NIP-44-encrypted document per\n * wallet, authored by its group-0 derived key. Pull always precedes publish in an unlock session —\n * replaceable events would otherwise let a stale local tree overwrite a newer remote document.\n * Debounced publishes are per wallet; a generation counter cancels in-flight write-backs on lock.\n */\nexport class MetaSyncController extends Controller<MetaSyncState> {\n private readonly options: MetaSyncControllerOptions;\n private generation = 0;\n private readonly pulled = new Set<string>();\n private readonly lastRemoteCreatedAt = new Map<string, number>();\n private readonly lastExported = new Map<string, string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly inflight = new Set<string>();\n private accountsUnsubscribe: (() => void) | undefined;\n\n constructor(options: MetaSyncControllerOptions) {\n super({ name: \"metaSync\", defaultState: () => ({ wallets: {} }) });\n this.options = options;\n }\n\n /** Unlocked: pull every wallet whose group-0 identity exists, then watch the tree. */\n async init(): Promise<void> {\n const gen = ++this.generation;\n this.accountsUnsubscribe = this.options.accounts.store.subscribe(() => {\n this.onTreeChange();\n });\n // pullAll covers every snapshot wallet at init — reconcile() is for additions later.\n await this.pullAll(gen);\n }\n\n async destroy(): Promise<void> {\n await this.lock();\n }\n\n /** Locked: cancel debounces and in-flight write-backs, forget the pull/publish bookkeeping. */\n async lock(): Promise<void> {\n this.generation += 1;\n this.accountsUnsubscribe?.();\n this.accountsUnsubscribe = undefined;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n this.pulled.clear();\n this.lastRemoteCreatedAt.clear();\n this.lastExported.clear();\n this.inflight.clear();\n this.update(() => ({ wallets: {} }));\n await Promise.resolve();\n }\n\n /** Snapshot changed while unlocked: pull newly-seen wallets, drop removed ones. */\n reconcile(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n const snap = this.options.wallet.getSnapshot();\n const live = new Set(snap.wallets.map((w) => w.walletId));\n const gen = this.generation;\n for (const w of snap.wallets) {\n if (this.getState().wallets[w.walletId] === undefined) {\n void this.pullOne(w.walletId, gen);\n }\n }\n this.update((s) => {\n const wallets = Object.fromEntries(\n Object.entries(s.wallets).filter(([walletId]) => live.has(walletId)),\n );\n return { ...s, wallets };\n });\n }\n\n /** Manual re-pull of every wallet that can sync. */\n async sync(): Promise<void> {\n await this.pullAll(this.generation);\n }\n\n private async pullAll(gen: number): Promise<void> {\n const snap = this.options.wallet.getSnapshot();\n await Promise.all(snap.wallets.map(async (w) => this.pullOne(w.walletId, gen)));\n }\n\n private async pubkeyFor(signer: WalletSigner): Promise<string> {\n return signer.getPublicKey();\n }\n\n private signerFor(walletId: string): WalletSigner | undefined {\n const snap = this.options.wallet.getSnapshot();\n const ref = { kind: \"derived\" as const, walletId, groupIndex: 0 };\n const hasKey = snap.nostr.keys.some(\n (k) => k.ref.kind === \"derived\" && k.ref.walletId === walletId && k.ref.groupIndex === 0,\n );\n if (!hasKey) {\n return undefined;\n }\n return this.options.nostr.signer(ref);\n }\n\n private setStatus(walletId: string, status: MetaSyncWalletStatus): void {\n this.update((s) => ({ ...s, wallets: { ...s.wallets, [walletId]: status } }));\n }\n\n private async pullOne(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || this.inflight.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"unavailable\" });\n }\n return;\n }\n this.inflight.add(walletId);\n this.setStatus(walletId, { status: \"syncing\" });\n try {\n const pubkey = await this.pubkeyFor(signer);\n const events = await config.relays.fetch(this.filterFor(pubkey, config.tag));\n let remote: Event | undefined;\n let remoteSkipped = 0;\n for (const e of events) {\n if (!this.acceptableEvent(e, pubkey, config.tag)) {\n remoteSkipped += 1;\n continue;\n }\n if (remote === undefined || e.created_at > remote.created_at) {\n remote = e;\n }\n }\n if (remote === undefined) {\n // No doc on the relay: publish only when the local tree holds a real edit\n // (updatedAt > 0) — a fresh device must not replace nothing with empty defaults.\n const local = this.options.accounts.exportMeta(walletId);\n const hasEdits = local.wallet.updatedAt > 0 || local.groups.some((g) => g.updatedAt > 0);\n if (gen !== this.generation) {\n return;\n }\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (hasEdits) {\n await this.publishNow(walletId, gen);\n }\n } else {\n // A verified event we cannot read must never be overwritten — a newer app version\n // (e.g. v: 2) is the most likely cause; decode failure is data corruption.\n const decrypt = signer.nip44Decrypt;\n const plaintext =\n decrypt === undefined\n ? undefined\n : await decrypt.call(signer, pubkey, remote.content).catch(() => undefined);\n const doc =\n plaintext === undefined\n ? undefined\n : decodeMetaDocBytes(new TextEncoder().encode(plaintext));\n if (doc === undefined) {\n if (gen !== this.generation) {\n return;\n }\n const error: MetaSyncErrorCategory =\n plaintext !== undefined && isUnsupportedDoc(plaintext) ? \"unsupported\" : \"corrupt\";\n this.setStatus(walletId, { status: \"error\", error });\n this.options.logger.warn(`meta sync: unreadable remote doc (${error})`);\n return; // not in `pulled` — debounced publishes stay blocked too\n }\n const merge = this.options.accounts.mergeMeta(walletId, doc);\n if (gen !== this.generation) {\n return;\n }\n this.lastRemoteCreatedAt.set(walletId, remote.created_at);\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (merge.localNewer) {\n await this.publishNow(walletId, gen);\n }\n }\n if (remoteSkipped > 0) {\n this.options.logger.warn(`meta sync: ignored ${remoteSkipped} invalid remote events`);\n }\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync pull failed\", error);\n }\n } finally {\n this.inflight.delete(walletId);\n }\n }\n\n private filterFor(pubkey: string, tag: string): Filter {\n return { kinds: [META_SYNC_KIND], authors: [pubkey], \"#d\": [tag] };\n }\n\n private acceptableEvent(e: Event, pubkey: string, tag: string): boolean {\n if (e.kind !== META_SYNC_KIND || e.pubkey !== pubkey || !verifyEvent(e)) {\n return false;\n }\n const dTags = e.tags.filter((t) => t[0] === \"d\");\n return dTags.length === 1 && dTags[0]?.[1] === tag;\n }\n\n /** Snapshot the wallet's exported doc — the debounce publishes only on a real change. */\n private rememberExport(walletId: string): void {\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n this.lastExported.set(walletId, JSON.stringify(doc));\n } catch {\n // Wallet not in the tree — nothing to remember.\n }\n }\n\n private onTreeChange(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n for (const walletId of this.pulled) {\n let current: string | undefined;\n try {\n current = JSON.stringify(this.options.accounts.exportMeta(walletId));\n } catch {\n continue;\n }\n if (current === this.lastExported.get(walletId)) {\n continue;\n }\n this.lastExported.set(walletId, current);\n const existing = this.timers.get(walletId);\n if (existing !== undefined) {\n clearTimeout(existing);\n }\n const gen = this.generation;\n this.timers.set(\n walletId,\n setTimeout(() => {\n this.timers.delete(walletId);\n void this.publishNow(walletId, gen);\n }, PUBLISH_DEBOUNCE_MS),\n );\n }\n }\n\n private async publishNow(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || !this.pulled.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n this.setStatus(walletId, { status: \"unavailable\" });\n return;\n }\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n const bytes = encodeMetaDoc(doc);\n if (bytes === undefined) {\n throw new MetaSyncError(\"internal\", \"meta doc exceeds 64 KB\");\n }\n const encrypt = signer.nip44Encrypt;\n if (encrypt === undefined) {\n throw new MetaSyncError(\"internal\", \"signer lacks nip44 encryption\");\n }\n const pubkey = await this.pubkeyFor(signer);\n const content = await encrypt.call(signer, pubkey, new TextDecoder().decode(bytes));\n const lastRemote = this.lastRemoteCreatedAt.get(walletId) ?? 0;\n const created_at = Math.max(Math.floor(this.options.now() / 1000), lastRemote + 1);\n const event = await signer.signEvent({\n pubkey,\n kind: META_SYNC_KIND,\n created_at,\n tags: [[\"d\", config.tag]],\n content,\n });\n if (gen !== this.generation) {\n return;\n }\n await config.relays.publish(event);\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync publish failed\", error);\n }\n }\n }\n}\n\nfunction categorizeSync(error: unknown): MetaSyncErrorCategory {\n return error instanceof MetaSyncError ? error.category : \"network\";\n}\n\n/** A decrypted doc that parses as JSON with a numeric `v` above 1 is a newer schema, not garbage. */\nfunction isUnsupportedDoc(plaintext: string): boolean {\n try {\n const doc: unknown = JSON.parse(plaintext);\n return (\n typeof doc === \"object\" &&\n doc !== null &&\n \"v\" in doc &&\n typeof doc.v === \"number\" &&\n doc.v > 1\n );\n } catch {\n return false;\n }\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport {\n bitcoinAddressScript,\n decodeBolt11,\n decodeSparkAddress,\n parseSparkInvoice,\n} from \"@qntx/spark\";\nimport type { SparkNetwork } from \"@qntx/spark\";\nimport type { LnurlPayRequest, LnurlWithdrawRequest } from \"@qntx/spark/lnurl\";\nimport { decodeLnurl, lightningAddressUrl } from \"@qntx/spark/lnurl\";\n\nexport type PaymentOption =\n | { readonly kind: \"spark\"; readonly address: string }\n | {\n readonly kind: \"spark-invoice\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly memo?: string;\n readonly expiresAt?: number;\n }\n | {\n readonly kind: \"lightning\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n }\n | { readonly kind: \"lnurl-pay\"; readonly request: LnurlPayRequest; readonly address?: string }\n | { readonly kind: \"lnurl-withdraw\"; readonly request: LnurlWithdrawRequest }\n | { readonly kind: \"bitcoin\"; readonly address: string };\n\nexport type PaymentRequest = {\n readonly options: ReadonlyArray<PaymentOption>;\n readonly amountSats?: number;\n readonly label?: string;\n readonly message?: string;\n};\n\nexport type PaymentParse =\n | { readonly kind: \"request\"; readonly request: PaymentRequest }\n | { readonly kind: \"lnurl\"; readonly url: string; readonly address?: string }\n | {\n readonly kind: \"unsupported\";\n readonly format:\n | \"bolt12\"\n | \"silent-payment\"\n | \"lnurl-auth\"\n | \"spark-token-invoice\"\n | \"nostr-wallet-connect\";\n }\n | {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n }\n | { readonly kind: \"unrecognized\" };\n\nexport type ParseOptions = {\n readonly network: SparkNetwork;\n readonly now: number;\n};\n\n/** Invoices with less than this much life left are treated as already expired. */\nconst BOLT11_EXPIRY_GRACE_MS = 60_000;\n\ntype ParseFailure = {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n};\n\nconst invalid = (reason: ParseFailure[\"reason\"]): PaymentParse => ({ kind: \"invalid\", reason });\n\n/** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */\nfunction btcAmountSats(text: string): number | undefined {\n const match = /^(\\d+)(?:\\.(\\d{1,8}))?$/.exec(text);\n if (match === null) {\n return undefined;\n }\n const [, whole] = match;\n if (whole === undefined) {\n return undefined;\n }\n const sats = BigInt(whole) * 100_000_000n + BigInt((match[2] ?? \"\").padEnd(8, \"0\") || \"0\");\n return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : undefined;\n}\n\ntype Bolt11Fields = {\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n};\n\n/**\n * BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `\"network\"` /\n * `\"expired\"` / `\"malformed\"` are the failure modes.\n */\nfunction bolt11Fields(\n text: string,\n options: ParseOptions,\n): Bolt11Fields | \"network\" | \"expired\" | \"malformed\" | undefined {\n let decoded;\n try {\n decoded = decodeBolt11(text);\n } catch {\n return undefined;\n }\n const network =\n decoded.network === \"mainnet\"\n ? \"mainnet\"\n : decoded.network === \"regtest\"\n ? \"regtest\"\n : undefined;\n if (network === undefined) {\n return \"network\";\n }\n if (network !== options.network) {\n return \"network\";\n }\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) {\n return \"expired\";\n }\n return {\n ...(decoded.amountMsat === undefined\n ? {}\n : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1000) }),\n paymentHash: bytesToHex(decoded.paymentHash),\n ...(decoded.description === undefined ? {} : { description: decoded.description }),\n expiresAt,\n };\n}\n\n/** Spark address or sats/token invoice → options. `null` means not a spark input. */\nfunction sparkOptions(\n text: string,\n options: ParseOptions,\n): PaymentOption[] | \"network\" | \"expired\" | \"malformed\" | \"token\" | undefined {\n let decoded;\n try {\n decoded = decodeSparkAddress(text);\n } catch {\n return undefined;\n }\n if (decoded.network !== options.network) {\n return \"network\";\n }\n if (decoded.invoice === undefined) {\n return [{ kind: \"spark\", address: text }];\n }\n // Expiry lives in the unsigned fields — check it before validating the signature so an\n // expired invoice reports `expired` rather than `malformed`.\n if (decoded.invoice.expiresAt !== undefined && decoded.invoice.expiresAt <= options.now) {\n return \"expired\";\n }\n if (decoded.invoice.payment?.type === \"tokens\") {\n return \"token\";\n }\n let parsed;\n try {\n parsed = parseSparkInvoice(text, { network: options.network, now: options.now });\n } catch {\n return \"malformed\";\n }\n const { payment } = parsed.fields;\n return [\n {\n kind: \"spark-invoice\",\n invoice: text,\n ...(payment?.type === \"sats\" && payment.amount !== undefined\n ? { amountSats: payment.amount }\n : {}),\n ...(parsed.fields.memo === undefined ? {} : { memo: parsed.fields.memo }),\n ...(parsed.fields.expiresAt === undefined ? {} : { expiresAt: parsed.fields.expiresAt }),\n },\n ];\n}\n\n/** Does `address` decode under the other network? Used only to classify a rejection. */\nfunction decodesOnOtherNetwork(address: string, options: ParseOptions): boolean {\n try {\n bitcoinAddressScript(address, options.network === \"mainnet\" ? \"regtest\" : \"mainnet\");\n return true;\n } catch {\n return false;\n }\n}\n\n/** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */\nfunction bip21Parse(text: string, options: ParseOptions): PaymentParse {\n const q = text.indexOf(\"?\");\n const address = text.slice(\"bitcoin:\".length, q === -1 ? undefined : q);\n const params = new Map<string, string>();\n if (q !== -1) {\n for (const pair of text.slice(q + 1).split(\"&\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return invalid(\"malformed\");\n }\n let key;\n let value;\n try {\n key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();\n value = decodeURIComponent(pair.slice(eq + 1));\n } catch {\n return invalid(\"malformed\");\n }\n if (params.has(key)) {\n return invalid(\"malformed\");\n }\n if (key.startsWith(\"req-\") && !BIP21_KNOWN_REQ_PARAMS.has(key)) {\n return invalid(\"malformed\");\n }\n params.set(key, value);\n }\n }\n const options_: PaymentOption[] = [];\n let declaredSats: number | undefined;\n const spark = params.get(\"spark\");\n if (spark !== undefined) {\n const parsed = sparkOptions(spark, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push(...parsed);\n const sats = parsed.find((o) => o.kind === \"spark-invoice\")?.amountSats;\n if (sats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n }\n const lightning = params.get(\"lightning\");\n if (lightning !== undefined) {\n const parsed = bolt11Fields(lightning, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push({\n kind: \"lightning\",\n invoice: lightning,\n ...(parsed.amountSats === undefined ? {} : { amountSats: parsed.amountSats }),\n paymentHash: parsed.paymentHash,\n ...(parsed.description === undefined ? {} : { description: parsed.description }),\n expiresAt: parsed.expiresAt,\n });\n if (parsed.amountSats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== parsed.amountSats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = parsed.amountSats;\n }\n }\n if (address.length > 0) {\n try {\n bitcoinAddressScript(address, options.network);\n } catch {\n return invalid(decodesOnOtherNetwork(address, options) ? \"network\" : \"malformed\");\n }\n options_.push({ kind: \"bitcoin\", address });\n }\n const declaredAmount = params.get(\"amount\");\n if (declaredAmount !== undefined) {\n const sats = btcAmountSats(declaredAmount);\n if (sats === undefined) {\n return invalid(\"malformed\");\n }\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n if (options_.length === 0) {\n if (params.has(\"lno\")) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n if (params.has(\"sp\")) {\n return { kind: \"unsupported\", format: \"silent-payment\" };\n }\n return invalid(\"malformed\");\n }\n return {\n kind: \"request\",\n request: {\n options: options_,\n ...(declaredSats === undefined ? {} : { amountSats: declaredSats }),\n ...(params.get(\"label\") === undefined ? {} : { label: params.get(\"label\") ?? \"\" }),\n ...(params.get(\"message\") === undefined ? {} : { message: params.get(\"message\") ?? \"\" }),\n },\n };\n}\n\nconst BIP21_KNOWN_REQ_PARAMS = new Set([\"req-amount\", \"req-label\", \"req-message\"]);\n\n/** `input` → PaymentParse. Never throws: every failure is a structured result. */\nexport function parsePayment(input: string, options: ParseOptions): PaymentParse {\n try {\n const text = input.trim();\n if (/^nostr\\+walletconnect:/i.test(text)) {\n return { kind: \"unsupported\", format: \"nostr-wallet-connect\" };\n }\n const stripped = text.toLowerCase().startsWith(\"lightning:\")\n ? text.slice(\"lightning:\".length)\n : text;\n if (/^bitcoin:/i.test(stripped)) {\n return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(\":\") + 1)}`, options);\n }\n const bolt11 = bolt11Fields(stripped, options);\n if (bolt11 === \"network\" || bolt11 === \"expired\" || bolt11 === \"malformed\") {\n return invalid(bolt11);\n }\n if (bolt11 !== undefined) {\n const option: PaymentOption = {\n kind: \"lightning\",\n invoice: stripped,\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n paymentHash: bolt11.paymentHash,\n ...(bolt11.description === undefined ? {} : { description: bolt11.description }),\n expiresAt: bolt11.expiresAt,\n };\n return {\n kind: \"request\",\n request: {\n options: [option],\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n },\n };\n }\n const spark = sparkOptions(stripped, options);\n if (spark === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (spark === \"network\" || spark === \"expired\" || spark === \"malformed\") {\n return invalid(spark);\n }\n if (spark !== undefined) {\n return { kind: \"request\", request: { options: spark } };\n }\n if (/^(lnurlp|lnurlw):/i.test(stripped)) {\n const rest = stripped.slice(stripped.indexOf(\"://\") + 3);\n const host = rest.split(/[/?#]/, 1)[0] ?? \"\";\n const url = `${host.toLowerCase().endsWith(\".onion\") ? \"http\" : \"https\"}://${rest}`;\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n }\n if (/^keyauth:/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n if (!stripped.includes(\":\") && stripped.includes(\"@\")) {\n return { kind: \"lnurl\", url: lightningAddressUrl(stripped), address: stripped };\n }\n // BOLT12 offer: bech32 charset, anchored — a lightning address like lnolan@x must not match.\n if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n try {\n const url = decodeLnurl(stripped);\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n } catch {\n // not a bech32 LNURL\n }\n try {\n bitcoinAddressScript(stripped, options.network);\n return { kind: \"request\", request: { options: [{ kind: \"bitcoin\", address: stripped }] } };\n } catch {\n if (decodesOnOtherNetwork(stripped, options)) {\n return invalid(\"network\");\n }\n }\n return { kind: \"unrecognized\" };\n } catch {\n return invalid(\"malformed\");\n }\n}\n","/** SparkController error categories — never carry request bytes or secrets. */\nexport type SparkErrorCategory =\n | \"network\"\n | \"approval-required\"\n | \"insufficient-funds\"\n | \"rejected\"\n | \"internal\";\n\nexport class SparkControllerError extends Error {\n readonly category: SparkErrorCategory;\n\n constructor(category: SparkErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"SparkControllerError\";\n this.category = category;\n }\n}\n\n/** Maps a thrown client/kernel error into a category without leaking payloads. */\nexport function categorize(error: unknown): SparkErrorCategory {\n const name = error instanceof Error ? error.name : \"\";\n const message = error instanceof Error ? error.message : \"\";\n if (/approval|denied|rejected/i.test(message)) {\n return /required/i.test(message) ? \"approval-required\" : \"rejected\";\n }\n if (/insufficient|not enough|balance/i.test(message)) {\n return \"insufficient-funds\";\n }\n if (name === \"SparkRequestError\" || /fetch|network|timeout|unavailable|closed/i.test(message)) {\n return \"network\";\n }\n return \"internal\";\n}\n","/** Payment layer error categories — messages never carry remote or secret content. */\nexport type PaymentErrorCategory = \"invalid-input\" | \"network\" | \"rejected\";\n\nexport class PaymentError extends Error {\n readonly category: PaymentErrorCategory;\n\n constructor(category: PaymentErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"PaymentError\";\n this.category = category;\n }\n}\n","import type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { requestInvoice, submitWithdraw } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { SparkControllerError } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\nimport type { PaymentOption } from \"./parse.ts\";\n\nexport type PayParams = {\n readonly account: SparkAccountRef;\n readonly option: PaymentOption;\n /** Caller-supplied amount — required by open invoices, the `spark` option, and LNURL flows. */\n readonly amountSats?: number;\n readonly comment?: string;\n readonly maxFeeSats?: number;\n readonly speed?: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n readonly verify: UnlockFactor;\n};\n\nexport type PayContext = {\n readonly spark: SparkController;\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\nexport type PayResult =\n | { readonly kind: \"spark\"; readonly transfer: SparkTransfer }\n | { readonly kind: \"lightning\"; readonly payment: LightningPayment }\n | { readonly kind: \"withdraw\"; readonly exit: CooperativeExitResult }\n | { readonly kind: \"lnurl-withdraw\"; readonly invoice: LightningInvoice };\n\n/**\n * Executes one parsed payment option. Every input validation happens before the approval round — a\n * `PaymentError` here never consumed a verification. `SparkControllerError` and `WalletError` pass\n * through untouched.\n */\nexport async function pay(context: PayContext, params: PayParams): Promise<PayResult> {\n const { spark } = context;\n const ref = params.account;\n let result: PayResult;\n switch (params.option.kind) {\n case \"spark\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"spark payment: amountSats is required\");\n }\n const transfer = await spark.send(ref, {\n receiver: params.option.address,\n amountSats: params.amountSats,\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"spark-invoice\": {\n if (params.option.expiresAt !== undefined && params.option.expiresAt <= context.now()) {\n throw new PaymentError(\"rejected\", \"spark invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\n \"invalid-input\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n // A fixed-amount invoice derives the amount itself — only an open one takes the caller's.\n const invoiceAmount = params.option.amountSats === undefined ? params.amountSats : undefined;\n const transfer = await spark.paySparkInvoice(ref, {\n invoice: params.option.invoice,\n ...(invoiceAmount === undefined ? {} : { amountSats: invoiceAmount }),\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"lightning\": {\n if (params.option.amountSats === undefined && params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"amountless invoice: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lightning payment: maxFeeSats is required\");\n }\n // amountSats is only for amountless invoices — a fixed-amount invoice must not carry it.\n if (params.option.expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"lightning invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\"invalid-input\", \"amountSats conflicts with the invoice amount\");\n }\n const payment = await spark.payInvoice(ref, {\n invoice: params.option.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.option.amountSats === undefined && params.amountSats !== undefined\n ? { amountSats: params.amountSats }\n : {}),\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-pay\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: maxFeeSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minSendableMsat || amountMsat > request.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: amount outside the service's range\");\n }\n if (request.commentAllowed === 0 && params.comment !== undefined) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comments not accepted by this service\");\n }\n if (params.comment !== undefined && params.comment.length > request.commentAllowed) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comment exceeds the service's limit\");\n }\n let requested;\n try {\n requested = await requestInvoice(request, {\n fetch: context.fetch,\n network: ref.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-pay: invoice request failed\", error);\n }\n const payment = await spark.payInvoice(ref, {\n invoice: requested.invoice,\n maxFeeSats: params.maxFeeSats,\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-withdraw\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-withdraw: amountSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minWithdrawableMsat || amountMsat > request.maxWithdrawableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-withdraw: amount outside the service's range\");\n }\n const invoice = await spark.createInvoice(ref, {\n amountSats: params.amountSats,\n memo: request.defaultDescription,\n });\n try {\n await submitWithdraw(request, { fetch: context.fetch, invoice: invoice.invoice });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-withdraw: submission failed\", error);\n }\n result = { kind: \"lnurl-withdraw\", invoice };\n break;\n }\n case \"bitcoin\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"bitcoin payment: amountSats is required\");\n }\n const exit = await spark.withdraw(ref, {\n address: params.option.address,\n speed: params.speed ?? \"MEDIUM\",\n verify: params.verify,\n amountSats: params.amountSats,\n ...(params.maxFeeSats === undefined ? {} : { maxFeeSats: params.maxFeeSats }),\n });\n result = { kind: \"withdraw\", exit };\n break;\n }\n }\n return result;\n}\n","import { resolveLnurl } from \"@qntx/spark/lnurl\";\n\nimport { PaymentError } from \"./errors.ts\";\nimport { parsePayment } from \"./parse.ts\";\nimport type { PaymentParse, ParseOptions } from \"./parse.ts\";\n\nexport type ResolveOptions = ParseOptions & {\n readonly fetch: typeof globalThis.fetch;\n};\n\n/**\n * `parsePayment` plus LNURL dereferencing: an `lnurl` result is fetched and turned into a concrete\n * `lnurl-pay` / `lnurl-withdraw` request (`tag=login` endpoints report as unsupported). Network\n * failures throw `PaymentError(\"network\")` — remote error bodies never enter the message.\n */\nexport async function resolvePayment(\n input: string,\n options: ResolveOptions,\n): Promise<PaymentParse> {\n const parsed = parsePayment(input, options);\n if (parsed.kind !== \"lnurl\") {\n return parsed;\n }\n let resolved;\n try {\n resolved = await resolveLnurl(parsed.url, { fetch: options.fetch });\n } catch {\n throw new PaymentError(\"network\", \"lnurl: resolution failed\");\n }\n if (resolved.tag === \"payRequest\") {\n return {\n kind: \"request\",\n request: {\n options: [\n {\n kind: \"lnurl-pay\",\n request: resolved,\n ...(parsed.address === undefined ? {} : { address: parsed.address }),\n },\n ],\n },\n };\n }\n if (resolved.tag === \"withdrawRequest\") {\n return {\n kind: \"request\",\n request: { options: [{ kind: \"lnurl-withdraw\", request: resolved }] },\n };\n }\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { Event, NostrSigner } from \"@qntx/nostr\";\nimport { makeZapRequest } from \"@qntx/nostr/nips/nip57\";\nimport { SparkInputError, decodeBolt11 } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport { encodeLnurl, lightningAddressUrl, requestInvoice, resolveLnurl } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { categorize } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\n\n/** A profile zap names the recipient pubkey; an event zap carries the event it zaps. */\nexport type ZapRecipient =\n | { readonly pubkey: string; readonly lightning: string }\n | { readonly event: Event; readonly lightning: string };\n\nexport type PrepareZapParams = {\n /** Any `NostrSigner` — wallet key, external key, NIP-07/46 — signs the 9734. */\n readonly signer: NostrSigner;\n readonly recipient: ZapRecipient;\n readonly amountSats: number;\n readonly comment?: string | undefined;\n readonly relays: ReadonlyArray<string>;\n readonly network: SparkNetwork;\n};\n\nexport type PrepareZapContext = {\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\n/** Everything a payer needs: the signed 9734, the invoice, and the note fields. */\nexport type PreparedZap = {\n readonly zapRequest: Event;\n readonly invoice: string;\n /** Hex payment hash decoded from the invoice. */\n readonly paymentHash: string;\n /** Millisecond expiry decoded from the invoice. */\n readonly expiresAt: number;\n readonly amountSats: number;\n /** The LNURL service's 9735 signing pubkey. */\n readonly receiptPubkey: string;\n readonly recipientPubkey: string;\n readonly eventId?: string;\n readonly comment?: string;\n /** The lud16 or LNURL as given. */\n readonly lightning: string;\n};\n\nexport type PayZapOptions = {\n readonly maxFeeSats: number;\n readonly verify: UnlockFactor;\n readonly now: () => number;\n};\n\n/** Everything up to payment: resolve LNURL, sign the 9734, request the invoice. */\nexport async function prepareZap(\n params: PrepareZapParams,\n context: PrepareZapContext,\n): Promise<PreparedZap> {\n const amountMsat = params.amountSats * 1000;\n if (\n !Number.isSafeInteger(params.amountSats) ||\n params.amountSats <= 0 ||\n !Number.isSafeInteger(amountMsat)\n ) {\n throw new PaymentError(\"invalid-input\", \"zap amount is not a positive safe integer\");\n }\n try {\n const resolved = await resolveLnurl(params.recipient.lightning, { fetch: context.fetch });\n if (resolved.tag !== \"payRequest\") {\n throw new PaymentError(\"rejected\", \"recipient is not an LNURL-pay endpoint\");\n }\n if (!resolved.allowsNostr || resolved.nostrPubkey === undefined) {\n throw new PaymentError(\"rejected\", \"LNURL service does not accept nostr zaps\");\n }\n if (amountMsat < resolved.minSendableMsat || amountMsat > resolved.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"zap amount outside the service's bounds\");\n }\n if (params.comment !== undefined) {\n if (resolved.commentAllowed === 0) {\n throw new PaymentError(\"rejected\", \"the service does not accept comments\");\n }\n if (params.comment.length > resolved.commentAllowed) {\n throw new PaymentError(\"rejected\", \"comment exceeds the service's limit\");\n }\n }\n // LNURL detection is case-insensitive; the 9734 carries lowercase bech32.\n const lnurl = params.recipient.lightning.toLowerCase().startsWith(\"lnurl1\")\n ? params.recipient.lightning.toLowerCase()\n : encodeLnurl(lightningAddressUrl(params.recipient.lightning));\n const base = {\n amount: amountMsat,\n relays: [...params.relays],\n comment: params.comment,\n lnurl,\n };\n const template =\n \"event\" in params.recipient\n ? makeZapRequest({ event: params.recipient.event, ...base })\n : makeZapRequest({ pubkey: params.recipient.pubkey, ...base });\n const unsigned = { ...template, pubkey: await params.signer.getPublicKey() };\n const zapRequest = await params.signer.signEvent(unsigned);\n // External signers (NIP-07/46) are untrusted: the 9734 must be validly signed over exactly\n // the template, or the receipt would commit to content the user never approved.\n if (!verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) {\n throw new PaymentError(\"rejected\", \"signer returned a zap request that does not match\");\n }\n const { invoice } = await requestInvoice(resolved, {\n fetch: context.fetch,\n network: params.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n zapRequest: JSON.stringify(zapRequest),\n });\n const decoded = decodeBolt11(invoice);\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expires too soon\");\n }\n const eventId = \"event\" in params.recipient ? params.recipient.event.id : undefined;\n return {\n zapRequest,\n invoice,\n paymentHash: bytesToHex(decoded.paymentHash),\n expiresAt,\n amountSats: params.amountSats,\n receiptPubkey: bytesToHex(resolved.nostrPubkey),\n recipientPubkey:\n \"event\" in params.recipient ? params.recipient.event.pubkey : params.recipient.pubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n lightning: params.recipient.lightning,\n };\n } catch (error) {\n if (error instanceof PaymentError) {\n throw error;\n }\n if (\n error instanceof SparkInputError ||\n (error instanceof Error && error.cause instanceof SparkInputError)\n ) {\n throw new PaymentError(\"rejected\", \"zap failed invoice validation\");\n }\n throw new PaymentError(categorizePayment(error), \"zap failed\");\n }\n}\n\n/**\n * Pays a prepared zap through the controller's approve-first path. A nearly-expired invoice is\n * rejected before approval — the user may have sat on the confirm screen since `prepareZap`.\n */\nexport async function payZap(\n spark: SparkController,\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: PayZapOptions,\n): Promise<LightningPayment> {\n if (prepared.expiresAt <= options.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expired\");\n }\n return spark.payInvoice(account, {\n invoice: prepared.invoice,\n maxFeeSats: options.maxFeeSats,\n verify: options.verify,\n note: {\n kind: \"zap\",\n recipientPubkey: prepared.recipientPubkey,\n ...(prepared.eventId === undefined ? {} : { eventId: prepared.eventId }),\n ...(prepared.comment === undefined ? {} : { comment: prepared.comment }),\n lightning: prepared.lightning,\n },\n });\n}\n\nfunction categorizePayment(error: unknown): \"network\" | \"rejected\" {\n const category = categorize(error);\n return category === \"network\" ? \"network\" : \"rejected\";\n}\n","import type { SparkPayment } from \"@qntx/spark\";\n\n/**\n * Local, engine-side metadata pinned to a history entry by transfer id. Written after the payment\n * it annotates has already succeeded — a missing or malformed note must never affect the payment\n * itself.\n */\nexport type PaymentNote = {\n readonly kind: \"zap\";\n /** 64 lowercase hex. */\n readonly recipientPubkey: string;\n /** 64 lowercase hex — event zaps carry the zapped event's id. */\n readonly eventId?: string;\n /** At most 2000 characters. */\n readonly comment?: string;\n /** The lud16 or LNURL the zap resolved. */\n readonly lightning: string;\n};\n\nexport type SparkActivity = SparkPayment & { readonly note?: PaymentNote };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst NOTE_FIELDS: ReadonlySet<string> = new Set([\n \"kind\",\n \"recipientPubkey\",\n \"eventId\",\n \"comment\",\n \"lightning\",\n]);\n\n/** Strict read-side validation: anything off-shape is `undefined`, never a throw. */\nexport function parsePaymentNote(value: unknown): PaymentNote | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const field of Object.keys(value)) {\n if (!NOTE_FIELDS.has(field)) {\n return undefined;\n }\n }\n const { kind, recipientPubkey, eventId, comment, lightning } = value;\n if (kind !== \"zap\") {\n return undefined;\n }\n if (typeof recipientPubkey !== \"string\" || !HEX64.test(recipientPubkey)) {\n return undefined;\n }\n if (eventId !== undefined && (typeof eventId !== \"string\" || !HEX64.test(eventId))) {\n return undefined;\n }\n if (comment !== undefined && (typeof comment !== \"string\" || comment.length > 2000)) {\n return undefined;\n }\n if (typeof lightning !== \"string\" || lightning.length === 0) {\n return undefined;\n }\n return {\n kind: \"zap\",\n recipientPubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(comment === undefined ? {} : { comment }),\n lightning,\n };\n}\n\nexport function encodePaymentNote(note: PaymentNote): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(note));\n}\n","/**\n * SparkExitChain persistence codec: JSON with Uint8Arrays tagged `{ $b64: \"…\" }` — small and\n * explicit rather than schema-bound, so upstream field additions survive a round-trip.\n */\nimport { base64 } from \"@scure/base\";\n\nimport type { SparkExitChain } from \"@qntx/spark\";\n\nfunction encodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { $b64: base64.encode(value) };\n }\n if (Array.isArray(value)) {\n return value.map(encodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, encodeValue(v)]));\n }\n return value;\n}\n\nfunction decodeValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(decodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value);\n const b64: unknown =\n entries.length === 1 && entries[0]?.[0] === \"$b64\" ? entries[0][1] : undefined;\n if (typeof b64 === \"string\") {\n return base64.decode(b64);\n }\n return Object.fromEntries(entries.map(([k, v]) => [k, decodeValue(v)]));\n }\n return value;\n}\n\nexport function encodeExitChain(chain: SparkExitChain): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(encodeValue(chain)));\n}\n\nexport function decodeExitChain(bytes: Uint8Array): SparkExitChain {\n const decoded: unknown = decodeValue(JSON.parse(new TextDecoder().decode(bytes)));\n // The codec round-trips what encodeExitChain wrote — the shape is structural.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return decoded as SparkExitChain;\n}\n","import type { SparkExitChain, SparkStore } from \"@qntx/spark\";\n\nimport type { EngineCollection } from \"../store/port.ts\";\nimport { decodeExitChain, encodeExitChain } from \"./exit-chain-codec.ts\";\n\nconst ALL = \"__all__\";\n\n/**\n * SparkStore over one EngineCollection: chains keyed by leafId, plus an index record listing them\n * (`exitChains` is a full listing — the port has no secondary index).\n */\nexport function sparkStore(col: EngineCollection): SparkStore {\n const readIndex = async (): Promise<string[]> => {\n const index = await col.get(ALL);\n if (index === undefined) {\n return [];\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(index));\n if (!Array.isArray(parsed)) {\n return [];\n }\n return parsed.filter((v): v is string => typeof v === \"string\");\n };\n const writeIndex = async (ids: ReadonlyArray<string>): Promise<void> => {\n await col.put(ALL, new TextEncoder().encode(JSON.stringify(ids)));\n };\n return {\n exitChains: async () => {\n const ids = await readIndex();\n const chains: SparkExitChain[] = [];\n for (const leafId of ids) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- reads must stay ordered and sequential\n const record = await col.get(leafId);\n if (record !== undefined) {\n chains.push(decodeExitChain(record));\n }\n }\n return chains;\n },\n putExitChains: async (chains) => {\n const ids = await readIndex();\n const set = new Set(ids);\n for (const chain of chains) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- writes commit one record at a time\n await col.put(chain.leafId, encodeExitChain(chain));\n set.add(chain.leafId);\n }\n await writeIndex([...set]);\n },\n deleteExitChains: async (leafIds) => {\n const ids = await readIndex();\n const drop = new Set(leafIds);\n for (const leafId of leafIds) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- deletes commit one record at a time\n await col.delete(leafId);\n }\n await writeIndex(ids.filter((leafId) => !drop.has(leafId)));\n },\n };\n}\n","import {\n bitcoinAddressScript,\n decodeSparkAddress,\n encodeSparkAddress,\n parseSparkInvoice,\n SparkInputError,\n uuidv7,\n} from \"@qntx/spark\";\nimport type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkClient,\n SparkPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { registerLightningAddress, unregisterLightningAddress } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef, SparkApproveIntent } from \"@qntx/wallet/protocol\";\nimport type { SparkSigner } from \"@qntx/wallet/spark\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore, EngineCollection } from \"../store/port.ts\";\nimport { categorize, SparkControllerError } from \"./errors.ts\";\nimport { encodePaymentNote, parsePaymentNote } from \"./notes.ts\";\nimport type { PaymentNote, SparkActivity } from \"./notes.ts\";\nimport { sparkStore } from \"./store.ts\";\n\nexport type SparkAccountState = {\n readonly status: \"locked\" | \"connecting\" | \"ready\" | \"error\";\n readonly balanceSats?: number;\n readonly identityPublicKey?: string;\n readonly sparkAddress?: string;\n readonly errorCategory?: string;\n /** First history page (20 entries, newest first), refreshed alongside the balance. */\n readonly recent?: ReadonlyArray<SparkActivity>;\n};\n\nexport type SparkControllerState = {\n readonly accounts: Readonly<Record<string, SparkAccountState>>;\n};\n\ntype SparkApis = {\n readonly signer: (ref: SparkAccountRef) => SparkSigner;\n readonly approve: (params: {\n account: SparkAccountRef;\n intent: SparkApproveIntent;\n verify: UnlockFactor;\n }) => Promise<unknown>;\n};\n\nexport type SparkClientFactory = (options: {\n readonly ref: SparkAccountRef;\n readonly store: ReturnType<typeof sparkStore>;\n readonly signer: SparkSigner;\n readonly fetch: typeof globalThis.fetch;\n}) => SparkClient;\n\nexport type SparkControllerOptions = {\n readonly spark: SparkApis;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly createClient: SparkClientFactory;\n};\n\nconst key = (ref: SparkAccountRef): string => `${ref.walletId}:${ref.groupIndex}:${ref.network}`;\n\n/** TransferId: the client and SO expect a UUIDv7 — mint it from the injected clock+random. */\nconst transferId = (random: (n: number) => Uint8Array, now: () => number): string =>\n uuidv7(random, now);\n\n/** Catch-up sync for one pass: claim every pending transfer, then read balance and identity. */\nasync function resync(\n client: SparkClient,\n log: (transferId: string, error: unknown) => void,\n): Promise<{ balance: number; identity: Uint8Array }> {\n const { failures } = await client.transfers.claimPending();\n for (const failure of failures) {\n log(failure.transferId, failure.error);\n }\n const [balance, identity] = await Promise.all([client.balance(), client.identityPublicKey()]);\n return { balance, identity };\n}\n\n/** Abortable backoff — resolves early when the signal aborts; removes its listener. */\nasync function eventsBackoff(failures: number, signal: AbortSignal): Promise<void> {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n Math.min(2 ** failures, 30) * 1000,\n );\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nexport class SparkController extends Controller<SparkControllerState> {\n private readonly options: SparkControllerOptions;\n private engineStore: EngineStore | undefined;\n private readonly accounts = new Map<string, SparkAccountRef>();\n private readonly clients = new Map<string, SparkClient>();\n private readonly recentSeq = new Map<string, number>();\n private readonly aborts = new Map<string, AbortController>();\n\n constructor(options: SparkControllerOptions) {\n super({ name: \"spark\", defaultState: () => ({ accounts: {} }) });\n this.options = options;\n }\n\n /** Engine calls this with the open store on unlock; `undefined` on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /**\n * Declarative account set: refs not yet tracked are patched `locked` and started when the store\n * is open; tracked refs no longer listed are stopped and dropped; running refs stay untouched.\n */\n setAccounts(refs: ReadonlyArray<SparkAccountRef>): void {\n const wanted = new Map(refs.map((ref) => [key(ref), ref]));\n for (const k of this.accounts.keys()) {\n if (!wanted.has(k)) {\n this.accounts.delete(k);\n this.stopAccount(k);\n }\n }\n for (const [k, ref] of wanted) {\n if (!this.accounts.has(k)) {\n this.accounts.set(k, ref);\n this.patch(k, { status: \"locked\" });\n }\n if (this.engineStore !== undefined && !this.clients.has(k)) {\n this.startAccount(ref);\n }\n }\n }\n\n async init(): Promise<void> {\n for (const ref of this.accounts.values()) {\n this.startAccount(ref);\n }\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n await this.lockAll();\n }\n\n private stopAccount(k: string): void {\n this.aborts.get(k)?.abort();\n this.aborts.delete(k);\n this.clients.get(k)?.close();\n this.clients.delete(k);\n this.update((s) => {\n if (!(k in s.accounts)) {\n return s;\n }\n const { [k]: _dropped, ...rest } = s.accounts;\n void _dropped;\n return { ...s, accounts: rest };\n });\n }\n\n /** Lock: abort every event loop, close every client, reset state. */\n async lockAll(): Promise<void> {\n for (const [k, client] of this.clients) {\n this.aborts.get(k)?.abort();\n client.close();\n }\n this.aborts.clear();\n this.clients.clear();\n this.engineStore = undefined;\n await Promise.resolve();\n this.update((s) =>\n Object.keys(s.accounts).length === 0\n ? s\n : {\n ...s,\n accounts: Object.fromEntries(\n Object.keys(s.accounts).map((k) => [k, { status: \"locked\" as const }]),\n ),\n },\n );\n }\n\n private startAccount(ref: SparkAccountRef): void {\n const k = key(ref);\n if (this.engineStore === undefined || this.clients.has(k)) {\n return;\n }\n this.patch(k, { status: \"connecting\" });\n try {\n const col = this.engineStore.collection(`spark-exit-chains:${k}`);\n const client = this.options.createClient({\n ref,\n store: sparkStore(col),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n this.clients.set(k, client);\n const abort = new AbortController();\n this.aborts.set(k, abort);\n // The initial sync lives in the event loop's catch-up pass: a transient failure at\n // account start retries through the loop's backoff instead of leaving the account dead\n // in \"error\".\n this.runEvents(k, client, abort.signal, ref.network);\n } catch (error) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n this.options.logger.warn(\"spark account failed to start\", error);\n }\n }\n\n private runEvents(\n k: string,\n client: SparkClient,\n signal: AbortSignal,\n network: SparkAccountRef[\"network\"],\n ): void {\n // Every pass resyncs before streaming: the catch-up claim retries anything a previous\n // pass failed on and covers events missed while disconnected — a failed claim is never\n // lost, only deferred one pass. Any throw or a clean stream end backs off (exponential,\n // abortable) and starts a new pass.\n const loop = async (): Promise<void> => {\n let failures = 0;\n while (!signal.aborted) {\n try {\n // Catch-up: claim pending transfers and refresh the balance snapshot. Per-transfer\n // failures are logged, not fatal — one poisoned transfer must not fail the pass.\n // oxlint-disable-next-line no-await-in-loop -- catch-up sync must precede streaming\n const { balance, identity } = await resync(client, (transferId, error) => {\n this.options.logger.warn(\n `spark catch-up claim failed for ${transferId} (${categorize(error)})`,\n );\n });\n if (signal.aborted) {\n return;\n }\n this.patch(k, {\n balanceSats: balance,\n status: \"ready\",\n identityPublicKey: [...identity].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\"),\n sparkAddress: encodeSparkAddress({\n network,\n identityPublicKey: identity,\n }),\n });\n void this.refreshRecent(k, client);\n const iterator = client.events(signal)[Symbol.asyncIterator]();\n let open = true;\n while (open) {\n // oxlint-disable-next-line no-await-in-loop -- events arrive in stream order\n const item = await iterator.next();\n if (item.done === true) {\n open = false;\n } else {\n const event = item.value;\n if (event.type === \"transfer\") {\n try {\n // oxlint-disable-next-line no-await-in-loop -- claims are ordered per event\n await this.handleTransfer(client, event, signal, k);\n failures = 0;\n } catch (error) {\n // A terminal status (expired, returned…) is not a stream failure — log the\n // transfer and keep consuming the stream.\n if (!(error instanceof SparkInputError)) {\n throw error;\n }\n this.options.logger.warn(\n `spark claim of ${event.transferId} rejected (${categorize(error)})`,\n );\n failures = 0;\n }\n }\n }\n }\n // A clean end is abnormal for a permanent stream — back off like a failure.\n failures += 1;\n this.options.logger.warn(\"spark event stream ended — resubscribing\");\n } catch (error) {\n if (signal.aborted) {\n return;\n }\n failures += 1;\n if (failures === 1) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n }\n this.options.logger.warn(\"spark event stream failed — resubscribing\", error);\n }\n // oxlint-disable-next-line no-await-in-loop -- the backoff bounds resubscribe pace\n await eventsBackoff(failures, signal);\n }\n };\n void loop();\n }\n\n private async handleTransfer(\n client: SparkClient,\n event: { readonly direction: \"incoming\" | \"outgoing\"; readonly transferId: string },\n signal: AbortSignal,\n k: string,\n ): Promise<void> {\n if (event.direction === \"incoming\") {\n // claim(id) re-queries until the transfer turns claimable — it owns the protocol-level\n // wait for the SSP's claimable window, so no extra delay or pending-list scan here.\n await client.transfers.claim(event.transferId, { signal });\n }\n this.patch(k, { balanceSats: await client.balance() });\n void this.refreshRecent(k, client);\n }\n\n private notesCollection(k: string): EngineCollection | undefined {\n return this.engineStore?.collection(`spark-notes:${k}`);\n }\n\n /** Attach locally written notes to a history page; malformed records warn and drop. */\n private async withNotes(\n k: string,\n payments: ReadonlyArray<SparkPayment>,\n ): Promise<ReadonlyArray<SparkActivity>> {\n const col = this.notesCollection(k);\n if (col === undefined) {\n return payments;\n }\n return Promise.all(\n payments.map(async (payment): Promise<SparkActivity> => {\n const bytes = await col.get(payment.id);\n if (bytes === undefined) {\n return payment;\n }\n let note: PaymentNote | undefined;\n try {\n note = parsePaymentNote(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n note = undefined;\n }\n if (note === undefined) {\n this.options.logger.warn(\n `spark note record for ${payment.id} ignored: malformed`,\n new Error(\"malformed payment note\"),\n );\n return payment;\n }\n return { ...payment, note };\n }),\n );\n }\n\n /**\n * Refill `recent` from the first history page. A failure keeps the previous page — it never\n * touches `status`/`errorCategory`. A per-account sequence keeps a slower older refresh from\n * overwriting a newer one.\n */\n private async refreshRecent(k: string, client: SparkClient): Promise<void> {\n const seq = (this.recentSeq.get(k) ?? 0) + 1;\n this.recentSeq.set(k, seq);\n try {\n const { payments } = await client.transfers.history({ limit: 20 });\n const items = await this.withNotes(k, payments);\n // A stale seq or a closed client (lockAll cleared the map) must not write.\n if (this.recentSeq.get(k) === seq && this.clients.get(k) === client) {\n this.patch(k, { recent: items });\n }\n } catch (error) {\n this.options.logger.warn(`spark recent refresh failed for ${k}`, error);\n }\n }\n\n private patch(k: string, delta: Partial<SparkAccountState>): void {\n this.update((s) => ({\n ...s,\n accounts: { ...s.accounts, [k]: { status: \"locked\" as const, ...s.accounts[k], ...delta } },\n }));\n }\n\n private clientFor(ref: SparkAccountRef): SparkClient {\n const client = this.clients.get(key(ref));\n if (client === undefined) {\n throw new SparkControllerError(\"internal\", \"account is not connected\");\n }\n return client;\n }\n\n private async guarded<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof SparkControllerError) {\n throw error;\n }\n throw new SparkControllerError(categorize(error), \"spark action failed\", error);\n }\n }\n\n /**\n * One-off balance + activity probe for an account that may not be running: builds a temporary\n * client through the same factory on the account's own exit-chain collection (nothing diverges —\n * `balance()`/`transfers.history` never write it), reads, and closes it in `finally`.\n */\n async inspect(ref: SparkAccountRef): Promise<{ balanceSats: number; used: boolean }> {\n return this.guarded(async () => {\n if (this.engineStore === undefined) {\n throw new SparkControllerError(\"internal\", \"engine store is not open\");\n }\n const k = key(ref);\n const running = this.clients.get(k);\n if (running !== undefined) {\n const [balance, page] = await Promise.all([\n running.balance(),\n running.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n }\n const client = this.options.createClient({\n ref,\n store: sparkStore(this.engineStore.collection(`spark-exit-chains:${k}`)),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n try {\n const [balance, page] = await Promise.all([\n client.balance(),\n client.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n } finally {\n client.close();\n }\n });\n }\n\n /** History for one account: a client page merged with locally written notes by id. */\n async history(\n ref: SparkAccountRef,\n options?: {\n readonly limit?: number;\n readonly offset?: number;\n },\n ): Promise<{\n readonly items: ReadonlyArray<SparkActivity>;\n readonly nextOffset: number | undefined;\n }> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const { payments, nextOffset } = await client.transfers.history({\n ...(options?.limit === undefined ? {} : { limit: options.limit }),\n ...(options?.offset === undefined ? {} : { offset: options.offset }),\n });\n return { items: await this.withNotes(key(ref), payments), nextOffset };\n });\n }\n\n async send(\n ref: SparkAccountRef,\n params: {\n receiver: string;\n amountSats: number;\n verify: UnlockFactor;\n },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const receiver = decodeSparkAddress(params.receiver);\n if (receiver.network !== ref.network) {\n throw new SparkControllerError(\"rejected\", \"receiver address is on a different network\");\n }\n const identity = receiver.identityPublicKey;\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: identity, amountSats: params.amountSats }],\n },\n verify: params.verify,\n });\n const transfer = await client.transfers.send({\n receiver: params.receiver,\n amountSats: params.amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return transfer;\n });\n }\n\n async registerLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string; description: string },\n ): Promise<{ lnurl: string; lightningAddress: string }> {\n const signer = this.options.spark.signer(ref);\n try {\n return await registerLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"registration failed\");\n }\n }\n\n async unregisterLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string },\n ): Promise<void> {\n const signer = this.options.spark.signer(ref);\n try {\n await unregisterLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"unregistration failed\");\n }\n }\n\n async payInvoice(\n ref: SparkAccountRef,\n params: {\n invoice: string;\n amountSats?: number;\n maxFeeSats: number;\n verify: UnlockFactor;\n /** Local annotation written under the payment's transfer id after it succeeds. */\n note?: PaymentNote;\n },\n ): Promise<LightningPayment> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"lightning\",\n invoice: params.invoice,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n maxFeeSats: params.maxFeeSats,\n },\n verify: params.verify,\n });\n const payment = await client.lightning.pay({\n invoice: params.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n transferId: transferId(this.options.random, this.options.now),\n });\n if (params.note !== undefined) {\n try {\n await this.notesCollection(key(ref))?.put(\n payment.transferId,\n encodePaymentNote(params.note),\n );\n } catch (error) {\n // The payment already succeeded — a lost annotation is a warning, not a failure.\n this.options.logger.warn(\"spark note write failed\", error);\n }\n }\n void this.refreshRecent(key(ref), client);\n return payment;\n });\n }\n\n /**\n * Pays a Spark invoice address. The approval intent mirrors `send`: receiver identity and amount\n * come from the parsed invoice (the supplied `amountSats` fills an open invoice). Then\n * `client.invoices.pay` executes it.\n */\n async paySparkInvoice(\n ref: SparkAccountRef,\n params: { invoice: string; amountSats?: number; verify: UnlockFactor },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const parsed = parseSparkInvoice(params.invoice, {\n network: ref.network,\n now: this.options.now(),\n });\n const invoicePayment = parsed.fields.payment;\n if (invoicePayment !== undefined && invoicePayment.type !== \"sats\") {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: only sats invoices are supported\",\n );\n }\n if (\n invoicePayment?.type === \"sats\" &&\n invoicePayment.amount !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== invoicePayment.amount\n ) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n const amountSats =\n invoicePayment?.type === \"sats\" && invoicePayment.amount !== undefined\n ? invoicePayment.amount\n : params.amountSats;\n if (amountSats === undefined) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountless invoice requires amountSats\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: parsed.receiverIdentityPublicKey, amountSats }],\n },\n verify: params.verify,\n });\n const result = await client.invoices.pay(params.invoice, {\n amount: amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n // invoices.pay returns a string for token invoices — unreachable after the pre-approval\n // sats check above, kept as the internal guard.\n if (typeof result === \"string\") {\n throw new SparkControllerError(\"internal\", \"unexpected token invoice result\");\n }\n return result;\n });\n }\n\n async createInvoice(\n ref: SparkAccountRef,\n params: { amountSats: number; memo?: string },\n ): Promise<LightningInvoice> {\n return this.guarded(async () =>\n this.clientFor(ref).lightning.createInvoice({\n amountSats: params.amountSats,\n ...(params.memo === undefined ? {} : { memo: params.memo }),\n }),\n );\n }\n\n async receiveAddress(ref: SparkAccountRef): Promise<string | undefined> {\n const state = this.getState().accounts[key(ref)];\n await Promise.resolve();\n return state?.sparkAddress;\n }\n\n /**\n * Cooperative exit to an L1 address. The client exits `amountSats` of leaves and the payout is\n * `amountSats - fee`, so the approval intent carries the PAYOUT: `amountSats: exit - fee` and\n * `maxFeeSats: fee` — the kernel matches the exit output against the intent, not the leaf total.\n */\n async withdraw(\n ref: SparkAccountRef,\n params: {\n address: string;\n amountSats?: number;\n speed: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n maxFeeSats?: number;\n verify: UnlockFactor;\n },\n ): Promise<CooperativeExitResult> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n try {\n bitcoinAddressScript(params.address, ref.network);\n } catch {\n throw new SparkControllerError(\"rejected\", \"withdrawal address is not on this network\");\n }\n const exitAmount = params.amountSats ?? (await client.balance());\n const quote = await client.withdrawals.quoteCooperativeExit({\n address: params.address,\n amountSats: exitAmount,\n });\n const fee =\n quote.fees[\n params.speed === \"FAST\" ? \"fast\" : params.speed === \"MEDIUM\" ? \"medium\" : \"slow\"\n ];\n if (params.maxFeeSats !== undefined && params.maxFeeSats < fee) {\n throw new SparkControllerError(\"rejected\", \"maxFeeSats below the quoted fee\");\n }\n if (fee >= exitAmount) {\n throw new SparkControllerError(\n \"insufficient-funds\",\n \"exit fee meets or exceeds the amount\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"exit\",\n address: params.address,\n amountSats: exitAmount - fee,\n maxFeeSats: fee,\n },\n verify: params.verify,\n });\n const exit = await client.withdrawals.cooperativeExit({\n address: params.address,\n speed: params.speed,\n maxFeeSats: fee,\n amountSats: exitAmount,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return exit;\n });\n }\n}\n","/**\n * Composition root: wires the Wallet's lock state to the SparkController's lifecycle. Unlocked →\n * open the EngineStore and start every declared account; locked → abort event loops, close every\n * client, close the store and reset account state. Transitions are serialized on one promise chain,\n * so an unlock→lock flip can never overlap a still-opening store.\n */\nimport { createSparkClient } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport { nostr } from \"@qntx/wallet/nostr\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\nimport { spark } from \"@qntx/wallet/spark\";\n\nimport { AccountTreeController } from \"./accounts/controller.ts\";\nimport { BackupController } from \"./backup/controller.ts\";\nimport type { CloudStore } from \"./backup/port.ts\";\nimport type { EngineLogger } from \"./events.ts\";\nimport { MetaSyncController } from \"./meta/controller.ts\";\nimport type { MetaSyncConfig } from \"./meta/controller.ts\";\nimport { parsePayment } from \"./payments/parse.ts\";\nimport type { PaymentParse } from \"./payments/parse.ts\";\nimport { pay as runPay } from \"./payments/pay.ts\";\nimport type { PayParams } from \"./payments/pay.ts\";\nimport { resolvePayment } from \"./payments/resolve.ts\";\nimport { payZap, prepareZap } from \"./payments/zap.ts\";\nimport type { PrepareZapParams, PreparedZap, PayZapOptions } from \"./payments/zap.ts\";\nimport { SparkController } from \"./spark/controller.ts\";\nimport type { SparkControllerOptions } from \"./spark/controller.ts\";\nimport type { EngineStore } from \"./store/port.ts\";\n\nexport type EngineOptions = {\n readonly wallet: Wallet;\n /** Every Spark account the engine touches lives on this network. */\n readonly sparkNetwork: SparkNetwork;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly openStore: () => Promise<EngineStore>;\n /** Cloud file transport for the backup controller; absent → `unavailable`. */\n readonly cloud?: CloudStore;\n /** Kind-30078 wallet-metadata sync; absent → every wallet reports `unavailable`. */\n readonly metaSync?: MetaSyncConfig;\n /** Test seam — defaults to the wallet's real spark proxy. */\n readonly sparkApis?: SparkControllerOptions[\"spark\"];\n};\n\nexport type WalletEngine = {\n readonly spark: SparkController;\n readonly accounts: AccountTreeController;\n readonly metaSync: MetaSyncController;\n readonly backup: BackupController;\n readonly zaps: {\n readonly prepare: (params: PrepareZapParams) => Promise<PreparedZap>;\n readonly pay: (\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: Omit<PayZapOptions, \"now\">,\n ) => Promise<LightningPayment>;\n };\n readonly payments: {\n readonly parse: (input: string, network: SparkNetwork) => PaymentParse;\n readonly resolve: (input: string, network: SparkNetwork) => Promise<PaymentParse>;\n readonly pay: (params: PayParams) => Promise<unknown>;\n };\n readonly unsubscribe: () => void;\n};\n\nexport function createWalletEngine(options: EngineOptions): WalletEngine {\n const backup = new BackupController({\n wallet: options.wallet,\n cloud: options.cloud,\n now: options.now,\n logger: options.logger,\n });\n\n const controller = new SparkController({\n spark: options.sparkApis ?? spark(options.wallet),\n fetch: options.fetch,\n random: options.random,\n now: options.now,\n logger: options.logger,\n createClient: ({ ref, store, signer, fetch }) =>\n createSparkClient({\n network: ref.network,\n signer,\n store,\n fetch,\n }),\n });\n\n const accounts = new AccountTreeController({\n wallet: options.wallet,\n spark: controller,\n sparkNetwork: options.sparkNetwork,\n logger: options.logger,\n now: options.now,\n });\n\n const metaSync = new MetaSyncController({\n wallet: options.wallet,\n accounts,\n nostr: { signer: (ref) => nostr(options.wallet).signer(ref) },\n metaSync: options.metaSync,\n logger: options.logger,\n now: options.now,\n });\n\n // The transition chain: every status change queues behind the previous one, so a late lock\n // always observes the snapshot left by a settled unlock (and vice versa).\n let chain: Promise<void> = Promise.resolve();\n let store: EngineStore | undefined;\n let started = false;\n\n const transition = async (): Promise<void> => {\n const unlocked = options.wallet.getSnapshot().vault === \"unlocked\";\n if (unlocked && !started) {\n started = true;\n try {\n store = await options.openStore();\n } catch (error) {\n // No store, no clients — reset so the next status event retries cleanly.\n started = false;\n store = undefined;\n options.logger.warn(\"engine store failed to open\", error);\n return;\n }\n controller.setStore(store);\n backup.setStore(store);\n accounts.setStore(store);\n backup.trigger(); // reconcile — never awaited on the transition chain\n // Load + reconcile + drive the selected account through spark.setAccounts.\n await accounts.init();\n await controller.init();\n // Pull → merge → maybe publish for every wallet with a group-0 identity.\n await metaSync.init();\n } else if (!unlocked && started) {\n started = false;\n // Lock: cancel sync write-backs, tree → locked, spark.setAccounts([]), totals flush.\n await metaSync.lock();\n await accounts.lock();\n await controller.lockAll();\n controller.setStore(undefined);\n const s = store;\n store = undefined;\n await s?.close();\n }\n };\n\n const snapshotListener = (): void => {\n // Every snapshot change while unlocked nudges the reconcile; the lock transition is\n // handled inside transition() and bumps the backup generation.\n if (options.wallet.getSnapshot().vault === \"unlocked\") {\n backup.trigger();\n accounts.reconcile();\n metaSync.reconcile();\n } else {\n backup.lock();\n }\n };\n\n const schedule = (): void => {\n const previous = chain;\n chain = (async () => {\n try {\n await previous;\n await transition();\n } catch (error) {\n options.logger.warn(\"engine lock transition failed\", error);\n }\n })();\n };\n const unsubscribe = options.wallet.subscribe(() => {\n schedule();\n snapshotListener();\n });\n schedule();\n return {\n spark: controller,\n accounts,\n metaSync,\n backup,\n zaps: {\n prepare: async (params) => prepareZap(params, { fetch: options.fetch, now: options.now }),\n pay: async (account, prepared, payOptions) =>\n payZap(controller, account, prepared, { ...payOptions, now: options.now }),\n },\n payments: {\n parse: (input, network) => parsePayment(input, { network, now: options.now() }),\n resolve: async (input, network) =>\n resolvePayment(input, { network, now: options.now(), fetch: options.fetch }),\n pay: async (params) =>\n runPay({ spark: controller, fetch: options.fetch, now: options.now }, params),\n },\n unsubscribe,\n };\n}\n","import type { CloudStore } from \"./port.ts\";\n\nconst tick = Promise.resolve();\n\n/** In-memory CloudStore for tests and the playground; swap the Map for cross-engine sharing. */\nexport function createMemoryCloudStore(backing?: Map<string, string>): CloudStore {\n const files = backing ?? new Map<string, string>();\n let reachable = true;\n const store: CloudStore & { readonly setReachable: (v: boolean) => void } = {\n available: async () => {\n await tick;\n return reachable;\n },\n list: async () => {\n await tick;\n return [...files.keys()].sort();\n },\n read: async (name) => {\n await tick;\n return files.get(name);\n },\n write: async (name, text) => {\n await tick;\n files.set(name, text);\n },\n delete: async (name) => {\n await tick;\n files.delete(name);\n },\n setReachable: (v) => {\n reachable = v;\n },\n };\n return store;\n}\n"],"ignoreList":[7,8,9,10],"mappings":";;;;;;;;;;;;;;;AAaA,IAAsB,aAAtB,MAAoE;CAClE;CACA;CAEA,YAAsB,SAA+B;EACnD,KAAK,OAAO,QAAQ;EACpB,KAAK,QAAQ,YAAe,QAAQ,YAAY;CAClD;CAEA,WAAc;EACZ,OAAO,KAAK,MAAM,SAAS;CAC7B;CAEA,OAAiB,QAA+B;EAC9C,KAAK,MAAM,UAAU,UAAU,OAAO,KAAK,CAAC;CAC9C;AAIF;;;ACrBA,SAAgB,eAAkB,QAAmC;CACnE,MAAM,4BAAY,IAAI,IAA8C;CACpE,OAAO;EACL,KAAwB,MAAS,SAAqB;GACpD,MAAM,MAAM,UAAU,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GACV;GAEF,KAAK,MAAM,YAAY,KACrB,IAAI;IACF,SAAS,OAAO;GAClB,SAAS,OAAO;IACd,OAAO,KAAK,wBAAwB,KAAK;GAC3C;EAEJ;EACA,GAAsB,MAAS,UAA+C;GAC5E,IAAI,MAAM,UAAU,IAAI,IAAI;GAC5B,IAAI,QAAQ,KAAA,GAAW;IACrB,sBAAM,IAAI,IA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