diff --git a/.changeset/peering-auto-pay-policy.md b/.changeset/peering-auto-pay-policy.md new file mode 100644 index 000000000..95864a46e --- /dev/null +++ b/.changeset/peering-auto-pay-policy.md @@ -0,0 +1,10 @@ +--- +"nostream": minor +--- + +feat(peering): enforce buyer budgets before paying peer invoices + +Adds the buying-side policy: verify a peer invoice against its advertised +NIP-11 term, dedupe on the payment hash, reserve per-peer and global budget +counters atomically, pay through the configured wallet, and hold anything +outside the envelope for operator approval. diff --git a/.knip.json b/.knip.json index d4375bd46..9b1aa99dc 100644 --- a/.knip.json +++ b/.knip.json @@ -19,7 +19,8 @@ ".nostr/**", "src/utils/relay-probe/**", "src/repositories/peering-invoice-repository.ts", - "src/utils/bolt11.ts" + "src/utils/bolt11.ts", + "src/services/peering-buyer-service.ts" ], "commitlint": false, "eslint": false, diff --git a/migrations/20261119_120000_add_peering_invoice_global_budget_window.js b/migrations/20261119_120000_add_peering_invoice_global_budget_window.js new file mode 100644 index 000000000..5ba59c707 --- /dev/null +++ b/migrations/20261119_120000_add_peering_invoice_global_budget_window.js @@ -0,0 +1,13 @@ +exports.up = async function (knex) { + await knex.schema.alterTable('peering_invoices', (table) => { + table.timestamp('global_budget_period_start', { useTz: true }).nullable() + table.timestamp('global_budget_period_end', { useTz: true }).nullable() + }) +} + +exports.down = async function (knex) { + await knex.schema.alterTable('peering_invoices', (table) => { + table.dropColumn('global_budget_period_start') + table.dropColumn('global_budget_period_end') + }) +} diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 809ffe449..f40b2a677 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -208,15 +208,15 @@ peering: # - pubkey: replace-with-peer-relay-pubkey-in-hex # relayUrl: wss://peer.example.com # enabled: true - # # Reserved for the buyer workflow; not active in this slice. - # budget: { amount: 10000, unit: sats, period: 2592000 } peers: [] - # Reserved for the buyer workflow. This slice stores the policy settings; - # the payment and admin approval paths ship in follow-up slices. + # Buying side automatic payment. Invoices are paid only when the peer is + # configured above, the amount matches the peer's advertised NIP-11 terms, + # the payment hash has not been seen, and both budgets have room. Anything + # else is held for operator approval. autoPay: enabled: false - # Optional cap across every peer, per this budget's own period. A zero - # amount means no global cap. + # Optional cap across every peer, per this budget's own period. + # A zero amount means no global cap. globalBudget: { amount: 0, unit: sats, period: 2592000 } network: maxPayloadSize: 524288 diff --git a/src/@types/clients.ts b/src/@types/clients.ts index 8f7ad151d..adbf33e4b 100644 --- a/src/@types/clients.ts +++ b/src/@types/clients.ts @@ -23,7 +23,27 @@ export interface CreateInvoiceRequest { export type GetInvoiceResponse = Partial +export interface PayInvoiceRequest { + bolt11: string +} + +export interface PayInvoiceResponse { + /** BOLT11 payment hash, used as the buyer-side dedupe key. */ + paymentHash: string + preimage?: string +} + +/** The configured processor only creates/reads incoming invoices; it cannot spend. */ +export class PaymentsProcessorCannotPayError extends Error { + public constructor() { + super('the configured payments processor cannot pay a BOLT11 invoice') + this.name = 'PaymentsProcessorCannotPayError' + } +} + export interface IPaymentsProcessor { createInvoice(request: CreateInvoiceRequest): Promise getInvoice(invoice: string | Invoice): Promise + /** Pays a BOLT11 invoice from the processor wallet. Absent on receive-only adapters. */ + payInvoice?(request: PayInvoiceRequest): Promise } diff --git a/src/@types/peering.ts b/src/@types/peering.ts index 5a7a7aedc..f80e77de3 100644 --- a/src/@types/peering.ts +++ b/src/@types/peering.ts @@ -110,6 +110,8 @@ export interface PeeringInvoice { autoPaid: boolean budgetPeriodStart?: Date | null budgetPeriodEnd?: Date | null + globalBudgetPeriodStart?: Date | null + globalBudgetPeriodEnd?: Date | null /** Period this invoice buys from the peer, from the advertised term. */ termPeriodSeconds?: number | null expiresAt?: Date | null @@ -130,6 +132,8 @@ export interface DBPeeringInvoice { auto_paid: boolean budget_period_start: Date | null budget_period_end: Date | null + global_budget_period_start: Date | null + global_budget_period_end: Date | null term_period_seconds: number | null expires_at: Date | null seen_count: number @@ -138,6 +142,28 @@ export interface DBPeeringInvoice { updated_at: Date } +/** One budget counter, either `global` or `peer:`. */ +export interface PeeringBudgetUsage { + scope: string + periodStart: Date + periodEnd: Date + spentMsats: bigint +} + +/** Admin view of one budget window, with invoice counts for its peer. */ +export interface PeeringBudgetSummary { + scope: 'peer' | 'global' + peerPubkey?: string + periodStart: Date + periodEnd: Date + limitMsats: bigint + spentMsats: bigint + remainingMsats: bigint + received: number + paid: number + held: number +} + export interface PeeringTermSnapshot { amountMsats: bigint periodSeconds: number diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index 1ab58bee4..a9b8a9e90 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -12,7 +12,7 @@ import { NotificationDeliveryStatus, OperatorNotificationChannelType, } from './operator-notifications' -import { PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering' +import { PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering' import { Report } from './report' import { EventKindsRange } from './settings' import { SubscriptionFilter } from './subscription' @@ -109,7 +109,20 @@ export interface IPeeringInvoiceRepository { findByHash(paymentHash: string, client?: DatabaseClient): Promise update( paymentHash: string, - changes: Partial>, + changes: Partial< + Pick< + PeeringInvoice, + | 'status' + | 'reason' + | 'autoPaid' + | 'paidAt' + | 'budgetPeriodStart' + | 'budgetPeriodEnd' + | 'globalBudgetPeriodStart' + | 'globalBudgetPeriodEnd' + | 'termPeriodSeconds' + > + >, client?: DatabaseClient, ): Promise /** Atomically moves one row from an allowed state; undefined when another writer won. */ @@ -129,6 +142,23 @@ export interface IPeeringInvoiceRepository { limitMsats: bigint, client: DatabaseClient, ): Promise + /** Adds manual spend even when it exceeds the auto-pay limit. */ + addBudgetSpend( + scope: string, + periodStart: Date, + periodEnd: Date, + amountMsats: bigint, + client: DatabaseClient, + ): Promise + releaseBudget(scope: string, periodStart: Date, amountMsats: bigint, client: DatabaseClient): Promise + /** Current and recent budget counters for the admin console. */ + listBudgets(): Promise + /** Invoice counts in one budget window, optionally for one peer. */ + countInWindow( + peerPubkey: string | undefined, + start: Date, + end: Date, + ): Promise<{ received: number; paid: number; held: number }> } export interface IUserSubscriptionRepository { diff --git a/src/@types/services.ts b/src/@types/services.ts index 5c2d68f78..87c4ed4d6 100644 --- a/src/@types/services.ts +++ b/src/@types/services.ts @@ -1,7 +1,9 @@ import { DatabaseTransaction, Pubkey } from './base' +import { Event } from './event' import { Invoice } from './invoice' import { NotificationOutboxPayload } from './notification-outbox' -import { PeeringAccess } from './peering' +import { PeeringAccess, PeeringAdvertisement, PeeringBudgetSummary, PeeringInvoice, PeeringInvoiceStatus } from './peering' +import { PeeringPeer } from './settings' export interface IMaintenanceService { clearOldEvents(): Promise @@ -53,6 +55,8 @@ export interface IPaymentsService { getPendingInvoices(offset?: number): Promise /** Completed peering invoices whose settlement did not commit, for retry. */ getUnconfirmedPeeringInvoices(limit?: number, offset?: number): Promise + /** Pays a BOLT11 invoice from the configured wallet and returns its payment hash. */ + payInvoice(bolt11: string): Promise } export interface IPeeringBillingService { @@ -68,6 +72,26 @@ export interface IPeeringBillingService { handleInvoiceExpired(invoice: Invoice): Promise } +export interface IPeeringBuyerService { + /** Validates a kind 402 invoice from a peer, then auto-pays or holds it. */ + handleInvoice( + peer: PeeringPeer, + advertisement: PeeringAdvertisement, + event: Event, + now?: Date, + ): Promise + /** Pays a held invoice on operator approval, bypassing the auto-pay budget guard. */ + approve(paymentHash: string, now?: Date): Promise + /** Rejects a held invoice without paying it. */ + reject(paymentHash: string): Promise + /** Recent buyer invoices for the admin console. */ + list(statuses?: PeeringInvoiceStatus[], limit?: number): Promise + /** Spend, remaining budget and invoice counts for the current period. */ + budgetSummary(now?: Date): Promise + /** Finishes invoices left in PAYING by a restart, before retrying anything. */ + recover(now?: Date): Promise +} + export interface ISubscriptionService { /** One pass of renewal invoices, period ends and grace expiries. Returns how many subscriptions changed. */ processLifecycle(now?: Date): Promise diff --git a/src/repositories/peering-invoice-repository.ts b/src/repositories/peering-invoice-repository.ts index 285e53ff2..d3b6f453f 100644 --- a/src/repositories/peering-invoice-repository.ts +++ b/src/repositories/peering-invoice-repository.ts @@ -1,6 +1,7 @@ import { DatabaseClient } from '../@types/base' import { DBPeeringInvoice, + PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceReason, PeeringInvoiceStatus, @@ -22,6 +23,8 @@ const toRow = (invoice: PeeringInvoice): DBPeeringInvoice => ({ auto_paid: invoice.autoPaid, budget_period_start: invoice.budgetPeriodStart ?? null, budget_period_end: invoice.budgetPeriodEnd ?? null, + global_budget_period_start: invoice.globalBudgetPeriodStart ?? null, + global_budget_period_end: invoice.globalBudgetPeriodEnd ?? null, term_period_seconds: invoice.termPeriodSeconds ?? null, expires_at: invoice.expiresAt ?? null, seen_count: invoice.seenCount, @@ -41,6 +44,8 @@ const fromRow = (row: DBPeeringInvoice): PeeringInvoice => ({ autoPaid: Boolean(row.auto_paid), budgetPeriodStart: row.budget_period_start, budgetPeriodEnd: row.budget_period_end, + globalBudgetPeriodStart: row.global_budget_period_start, + globalBudgetPeriodEnd: row.global_budget_period_end, termPeriodSeconds: row.term_period_seconds, expiresAt: row.expires_at, seenCount: row.seen_count, @@ -112,6 +117,8 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository { | 'paidAt' | 'budgetPeriodStart' | 'budgetPeriodEnd' + | 'globalBudgetPeriodStart' + | 'globalBudgetPeriodEnd' | 'termPeriodSeconds' > >, @@ -136,6 +143,12 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository { if (changes.budgetPeriodEnd !== undefined) { patch.budget_period_end = changes.budgetPeriodEnd } + if (changes.globalBudgetPeriodStart !== undefined) { + patch.global_budget_period_start = changes.globalBudgetPeriodStart + } + if (changes.globalBudgetPeriodEnd !== undefined) { + patch.global_budget_period_end = changes.globalBudgetPeriodEnd + } if (changes.termPeriodSeconds !== undefined) { patch.term_period_seconds = changes.termPeriodSeconds } @@ -193,7 +206,7 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository { ON CONFLICT (scope, period_start) DO UPDATE SET spent_msats = peering_budgets.spent_msats + EXCLUDED.spent_msats, period_end = EXCLUDED.period_end - WHERE peering_budgets.spent_msats + EXCLUDED.spent_msats <= CAST(? AS bigint) + WHERE peering_budgets.spent_msats <= CAST(? AS bigint) - CAST(? AS bigint) RETURNING spent_msats`, [ scope, @@ -203,6 +216,7 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository { amountMsats.toString(), limitMsats.toString(), limitMsats.toString(), + amountMsats.toString(), ], ) const row = firstRow(result) @@ -214,5 +228,79 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository { return BigInt(row.spent_msats) } + public async addBudgetSpend( + scope: string, + periodStart: Date, + periodEnd: Date, + amountMsats: bigint, + client: DatabaseClient, + ): Promise { + if (amountMsats < 0n) { + throw new Error('budget spend amount must be non-negative') + } + + const result = await client.raw( + `INSERT INTO peering_budgets (scope, period_start, period_end, spent_msats) + VALUES (?, ?, ?, ?) + ON CONFLICT (scope, period_start) DO UPDATE + SET spent_msats = peering_budgets.spent_msats + EXCLUDED.spent_msats, + period_end = EXCLUDED.period_end + RETURNING spent_msats`, + [scope, periodStart, periodEnd, amountMsats.toString()], + ) + + return BigInt(firstRow(result).spent_msats) + } + + public async releaseBudget( + scope: string, + periodStart: Date, + amountMsats: bigint, + client: DatabaseClient, + ): Promise { + if (amountMsats < 0n) { + throw new Error('budget release amount must be non-negative') + } + await client.raw( + `UPDATE peering_budgets + SET spent_msats = GREATEST(spent_msats - ?, 0) + WHERE scope = ? AND period_start = ?`, + [amountMsats.toString(), scope, periodStart], + ) + } + + public async countInWindow( + peerPubkey: string | undefined, + start: Date, + end: Date, + ): Promise<{ received: number; paid: number; held: number }> { + const result = await this.dbClient.raw( + `SELECT COUNT(*) AS received, + COUNT(*) FILTER (WHERE status = 'paid') AS paid, + COUNT(*) FILTER (WHERE status IN ('held', 'failed')) AS held + FROM peering_invoices + WHERE created_at >= ? AND created_at < ? + ${peerPubkey ? 'AND peer_pubkey = ?' : ''}`, + peerPubkey ? [start, end, toBuffer(peerPubkey)] : [start, end], + ) + const row = firstRow(result) ?? {} + + return { + received: Number(row.received ?? 0), + paid: Number(row.paid ?? 0), + held: Number(row.held ?? 0), + } + } + + public async listBudgets(): Promise { + const rows = await this.dbClient('peering_budgets').orderBy('period_start', 'desc') + + return rows.map((row) => ({ + scope: row.scope, + periodStart: row.period_start, + periodEnd: row.period_end, + spentMsats: BigInt(row.spent_msats), + })) + } } diff --git a/src/services/payments-service.ts b/src/services/payments-service.ts index cbc9a2190..e9c9fd833 100644 --- a/src/services/payments-service.ts +++ b/src/services/payments-service.ts @@ -16,7 +16,7 @@ import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../@types/i import { Event, ExpiringEvent, UnidentifiedEvent } from '../@types/event' import { EventExpirationTimeMetadataKey, EventKinds, EventTags } from '../constants/base' import { createLogger } from '../factories/logger-factory' -import { IPaymentsProcessor } from '../@types/clients' +import { IPaymentsProcessor, PaymentsProcessorCannotPayError } from '../@types/clients' import { IPaymentsService } from '../@types/services' import { PeeringPaymentStatus } from '../@types/peering' import { Transaction } from '../database/transaction' @@ -71,6 +71,17 @@ export class PaymentsService implements IPaymentsService { } } + public async payInvoice(bolt11: string): Promise { + if (typeof this.paymentsProcessor.payInvoice !== 'function') { + throw new PaymentsProcessorCannotPayError() + } + + logger('paying a peering invoice from the configured wallet') + const result = await this.paymentsProcessor.payInvoice({ bolt11 }) + + return result.paymentHash + } + public async getInvoiceFromPaymentsProcessor(invoice: Invoice | string): Promise> { try { return await this.paymentsProcessor.getInvoice( diff --git a/src/services/peering-buyer-service.ts b/src/services/peering-buyer-service.ts new file mode 100644 index 000000000..129b32842 --- /dev/null +++ b/src/services/peering-buyer-service.ts @@ -0,0 +1,702 @@ +import { createHash } from 'crypto' + +import { DatabaseClient, Pubkey } from '../@types/base' +import { PaymentsProcessorCannotPayError } from '../@types/clients' +import { Event } from '../@types/event' +import { InvoiceStatus } from '../@types/invoice' +import { OperatorNotificationEventType } from '../@types/operator-notifications' +import { + PeeringAdvertisement, + PeeringBudgetSummary, + PeeringInvoice, + PeeringInvoiceReason, + PeeringInvoiceStatus, +} from '../@types/peering' +import { INotificationOutboxRepository, IPeeringInvoiceRepository } from '../@types/repositories' +import { IPaymentsService, IPeeringBuyerService } from '../@types/services' +import { PeeringPeer, Settings } from '../@types/settings' +import { EventKinds, EventTags } from '../constants/base' +import { Transaction } from '../database/transaction' +import { createLogger } from '../factories/logger-factory' +import { decodeBolt11 } from '../utils/bolt11' +import { getPublicKey, getRelayPrivateKey } from '../utils/event' +import { findConfiguredPeeringPeer, parsePeeringPeerPubkey } from '../utils/peering-auth' +import { + PEERING_INVOICE_TAG, + PeeringBudgetSnapshot, + peeringBudgetWindow, + resolvePeeringBudget, + resolvePeeringTerm, +} from '../utils/peering-billing' + +const logger = createLogger('peering-buyer-service') + +const tagValues = (event: Event, name: string): string[] => + event.tags.filter((tag) => tag[0] === name && typeof tag[1] === 'string').map((tag) => tag[1]) + +const expirationDate = (event: Event): Date | undefined => { + const value = tagValues(event, EventTags.Expiration)[0] + if (!value) { + return undefined + } + + const seconds = Number(value) + return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : undefined +} + +const isInvoiceEventFor = (event: Event, selfPubkey: string): boolean => { + if (event.kind !== EventKinds.INVOICE_UPDATE) { + return false + } + + return tagValues(event, EventTags.Pubkey).includes(selfPubkey) && + tagValues(event, EventTags.Tag).includes(PEERING_INVOICE_TAG) && + tagValues(event, EventTags.Invoice).length > 0 +} + +interface ReserveResult { + reserved: boolean + peerBudget?: PeeringBudgetSnapshot + globalBudget?: PeeringBudgetSnapshot + peerWindow?: { start: Date; end: Date } + globalWindow?: { start: Date; end: Date } +} + +export class PeeringBuyerService implements IPeeringBuyerService { + public constructor( + private readonly dbClient: DatabaseClient, + private readonly invoiceRepository: IPeeringInvoiceRepository, + private readonly paymentsService: IPaymentsService, + private readonly notificationOutboxRepository: INotificationOutboxRepository, + private readonly settings: () => Settings, + private readonly selfPubkey: () => string = () => + getPublicKey(getRelayPrivateKey(settings().info?.relay_url)), + ) {} + + public async handleInvoice( + peer: PeeringPeer, + advertisement: PeeringAdvertisement, + event: Event, + now = new Date(), + ): Promise { + const configured = findConfiguredPeeringPeer(this.settings(), event.pubkey) + const peerPubkey = parsePeeringPeerPubkey(peer.pubkey) ?? peer.pubkey.toLowerCase() + + let base: PeeringInvoice + try { + base = this.baseInvoice(peerPubkey, event) + } catch (error) { + logger('unable to decode a peering invoice from %s: %o', peerPubkey, error) + const malformed = this.malformedInvoice(peerPubkey, event, now) + const storedMalformed = await this.invoiceRepository.insertIfNew({ + ...malformed, + status: PeeringInvoiceStatus.RECEIVED, + reason: null, + }) + return storedMalformed.inserted + ? this.hold(storedMalformed.invoice, PeeringInvoiceReason.INVALID_INVOICE) + : storedMalformed.invoice + } + + const stored = await this.invoiceRepository.insertIfNew({ + ...base, + status: PeeringInvoiceStatus.RECEIVED, + reason: null, + }) + const invoice = stored.invoice + + if (!stored.inserted) { + return invoice.status === PeeringInvoiceStatus.PAYING ? this.recoverInvoice(invoice, now) : invoice + } + + if (event.pubkey.toLowerCase() !== peerPubkey || !configured) { + return this.hold(invoice, PeeringInvoiceReason.UNKNOWN_PEER) + } + + if (!isInvoiceEventFor(event, this.selfPubkey())) { + return this.hold(invoice, PeeringInvoiceReason.INVALID_INVOICE) + } + + const expiresAt = expirationDate(event) + if (expiresAt && expiresAt.getTime() <= now.getTime()) { + return this.hold({ ...invoice, expiresAt }, PeeringInvoiceReason.EXPIRED) + } + + let expected + try { + expected = resolvePeeringTerm(advertisement.terms) + } catch (error) { + logger('peer %s advertised an invalid term: %o', peerPubkey, error) + return this.hold(invoice, PeeringInvoiceReason.AMOUNT_MISMATCH) + } + + if (!expected || expected.amountMsats !== invoice.amountMsats) { + return this.hold(invoice, PeeringInvoiceReason.AMOUNT_MISMATCH) + } + + const autoPay = this.settings().peering?.autoPay + if (autoPay?.enabled !== true) { + return this.hold({ ...invoice, termPeriodSeconds: expected.periodSeconds }, PeeringInvoiceReason.AUTO_PAY_DISABLED) + } + + const peerBudget = resolvePeeringBudget(peer.budget) + if (!peerBudget) { + return this.hold( + { ...invoice, termPeriodSeconds: expected.periodSeconds }, + PeeringInvoiceReason.BUDGET_NOT_CONFIGURED, + ) + } + + return this.pay(invoice, peerBudget, expected.periodSeconds, expiresAt, true, now) + } + + public async approve(paymentHash: string, now = new Date()): Promise { + let invoice = await this.invoiceRepository.findByHash(paymentHash) + if (!invoice) { + throw new Error(`peering invoice ${paymentHash} not found`) + } + + if (invoice.status === PeeringInvoiceStatus.PAYING) { + invoice = await this.recoverInvoice(invoice, now) + } + if (invoice.status === PeeringInvoiceStatus.PAID) { + return invoice + } + + const claimed = await this.invoiceRepository.claim( + paymentHash, + [PeeringInvoiceStatus.HELD, PeeringInvoiceStatus.FAILED], + PeeringInvoiceStatus.PAYING, + ) + if (!claimed) { + throw new Error(`peering invoice ${paymentHash} is not awaiting approval`) + } + + const peer = findConfiguredPeeringPeer(this.settings(), invoice.peerPubkey) + const peerBudget = resolvePeeringBudget(peer?.budget) + + return this.settle(claimed, peerBudget, claimed.termPeriodSeconds ?? null, false, now) + } + + public async reject(paymentHash: string): Promise { + const invoice = await this.invoiceRepository.findByHash(paymentHash) + if (invoice?.status === PeeringInvoiceStatus.PAYING) { + await this.recoverInvoice(invoice, new Date()) + } + + const claimed = await this.invoiceRepository.claim( + paymentHash, + [PeeringInvoiceStatus.HELD, PeeringInvoiceStatus.FAILED], + PeeringInvoiceStatus.REJECTED, + ) + if (!claimed) { + throw new Error(`peering invoice ${paymentHash} is not awaiting a decision`) + } + + return claimed + } + + public async recover(now = new Date()): Promise { + const paying = await this.invoiceRepository.list([PeeringInvoiceStatus.PAYING], 100) + let changed = 0 + + for (const invoice of paying) { + const recovered = await this.recoverInvoice(invoice, now) + if (recovered.status !== invoice.status) { + changed++ + } + } + + return changed + } + + private async recoverInvoice(invoice: PeeringInvoice, now: Date): Promise { + try { + const result = await this.paymentsService.getInvoiceFromPaymentsProcessor(invoice.paymentHash) + if (result.status === InvoiceStatus.COMPLETED) { + return ( + (await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.PAID, + reason: null, + autoPaid: invoice.autoPaid, + paidAt: now, + })) ?? { + ...invoice, + status: PeeringInvoiceStatus.PAID, + reason: null, + autoPaid: invoice.autoPaid, + paidAt: now, + } + ) + } + + if (result.status !== InvoiceStatus.EXPIRED) { + return invoice + } + + const reservation = { + reserved: true, + ...(invoice.budgetPeriodStart && invoice.budgetPeriodEnd + ? { peerWindow: { start: invoice.budgetPeriodStart, end: invoice.budgetPeriodEnd } } + : {}), + ...(invoice.globalBudgetPeriodStart && invoice.globalBudgetPeriodEnd + ? { globalWindow: { start: invoice.globalBudgetPeriodStart, end: invoice.globalBudgetPeriodEnd } } + : {}), + } + const transaction = new Transaction(this.dbClient) + let started = false + try { + await transaction.begin() + started = true + const claimed = await this.invoiceRepository.claim( + invoice.paymentHash, + [PeeringInvoiceStatus.PAYING], + PeeringInvoiceStatus.HELD, + transaction.transaction, + ) + if (!claimed) { + await transaction.rollback() + return invoice + } + if (reservation.peerWindow) { + await this.invoiceRepository.releaseBudget( + `peer:${invoice.peerPubkey.toLowerCase()}`, + reservation.peerWindow.start, + invoice.amountMsats, + transaction.transaction, + ) + } + if (reservation.globalWindow) { + await this.invoiceRepository.releaseBudget( + 'global', + reservation.globalWindow.start, + invoice.amountMsats, + transaction.transaction, + ) + } + await this.invoiceRepository.update( + invoice.paymentHash, + { reason: PeeringInvoiceReason.PAYMENT_FAILED, autoPaid: false }, + transaction.transaction, + ) + await transaction.commit() + started = false + return claimed + } catch (error) { + if (started) { + await transaction.rollback() + } + logger('unable to release and hold recovering invoice %s: %o', invoice.paymentHash, error) + return invoice + } + } catch (error) { + logger('unable to recover peering invoice %s: %o', invoice.paymentHash, error) + return invoice + } + } + + public list(statuses?: PeeringInvoiceStatus[], limit = 100): Promise { + return this.invoiceRepository.list(statuses, limit) + } + + public async budgetSummary(now = new Date()): Promise { + const usage = await this.invoiceRepository.listBudgets() + const byScope = new Map(usage.map((entry) => [`${entry.scope}|${entry.periodStart.toISOString()}`, entry])) + const summaries: PeeringBudgetSummary[] = [] + + const summarize = async ( + scope: 'peer' | 'global', + peerPubkey: string | undefined, + budget: { amount: number; unit: string; period: number } | undefined, + ) => { + const resolved = resolvePeeringBudget(budget) + if (!resolved) { + return + } + + const window = peeringBudgetWindow(now, resolved.periodSeconds) + const key = `${scope === 'global' ? 'global' : `peer:${peerPubkey!.toLowerCase()}`}|${window.start.toISOString()}` + const spent = byScope.get(key)?.spentMsats ?? 0n + const counts = await this.invoiceRepository.countInWindow( + scope === 'global' ? undefined : peerPubkey, + window.start, + window.end, + ) + + summaries.push({ + scope, + ...(peerPubkey ? { peerPubkey } : {}), + periodStart: window.start, + periodEnd: window.end, + limitMsats: resolved.amountMsats, + spentMsats: spent, + remainingMsats: resolved.amountMsats > spent ? resolved.amountMsats - spent : 0n, + ...counts, + }) + } + + await summarize('global', undefined, this.settings().peering?.autoPay?.globalBudget) + for (const peer of this.settings().peering?.peers ?? []) { + if (peer.enabled === false) { + continue + } + await summarize('peer', parsePeeringPeerPubkey(peer.pubkey) ?? peer.pubkey, peer.budget) + } + + return summaries.sort((left, right) => (left.peerPubkey ?? '').localeCompare(right.peerPubkey ?? '')) + } + + private malformedInvoice(peerPubkey: Pubkey, event: Event, now: Date): PeeringInvoice { + const digest = createHash('sha256').update(event.id).digest('hex') + + return { + paymentHash: `invalid:${digest}`, + eventId: event.id, + peerPubkey, + bolt11: tagValues(event, EventTags.Invoice)[0] ?? '', + amountMsats: 0n, + status: PeeringInvoiceStatus.RECEIVED, + reason: null, + autoPaid: false, + budgetPeriodStart: null, + budgetPeriodEnd: null, + termPeriodSeconds: null, + expiresAt: expirationDate(event) ?? null, + seenCount: 1, + paidAt: null, + createdAt: now, + updatedAt: now, + } + } + + private baseInvoice(peerPubkey: Pubkey, event: Event): PeeringInvoice { + const bolt11 = tagValues(event, EventTags.Invoice)[0] + const decoded = decodeBolt11(bolt11) + const now = new Date() + + return { + paymentHash: decoded.paymentHash, + eventId: event.id, + peerPubkey, + bolt11, + amountMsats: decoded.amountMsats, + status: PeeringInvoiceStatus.RECEIVED, + reason: null, + autoPaid: false, + budgetPeriodStart: null, + budgetPeriodEnd: null, + termPeriodSeconds: null, + expiresAt: expirationDate(event) ?? null, + seenCount: 1, + paidAt: null, + createdAt: now, + updatedAt: now, + } + } + + private async hold(invoice: PeeringInvoice, reason: PeeringInvoiceReason): Promise { + const updated = await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.HELD, + reason, + autoPaid: false, + termPeriodSeconds: invoice.termPeriodSeconds ?? null, + }) + + await this.notify(OperatorNotificationEventType.PEERING_INVOICE_FAILED, { + paymentHash: invoice.paymentHash, + peerPubkey: invoice.peerPubkey, + amountMsats: invoice.amountMsats.toString(), + reason, + }) + + return updated ?? { ...invoice, status: PeeringInvoiceStatus.HELD, reason } + } + + private async pay( + invoice: PeeringInvoice, + peerBudget: PeeringBudgetSnapshot, + termPeriodSeconds: number, + expiresAt: Date | undefined, + auto: boolean, + now: Date, + ): Promise { + const claimed = await this.invoiceRepository.claim( + invoice.paymentHash, + [PeeringInvoiceStatus.RECEIVED], + PeeringInvoiceStatus.PAYING, + ) + if (!claimed) { + // A restart can leave the row in PAYING. Check the wallet before letting + // the redelivery return, and finalize or release it when the outcome is known. + const current = (await this.invoiceRepository.findByHash(invoice.paymentHash)) ?? invoice + return current.status === PeeringInvoiceStatus.PAYING ? this.recoverInvoice(current, now) : current + } + + const reservation = await this.reserve(claimed, peerBudget, auto, now) + if (!reservation.reserved) { + return this.hold( + { ...claimed, termPeriodSeconds }, + PeeringInvoiceReason.BUDGET_EXCEEDED, + ) + } + + return this.settle( + { ...claimed, termPeriodSeconds, expiresAt: expiresAt ?? claimed.expiresAt ?? null }, + peerBudget, + termPeriodSeconds, + auto, + now, + reservation, + ) + } + + private async settle( + invoice: PeeringInvoice, + peerBudget: PeeringBudgetSnapshot | undefined, + termPeriodSeconds: number | null, + auto: boolean, + now: Date, + reservation?: ReserveResult, + ): Promise { + const current = reservation ?? (await this.reserve(invoice, peerBudget, auto, now)) + if (!current.reserved) { + return this.hold(invoice, PeeringInvoiceReason.BUDGET_EXCEEDED) + } + + if (current.peerWindow || current.globalWindow) { + try { + await this.invoiceRepository.update(invoice.paymentHash, { + autoPaid: auto, + budgetPeriodStart: current.peerWindow?.start ?? null, + budgetPeriodEnd: current.peerWindow?.end ?? null, + globalBudgetPeriodStart: current.globalWindow?.start ?? null, + globalBudgetPeriodEnd: current.globalWindow?.end ?? null, + termPeriodSeconds, + }) + } catch (error) { + logger('unable to persist the reserved budget for %s: %o', invoice.paymentHash, error) + const released = await this.release(invoice, current, now) + return released + ? this.hold(invoice, PeeringInvoiceReason.PAYMENT_FAILED) + : { ...invoice, status: PeeringInvoiceStatus.PAYING, reason: PeeringInvoiceReason.PAYMENT_FAILED } + } + } + + let paidHash: string + try { + paidHash = await this.paymentsService.payInvoice(invoice.bolt11) + } catch (error) { + logger('unable to pay peering invoice %s: %o', invoice.paymentHash, error) + const reason = + error instanceof PaymentsProcessorCannotPayError + ? PeeringInvoiceReason.UNSUPPORTED_PROCESSOR + : PeeringInvoiceReason.PAYMENT_FAILED + const released = await this.release(invoice, current, now) + if (!released) { + await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.PAYING, + reason, + autoPaid: false, + termPeriodSeconds, + }) + return { ...invoice, status: PeeringInvoiceStatus.PAYING, reason, autoPaid: false } + } + + const held = await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.HELD, + reason, + autoPaid: false, + termPeriodSeconds, + }) + + await this.notify(OperatorNotificationEventType.PEERING_INVOICE_FAILED, { + paymentHash: invoice.paymentHash, + peerPubkey: invoice.peerPubkey, + amountMsats: invoice.amountMsats.toString(), + reason, + }) + + return held ?? { + ...invoice, + status: PeeringInvoiceStatus.HELD, + reason, + autoPaid: false, + } + } + + if (paidHash.toLowerCase() !== invoice.paymentHash.toLowerCase()) { + logger( + 'processor reported payment hash %s for peering invoice %s; keeping the charge for recovery', + paidHash, + invoice.paymentHash, + ) + await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.PAYING, + reason: PeeringInvoiceReason.PAYMENT_FAILED, + autoPaid: false, + }) + + return { ...invoice, status: PeeringInvoiceStatus.PAYING, reason: PeeringInvoiceReason.PAYMENT_FAILED } + } + + try { + const paid = await this.invoiceRepository.update(invoice.paymentHash, { + status: PeeringInvoiceStatus.PAID, + reason: null, + autoPaid: auto, + paidAt: now, + termPeriodSeconds, + }) + + await this.notify(OperatorNotificationEventType.PEERING_INVOICE_PAID, { + paymentHash: invoice.paymentHash, + peerPubkey: invoice.peerPubkey, + amountMsats: invoice.amountMsats.toString(), + autoPaid: auto, + }) + + return paid ?? { ...invoice, status: PeeringInvoiceStatus.PAID, reason: null, autoPaid: auto, paidAt: now } + } catch (error) { + // The wallet already paid. Keep the budget charge and PAYING status so + // recover() can finish the row instead of releasing spent money. + logger('wallet settled peering invoice %s but the invoice update failed: %o', invoice.paymentHash, error) + return { ...invoice, status: PeeringInvoiceStatus.PAYING, reason: null, autoPaid: auto, paidAt: now } + } + } + + private async reserve( + invoice: PeeringInvoice, + peerBudget: PeeringBudgetSnapshot | undefined, + auto: boolean, + now: Date, + ): Promise { + const globalBudget = resolvePeeringBudget(this.settings().peering?.autoPay?.globalBudget) + const peerWindow = peerBudget ? peeringBudgetWindow(now, peerBudget.periodSeconds) : undefined + const globalWindow = globalBudget ? peeringBudgetWindow(now, globalBudget.periodSeconds) : undefined + + if (auto && !peerBudget) { + return { reserved: false } + } + + if (!peerBudget && !globalBudget) { + return { reserved: true, peerBudget, globalBudget } + } + + const transaction = new Transaction(this.dbClient) + let started = false + + try { + await transaction.begin() + started = true + + if (peerBudget && peerWindow) { + const peerScope = `peer:${invoice.peerPubkey.toLowerCase()}` + if (auto) { + const peerSpent = await this.invoiceRepository.reserveBudget( + peerScope, + peerWindow.start, + peerWindow.end, + invoice.amountMsats, + peerBudget.amountMsats, + transaction.transaction, + ) + if (peerSpent === undefined) { + await transaction.rollback() + return { reserved: false, peerBudget, peerWindow, globalBudget, globalWindow } + } + } else { + await this.invoiceRepository.addBudgetSpend( + peerScope, + peerWindow.start, + peerWindow.end, + invoice.amountMsats, + transaction.transaction, + ) + } + } + + if (globalBudget && globalWindow) { + if (auto) { + const globalSpent = await this.invoiceRepository.reserveBudget( + 'global', + globalWindow.start, + globalWindow.end, + invoice.amountMsats, + globalBudget.amountMsats, + transaction.transaction, + ) + if (globalSpent === undefined) { + await transaction.rollback() + return { reserved: false, peerBudget, peerWindow, globalBudget, globalWindow } + } + } else { + await this.invoiceRepository.addBudgetSpend( + 'global', + globalWindow.start, + globalWindow.end, + invoice.amountMsats, + transaction.transaction, + ) + } + } + + await transaction.commit() + started = false + + return { reserved: true, peerBudget, peerWindow, globalBudget, globalWindow } + } catch (error) { + if (started) { + await transaction.rollback() + } + logger('unable to reserve a peering budget for %s: %o', invoice.paymentHash, error) + + return { reserved: false, peerBudget, peerWindow, globalBudget, globalWindow } + } + } + + private async release(invoice: PeeringInvoice, reservation: ReserveResult, now: Date): Promise { + if (!reservation.reserved) { + return true + } + + const transaction = new Transaction(this.dbClient) + let started = false + try { + await transaction.begin() + started = true + if (reservation.peerWindow) { + await this.invoiceRepository.releaseBudget( + `peer:${invoice.peerPubkey.toLowerCase()}`, + reservation.peerWindow.start, + invoice.amountMsats, + transaction.transaction, + ) + } + if (reservation.globalWindow) { + await this.invoiceRepository.releaseBudget( + 'global', + reservation.globalWindow.start, + invoice.amountMsats, + transaction.transaction, + ) + } + await transaction.commit() + started = false + return true + } catch (error) { + if (started) { + await transaction.rollback() + } + logger('unable to release the peering budget for %s: %o', invoice.paymentHash, error) + return false + } + } + + private async notify(type: OperatorNotificationEventType, payload: Record): Promise { + try { + await this.notificationOutboxRepository.enqueue(type, payload) + } catch (error) { + logger('unable to enqueue %s: %o', type, error) + } + } +} diff --git a/src/utils/bolt11.ts b/src/utils/bolt11.ts index 15e9069c6..c2577e926 100644 --- a/src/utils/bolt11.ts +++ b/src/utils/bolt11.ts @@ -1,6 +1,6 @@ -/** The relay's max payload is 512 KiB; a longer tag cannot arrive on a peer socket. */ -const MAX_BOLT11_LENGTH = 1_000 +/** Bounds decode work without rejecting real invoices with route hints (a few KB). */ +const MAX_BOLT11_LENGTH = 4_096 const BECH32_ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l' const BECH32_ALPHABET_MAP: Record = {} @@ -63,7 +63,7 @@ const bech32Convert = (data: number[], inBits: number, outBits: number, pad: boo const bech32Decode = (input: string): { prefix: string; words: number[] } => { const value = input.trim() if (!value || value.length > MAX_BOLT11_LENGTH) { - throw new Error('Invalid bolt11 invoice') + throw new Error(`Invalid bolt11 invoice (length ${value.length})`) } const lower = value.toLowerCase() if (value !== lower && value !== value.toUpperCase()) { diff --git a/src/utils/peering-billing.ts b/src/utils/peering-billing.ts index ea3ac26a1..85bc9bc3e 100644 --- a/src/utils/peering-billing.ts +++ b/src/utils/peering-billing.ts @@ -1,5 +1,5 @@ import { PeeringAccess, PeeringTermSnapshot } from '../@types/peering' -import { Settings } from '../@types/settings' +import { PeeringTerm, Settings } from '../@types/settings' import { SubscriptionFilter } from '../@types/subscription' import { EventKinds } from '../constants/base' @@ -50,15 +50,18 @@ const toMsats = (amount: number, unit: string): bigint | undefined => { return BigInt(amount) * multiplier } +/** Converts an advertised or configured amount to msats, or undefined for an unknown unit. */ +export const peeringAmountToMsats = (amount: number, unit: string): bigint | undefined => toMsats(amount, unit) + /** - * The paid term this relay sells. An empty list, or only zero-amount terms, means - * settlement-free peering and returns undefined. A configured paid term that cannot - * be charged safely throws instead of silently granting free access. + * Resolves the single paid term in a list. An empty list, or only zero-amount + * terms, means settlement-free peering and returns undefined. Anything unsafe + * throws instead of silently granting free access. */ -export const resolvePaidPeeringTerm = (settings: Settings): PeeringTermSnapshot | undefined => { - const terms = settings.peering?.terms ?? [] +export const resolvePeeringTerm = (terms: PeeringTerm[] | undefined): PeeringTermSnapshot | undefined => { + let resolved: PeeringTermSnapshot | undefined - for (const term of terms) { + for (const term of terms ?? []) { if (typeof term !== 'object' || term === null) { throw new InvalidPeeringTermError('peering term must be an object') } @@ -103,15 +106,32 @@ export const resolvePaidPeeringTerm = (settings: Settings): PeeringTermSnapshot throw new InvalidPeeringTermError('peering term period must be a positive number of seconds') } - return { + if (resolved) { + throw new InvalidPeeringTermError('multiple paid peering terms are not supported') + } + + resolved = { amountMsats, periodSeconds: term.period, } } - return undefined + return resolved } +/** + * The paid term this relay sells. An empty list, or only zero-amount terms, means + * settlement-free peering and returns undefined. + */ +export const resolvePaidPeeringTerm = (settings: Settings): PeeringTermSnapshot | undefined => + resolvePeeringTerm(settings.peering?.terms) + +/** A configured buying budget, normalized for comparison with invoice amounts. */ +export type PeeringBudgetSnapshot = PeeringTermSnapshot + +export const resolvePeeringBudget = (budget: PeeringTerm | undefined): PeeringBudgetSnapshot | undefined => + budget === undefined ? undefined : resolvePeeringTerm([budget]) + export const isPeeringInvoiceFilter = (filter: SubscriptionFilter, peerPubkey: string): boolean => { const kinds = filter.kinds const pubkeys = filter['#p'] @@ -134,6 +154,20 @@ export const isPeeringInvoiceRequest = (filters: SubscriptionFilter[], peerPubke export const peeringPeriodEnd = (start: Date, periodSeconds: number): Date => new Date(start.getTime() + periodSeconds * 1000) +/** Fixed, epoch-aligned budget window. Renewals inside it share one counter. */ +export const peeringBudgetWindow = ( + now: Date, + periodSeconds: number, +): { start: Date; end: Date } => { + const periodMs = periodSeconds * 1000 + const startMs = Math.floor(now.getTime() / periodMs) * periodMs + + return { + start: new Date(startMs), + end: new Date(startMs + periodMs), + } +} + export const peeringInvoiceDescription = ( settings: Settings, peerPubkey: string, diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index b1e1419b3..eced71449 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -953,6 +953,7 @@ const PEERING_POW_MAX_BITS = 256 const PEERING_SCOPE_KEYS = new Set(['kinds', 'since', 'until', 'windowSeconds']) const PEERING_TERM_KEYS = new Set(['amount', 'unit', 'period']) const PEERING_PEER_KEYS = new Set(['pubkey', 'relayUrl', 'enabled', 'budget']) +const PEERING_AUTOPAY_KEYS = new Set(['enabled', 'globalBudget']) const isValidPeeringKindValue = (value: unknown): boolean => typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= PEERING_KIND_MAX @@ -1042,44 +1043,53 @@ const validatePeeringScopes = (scopes: unknown, issues: ValidationIssue[]): void }) } -const validatePeeringTerms = (terms: unknown, issues: ValidationIssue[]): void => { - if (!Array.isArray(terms)) { +const validatePeeringTermValue = ( + term: unknown, + prefix: string, + issues: ValidationIssue[], + options: { allowZero: boolean }, +): void => { + if (!isPlainObject(term)) { + issues.push({ path: prefix, message: 'term must be an object' }) return } - terms.forEach((term, index) => { - const prefix = `peering.terms[${index}]` - - if (!isPlainObject(term)) { - issues.push({ path: prefix, message: 'term must be an object' }) - return + for (const key of Object.keys(term)) { + if (!PEERING_TERM_KEYS.has(key)) { + issues.push({ path: `${prefix}.${key}`, message: 'Unknown setting key' }) } + } - for (const key of Object.keys(term)) { - if (!PEERING_TERM_KEYS.has(key)) { - issues.push({ path: `${prefix}.${key}`, message: 'Unknown setting key' }) - } - } + if (!(typeof term.amount === 'number' && Number.isSafeInteger(term.amount) && term.amount >= 0)) { + issues.push({ path: `${prefix}.amount`, message: 'amount must be a non-negative integer' }) + } else if (!options.allowZero && term.amount === 0) { + issues.push({ path: `${prefix}.amount`, message: 'amount must be positive' }) + } - if (!(typeof term.amount === 'number' && Number.isSafeInteger(term.amount) && term.amount >= 0)) { - issues.push({ path: `${prefix}.amount`, message: 'amount must be a non-negative integer' }) + if (typeof term.unit !== 'string' || !term.unit.trim()) { + issues.push({ path: `${prefix}.unit`, message: 'unit must be a non-empty string' }) + } else if (typeof term.amount === 'number' && term.amount > 0) { + const unit = term.unit.trim().toLowerCase() + if (!['msats', 'sats', 'btc'].includes(unit)) { + issues.push({ path: `${prefix}.unit`, message: 'paid terms must use msats, sats or btc' }) + } else if (unit === 'msats' && term.amount % 1000 !== 0) { + // Processors such as LNbits and OpenNode truncate msats to whole sats. + issues.push({ path: `${prefix}.amount`, message: 'paid msat terms must be a whole number of satoshis' }) } + } - if (typeof term.unit !== 'string' || !term.unit.trim()) { - issues.push({ path: `${prefix}.unit`, message: 'unit must be a non-empty string' }) - } else if (typeof term.amount === 'number' && term.amount > 0) { - const unit = term.unit.trim().toLowerCase() - if (!['msats', 'sats', 'btc'].includes(unit)) { - issues.push({ path: `${prefix}.unit`, message: 'paid terms must use msats, sats or btc' }) - } else if (unit === 'msats' && term.amount % 1000 !== 0) { - // Processors such as LNbits and OpenNode truncate msats to whole sats. - issues.push({ path: `${prefix}.amount`, message: 'paid msat terms must be a whole number of satoshis' }) - } - } + if (!(typeof term.period === 'number' && Number.isSafeInteger(term.period) && term.period > 0)) { + issues.push({ path: `${prefix}.period`, message: 'period must be a positive integer (seconds)' }) + } +} - if (!(typeof term.period === 'number' && Number.isSafeInteger(term.period) && term.period > 0)) { - issues.push({ path: `${prefix}.period`, message: 'period must be a positive integer (seconds)' }) - } +const validatePeeringTerms = (terms: unknown, issues: ValidationIssue[]): void => { + if (!Array.isArray(terms)) { + return + } + + terms.forEach((term, index) => { + validatePeeringTermValue(term, `peering.terms[${index}]`, issues, { allowZero: true }) }) } @@ -1134,35 +1144,7 @@ const validatePeeringPeers = (peers: unknown, issues: ValidationIssue[]): void = } if (peer.budget !== undefined) { - if (!isPlainObject(peer.budget)) { - issues.push({ path: `${prefix}.budget`, message: 'budget must be an object' }) - } else { - for (const key of Object.keys(peer.budget)) { - if (!PEERING_TERM_KEYS.has(key)) { - issues.push({ path: `${prefix}.budget.${key}`, message: 'Unknown setting key' }) - } - } - - const { amount, unit, period } = peer.budget - if (!(typeof amount === 'number' && Number.isSafeInteger(amount) && amount > 0)) { - issues.push({ path: `${prefix}.budget.amount`, message: 'amount must be a positive integer' }) - } - - if (typeof unit !== 'string' || !unit.trim()) { - issues.push({ path: `${prefix}.budget.unit`, message: 'unit must be a non-empty string' }) - } else if (typeof amount === 'number' && amount > 0) { - const normalized = unit.trim().toLowerCase() - if (!['msats', 'sats', 'btc'].includes(normalized)) { - issues.push({ path: `${prefix}.budget.unit`, message: 'paid terms must use msats, sats or btc' }) - } else if (normalized === 'msats' && amount % 1000 !== 0) { - issues.push({ path: `${prefix}.budget.amount`, message: 'paid msat terms must be a whole number of satoshis' }) - } - } - - if (!(typeof period === 'number' && Number.isSafeInteger(period) && period > 0)) { - issues.push({ path: `${prefix}.budget.period`, message: 'period must be a positive integer (seconds)' }) - } - } + validatePeeringTermValue(peer.budget, `${prefix}.budget`, issues, { allowZero: false }) } }) } @@ -1226,6 +1208,35 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => validatePeeringTerms(peering.terms, issues) validatePeeringPeers(peering.peers, issues) + if (peering.autoPay !== undefined) { + if (!isPlainObject(peering.autoPay)) { + issues.push({ path: 'peering.autoPay', message: 'must be an object' }) + } else { + for (const key of Object.keys(peering.autoPay)) { + if (!PEERING_AUTOPAY_KEYS.has(key)) { + issues.push({ path: `peering.autoPay.${key}`, message: 'Unknown setting key' }) + } + } + + if (typeof peering.autoPay.enabled !== 'boolean') { + issues.push({ path: 'peering.autoPay.enabled', message: 'must be a boolean' }) + } + + if (peering.autoPay.globalBudget !== undefined) { + validatePeeringTermValue(peering.autoPay.globalBudget, 'peering.autoPay.globalBudget', issues, { + allowZero: true, + }) + } + + if (peering.autoPay.enabled === true && settings.payments?.enabled !== true) { + issues.push({ + path: 'peering.autoPay.enabled', + message: 'payments must be enabled to auto-pay peering invoices', + }) + } + } + } + const paidTerms = Array.isArray(peering.terms) ? peering.terms.filter( (term) => isPlainObject(term) && typeof term.amount === 'number' && term.amount > 0, diff --git a/test/integration/features/peering/peering-auto-pay.feature b/test/integration/features/peering/peering-auto-pay.feature new file mode 100644 index 000000000..1f0cee27f --- /dev/null +++ b/test/integration/features/peering/peering-auto-pay.feature @@ -0,0 +1,27 @@ +@peering-auto-pay +Feature: Paid peering auto-pay + + The buying side pays a trusted peer invoice only inside its advertised terms + and budgets, and holds everything else for operator approval. + + Scenario: A trusted invoice inside budget is paid automatically + When a trusted peer sends a 250000000 msat invoice with a 1000000000 sat budget + Then the buyer invoice is paid and the budget records the spend + + Scenario: An invoice over the per-peer budget is held + When a trusted peer sends a 250000000 msat invoice with a 100 sat budget + Then the buyer invoice is held for operator approval + + Scenario: A duplicate payment hash is not paid twice + When a trusted peer sends a 250000000 msat invoice with a 1000000000 sat budget + And the same invoice event is delivered again + Then the buyer wallet was called once + + Scenario: An operator can approve a held invoice + When a trusted peer sends a 250000000 msat invoice with a 100 sat budget + And the operator approves the held invoice + Then the invoice is paid manually and the spend is recorded + + Scenario: An interrupted payment is recovered from the wallet + When a paying buyer invoice is recovered from the wallet + Then the invoice is paid without refunding its budget diff --git a/test/integration/features/peering/peering-auto-pay.feature.ts b/test/integration/features/peering/peering-auto-pay.feature.ts new file mode 100644 index 000000000..e776803d1 --- /dev/null +++ b/test/integration/features/peering/peering-auto-pay.feature.ts @@ -0,0 +1,261 @@ +import { After, Before, Then, When, World } from '@cucumber/cucumber' +import { expect } from 'chai' +import { randomBytes } from 'node:crypto' +import Sinon from 'sinon' + +import { Event } from '../../../../src/@types/event' +import { + PeeringInvoiceReason, + PeeringInvoiceStatus, +} from '../../../../src/@types/peering' +import { PeeringPeer, Settings } from '../../../../src/@types/settings' +import { getMasterDbClient } from '../../../../src/database/client' +import { PeeringInvoiceRepository } from '../../../../src/repositories/peering-invoice-repository' +import { PeeringBuyerService } from '../../../../src/services/peering-buyer-service' +import { getPublicKey, identifyEvent, signEvent } from '../../../../src/utils/event' + +const INVOICE = + 'lnbc2500u1pvjluezsp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpu9qrsgquk0rl77nj30yxdy8j9vdx85fkpmdla2087ne0xh8nhedh8w27kyke0lp53ut353s06fv3qfegext0eh0ymjpf39tuven09sam30g4vgpfna3rh' +const PAYMENT_HASH = '0001020304050607080900010203040506070809000102030405060708090102' +const TERM_MSATS = 250_000_000n +const TERM_SECONDS = 2592000 +const SELF_PRIVATE_KEY = 'c'.repeat(64) +const SELF_PUBKEY = getPublicKey(SELF_PRIVATE_KEY) + +const randomPeer = async () => { + const privateKey = randomBytes(32).toString('hex') + return { privateKey, pubkey: getPublicKey(privateKey) } +} + +const invoiceEvent = async (peerPubkey: string, privateKey: string, createdAt: number): Promise => + signEvent(privateKey)( + await identifyEvent({ + pubkey: peerPubkey, + created_at: createdAt, + kind: 402, + tags: [ + ['p', SELF_PUBKEY], + ['t', 'peering'], + ['bolt11', INVOICE], + ['i', 'peer-processor-invoice'], + ['expiration', String(createdAt + 900)], + ], + content: '', + }), + ) + +const setupBuyer = ( + world: World>, + budgetSats: number, +): { service: PeeringBuyerService; peer: PeeringPeer; payInvoice: Sinon.SinonStub } => { + const db = getMasterDbClient() + const peer = { + pubkey: world.parameters.autoPayPeerPubkey, + relayUrl: 'wss://peer.example.com', + budget: { amount: budgetSats, unit: 'sats', period: TERM_SECONDS }, + } + const settings = { + info: { name: 'Test Relay', relay_url: 'wss://relay.example.com' }, + payments: { enabled: true }, + peering: { + enabled: true, + autoPay: { enabled: true }, + peers: [peer], + }, + } as Settings + const payInvoice = Sinon.stub().resolves(PAYMENT_HASH) + const notificationOutboxRepository = { enqueue: Sinon.stub().resolves() } + const repository = new PeeringInvoiceRepository(db) + const service = new PeeringBuyerService( + db, + repository, + { payInvoice } as any, + notificationOutboxRepository as any, + () => settings, + () => SELF_PUBKEY, + ) + + world.parameters.autoPayService = service + world.parameters.autoPayRepository = repository + world.parameters.autoPayPeer = peer + world.parameters.autoPayPayInvoice = payInvoice + world.parameters.autoPayAdvertisement = { + enabled: true, + scopes: [{ kinds: [1] }], + terms: [{ amount: Number(TERM_MSATS), unit: 'msats', period: TERM_SECONDS }], + supportedNips: [77], + } + + return { service, peer, payInvoice } +} + +Before({ tags: '@peering-auto-pay' }, async function (this: World>) { + this.parameters.autoPayDb = getMasterDbClient() + this.parameters.autoPayPeers = [] + this.parameters.autoPayScopes = [] + this.parameters.autoPaySandbox = Sinon.createSandbox() +}) + +After({ tags: '@peering-auto-pay' }, async function (this: World>) { + const db = this.parameters.autoPayDb + const peers: string[] = this.parameters.autoPayPeers ?? [] + const scopes: string[] = this.parameters.autoPayScopes ?? [] + + try { + if (db && peers.length) { + await db('peering_invoices') + .whereIn( + 'peer_pubkey', + peers.map((peer) => Buffer.from(peer, 'hex')), + ) + .delete() + } + if (db && scopes.length) { + await db('peering_budgets').whereIn('scope', scopes).delete() + } + } finally { + this.parameters.autoPaySandbox?.restore() + this.parameters.autoPayDb = undefined + this.parameters.autoPayPeers = [] + this.parameters.autoPayScopes = [] + this.parameters.autoPaySandbox = undefined + this.parameters.autoPayService = undefined + this.parameters.autoPayPeer = undefined + this.parameters.autoPayPayInvoice = undefined + this.parameters.autoPayResult = undefined + this.parameters.autoPayEvent = undefined + this.parameters.autoPayRepository = undefined + } +}) + +When( + 'a trusted peer sends a {int} msat invoice with a {int} sat budget', + async function (this: World>, amountMsats: number, budgetSats: number) { + expect(amountMsats).to.equal(Number(TERM_MSATS)) + const { privateKey, pubkey } = await randomPeer() + this.parameters.autoPayPeerPubkey = pubkey + this.parameters.autoPayPeers.push(pubkey) + this.parameters.autoPayScopes.push(`peer:${pubkey}`) + + const { service, peer } = setupBuyer(this, budgetSats) + const now = new Date() + const event = await invoiceEvent(pubkey, privateKey, Math.floor(now.getTime() / 1000)) + this.parameters.autoPayEvent = event + this.parameters.autoPayResult = await service.handleInvoice( + peer, + this.parameters.autoPayAdvertisement, + event, + now, + ) + }, +) + + +When('a paying buyer invoice is recovered from the wallet', async function (this: World>) { + const { pubkey } = await randomPeer() + this.parameters.autoPayPeerPubkey = pubkey + this.parameters.autoPayPeers.push(pubkey) + this.parameters.autoPayScopes.push(`peer:${pubkey}`) + + const { service, payInvoice } = setupBuyer(this, 1000000000) + const now = new Date() + const repository = this.parameters.autoPayRepository as PeeringInvoiceRepository + await repository.insertIfNew( + { + paymentHash: PAYMENT_HASH, + eventId: `event-${pubkey}`, + peerPubkey: pubkey, + bolt11: INVOICE, + amountMsats: TERM_MSATS, + status: PeeringInvoiceStatus.PAYING, + reason: null, + autoPaid: true, + budgetPeriodStart: now, + budgetPeriodEnd: new Date(now.getTime() + 60_000), + termPeriodSeconds: TERM_SECONDS, + expiresAt: null, + seenCount: 1, + paidAt: null, + createdAt: now, + updatedAt: now, + }, + ) + await repository.reserveBudget(`peer:${pubkey}`, now, new Date(now.getTime() + 60_000), TERM_MSATS, 1_000_000_000n, this.parameters.autoPayDb) + ;(service as any).paymentsService.getInvoiceFromPaymentsProcessor = Sinon.stub().resolves({ status: 'completed' }) + this.parameters.autoPayPayInvoice = payInvoice + this.parameters.autoPayResult = await service.recover(now) +}) + +Then('the invoice is paid without refunding its budget', async function (this: World>) { + expect(this.parameters.autoPayResult).to.equal(1) + expect(this.parameters.autoPayPayInvoice).not.to.have.been.called + + const row = await this.parameters.autoPayDb('peering_invoices').where('payment_hash', PAYMENT_HASH).first() + expect(row.status).to.equal('paid') + expect(row.auto_paid).to.equal(true) + + const budget = await this.parameters.autoPayDb('peering_budgets') + .where('scope', `peer:${this.parameters.autoPayPeerPubkey}`) + .first() + expect(String(budget.spent_msats)).to.equal(TERM_MSATS.toString()) +}) + +Then( + 'the buyer invoice is paid and the budget records the spend', + async function (this: World>) { + expect(this.parameters.autoPayResult.status).to.equal(PeeringInvoiceStatus.PAID) + expect(this.parameters.autoPayPayInvoice).to.have.been.calledOnce + + const row = await this.parameters.autoPayDb('peering_invoices').where('payment_hash', PAYMENT_HASH).first() + expect(row.status).to.equal('paid') + expect(row.auto_paid).to.equal(true) + + const budget = await this.parameters.autoPayDb('peering_budgets') + .where('scope', `peer:${this.parameters.autoPayPeerPubkey}`) + .first() + expect(String(budget.spent_msats)).to.equal(TERM_MSATS.toString()) + }, +) + +Then( + 'the buyer invoice is held for operator approval', + async function (this: World>) { + expect(this.parameters.autoPayResult.status).to.equal(PeeringInvoiceStatus.HELD) + expect(this.parameters.autoPayResult.reason).to.equal(PeeringInvoiceReason.BUDGET_EXCEEDED) + expect(this.parameters.autoPayPayInvoice).not.to.have.been.called + + const row = await this.parameters.autoPayDb('peering_invoices').where('payment_hash', PAYMENT_HASH).first() + expect(row.status).to.equal('held') + expect(row.reason).to.equal('budget_exceeded') + }, +) + +When('the same invoice event is delivered again', async function (this: World>) { + await this.parameters.autoPayService.handleInvoice( + this.parameters.autoPayPeer, + this.parameters.autoPayAdvertisement, + this.parameters.autoPayEvent, + ) +}) + +Then('the buyer wallet was called once', function (this: World>) { + expect(this.parameters.autoPayPayInvoice).to.have.been.calledOnce +}) + +When('the operator approves the held invoice', async function (this: World>) { + this.parameters.autoPayResult = await this.parameters.autoPayService.approve(PAYMENT_HASH) +}) + +Then( + 'the invoice is paid manually and the spend is recorded', + async function (this: World>) { + expect(this.parameters.autoPayResult.status).to.equal(PeeringInvoiceStatus.PAID) + expect(this.parameters.autoPayResult.autoPaid).to.equal(false) + expect(this.parameters.autoPayPayInvoice).to.have.been.calledOnce + + const budget = await this.parameters.autoPayDb('peering_budgets') + .where('scope', `peer:${this.parameters.autoPayPeerPubkey}`) + .first() + expect(String(budget.spent_msats)).to.equal(TERM_MSATS.toString()) + }, +) diff --git a/test/unit/repositories/peering-invoice-repository.spec.ts b/test/unit/repositories/peering-invoice-repository.spec.ts index 4cf07aa3d..2418ff362 100644 --- a/test/unit/repositories/peering-invoice-repository.spec.ts +++ b/test/unit/repositories/peering-invoice-repository.spec.ts @@ -169,6 +169,17 @@ describe('PeeringInvoiceRepository', () => { expect(recording.queries).to.be.empty }) + it('counts invoices in a budget window without a capped list', async () => { + const recording = createRecordingKnex() + const repository = new PeeringInvoiceRepository(recording.db) + recording.respondWith([{ received: '2', paid: '1', held: '1' }]) + + const counts = await repository.countInWindow(peerPubkey, now, new Date(now.getTime() + 60_000)) + + expect(counts).to.deep.equal({ received: 2, paid: 1, held: 1 }) + expect(recording.queries[0].sql.toLowerCase()).to.include('filter (where status =') + }) + it('refuses a first reservation that already exceeds the limit', async () => { const recording = createRecordingKnex() const repository = new PeeringInvoiceRepository(recording.db) @@ -205,5 +216,7 @@ describe('PeeringInvoiceRepository', () => { expect(reserved).to.equal(250_000_000n) expect(recording.queries[0].sql.toLowerCase()).to.include('on conflict') expect(recording.queries[0].sql).to.include('<=') + expect(recording.queries[0].bindings).to.have.length(8) + expect(recording.queries[0].bindings[6]).to.equal('1000000000') }) }) diff --git a/test/unit/services/payments-service.spec.ts b/test/unit/services/payments-service.spec.ts index 576fc653a..8b995c0b1 100644 --- a/test/unit/services/payments-service.spec.ts +++ b/test/unit/services/payments-service.spec.ts @@ -8,6 +8,7 @@ chai.use(chaiAsPromised) import * as eventUtils from '../../../src/utils/event' import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../src/@types/invoice' +import { PaymentsProcessorCannotPayError } from '../../../src/@types/clients' import { OperatorNotificationEventType } from '../../../src/@types/operator-notifications' import { PENDING_INVOICE_PAGE_SIZE, PaymentsService } from '../../../src/services/payments-service' @@ -54,6 +55,7 @@ describe('PaymentsService', () => { paymentsProcessor = { createInvoice: sandbox.stub(), getInvoice: sandbox.stub(), + payInvoice: sandbox.stub(), } userRepository = { @@ -212,6 +214,21 @@ describe('PaymentsService', () => { }) + describe('payInvoice', () => { + it('pays through the processor and returns the payment hash', async () => { + paymentsProcessor.payInvoice.resolves({ paymentHash: 'paid-hash' }) + + expect(await service.payInvoice('lnbc1invoice')).to.equal('paid-hash') + expect(paymentsProcessor.payInvoice).to.have.been.calledOnceWith({ bolt11: 'lnbc1invoice' }) + }) + + it('fails closed when the processor cannot spend', async () => { + delete paymentsProcessor.payInvoice + + await expect(service.payInvoice('lnbc1invoice')).to.be.rejectedWith(PaymentsProcessorCannotPayError) + }) + }) + describe('createInvoice', () => { const invoiceResponse = { id: 'new-inv-id', diff --git a/test/unit/services/peering-buyer-service.spec.ts b/test/unit/services/peering-buyer-service.spec.ts new file mode 100644 index 000000000..3b462188c --- /dev/null +++ b/test/unit/services/peering-buyer-service.spec.ts @@ -0,0 +1,506 @@ +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import { Event } from '../../../src/@types/event' +import { + PeeringInvoice, + PeeringInvoiceReason, + PeeringInvoiceStatus, +} from '../../../src/@types/peering' +import { PeeringPeer, Settings } from '../../../src/@types/settings' +import { PeeringBuyerService } from '../../../src/services/peering-buyer-service' +import { peeringBudgetWindow } from '../../../src/utils/peering-billing' + +chai.use(sinonChai) +chai.use(chaiAsPromised) +const { expect } = chai + +const INVOICE = + 'lnbc2500u1pvjluezsp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpu9qrsgquk0rl77nj30yxdy8j9vdx85fkpmdla2087ne0xh8nhedh8w27kyke0lp53ut353s06fv3qfegext0eh0ymjpf39tuven09sam30g4vgpfna3rh' +const PAYMENT_HASH = '0001020304050607080900010203040506070809000102030405060708090102' +const SELF = 'b'.repeat(64) +const PEER = 'a'.repeat(64) + +describe('PeeringBuyerService', () => { + const now = new Date('2026-11-18T12:00:00.000Z') + let sandbox: Sinon.SinonSandbox + let service: PeeringBuyerService + let dbClient: any + let trx: { commit: Sinon.SinonStub; rollback: Sinon.SinonStub } + let invoiceRepository: any + let paymentsService: any + let notificationOutboxRepository: any + let settings: Settings + let peer: PeeringPeer + let event: Event + + const invoice = (overrides: Partial = {}): PeeringInvoice => ({ + paymentHash: PAYMENT_HASH, + eventId: 'event-1', + peerPubkey: PEER, + bolt11: INVOICE, + amountMsats: 250_000_000n, + status: PeeringInvoiceStatus.RECEIVED, + reason: null, + autoPaid: false, + budgetPeriodStart: null, + budgetPeriodEnd: null, + termPeriodSeconds: 2592000, + expiresAt: new Date(now.getTime() + 60_000), + seenCount: 1, + paidAt: null, + createdAt: now, + updatedAt: now, + ...overrides, + }) + + const advertisement = { + enabled: true, + scopes: [{ kinds: [1] }], + terms: [{ amount: 250_000_000, unit: 'msats', period: 2592000 }], + supportedNips: [77], + } + + beforeEach(() => { + sandbox = Sinon.createSandbox() + trx = { commit: sandbox.stub().resolves(), rollback: sandbox.stub().resolves() } + dbClient = { transaction: sandbox.stub().resolves(trx) } + + invoiceRepository = { + insertIfNew: sandbox.stub().resolves({ inserted: true, invoice: invoice() }), + findByHash: sandbox.stub().resolves(invoice()), + update: sandbox.stub().callsFake(async (_hash, changes) => invoice(changes)), + claim: sandbox.stub().resolves(invoice({ status: PeeringInvoiceStatus.PAYING })), + list: sandbox.stub().resolves([]), + reserveBudget: sandbox.stub().resolves(250_000_000n), + addBudgetSpend: sandbox.stub().resolves(250_000_000n), + releaseBudget: sandbox.stub().resolves(), + listBudgets: sandbox.stub().resolves([]), + countInWindow: sandbox.stub().resolves({ received: 0, paid: 0, held: 0 }), + } + + paymentsService = { + payInvoice: sandbox.stub().resolves(PAYMENT_HASH), + } + + notificationOutboxRepository = { enqueue: sandbox.stub().resolves() } + + settings = { + info: { name: 'relay', relay_url: 'wss://relay.example.com' }, + payments: { enabled: true }, + peering: { + enabled: true, + autoPay: { + enabled: true, + globalBudget: { amount: 10_000_000_000, unit: 'msats', period: 2592000 }, + }, + peers: [ + { + pubkey: PEER, + relayUrl: 'wss://peer.example.com', + budget: { amount: 1_000_000_000, unit: 'msats', period: 2592000 }, + }, + ], + }, + } as Settings + + peer = settings.peering!.peers![0] + event = { + id: 'event-1', + pubkey: PEER, + created_at: Math.floor(now.getTime() / 1000), + kind: 402, + tags: [ + ['p', SELF], + ['t', 'peering'], + ['bolt11', INVOICE], + ['i', 'seller-invoice-1'], + ['expiration', String(Math.floor(now.getTime() / 1000) + 60)], + ], + content: '', + sig: 'c'.repeat(128), + } + + service = new PeeringBuyerService( + dbClient, + invoiceRepository, + paymentsService, + notificationOutboxRepository, + () => settings, + () => SELF, + ) + }) + + afterEach(() => sandbox.restore()) + + it('auto-pays a trusted invoice that matches the advertised term', async () => { + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).to.have.been.calledOnceWith(INVOICE) + expect(invoiceRepository.reserveBudget).to.have.been.calledTwice + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ + status: PeeringInvoiceStatus.PAID, + autoPaid: true, + reason: null, + }), + ) + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + }) + + it('holds an invoice over the per-peer budget without paying', async () => { + invoiceRepository.reserveBudget.resolves(undefined) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.status).to.equal(PeeringInvoiceStatus.HELD) + expect(result.reason).to.equal(PeeringInvoiceReason.BUDGET_EXCEEDED) + }) + + it('holds an invoice whose amount does not match the advertised term', async () => { + const result = await service.handleInvoice( + peer, + { ...advertisement, terms: [{ amount: 21_000, unit: 'sats', period: 2592000 }] }, + event, + now, + ) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.AMOUNT_MISMATCH) + }) + + it('holds an invoice when auto-pay is disabled', async () => { + settings.peering!.autoPay!.enabled = false + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.AUTO_PAY_DISABLED) + }) + + it('holds an invoice from an unconfigured pubkey', async () => { + event.pubkey = 'd'.repeat(64) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.UNKNOWN_PEER) + }) + + it('does not pay a duplicate payment hash twice', async () => { + invoiceRepository.insertIfNew.resolves({ + inserted: false, + invoice: invoice({ status: PeeringInvoiceStatus.PAID, paidAt: now }), + }) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + }) + + it('holds and releases the budget when the wallet payment fails', async () => { + paymentsService.payInvoice.rejects(new Error('insufficient balance')) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(invoiceRepository.releaseBudget).to.have.been.calledTwice + expect(result.status).to.equal(PeeringInvoiceStatus.HELD) + expect(result.reason).to.equal(PeeringInvoiceReason.PAYMENT_FAILED) + }) + + it('approves a held invoice and records manual spend', async () => { + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.HELD })) + invoiceRepository.claim.resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + + const result = await service.approve(PAYMENT_HASH, now) + + expect(paymentsService.payInvoice).to.have.been.calledOnce + expect(invoiceRepository.addBudgetSpend).to.have.been.calledTwice + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ status: PeeringInvoiceStatus.PAID, autoPaid: false }), + ) + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + }) + + it('rejects a held invoice', async () => { + invoiceRepository.claim.resolves(invoice({ status: PeeringInvoiceStatus.REJECTED })) + + const result = await service.reject(PAYMENT_HASH) + + expect(result.status).to.equal(PeeringInvoiceStatus.REJECTED) + expect(paymentsService.payInvoice).not.to.have.been.called + }) + + + it('holds an invoice when the peer advertises an invalid term', async () => { + const result = await service.handleInvoice( + peer, + { + ...advertisement, + terms: [ + { amount: 1000, unit: 'msats', period: 3600 }, + { amount: 2000, unit: 'msats', period: 3600 }, + ], + }, + event, + now, + ) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.AMOUNT_MISMATCH) + }) + + it('holds an invoice when the peer has no budget configured', async () => { + peer.budget = undefined + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.BUDGET_NOT_CONFIGURED) + }) + + it('holds an expired invoice without reserving a budget', async () => { + event.tags = event.tags.map((tag) => + tag[0] === 'expiration' ? ['expiration', String(Math.floor(now.getTime() / 1000) - 1)] : tag, + ) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(invoiceRepository.reserveBudget).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.EXPIRED) + }) + + it('holds when the global budget has no room even if the peer budget does', async () => { + invoiceRepository.reserveBudget.onFirstCall().resolves(250_000_000n) + invoiceRepository.reserveBudget.onSecondCall().resolves(undefined) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.BUDGET_EXCEEDED) + }) + + it('holds when the processor reports a different payment hash', async () => { + paymentsService.payInvoice.resolves('f'.repeat(64)) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(invoiceRepository.releaseBudget).not.to.have.been.called + expect(result.status).to.equal(PeeringInvoiceStatus.PAYING) + expect(result.reason).to.equal(PeeringInvoiceReason.PAYMENT_FAILED) + }) + + it('keeps the charge when the wallet paid but the paid update fails', async () => { + invoiceRepository.update + .onFirstCall() + .resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + .onSecondCall() + .rejects(new Error('database down')) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(invoiceRepository.releaseBudget).not.to.have.been.called + expect(result.status).to.equal(PeeringInvoiceStatus.PAYING) + }) + + it('recovers a paying invoice from the wallet result', async () => { + invoiceRepository.list.resolves([invoice({ status: PeeringInvoiceStatus.PAYING })]) + paymentsService.getInvoiceFromPaymentsProcessor = sandbox.stub().resolves({ status: 'completed' }) + + expect(await service.recover(now)).to.equal(1) + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ status: PeeringInvoiceStatus.PAID, autoPaid: false }), + ) + }) + + it('releases and holds a paying invoice the wallet reports expired', async () => { + invoiceRepository.list.resolves([ + invoice({ + status: PeeringInvoiceStatus.PAYING, + autoPaid: true, + budgetPeriodStart: now, + budgetPeriodEnd: new Date(now.getTime() + 60_000), + globalBudgetPeriodStart: now, + globalBudgetPeriodEnd: new Date(now.getTime() + 60_000), + }), + ]) + paymentsService.getInvoiceFromPaymentsProcessor = sandbox.stub().resolves({ status: 'expired' }) + invoiceRepository.claim.resolves(invoice({ status: PeeringInvoiceStatus.HELD })) + + expect(await service.recover(now)).to.equal(1) + expect(invoiceRepository.claim).to.have.been.calledWith( + PAYMENT_HASH, + [PeeringInvoiceStatus.PAYING], + PeeringInvoiceStatus.HELD, + ) + expect(invoiceRepository.releaseBudget).to.have.been.calledTwice + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ reason: PeeringInvoiceReason.PAYMENT_FAILED, autoPaid: false }), + ) + }) + + it('still records a payment when the notification outbox fails', async () => { + notificationOutboxRepository.enqueue.rejects(new Error('outbox down')) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + }) + + it('throws when approving an unknown or already-decided invoice', async () => { + invoiceRepository.findByHash.resolves(undefined) + await expect(service.approve(PAYMENT_HASH, now)).to.be.rejectedWith('not found') + + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.PAID })) + expect((await service.approve(PAYMENT_HASH, now)).status).to.equal(PeeringInvoiceStatus.PAID) + + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.HELD })) + invoiceRepository.claim.resolves(undefined) + await expect(service.approve(PAYMENT_HASH, now)).to.be.rejectedWith('not awaiting approval') + await expect(service.reject(PAYMENT_HASH)).to.be.rejectedWith('not awaiting a decision') + }) + + + it('records a malformed invoice instead of dropping it', async () => { + event.tags = event.tags.filter((tag) => tag[0] !== 'bolt11') + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.reason).to.equal(PeeringInvoiceReason.INVALID_INVOICE) + expect(invoiceRepository.insertIfNew).to.have.been.calledWith( + Sinon.match({ paymentHash: Sinon.match(/^invalid:/), amountMsats: 0n }), + ) + }) + + it('persists the known period when holding an invoice', async () => { + settings.peering!.autoPay!.enabled = false + + await service.handleInvoice(peer, advertisement, event, now) + + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ status: PeeringInvoiceStatus.HELD, termPeriodSeconds: 2592000 }), + ) + }) + + it('records manual global spend when the peer has no budget', async () => { + peer.budget = undefined + const held = await service.handleInvoice(peer, advertisement, event, now) + expect(held.reason).to.equal(PeeringInvoiceReason.BUDGET_NOT_CONFIGURED) + + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.HELD })) + invoiceRepository.claim.resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + await service.approve(PAYMENT_HASH, now) + + expect(invoiceRepository.addBudgetSpend).to.have.been.calledOnceWith( + 'global', + Sinon.match.any, + Sinon.match.any, + 250_000_000n, + Sinon.match.any, + ) + }) + + + it('does not pay a manual invoice when recording spend fails', async () => { + peer.budget = undefined + const held = await service.handleInvoice(peer, advertisement, event, now) + expect(held.reason).to.equal(PeeringInvoiceReason.BUDGET_NOT_CONFIGURED) + + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.HELD })) + invoiceRepository.claim.resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + invoiceRepository.addBudgetSpend.rejects(new Error('budget store down')) + + const result = await service.approve(PAYMENT_HASH, now) + + expect(paymentsService.payInvoice).not.to.have.been.called + expect(result.status).to.equal(PeeringInvoiceStatus.HELD) + expect(result.reason).to.equal(PeeringInvoiceReason.BUDGET_EXCEEDED) + }) + + it('keeps a failed payment recoverable when the refund also fails', async () => { + paymentsService.payInvoice.rejects(new Error('wallet down')) + invoiceRepository.releaseBudget.rejects(new Error('budget store down')) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(result.status).to.equal(PeeringInvoiceStatus.PAYING) + expect(result.reason).to.equal(PeeringInvoiceReason.PAYMENT_FAILED) + expect(invoiceRepository.update).not.to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ status: PeeringInvoiceStatus.HELD }), + ) + }) + + + it('recovers a paying invoice when the peer redelivers it', async () => { + invoiceRepository.insertIfNew.resolves({ + inserted: false, + invoice: invoice({ status: PeeringInvoiceStatus.PAYING }), + }) + paymentsService.getInvoiceFromPaymentsProcessor = sandbox.stub().resolves({ status: 'completed' }) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + expect(invoiceRepository.update).to.have.been.calledWith( + PAYMENT_HASH, + Sinon.match({ status: PeeringInvoiceStatus.PAID }), + ) + }) + + it('recovers a paying invoice before an operator approval', async () => { + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + paymentsService.getInvoiceFromPaymentsProcessor = sandbox.stub().resolves({ status: 'completed' }) + + const result = await service.approve(PAYMENT_HASH, now) + + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + expect(paymentsService.payInvoice).not.to.have.been.called + }) + + + it('recovers a PAYING row when the claim is lost to a restart', async () => { + invoiceRepository.claim.resolves(undefined) + invoiceRepository.findByHash.resolves(invoice({ status: PeeringInvoiceStatus.PAYING })) + paymentsService.getInvoiceFromPaymentsProcessor = sandbox.stub().resolves({ status: 'completed' }) + + const result = await service.handleInvoice(peer, advertisement, event, now) + + expect(result.status).to.equal(PeeringInvoiceStatus.PAID) + expect(paymentsService.payInvoice).not.to.have.been.called + }) + + it('summarizes per-peer and global budget spend', async () => { + const window = peeringBudgetWindow(now, 2592000) + invoiceRepository.countInWindow.resolves({ received: 2, paid: 1, held: 1 }) + invoiceRepository.listBudgets.resolves([ + { scope: `peer:${PEER}`, periodStart: window.start, periodEnd: window.end, spentMsats: 250_000_000n }, + { scope: 'global', periodStart: window.start, periodEnd: window.end, spentMsats: 250_000_000n }, + ]) + + const summaries = await service.budgetSummary(now) + const peerSummary = summaries.find((summary) => summary.scope === 'peer') + const globalSummary = summaries.find((summary) => summary.scope === 'global') + + expect(peerSummary).to.include({ + peerPubkey: PEER, + spentMsats: 250_000_000n, + remainingMsats: 750_000_000n, + received: 2, + paid: 1, + held: 1, + }) + expect(globalSummary?.remainingMsats).to.equal(9_750_000_000n) + }) +}) diff --git a/test/unit/utils/bolt11.spec.ts b/test/unit/utils/bolt11.spec.ts index 28cdf9d4d..04ae66a16 100644 --- a/test/unit/utils/bolt11.spec.ts +++ b/test/unit/utils/bolt11.spec.ts @@ -26,7 +26,7 @@ describe('decodeBolt11', () => { }) it('rejects an invoice longer than the parser bound', () => { - expect(() => decodeBolt11(`lnbc1${'q'.repeat(1_000)}`)).to.throw('Invalid bolt11 invoice') + expect(() => decodeBolt11(`lnbc1${'q'.repeat(4_096)}`)).to.throw('Invalid bolt11 invoice') }) it('rejects a broken checksum', () => { diff --git a/test/unit/utils/peering-billing.spec.ts b/test/unit/utils/peering-billing.spec.ts index 55d8adc2a..cc6612009 100644 --- a/test/unit/utils/peering-billing.spec.ts +++ b/test/unit/utils/peering-billing.spec.ts @@ -4,8 +4,10 @@ import { Settings } from '../../../src/@types/settings' import { InvalidPeeringTermError, isPeeringInvoiceRequest, + peeringBudgetWindow, peeringPaymentRequiredReason, resolvePaidPeeringTerm, + resolvePeeringBudget, } from '../../../src/utils/peering-billing' const withTerms = (terms: unknown[]): Settings => @@ -84,8 +86,28 @@ describe('resolvePaidPeeringTerm', () => { }) }) -describe('peeringPaymentRequiredReason', () => { - it('prefixes an unprefixed denial reason', () => { +describe('peering budget windows', () => { + it('resolves a configured budget to msats', () => { + expect(resolvePeeringBudget({ amount: 10000, unit: 'sats', period: 3600 })).to.deep.equal({ + amountMsats: 10_000_000n, + periodSeconds: 3600, + }) + }) + + it('treats a zero budget as no budget', () => { + expect(resolvePeeringBudget({ amount: 0, unit: 'sats', period: 3600 })).to.be.undefined + expect(resolvePeeringBudget(undefined)).to.be.undefined + }) + + it('aligns a budget window to the period boundary', () => { + const window = peeringBudgetWindow(new Date('2026-11-18T12:34:56.000Z'), 3600) + + expect(window.start.toISOString()).to.equal('2026-11-18T12:00:00.000Z') + expect(window.end.toISOString()).to.equal('2026-11-18T13:00:00.000Z') + }) +}) + +describe('peeringPaymentRequiredReason', () => { it('prefixes an unprefixed denial reason', () => { expect(peeringPaymentRequiredReason({ reason: 'peering access lapsed' })).to.equal( 'payment-required: peering access lapsed', ) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 045d772a6..b94deab3f 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -294,13 +294,17 @@ describe('settings-config', () => { expect(issues.find((issue) => issue.path === 'peering.terms')?.message).to.include('payments must be enabled') }) - it('accepts a per-peer buyer budget in sats', () => { + it('accepts buyer budgets when payments are enabled', () => { const issues = validateSettings({ info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, payments: { enabled: true }, network: { maxPayloadSize: 1024 }, peering: { ...settlementFreePeering, + autoPay: { + enabled: true, + globalBudget: { amount: 100000, unit: 'sats', period: 2592000 }, + }, peers: [ { pubkey: 'a'.repeat(64), @@ -314,27 +318,62 @@ describe('settings-config', () => { expect(issues.filter((issue) => issue.path.startsWith('peering'))).to.deep.equal([]) }) - it('rejects a malformed per-peer budget', () => { + it('rejects malformed buyer budgets', () => { const issues = validateSettings({ info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, payments: { enabled: true }, network: { maxPayloadSize: 1024 }, peering: { ...settlementFreePeering, + autoPay: { + enabled: true, + globalBudget: { amount: 0.5, unit: 'usd', period: 0, extra: true }, + }, peers: [ { pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com', - budget: { amount: 0.5, unit: 'usd', period: 0, extra: true }, + budget: { amount: 0, unit: 'msats', period: 2592000 }, }, ], }, } as any) + expect(issues.some((issue) => issue.path === 'peering.autoPay.globalBudget.amount')).to.equal(true) + expect(issues.some((issue) => issue.path === 'peering.autoPay.globalBudget.unit')).to.equal(true) + expect(issues.some((issue) => issue.path === 'peering.autoPay.globalBudget.period')).to.equal(true) + expect(issues.some((issue) => issue.path === 'peering.autoPay.globalBudget.extra')).to.equal(true) expect(issues.some((issue) => issue.path === 'peering.peers[0].budget.amount')).to.equal(true) - expect(issues.some((issue) => issue.path === 'peering.peers[0].budget.unit')).to.equal(true) - expect(issues.some((issue) => issue.path === 'peering.peers[0].budget.period')).to.equal(true) - expect(issues.some((issue) => issue.path === 'peering.peers[0].budget.extra')).to.equal(true) + }) + + it('accepts a zero global budget as no cap', () => { + const issues = validateSettings({ + info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, + payments: { enabled: true }, + network: { maxPayloadSize: 1024 }, + peering: { + ...settlementFreePeering, + autoPay: { + enabled: true, + globalBudget: { amount: 0, unit: 'sats', period: 2592000 }, + }, + }, + } as any) + + expect(issues.filter((issue) => issue.path.startsWith('peering'))).to.deep.equal([]) + }) + + it('rejects auto-pay while payments are disabled', () => { + const issues = validateSettings({ + info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, + network: { maxPayloadSize: 1024 }, + peering: { + ...settlementFreePeering, + autoPay: { enabled: true }, + }, + } as any) + + expect(issues.some((issue) => issue.path === 'peering.autoPay.enabled')).to.equal(true) }) it('rejects a proof-of-work requirement above the NIP-13 maximum', () => {