import type { Engine, GetSpendableResourcesParameters, InvitationParameters, } from "@xo-cash/engine"; import { generateTemplateIdentifier, hasInvitationExpired, mergeInvitationCommits, } from "@xo-cash/engine"; import type { XOInvitation, XOInvitationCommit, XOInvitationInput, XOInvitationOutput, XOInvitationVariable, XOInvitationVariableValue, XOTemplate, XOTemplateActionIntent, } from "@xo-cash/types"; import type { UnspentOutputData } from "@xo-cash/state"; import { binToHex, encodeTransaction, generateTransaction, hashTransaction, hexToBin, } from "@bitauth/libauth"; import type { SSEvent } from "../utils/sse-client.js"; import type { SyncServer } from "../utils/sync-server.js"; import type { BaseStorage } from "./storage.js"; import type { BlockchainService } from "./electrum.js"; import { EventEmitter } from "../utils/event-emitter.js"; import { decodeExtendedJsonObject } from "../utils/ext-json.js"; import { compileCashAssemblyString } from "@xo-cash/utils"; import type { ResolvedInvitationData } from "../utils/resolve-invitation-data.js"; import { resolveCommitReferences } from "../utils/resolve-invitation-data.js"; export type InvitationEventMap = { "invitation-updated": XOInvitation; "invitation-status-changed": string; "invitation-removed": string; error: Error; }; export type InvitationDependencies = { syncServer: SyncServer; storage: BaseStorage; engine: Engine; electrum: BlockchainService; }; export type FeeAwareChangeResult = { changeAmountSatoshis: bigint; feeSatoshis: bigint; }; function stripLocalInvitationMetadata(invitation: XOInvitation): XOInvitation { const { entityIdentifier: _entityIdentifier, ...sharedInvitation } = invitation as XOInvitation & { entityIdentifier?: string }; return sharedInvitation; } export class Invitation extends EventEmitter { /** * Create an invitation and start the SSE Session required for it. */ static async create( invitation: XOInvitation | string, dependencies: InvitationDependencies, ): Promise { // If the invitation is a string, its probably an invitation identifier. // We will try to find the data then just call the create method again, but this time with the data. if (typeof invitation === "string") { // Try to get the invitation from the storage const invitationFromStorage = await dependencies.storage.get(invitation); if (invitationFromStorage) { return this.create(invitationFromStorage, dependencies); } // Try to get the invitation from the sync server const invitationFromSyncServer = await dependencies.syncServer.getInvitation(invitation); if ( invitationFromSyncServer && invitationFromSyncServer.invitationIdentifier === invitation ) { return this.create(invitationFromSyncServer, dependencies); } // We cant find it. Throw an error. throw new Error( `Invitation not found in local or remote storage: ${invitation}`, ); } const template = await dependencies.engine.getTemplate( invitation.templateIdentifier, ); if (!template) { throw new Error(`Template not found: ${invitation.templateIdentifier}`); } const ensureEngineInvitation = async (invitation: XOInvitation) => { try { return await dependencies.engine.getInvitationOrThrow(invitation.invitationIdentifier); } catch { return await dependencies.engine.acceptInvitation(invitation); } } const engineInvitation = await ensureEngineInvitation(invitation); // Create the invitation const invitationInstance = new Invitation( engineInvitation, dependencies, template, ); return invitationInstance; } /** * Flattened, template-enriched view of {@link Invitation.data}. * Updated automatically whenever invitation data changes. */ public resolvedData: ResolvedInvitationData = { invitationIdentifier: "", templateIdentifier: "", actionIdentifier: "", variables: [], inputs: [], outputs: [], }; /** * The template used to enrich {@link resolvedData}. */ private template: XOTemplate; /** * The invitation data. */ public data: XOInvitation = { invitationIdentifier: "", commits: [], createdAtTimestamp: 0, templateIdentifier: "", actionIdentifier: "", }; /** * The sync server instance. */ private syncServer: SyncServer; /** * The engine instance. */ private engine: Engine; /** * The storage instance. * TODO: This should be a composite with the sync server (probably. We currently double handle this work, which is stupid) */ private storage: BaseStorage; private electrum: BlockchainService; private sseUpdateQueue: Promise = Promise.resolve(); /** * The status of the invitation (last emitted word: pending, actionable, signed, ready, complete, expired, unknown). */ public status: string = "unknown"; /** * Create an invitation and start the SSE Session required for it. */ constructor( invitation: XOInvitation, dependencies: InvitationDependencies, template: XOTemplate, ) { super(); this.template = template; this.engine = dependencies.engine; this.syncServer = dependencies.syncServer; this.storage = dependencies.storage; this.electrum = dependencies.electrum; this.updateInvitationData(invitation); // Apply SSE updates serially so each engine update sees the latest history. this.syncServer.on("message", (event) => { this.enqueueSyncUpdate(() => this.handleSSEMessage(event)).catch( (error) => { this.emit( "error", error instanceof Error ? error : new Error(String(error)), ); }, ); }); } /** * Updates raw invitation data and recomputes {@link resolvedData}. */ private updateInvitationData(invitation: XOInvitation): void { this.data = invitation; this.resolvedData = resolveCommitReferences(invitation, this.template); } private enqueueSyncUpdate(update: () => Promise): Promise { const queuedUpdate = this.sseUpdateQueue.then(update); this.sseUpdateQueue = queuedUpdate.catch(() => {}); return queuedUpdate; } /** * Start the invitation - Connect sync server and download latest invitation data. */ async start(): Promise { // Persist immediately so imports survive sync-server outages and appear in the TUI // after a CLI import or app restart. await this.storage.set(this.data.invitationIdentifier, this.data); try { // Connect to the sync server and get the invitation (in parallel) const [_, invitation] = await Promise.all([ this.syncServer.connect(), this.syncServer.getInvitation(this.data.invitationIdentifier), ]); await this.enqueueSyncUpdate(async () => { // SSE messages can arrive before the GET request completes. const combinedCommits = this.mergeCommits( this.data.commits, invitation?.commits ?? [], ); try { // Prefer keeping the engine's local invitation state in sync. this.updateInvitationData( stripLocalInvitationMetadata( await this.engine.updateInvitation( { ...this.data, ...invitation, commits: combinedCommits, } ), ), ); } catch (error) { console.error(error); this.emit( "error", error instanceof Error ? error : new Error(String(error)), ); this.updateInvitationData({ ...this.data, commits: combinedCommits }); } await this.storage.set(this.data.invitationIdentifier, this.data); }); // Publish the invitation to the sync server this.publishInvitation(this.data); // Compute and emit initial status await this.updateStatus(); } catch (err) { this.emit("error", err instanceof Error ? err : new Error(String(err))); } } /** * Handle an SSE message. * * TODO: Invitation should sync up the initial data (top level) then everything after that should be the commits. This makes it easier to merge as we go instead of just having to overwrite the entire invitation. */ private async handleSSEMessage(event: { event: "invitation-updated"; data: XOInvitation }): Promise { const invitation = event.data; if ( !invitation || invitation.invitationIdentifier !== this.data.invitationIdentifier ) { return; } // Filter out commits that already exist const newCommits = this.mergeCommits(this.data.commits, invitation.commits); try { this.updateInvitationData( stripLocalInvitationMetadata( await this.engine.updateInvitation({ ...this.data, ...invitation, commits: newCommits, }), ), ); } catch (error) { console.error(error); this.emit( "error", error instanceof Error ? error : new Error(String(error)), ); this.updateInvitationData({ ...this.data, commits: newCommits }); } await this.storage.set(this.data.invitationIdentifier, this.data); await this.updateStatus(); this.emit("invitation-updated", this.data); } private parseInvitationFromSSEMessage(event: SSEvent): XOInvitation | null { try { const parsed = JSON.parse(event.data) as unknown; const payload = event.event === "invitation-updated" ? this.unwrapInvitationUpdatedPayload(parsed) : this.unwrapLegacyInvitationUpdatedPayload(parsed); if (!payload) return null; const decoded = decodeExtendedJsonObject(payload) as XOInvitation; return stripLocalInvitationMetadata( decoded, ); } catch { return null; } } private unwrapInvitationUpdatedPayload(payload: unknown): unknown | null { if ( payload && typeof payload === "object" && "topic" in payload && "data" in payload ) { return this.unwrapLegacyInvitationUpdatedPayload(payload); } return payload; } private unwrapLegacyInvitationUpdatedPayload( payload: unknown, ): unknown | null { if ( payload && typeof payload === "object" && "topic" in payload && "data" in payload && payload.topic === "invitation-updated" ) { return payload.data; } return null; } /** * Publish the invitation to the sync server */ private async publishInvitation( invitation: XOInvitation = this.data, ): Promise { this.syncServer.publishInvitation(invitation).catch((error) => { this.emit( "error", error instanceof Error ? error : new Error(String(error)), ); }); } /** * Merge the commits * @param initial - The initial commits * @param additional - The additional commits * @returns The merged commits */ private mergeCommits( initial: XOInvitationCommit[], additional: XOInvitationCommit[], ): XOInvitationCommit[] { // Create a map of the initial commits const initialMap = new Map(); for (const commit of initial) { initialMap.set(commit.commitIdentifier, commit); } // Merge the additional commits // TODO: They are immutable? So, it should be fine to "ovewrite" existing commits as it should be the same data, right? for (const commit of additional) { initialMap.set(commit.commitIdentifier, commit); } // Return the merged commits return Array.from(initialMap.values()); } /** * Compute the invitation status as a single word: expired | complete | ready | signed | actionable | unknown. */ private async computeStatus(): Promise { try { return await this.computeStatusInternal(); } catch (err) { return `error (${err instanceof Error ? err.message : String(err)})`; } } /** * Internal status computation: returns a single word. * NOTE: This could be a Enum-like object as well. May be a nice improvement. - DO NOT USE TS ENUM, THEY ARENT NATIVELY SUPPORTED IN NODE.JS * - complete: we have broadcast this invitation * - expired: any commit has expired * - ready: no missing requirements and we have signed (ready to broadcast) * - signed: we have signed but there are still missing parts (waiting for others) * - actionable: you can provide data (missing requirements and/or you can sign) * - unknown: template/action not found or error */ private async computeStatusInternal(): Promise { let missingReqs; try { const missingRequirements = await this.engine.listMissingRequirements( this.data.invitationIdentifier, ); missingReqs = missingRequirements.templateRequirements; } catch { return "unknown"; } const hasMissing = (missingReqs.variables?.length ?? 0) > 0 || (missingReqs.inputs?.length ?? 0) > 0 || (missingReqs.outputs?.length ?? 0) > 0 || (missingReqs.roles !== undefined && Object.keys(missingReqs.roles).length > 0); const hasSignedCommit = this.hasSignedCommitInInvitation(); if (!hasMissing) { const transactionHash = await this.deriveTransactionHash(); if ( transactionHash && (await this.electrum.hasSeenTransaction(transactionHash)) ) { return "complete"; } } if (hasInvitationExpired(this.data)) { return "expired"; } if (!hasMissing && hasSignedCommit) { return "ready"; } if (hasMissing && hasSignedCommit) { return "signed"; } return "actionable"; } private hasSignedCommitInInvitation(): boolean { for (const commit of this.data.commits) { for (const input of commit.data.inputs ?? []) { if (!input.mergesWith) continue; if (input.unlockingBytecode === undefined) continue; return true; } } return false; } /** * Build the transaction to get the TX hash, this is so we can check its status on the blockchain. * TODO: Remove this. This should be part of the engine. The code is virtually identical to `executeAction` except it doesnt throw if the invitation is expired * @returns txHash or undefined if the transaction could not be built */ private async deriveTransactionHash(): Promise { try { const template = await this.engine.getTemplate( this.data.templateIdentifier, ); if (!template) return undefined; const mergedCommit = mergeInvitationCommits(this.data, template); if (!mergedCommit) return undefined; const transactionResult = generateTransaction({ version: mergedCommit.transactionVersion, locktime: mergedCommit.transactionLocktime, // @ts-expect-error merged inputs include additional invitation metadata. inputs: mergedCommit.inputs, // @ts-expect-error merged outputs include additional invitation metadata. outputs: mergedCommit.outputs, }); if (!transactionResult.success) return undefined; const transactionHex = binToHex( encodeTransaction(transactionResult.transaction), ); const rawHash: unknown = hashTransaction(hexToBin(transactionHex)); if (typeof rawHash === "string") return rawHash; if (rawHash instanceof Uint8Array) return binToHex(rawHash); return undefined; } catch { return undefined; } } /** * Update the status of the invitation and emit the new single-word status. */ private async updateStatus(): Promise { this.computeStatus() .then((status) => { this.status = status; this.emit("invitation-status-changed", status); }) .catch((error) => { this.status = `error (${error instanceof Error ? error.message : String(error)})`; this.emit( "error", error instanceof Error ? error : new Error(String(error)), ); }); } /** * Accept the invitation */ async accept(acceptParams?: InvitationParameters): Promise { // Accept the invitation this.updateInvitationData( await this.engine.acceptInvitation(this.data, acceptParams), ); // Sync the invitation to the sync server await this.publishInvitation(this.data); // Store the accepted invitation and notify reactive consumers. await this.storage.set(this.data.invitationIdentifier, this.data); this.emit("invitation-updated", this.data); // Update the status of the invitation await this.updateStatus(); } /** * Accept the invitation once for this engine entity so future appends have a root commit. */ async ensureAccepted(): Promise { const ownCommits = await this.engine.findOwnCommits( this.data.invitationIdentifier, ); if (ownCommits.length === 0) { await this.accept(); } } /** * Sign the invitation */ async sign(): Promise { // Sign the invitation const signedInvitation = await this.engine.signInvitation( this.data.invitationIdentifier, ); // Publish the signed invitation to the sync server this.publishInvitation(signedInvitation); // Store the signed invitation in the storage await this.storage.set(this.data.invitationIdentifier, signedInvitation); this.updateInvitationData(signedInvitation); // Update the status of the invitation await this.updateStatus(); } /** * Broadcast the invitation. * @returns The transaction hash returned by the network after broadcast. */ async broadcast(): Promise { const engineInvitation = await this.engine.getInvitationOrThrow(this.data.invitationIdentifier); console.log(engineInvitation); const txHash = await this.engine.executeAction( this.data.invitationIdentifier, { broadcastTransaction: true, }, ); await this.updateStatus(); return String(txHash); } // ============================================================================ // Append Operations // ============================================================================ /** * Append a commit to the invitation */ async append(data: InvitationParameters): Promise { await this.ensureAccepted(); // Append the commit to the invitation this.updateInvitationData( await this.engine.appendInvitation(this.data.invitationIdentifier, data), ); // Sync the invitation to the sync server await this.publishInvitation(this.data); // Store the invitation in the storage await this.storage.set(this.data.invitationIdentifier, this.data); // Update the status of the invitation await this.updateStatus(); } /** * Add inputs to the invitation */ async addInputs(inputs: XOInvitationInput[]): Promise { // Append the inputs to the invitation await this.append({ inputs }); // Sync the invitation to the sync server await this.publishInvitation(this.data); } /** * Generate the locking bytecode for the invitation * TODO: Find out if this has side-effects or needs special handling */ async generateLockingBytecode( outputIdentifier: string, roleIdentifier?: string, ): Promise { return this.engine.generateLockingBytecode( this.data.templateIdentifier, outputIdentifier, roleIdentifier, ); } async addOutputs(outputs: XOInvitationOutput[]): Promise { // Add the outputs to the invitation await this.append({ outputs }); // Sync the invitation to the sync server await this.publishInvitation(this.data); } /** * Ask the engine to calculate and append fee-aware change for the current * merged invitation. If no spendable change can be created, the remaining * surplus is left as the miner fee. */ async addFeeAwareChange(): Promise { const availability = await this.engine.getChangeAvailability( this.data.invitationIdentifier, ); const availableFeeSatoshis = availability.inputTotalSatoshis - availability.outputTotalSatoshis; if (availableFeeSatoshis < availability.estimatedMinFeeSatoshis) { throw new Error( `Insufficient funds for miner fee. Available ${availableFeeSatoshis} satoshis, estimated minimum ${availability.estimatedMinFeeSatoshis} satoshis.`, ); } if (!availability.canAddChange) { return { changeAmountSatoshis: 0n, feeSatoshis: availableFeeSatoshis, }; } this.updateInvitationData( await this.engine.addChangeToInvitation(this.data.invitationIdentifier), ); await this.publishInvitation(this.data); await this.storage.set(this.data.invitationIdentifier, this.data); await this.updateStatus(); const finalAvailability = await this.engine.getChangeAvailability( this.data.invitationIdentifier, ); return { changeAmountSatoshis: availability.changeAmountSatoshis, feeSatoshis: finalAvailability.inputTotalSatoshis - finalAvailability.outputTotalSatoshis, }; } async addVariables(variables: XOInvitationVariable[]): Promise { // Add the variables to the invitation await this.append({ variables }); // Sync the invitation to the sync server await this.publishInvitation(this.data); } async findSuitableResources( options: Partial = {}, ): Promise { const templateIdentifier = options.templateIdentifier ?? this.data.templateIdentifier; const template = await this.engine.getTemplate(templateIdentifier); const fallbackOutputIdentifier = Object.keys(template?.outputs ?? {})[0]; if (!fallbackOutputIdentifier && !options.outputIdentifier) { throw new Error( `No output identifiers found for template: ${templateIdentifier}`, ); } // const resolvedOptions: GetSpendableResourcesParameters = { // templateIdentifier, // outputIdentifier: options.outputIdentifier ?? fallbackOutputIdentifier ?? "", // }; // There are disagreements around whether all spendables should be returned from getSpendableResources. // I had a fix merged in, but it got overwritten. So, im just going to get all of them manually and go around // The engine's expectations. // To do this, we are going to grab all out templates const templates = await this.engine.listImportedTemplates(); // For each template, we need to create a 2d array of all the outputs const outputs = templates.map((template) => { return Object.keys(template.outputs).map((output) => { const templateIdentifier = generateTemplateIdentifier(template); return { templateIdentifier, outputIdentifier: output, }; }); }); // then, for each output, we need to get the spendable resources const spendableResources = await Promise.all( outputs.flat().map((output) => { return this.engine.getSpendableResources(this.data, { templateIdentifier: output.templateIdentifier, outputIdentifier: output.outputIdentifier, }); }), ); const unspentOutputs = spendableResources.flatMap( (resource) => resource.unspentOutputs, ); // Update the status of the invitation await this.updateStatus(); // Return the suitable resources return unspentOutputs; } // ============================================================================ // Getters and Queries // ============================================================================ /** * Get the missing requirements for the invitation */ async getMissingRequirements() { return this.engine.listMissingRequirements(this.data.invitationIdentifier); } /** * Get the requirements for the invitation */ async getRequirements() { return this.engine.listRequirements(this.data); } /** * Get the available roles for the invitation */ async getAvailableRoles() { return this.engine.listAvailableRoles(this.data); } /** * Get the starting actions for the invitation */ async getStartingActions(): Promise { return this.engine.listStartingActions(this.data.templateIdentifier); } /** * Get the locking bytecode for the invitation */ async getLockingBytecode( outputIdentifier: string, roleIdentifier?: string, ): Promise { return this.engine.generateLockingBytecode( this.data.templateIdentifier, outputIdentifier, roleIdentifier, ); } /** * Get the sats out for the invitation * TODO: Clean up this function. Why is it so big? Can obviously make it 2 functions instead of recursive, but still... */ async getSatsOut(outputIdentifier?: string): Promise { // If an output identifier is provided, find all outputs with that identifier, and its valueSatoshis identifier back to the variables if (outputIdentifier) { // Get the valueSatoshis identifier from the template const template = await this.engine.getTemplate( this.data.templateIdentifier, ); if (!template) { throw new Error( `Template not found: ${this.data.templateIdentifier} when trying to get sats out for output: ${outputIdentifier}`, ); } const output = template.outputs[outputIdentifier]; if (!output) { throw new Error( `Output not found: ${outputIdentifier} in template: ${this.data.templateIdentifier}`, ); } const valueSatoshisExpression = output.valueSatoshis; if (!valueSatoshisExpression) { throw new Error( `Value satoshis identifier not found: ${outputIdentifier} in template: ${this.data.templateIdentifier}`, ); } // Create a list of all the variables from the commits const variables = this.data.commits.flatMap( (c) => c.data?.variables ?? [], ); // Create a dictionary of the variables const formattedVariables = variables.reduce( (acc, v) => { const { variableIdentifier, value } = v; acc[variableIdentifier ?? ""] = value; return acc; }, {} as Record, ); // Compile the CashAssembly expression to get the value satoshis (It handles the variable replacement for us) const valueSatoshis = compileCashAssemblyString({ cashAssemblyText: String(valueSatoshisExpression), variables: formattedVariables, evaluationDecodeMode: "bigint", }); // Return the value satoshis as a bigint // TODO: Check this of a vulnerability or crash - I assume there might be one if someone made the `valueSatoshis` a malicious expression return BigInt(valueSatoshis); } // If we didnt get an output identifier, go through the action outputs and sum the valueSatoshis const action = this.data.actionIdentifier; if (!action) { throw new Error( `Action not found: ${this.data.actionIdentifier} when trying to get sats out for output: ${outputIdentifier}`, ); } // Get the template const template = await this.engine.getTemplate( this.data.templateIdentifier, ); if (!template) { throw new Error( `Template not found: ${this.data.templateIdentifier} when trying to get sats out for action: ${action}`, ); } // Get the transaction ID from the action const transactionID = template.actions[action]?.transaction; if (!transactionID) { throw new Error( `Transactions not found: ${action} in template: ${this.data.templateIdentifier}`, ); } // Get the transaction from the template const transaction = template.transactions?.[transactionID]; if (!transaction) { throw new Error( `Transaction not found: ${transactionID} in template: ${this.data.templateIdentifier}`, ); } // Get the outputs from the transaction const outputs = transaction.outputs; if (!outputs) { throw new Error( `Outputs not found: ${transactionID} in template: ${this.data.templateIdentifier}`, ); } // Create a value to store the cummulative total of the outputs let totalSats = 0n; // Iterate through the outputs and sum the valueSatoshis for (const output of outputs) { if (typeof output === "string") { const sats = await this.getSatsOut(output); totalSats += sats; } else { const sats = await this.getSatsOut(output.output); totalSats += sats; } } return totalSats; } /** * Removes the invitation from the Local SQLite db as well as the Engine's internal DB * NOTE: This uses methods that are marked "DANGEROUSLY" inside the engine and behaviour may change */ public async delete() { // Remove the invitation from our local db this.storage.remove(this.data.invitationIdentifier); // Remove the invitation from the engine's internal db await this.engine.archiveInvitation( this.data.invitationIdentifier, ); this.emit("invitation-removed", this.data.invitationIdentifier); // Update the status of the invitation await this.updateStatus(); } }