diff --git a/.changeset/paid-peering-delivery.md b/.changeset/paid-peering-delivery.md new file mode 100644 index 00000000..ba2e7f65 --- /dev/null +++ b/.changeset/paid-peering-delivery.md @@ -0,0 +1,11 @@ +--- +"nostream": minor +--- + +feat(peering): deliver paid peering invoices and gate peer feeds + +Configured peers can request their BOLT11 invoice as a signed `kind 402` event +and pay it through Relay B's existing processor. Feed `REQ`, `COUNT` and NIP-77 +requests are refused with a payment-required reason until a paid period is +active. Expired invoices are reissued after a cooldown, and a missed webhook is +rechecked before access is denied. diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 1d7ed2c3..eac3aa74 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -193,8 +193,10 @@ peering: # windowSeconds: 3600 scopes: [] # Terms for peering, reusing the NIP-11 fee-object shape. `period` is in - # seconds. An empty list means settlement-free peering. - # Example: [{ amount: 1000, unit: msats, period: 2592000 }] + # seconds. An empty list means settlement-free peering. One positive term + # makes this a paid feed: payments must be enabled, and a paid msats amount + # must be a whole number of satoshis. + # Example: [{ amount: 21000, unit: msats, period: 2592000 }] terms: [] # Peering peers trusted by their relay pubkey (hex or npub), never by URL # alone. A connection that proves one of these keys with NIP-42 AUTH is diff --git a/src/@types/adapters.ts b/src/@types/adapters.ts index 36c8005b..465f999b 100644 --- a/src/@types/adapters.ts +++ b/src/@types/adapters.ts @@ -39,6 +39,13 @@ export type IWebSocketAdapter = EventEmitter & { getNegentropySessions(): INegentropySessions /** Removes a subscription and aborts any in-flight read still serving it. */ endSubscription(subscriptionId: string): void + /** + * Schedules a paid-access expiry check for this subscription. The adapter owns + * the timer and clears it on CLOSE, socket close and subscription ID reuse. + * `check` returns the next period end when access continues, `null` when access + * is free and no longer expires, or `false` when the subscription should close. + */ + setSubscriptionExpiry(subscriptionId: string, periodEnd: Date, check: () => Promise): void } export interface ICacheAdapter { diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index 1a03d508..2009c336 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -90,6 +90,8 @@ export interface IPeeringPaymentRepository { /** SELECT ... FOR UPDATE; must run inside a transaction. */ lockByPeer(pubkey: Pubkey, client: DatabaseClient): Promise save(payment: PeeringPayment, client?: DatabaseClient): Promise + /** Updates only the processor-check diagnostics, so a concurrent settlement is not overwritten. */ + recordCheck(pubkey: Pubkey, checkedAt: Date, error: string | null, client?: DatabaseClient): Promise list(): Promise /** Active or renewal-pending relationships whose period ends by `before`. */ findDueForRenewal(before: Date, limit: number, offset: number): Promise diff --git a/src/@types/services.ts b/src/@types/services.ts index de936622..dd81e14c 100644 --- a/src/@types/services.ts +++ b/src/@types/services.ts @@ -1,6 +1,7 @@ import { DatabaseTransaction, Pubkey } from './base' import { Invoice } from './invoice' import { NotificationOutboxPayload } from './notification-outbox' +import { PeeringAccess } from './peering' export interface IMaintenanceService { clearOldEvents(): Promise @@ -54,6 +55,17 @@ export interface IPaymentsService { getUnconfirmedPeeringInvoices(limit?: number, offset?: number): Promise } +export interface IPeeringBillingService { + /** Access decision for a configured peer's feed. Optionally rechecks a pending invoice first. */ + getAccess(peerPubkey: Pubkey, options?: { now?: Date; recheck?: boolean }): Promise + /** Returns a usable invoice, creating or reissuing one when needed. */ + ensureInvoice(peerPubkey: Pubkey, options?: { now?: Date; renewal?: boolean }): Promise + /** Ends expired periods once, marking them lapsed and alerting the operator. */ + processLapses(now?: Date): Promise + /** Clears a pointer and updates status after the processor confirms an invoice expired. */ + handleInvoiceExpired(invoice: Invoice): 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/adapters/web-socket-adapter.ts b/src/adapters/web-socket-adapter.ts index 9d175180..48551bd3 100644 --- a/src/adapters/web-socket-adapter.ts +++ b/src/adapters/web-socket-adapter.ts @@ -77,6 +77,7 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter private alive: boolean private pendingSend: Promise | undefined private subscriptions: Map + private readonly subscriptionExpiries = new Map() private readonly session: Nip42SessionManager /** Configured peering peer proven by AUTH on this socket, if any. */ private peerPubkey: string | undefined @@ -152,14 +153,94 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter public onUnsubscribed(subscriptionId: string): void { logger('client %s unsubscribed %s', this.clientId, subscriptionId) + this.clearSubscriptionExpiry(subscriptionId) this.subscriptions.delete(subscriptionId) } public onSubscribed(subscriptionId: string, filters: SubscriptionFilter[]): void { logger('client %s subscribed %s to %o', this.clientId, subscriptionId, filters) + // Reusing an id starts a new subscription; the old expiry must not close it. + this.clearSubscriptionExpiry(subscriptionId) this.subscriptions.set(subscriptionId, filters) } + public setSubscriptionExpiry( + subscriptionId: SubscriptionId, + periodEnd: Date, + check: () => Promise, + ): void { + this.clearSubscriptionExpiry(subscriptionId) + + const token = Symbol(subscriptionId) + const remaining = Math.max(0, periodEnd.getTime() - Date.now()) + const delay = Math.min(remaining, 2_147_483_647) + + const timer = setTimeout(() => { + if (this.subscriptionExpiries.get(subscriptionId)?.token !== token) { + return + } + + if (remaining > delay) { + this.setSubscriptionExpiry(subscriptionId, periodEnd, check) + return + } + + void this.runSubscriptionExpiry(subscriptionId, token, check) + }, delay) + + this.subscriptionExpiries.set(subscriptionId, { timer, token }) + } + + private async runSubscriptionExpiry( + subscriptionId: SubscriptionId, + token: symbol, + check: () => Promise, + ): Promise { + let nextPeriodEnd: Date | null | false = false + + try { + nextPeriodEnd = await check() + } catch (error) { + logger.error('unable to check paid subscription expiry for %s: %o', subscriptionId, error) + } + + // The id may have been reused, closed or disconnected while the check ran. + if (this.subscriptionExpiries.get(subscriptionId)?.token !== token) { + return + } + + if (nextPeriodEnd === null) { + // Free peering: access no longer has an expiry, so stop watching it. + this.clearSubscriptionExpiry(subscriptionId) + return + } + + if (nextPeriodEnd instanceof Date && nextPeriodEnd.getTime() > Date.now()) { + this.setSubscriptionExpiry(subscriptionId, nextPeriodEnd, check) + return + } + + this.clearSubscriptionExpiry(subscriptionId) + this.endSubscription(subscriptionId) + this.sendMessage(createClosedMessage(subscriptionId, 'payment-required: peering access expired')) + } + + private clearSubscriptionExpiry(subscriptionId: SubscriptionId): void { + const entry = this.subscriptionExpiries.get(subscriptionId) + if (!entry) { + return + } + + clearTimeout(entry.timer) + this.subscriptionExpiries.delete(subscriptionId) + } + + private clearAllSubscriptionExpiries(): void { + for (const subscriptionId of this.subscriptionExpiries.keys()) { + this.clearSubscriptionExpiry(subscriptionId) + } + } + public onBroadcast(event: Event): void { this.webSocketServer.emit(WebSocketServerAdapterEvent.Broadcast, event) if (cluster.isWorker && typeof process.send === 'function') { @@ -245,6 +326,8 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter } public drainAndClose(reason = 'relay shutting down'): void { + this.clearAllSubscriptionExpiries() + this.subscriptions.forEach((_filters, subscriptionId) => { this.sendMessage(createClosedMessage(subscriptionId, `error: ${reason}`)) }) @@ -466,6 +549,7 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter private onClientClose() { recordWebsocketConnectionClosed() this.alive = false + this.clearAllSubscriptionExpiries() this.subscriptions.clear() this.negentropySessions.closeAll() this.session.clear() diff --git a/src/app/maintenance-worker.ts b/src/app/maintenance-worker.ts index e066b3a4..a049f7ce 100644 --- a/src/app/maintenance-worker.ts +++ b/src/app/maintenance-worker.ts @@ -2,7 +2,7 @@ import { FSWatcher } from 'fs' import { mergeDeepLeft, path, pipe } from 'ramda' import { ICacheAdapter } from '../@types/adapters' import { IRunnable } from '../@types/base' -import { InvoiceStatus } from '../@types/invoice' +import { InvoicePurpose, InvoiceStatus } from '../@types/invoice' import { Nip05Verification } from '../@types/nip05' import { OperatorNotificationEventType } from '../@types/operator-notifications' import { @@ -14,6 +14,7 @@ import { IMaintenanceService, INotificationOutboxService, IPaymentsService, + IPeeringBillingService, ISubscriptionService, } from '../@types/services' import { Settings } from '../@types/settings' @@ -111,6 +112,7 @@ export class MaintenanceWorker implements IRunnable { private readonly notificationOutboxRepository: INotificationOutboxRepository, private readonly opsCache?: ICacheAdapter, private readonly subscriptionService?: ISubscriptionService, + private readonly peeringBillingService?: IPeeringBillingService, ) { this.process .on('SIGINT', this.onExit.bind(this)) @@ -287,14 +289,18 @@ export class MaintenanceWorker implements IRunnable { id: invoice.id, status: InvoiceStatus.EXPIRED, }) - try { - await this.notificationOutboxRepository.enqueue(OperatorNotificationEventType.ADMISSION_INVOICE_FAILED, { - invoiceId: invoice.id, - pubkey: invoice.pubkey, - reason: 'expired', - }) - } catch (error) { - logger.error('Unable to enqueue admission.invoice.failed notification', error) + if (invoice.purpose === InvoicePurpose.PEERING) { + await this.peeringBillingService?.handleInvoiceExpired(invoice) + } else { + try { + await this.notificationOutboxRepository.enqueue(OperatorNotificationEventType.ADMISSION_INVOICE_FAILED, { + invoiceId: invoice.id, + pubkey: invoice.pubkey, + reason: 'expired', + }) + } catch (error) { + logger.error('Unable to enqueue admission.invoice.failed notification', error) + } } successful++ continue @@ -307,6 +313,7 @@ export class MaintenanceWorker implements IRunnable { } await this.processSubscriptions() + await this.processPeeringLapses() await clearOldEventsPromise await this.publishOpsHeartbeat({ @@ -326,6 +333,17 @@ export class MaintenanceWorker implements IRunnable { } } + private async processPeeringLapses(): Promise { + try { + const changed = await this.peeringBillingService?.processLapses() + if (changed) { + logger('lapsed %d peering relationship(s)', changed) + } + } catch (error) { + logger.error('Unable to process peering lapses', error) + } + } + private async processNotificationOutbox(): Promise { try { const delivered = await this.notificationOutboxService.processBatch() diff --git a/src/factories/maintenance-worker-factory.ts b/src/factories/maintenance-worker-factory.ts index dd2e4a90..5e2e7981 100644 --- a/src/factories/maintenance-worker-factory.ts +++ b/src/factories/maintenance-worker-factory.ts @@ -2,6 +2,7 @@ import { createAdminOpsCacheAdapter } from './admin-ops-cache-adapter-factory' import { createMaintenanceService } from './maintenance-service-factory' import { createNotificationOutboxService } from './notification-outbox-service-factory' import { createPaymentsService } from './payments-service-factory' +import { createPeeringBillingService } from './peering-billing-service-factory' import { createSubscriptionService } from './subscription-service-factory' import { createSettings } from './settings-factory' import { getMasterDbClient } from '../database/client' @@ -26,5 +27,6 @@ export const maintenanceWorkerFactory = () => { notificationOutboxRepository, createAdminOpsCacheAdapter(), createSubscriptionService(), + createPeeringBillingService(), ) } diff --git a/src/factories/message-handler-factory.ts b/src/factories/message-handler-factory.ts index 3fe59796..3147ee0d 100644 --- a/src/factories/message-handler-factory.ts +++ b/src/factories/message-handler-factory.ts @@ -8,6 +8,7 @@ import { IReportRepository, IUserRepository, } from '../@types/repositories' +import { IPeeringBillingService } from '../@types/services' import { RedisAdapter } from '../adapters/redis-adapter' import { getCacheClient } from '../cache/client' import { getMasterDbClient } from '../database/client' @@ -22,6 +23,7 @@ import { UnsubscribeMessageHandler } from '../handlers/unsubscribe-message-handl import { UserSubscriptionRepository } from '../repositories/user-subscription-repository' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' import { eventStrategyFactory } from './event-strategy-factory' +import { createPeeringBillingService } from './peering-billing-service-factory' import { rateLimiterFactory } from './rate-limiter-factory' import { createSettings } from './settings-factory' import { wotGraphServiceFactory } from './wot-graph-service-factory' @@ -50,6 +52,25 @@ export const getPeerRequestStatsStore = (): PeeringRequestStatsStore => { return peerRequestStatsStore } +let peeringBillingService: IPeeringBillingService | undefined = undefined +export const getPeeringBillingService = (): IPeeringBillingService => { + if (!peeringBillingService) { + peeringBillingService = createPeeringBillingService() + } + return peeringBillingService +} + +/** + * Only a connection that proved a configured peer identity needs billing. Creating + * the billing service eagerly would build a payments processor for every ordinary + * REQ/COUNT/NEG-OPEN, which can fail before the handler runs when a payment + * provider is misconfigured. + */ +export const peeringBillingServiceFor = ( + adapter: IWebSocketAdapter, + get: () => IPeeringBillingService = getPeeringBillingService, +): IPeeringBillingService | undefined => (adapter.getPeerPubkey?.() ? get() : undefined) + export const messageHandlerFactory = ( eventRepository: IEventRepository, @@ -91,6 +112,7 @@ export const messageHandlerFactory = inviteCodeRepository, rateLimiterFactory, getPeerRequestStatsStore(), + peeringBillingServiceFor(adapter), ) case MessageType.CLOSE: return new UnsubscribeMessageHandler(adapter) @@ -101,6 +123,7 @@ export const messageHandlerFactory = createSettings, rateLimiterFactory, getPeerRequestStatsStore(), + peeringBillingServiceFor(adapter), ) case MessageType.AUTH: return new AuthMessageHandler(adapter, createSettings) @@ -111,6 +134,7 @@ export const messageHandlerFactory = createSettings, rateLimiterFactory, getPeerRequestStatsStore(), + peeringBillingServiceFor(adapter), ) case MessageType.NEG_MSG: return new NegMsgMessageHandler(adapter, createSettings) diff --git a/src/factories/payments-processor-factory.ts b/src/factories/payments-processor-factory.ts index 1798cc2b..eee6c607 100644 --- a/src/factories/payments-processor-factory.ts +++ b/src/factories/payments-processor-factory.ts @@ -1,3 +1,10 @@ +import { + CreateInvoiceRequest, + CreateInvoiceResponse, + GetInvoiceResponse, + IPaymentsProcessor, +} from '../@types/clients' +import { Invoice } from '../@types/invoice' import { createLNbitsPaymentProcessor } from './payments-processors/lnbits-payments-processor-factory' import { createLnurlPaymentsProcessor } from './payments-processors/lnurl-payments-processor-factory' import { createLogger } from './logger-factory' @@ -6,7 +13,6 @@ import { createNwcPaymentsProcessor } from './payments-processors/nwc-payments-p import { createOpenNodePaymentsProcessor } from './payments-processors/opennode-payments-processor-factory' import { createSettings } from './settings-factory' import { createZebedeePaymentsProcessor } from './payments-processors/zebedee-payments-processor-factory' -import { IPaymentsProcessor } from '../@types/clients' import { NullPaymentsProcessor } from '../payments-processors/null-payments-processor' const logger = createLogger('create-payments-processor') @@ -36,3 +42,30 @@ export const createPaymentsProcessor = (): IPaymentsProcessor => { return new NullPaymentsProcessor() } } + +/** + * Defers the real processor creation until a call needs it. This keeps creating + * the peering billing service (or the payments service) from throwing on a + * missing provider credential for clients that never use payments. + */ +export class LazyPaymentsProcessor implements IPaymentsProcessor { + private processor?: IPaymentsProcessor + + public constructor(private readonly createProcessor: () => IPaymentsProcessor = createPaymentsProcessor) {} + + private get(): IPaymentsProcessor { + if (!this.processor) { + this.processor = this.createProcessor() + } + + return this.processor + } + + public createInvoice(request: CreateInvoiceRequest): Promise { + return this.get().createInvoice(request) + } + + public getInvoice(invoice: string | Invoice): Promise { + return this.get().getInvoice(invoice) + } +} diff --git a/src/factories/payments-service-factory.ts b/src/factories/payments-service-factory.ts index b9ef8e58..c4a03e0c 100644 --- a/src/factories/payments-service-factory.ts +++ b/src/factories/payments-service-factory.ts @@ -1,6 +1,6 @@ import { getMasterDbClient, getReadReplicaDbClient } from '../database/client' import { createEventRepository } from './event-repository-factory' -import { createPaymentsProcessor } from './payments-processor-factory' +import { LazyPaymentsProcessor } from './payments-processor-factory' import { createSettings } from './settings-factory' import { InvoiceRepository } from '../repositories/invoice-repository' import { PaymentsService } from '../services/payments-service' @@ -16,7 +16,7 @@ export const createPaymentsService = () => { const eventRepository = createEventRepository(dbClient, rrDbClient) const userRepository = new UserRepository(dbClient, eventRepository) const notificationOutboxRepository = new NotificationOutboxRepository(dbClient) - const paymentsProcessor = createPaymentsProcessor() + const paymentsProcessor = new LazyPaymentsProcessor() return new PaymentsService( dbClient, diff --git a/src/factories/peering-billing-service-factory.ts b/src/factories/peering-billing-service-factory.ts new file mode 100644 index 00000000..3955875e --- /dev/null +++ b/src/factories/peering-billing-service-factory.ts @@ -0,0 +1,20 @@ +import { getMasterDbClient } from '../database/client' +import { InvoiceRepository } from '../repositories/invoice-repository' +import { NotificationOutboxRepository } from '../repositories/notification-outbox-repository' +import { PeeringPaymentRepository } from '../repositories/peering-payment-repository' +import { PeeringBillingService } from '../services/peering-billing-service' +import { createPaymentsService } from './payments-service-factory' +import { createSettings } from './settings-factory' + +export const createPeeringBillingService = (): PeeringBillingService => { + const dbClient = getMasterDbClient() + + return new PeeringBillingService( + dbClient, + new PeeringPaymentRepository(dbClient), + new InvoiceRepository(dbClient), + createPaymentsService(), + new NotificationOutboxRepository(dbClient), + createSettings, + ) +} diff --git a/src/handlers/count-message-handler.ts b/src/handlers/count-message-handler.ts index 1f5140b4..7e6aba8d 100644 --- a/src/handlers/count-message-handler.ts +++ b/src/handlers/count-message-handler.ts @@ -4,7 +4,9 @@ import { IWebSocketAdapter } from '../@types/adapters' import { Factory } from '../@types/base' import { IMessageHandler } from '../@types/message-handlers' import { CountMessage } from '../@types/messages' +import { PeeringAccess } from '../@types/peering' import { IEventRepository } from '../@types/repositories' +import { IPeeringBillingService } from '../@types/services' import { Settings } from '../@types/settings' import { SubscriptionFilter, SubscriptionId } from '../@types/subscription' import { IRateLimiter } from '../@types/utils' @@ -26,6 +28,7 @@ export class CountMessageHandler implements IMessageHandler { private readonly settings: () => Settings, private readonly rateLimiter?: Factory, private readonly requestStats?: PeeringRequestStatsStore, + private readonly peeringBillingService?: IPeeringBillingService, ) {} public async handleMessage(message: CountMessage): Promise { @@ -53,6 +56,28 @@ export class CountMessageHandler implements IMessageHandler { void this.requestStats?.recordRequest(peerPubkey, 'COUNT') } + if (peerPubkey && this.peeringBillingService) { + let access: PeeringAccess + try { + access = await this.peeringBillingService.getAccess(peerPubkey, { recheck: true }) + } catch (error) { + debug('unable to check peering access for %s: %o', peerPubkey, error) + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createClosedMessage(queryId, 'error: unable to check peering access'), + ) + return + } + + if (!access.allowed) { + const reason = access.reason?.startsWith('payment-required:') + ? access.reason + : `payment-required: ${access.reason ?? 'peering payment required; request the kind 402 peering invoice'}` + this.webSocket.emit(WebSocketAdapterEvent.Message, createClosedMessage(queryId, reason)) + return + } + } + // Some clients send the same filter more than once. Bound the raw list // before deduplicating it, since uniqWith() is O(n^2) and the schema no // longer caps filter counts so peer limits can be larger. diff --git a/src/handlers/neg-open-message-handler.ts b/src/handlers/neg-open-message-handler.ts index d8b9c1de..f49a2756 100644 --- a/src/handlers/neg-open-message-handler.ts +++ b/src/handlers/neg-open-message-handler.ts @@ -3,7 +3,9 @@ import { Factory } from '../@types/base' import { IMessageHandler } from '../@types/message-handlers' import { NegOpenMessage, OutgoingMessage } from '../@types/messages' import { INegentropySessions } from '../@types/negentropy' +import { PeeringAccess } from '../@types/peering' import { IEventRepository, ReconciliationItem } from '../@types/repositories' +import { IPeeringBillingService } from '../@types/services' import { Settings } from '../@types/settings' import { SubscriptionFilter, SubscriptionId } from '../@types/subscription' import { IRateLimiter } from '../@types/utils' @@ -31,6 +33,7 @@ export class NegOpenMessageHandler implements IMessageHandler { private readonly settings: () => Settings, private readonly rateLimiter?: Factory, private readonly requestStats?: PeeringRequestStatsStore, + private readonly peeringBillingService?: IPeeringBillingService, ) {} public async handleMessage(message: NegOpenMessage): Promise { @@ -85,6 +88,36 @@ export class NegOpenMessageHandler implements IMessageHandler { return } + if (peerPubkey && this.peeringBillingService) { + let access: PeeringAccess + try { + access = await this.peeringBillingService.getAccess(peerPubkey, { recheck: true }) + } catch (error) { + sessions.endRead(token) + if (sessions.isCurrent(subscriptionId, token)) { + logger.error('unable to check peering access for %s: %o', peerPubkey, error) + this.reject(sessions, subscriptionId, 'error: unable to check peering access') + } + return + } + + // A replacement NEG-OPEN may have claimed this id while billing was pending. + // The older check must not close the newer session. + if (!sessions.isCurrent(subscriptionId, token)) { + sessions.endRead(token) + return + } + + if (!access.allowed) { + sessions.endRead(token) + const reason = access.reason?.startsWith('payment-required:') + ? access.reason + : `payment-required: ${access.reason ?? 'peering payment required; request the kind 402 peering invoice'}` + this.reject(sessions, subscriptionId, reason) + return + } + } + if (peerPubkey) { void this.requestStats?.recordRequest(peerPubkey, 'NEG-OPEN') } diff --git a/src/handlers/subscribe-message-handler.ts b/src/handlers/subscribe-message-handler.ts index cd81daeb..aa6ed2de 100644 --- a/src/handlers/subscribe-message-handler.ts +++ b/src/handlers/subscribe-message-handler.ts @@ -5,8 +5,10 @@ import { IWebSocketAdapter } from '../@types/adapters' import { Factory, Pubkey } from '../@types/base' import { Event } from '../@types/event' import { IAbortable, IMessageHandler } from '../@types/message-handlers' +import { PeeringAccess } from '../@types/peering' import { SubscribeMessage } from '../@types/messages' import { IEventRepository, IInviteCodeRepository } from '../@types/repositories' +import { IPeeringBillingService } from '../@types/services' import { Settings } from '../@types/settings' import { SubscriptionFilter, SubscriptionId } from '../@types/subscription' import { IRateLimiter } from '../@types/utils' @@ -25,11 +27,15 @@ import { isNip43InviteRequestFilter, isRelaySelfConsistent } from '../utils/nip4 import { buildInviteCodeEvent, issueInviteCode } from '../utils/nip43-invites' import { subscriptionLimitsFor } from '../utils/peer-limits' import { getPeerRequestRetryAfterMs } from '../utils/peer-requests' +import { isPeeringInvoiceRequest, PeeringInvoiceCooldownError } from '../utils/peering-billing' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' import { streamEachAsync, streamEnd, streamFilter, streamMap } from '../utils/stream' const logger = createLogger('subscribe-message-handler') +/** Keep invoice re-requests from growing the socket's subscription map without bound. */ +const MAX_PEERING_INVOICE_SUBSCRIPTIONS = 1 + export class SubscribeMessageHandler implements IMessageHandler, IAbortable { private readonly abortController: AbortController @@ -43,6 +49,7 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { private readonly inviteCodeRepository: IInviteCodeRepository, private readonly rateLimiter: Factory, private readonly requestStats?: PeeringRequestStatsStore, + private readonly peeringBillingService?: IPeeringBillingService, ) { this.abortController = new AbortController() } @@ -113,13 +120,104 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { return } + let peeringAccess: PeeringAccess | undefined + if (peerPubkey && this.peeringBillingService) { + const result = await this.enforcePeeringAccess(subscriptionId, filters, peerPubkey) + if (this.abortController.signal.aborted || result.rejected) { + return + } + peeringAccess = result.access + } + + // A CLOSE may have arrived while billing was pending. Do not register a + // subscription the peer has already abandoned. + if (this.abortController.signal.aborted) { + return + } + this.webSocket.emit(WebSocketAdapterEvent.Subscribe, subscriptionId, filters) + if (peeringAccess?.periodEnd) { + this.webSocket.setSubscriptionExpiry(subscriptionId, peeringAccess.periodEnd, async () => { + // A renewal may have been paid after the last maintenance poll but before + // this period ended. Recheck the pending invoice before closing the feed. + const latest = await this.peeringBillingService!.getAccess(peerPubkey!, { recheck: true }) + if (!latest.allowed) { + return false + } + + // Free peering has no expiry; keep the feed open and stop the timer. + return latest.periodEnd ?? null + }) + } + await this.maybeIssueInviteCode(subscriptionId, filters) await this.fetchAndSend(subscriptionId, filters) } + /** + * Peers may always ask for their invoice; everything else is a paid feed and + * needs a running period. Returns the access window when the feed is allowed. + */ + private async enforcePeeringAccess( + subscriptionId: SubscriptionId, + filters: SubscriptionFilter[], + peerPubkey: Pubkey, + ): Promise<{ rejected: boolean; access?: PeeringAccess }> { + const isInvoiceRequest = isPeeringInvoiceRequest(filters, peerPubkey) + + if (isInvoiceRequest) { + try { + await this.peeringBillingService!.ensureInvoice(peerPubkey) + return { rejected: false } + } catch (error) { + if (error instanceof PeeringInvoiceCooldownError) { + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createClosedMessage( + subscriptionId, + 'rate-limited: peering invoice reissue cooling down', + String(error.retryAfterSeconds * 1000), + ), + ) + return { rejected: true } + } + + logger('unable to issue peering invoice for %s: %o', peerPubkey, error) + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createClosedMessage(subscriptionId, 'error: unable to issue peering invoice'), + ) + return { rejected: true } + } + } + + let access: PeeringAccess + try { + access = await this.peeringBillingService!.getAccess(peerPubkey, { recheck: true }) + } catch (error) { + logger.error('unable to check peering access for %s: %o', peerPubkey, error) + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createClosedMessage(subscriptionId, 'error: unable to check peering access'), + ) + return { rejected: true } + } + + if (access.allowed) { + return { rejected: false, access } + } + + const reason = access.reason?.startsWith('payment-required:') + ? access.reason + : `payment-required: ${access.reason ?? 'peering payment required; request the kind 402 peering invoice'}` + + logger('subscription %s with %o rejected for peer %s: %s', subscriptionId, filters, peerPubkey, reason) + this.webSocket.emit(WebSocketAdapterEvent.Message, createClosedMessage(subscriptionId, reason)) + return { rejected: true } + } + // NIP-43: kind 28935 is never published by a client and never stored. A REQ for // it asks the relay to mint an invite code, which we answer with a relay-signed // ephemeral event on this socket only. fetchAndSend still runs afterwards: its @@ -306,14 +404,33 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { private canSubscribe(subscriptionId: SubscriptionId, filters: SubscriptionFilter[]): string | undefined { const subscriptions = this.webSocket.getSubscriptions() const existingSubscription = subscriptions.get(subscriptionId) - const subscriptionLimits = subscriptionLimitsFor(this.settings(), this.webSocket.getPeerPubkey() !== undefined) + const peerPubkey = this.webSocket.getPeerPubkey() + const subscriptionLimits = subscriptionLimitsFor(this.settings(), peerPubkey !== undefined) + const isInvoiceRequest = peerPubkey ? isPeeringInvoiceRequest(filters, peerPubkey) : false if (existingSubscription?.length && equals(filters, existingSubscription)) { - return `Duplicate subscription ${subscriptionId}: Ignoring` + // Asking for the peering invoice again is how a peer recovers a missed event; + // it must not be rejected as a duplicate subscription. + if (!isInvoiceRequest) { + return `Duplicate subscription ${subscriptionId}: Ignoring` + } + } + + const invoiceSubscriptions = peerPubkey + ? [...subscriptions.values()].filter((current) => isPeeringInvoiceRequest(current, peerPubkey)).length + : 0 + const isNewInvoiceSubscription = isInvoiceRequest && !existingSubscription?.length + if (isNewInvoiceSubscription && invoiceSubscriptions >= MAX_PEERING_INVOICE_SUBSCRIPTIONS) { + return `Too many peering invoice subscriptions: close the previous invoice subscription before opening another` } const maxSubscriptions = subscriptionLimits?.maxSubscriptions ?? 0 - if (maxSubscriptions > 0 && !existingSubscription?.length && subscriptions.size + 1 > maxSubscriptions) { + if ( + maxSubscriptions > 0 && + !isInvoiceRequest && + !existingSubscription?.length && + subscriptions.size + 1 > maxSubscriptions + ) { return `Too many subscriptions: Number of subscriptions must be less than or equal to ${maxSubscriptions}` } diff --git a/src/repositories/peering-payment-repository.ts b/src/repositories/peering-payment-repository.ts index 708cf634..95d136b1 100644 --- a/src/repositories/peering-payment-repository.ts +++ b/src/repositories/peering-payment-repository.ts @@ -62,6 +62,24 @@ export class PeeringPaymentRepository implements IPeeringPaymentRepository { return row ? fromDBPeeringPayment(row) : undefined } + public async recordCheck( + pubkey: Pubkey, + checkedAt: Date, + error: string | null, + client: DatabaseClient = this.dbClient, + ): Promise { + await client('peering_payments') + .update({ + last_checked_at: checkedAt, + last_error: error, + updated_at: new Date(), + }) + .where({ + peer_pubkey: toBuffer(pubkey), + direction: PeeringPaymentDirection.SELL, + }) + } + public async save(payment: PeeringPayment, client: DatabaseClient = this.dbClient): Promise { const row = toRow(payment) const now = new Date() diff --git a/src/services/peering-billing-service.ts b/src/services/peering-billing-service.ts new file mode 100644 index 00000000..9913a437 --- /dev/null +++ b/src/services/peering-billing-service.ts @@ -0,0 +1,483 @@ +import { DatabaseClient, Pubkey } from '../@types/base' +import { Invoice, InvoicePurpose, InvoiceStatus } from '../@types/invoice' +import { OperatorNotificationEventType } from '../@types/operator-notifications' +import { PeeringAccess, PeeringPayment, PeeringPaymentStatus, PeeringTermSnapshot } from '../@types/peering' +import { IInvoiceRepository, INotificationOutboxRepository, IPeeringPaymentRepository } from '../@types/repositories' +import { IPaymentsService, IPeeringBillingService } from '../@types/services' +import { Settings } from '../@types/settings' +import { Transaction } from '../database/transaction' +import { createLogger } from '../factories/logger-factory' +import { + InvalidPeeringTermError, + PEERING_RECHECK_COOLDOWN_SECONDS, + PEERING_REISSUE_COOLDOWN_SECONDS, + PeeringInvoiceCooldownError, + peeringInvoiceDescription, + resolvePaidPeeringTerm, +} from '../utils/peering-billing' + +const logger = createLogger('peering-billing-service') + +const SWEEP_PAGE_SIZE = 10 +const SWEEP_MAX_PAGES = 10 + +const isExpiredAt = (invoice: Invoice, now: Date): boolean => + invoice.expiresAt instanceof Date && invoice.expiresAt.getTime() <= now.getTime() + +export class PeeringBillingService implements IPeeringBillingService { + private readonly cursors = { renewal: 0, ended: 0 } + + public constructor( + private readonly dbClient: DatabaseClient, + private readonly peeringPaymentRepository: IPeeringPaymentRepository, + private readonly invoiceRepository: IInvoiceRepository, + private readonly paymentsService: IPaymentsService, + private readonly notificationOutboxRepository: INotificationOutboxRepository, + private readonly settings: () => Settings, + private readonly revokePeer?: (pubkey: Pubkey) => void, + ) {} + + public async getAccess(peerPubkey: Pubkey, options: { now?: Date; recheck?: boolean } = {}): Promise { + const now = options.now ?? new Date() + let term: PeeringTermSnapshot | undefined + + try { + term = resolvePaidPeeringTerm(this.settings()) + } catch (error) { + logger.error('invalid paid peering term for %s: %o', peerPubkey, error) + return { + allowed: false, + status: 'unconfigured', + reason: error instanceof InvalidPeeringTermError ? error.message : 'invalid peering term', + } + } + + // An empty/zero term list means settlement-free peering. + if (!term) { + return { allowed: true, status: 'free' } + } + + let payment = await this.peeringPaymentRepository.findByPeer(peerPubkey) + let access = this.accessFrom(payment, now) + + if (!access.allowed && options.recheck) { + const settled = await this.recheckPendingInvoice(peerPubkey, now) + if (settled) { + payment = await this.peeringPaymentRepository.findByPeer(peerPubkey) + access = this.accessFrom(payment, now) + } + } + + return access + } + + private accessFrom(payment: PeeringPayment | undefined, now: Date): PeeringAccess { + if (!payment) { + return { + allowed: false, + status: PeeringPaymentStatus.UNPAID, + reason: 'no peering invoice has been issued yet', + } + } + + const running = payment.periodEnd instanceof Date && payment.periodEnd.getTime() > now.getTime() + const payingStatus = + payment.status === PeeringPaymentStatus.ACTIVE || payment.status === PeeringPaymentStatus.RENEWAL_PENDING + + if (running && payingStatus) { + return { + allowed: true, + status: payment.status, + periodEnd: payment.periodEnd, + } + } + + return { + allowed: false, + status: payment.status, + periodEnd: payment.periodEnd, + reason: + payment.status === PeeringPaymentStatus.LAPSED + ? 'peering access lapsed; request a new invoice' + : 'peering payment required; request the kind 402 peering invoice', + } + } + + public async ensureInvoice( + peerPubkey: Pubkey, + options: { now?: Date; renewal?: boolean } = {}, + ): Promise { + let term: PeeringTermSnapshot | undefined + try { + term = resolvePaidPeeringTerm(this.settings()) + } catch (error) { + logger.error('unable to resolve paid peering term for %s: %o', peerPubkey, error) + throw error + } + + if (!term) { + return undefined + } + + if (this.settings().payments?.enabled !== true) { + throw new Error('paid peering requires payments to be enabled') + } + + const now = options.now ?? new Date() + + // Check the open invoice before retiring a locally expired one. The processor + // may have accepted payment just before expiry, especially without webhooks. + const settled = await this.recheckPendingInvoice(peerPubkey, now, true) + if (settled) { + const payment = await this.peeringPaymentRepository.findByPeer(peerPubkey) + const settledInvoiceId = payment?.lastSettledInvoiceId + if (settledInvoiceId) { + const settledInvoice = await this.invoiceRepository.findById(settledInvoiceId) + if (settledInvoice) { + try { + await this.paymentsService.ensurePeeringInvoiceNotification(settledInvoice) + } catch (error) { + logger.error('unable to publish settled peering invoice %s: %o', settledInvoice.id, error) + } + return settledInvoice + } + } + + return undefined + } + + const transaction = new Transaction(this.dbClient) + let invoice: Invoice | undefined + + await transaction.begin() + try { + await this.peeringPaymentRepository.ensureRow(peerPubkey, transaction.transaction) + const payment = await this.peeringPaymentRepository.lockByPeer(peerPubkey, transaction.transaction) + if (!payment) { + throw new Error(`Unable to lock peering payment row for ${peerPubkey}`) + } + + const running = payment.periodEnd instanceof Date && payment.periodEnd.getTime() > now.getTime() + + // Any open invoice is returned first, even one issued before the period ended: + // it is still payable and creating a second one would charge the peer twice. + const openInvoice = await this.findOpenInvoice(payment, now, transaction.transaction) + if (openInvoice) { + invoice = openInvoice + } else { + // findOpenInvoice clears pointers to invoices it retired. Re-read the locked row + // so the new invoice is written against those cleared pointers, not stale ones. + const current = + (await this.peeringPaymentRepository.lockByPeer(peerPubkey, transaction.transaction)) ?? payment + const renewal = options.renewal === true || running + const created = await this.paymentsService.createPeeringInvoice( + peerPubkey, + term.amountMsats, + peeringInvoiceDescription(this.settings(), peerPubkey, term), + term.periodSeconds, + transaction.transaction, + ) + + const next: PeeringPayment = { + ...current, + status: renewal ? PeeringPaymentStatus.RENEWAL_PENDING : PeeringPaymentStatus.INVOICED, + currentInvoiceId: renewal ? (current.currentInvoiceId ?? null) : created.id, + renewalInvoiceId: renewal ? created.id : null, + termAmountMsats: term.amountMsats, + termPeriodSeconds: term.periodSeconds, + lastError: null, + } + + await this.peeringPaymentRepository.save(next, transaction.transaction) + invoice = created + } + + await transaction.commit() + } catch (error) { + await transaction.rollback() + logger.error('unable to ensure peering invoice for %s: %o', peerPubkey, error) + throw error + } + + // Publishing after the commit avoids advertising an invoice the database did + // not accept. A failure here leaves the row intact; the next request republishes it. + if (invoice) { + try { + await this.paymentsService.ensurePeeringInvoiceNotification(invoice) + } catch (error) { + logger.error('unable to publish peering invoice %s: %o', invoice.id, error) + } + } + + return invoice + } + + private async findOpenInvoice( + payment: PeeringPayment, + now: Date, + client: DatabaseClient, + ): Promise { + const candidates = [payment.renewalInvoiceId, payment.currentInvoiceId].filter( + (id): id is string => typeof id === 'string' && id.length > 0, + ) + + let expired: Invoice | undefined + for (const id of candidates) { + const invoice = await this.invoiceRepository.findById(id, client) + if (!invoice) { + continue + } + + if (invoice.status === InvoiceStatus.PENDING && !isExpiredAt(invoice, now)) { + return invoice + } + + if (invoice.status === InvoiceStatus.PENDING && isExpiredAt(invoice, now)) { + expired = invoice + await this.invoiceRepository.updateStatus({ id: invoice.id, status: InvoiceStatus.EXPIRED }, client) + await this.enqueueFailed(invoice, 'expired', client) + + // Clear the pointer immediately, even if the other candidate is still usable. + payment.currentInvoiceId = payment.currentInvoiceId === invoice.id ? null : payment.currentInvoiceId + payment.renewalInvoiceId = payment.renewalInvoiceId === invoice.id ? null : payment.renewalInvoiceId + await this.peeringPaymentRepository.save(payment, client) + } + } + + if (expired) { + // The peer just let the invoice expire. Do not let it mint another one in a loop. + const expiredAt = expired.expiresAt ?? payment.updatedAt + const elapsedSeconds = Math.floor((now.getTime() - expiredAt.getTime()) / 1000) + if (elapsedSeconds >= 0 && elapsedSeconds < PEERING_REISSUE_COOLDOWN_SECONDS) { + throw new PeeringInvoiceCooldownError(PEERING_REISSUE_COOLDOWN_SECONDS - elapsedSeconds) + } + } + + return undefined + } + + public async recheckPendingInvoice(peerPubkey: Pubkey, now = new Date(), force = false): Promise { + const payment = await this.peeringPaymentRepository.findByPeer(peerPubkey) + const invoiceId = payment?.renewalInvoiceId ?? payment?.currentInvoiceId + if (!payment || !invoiceId) { + return false + } + + if ( + !force && + payment.lastCheckedAt instanceof Date && + now.getTime() - payment.lastCheckedAt.getTime() < PEERING_RECHECK_COOLDOWN_SECONDS * 1000 + ) { + return false + } + + const invoice = await this.invoiceRepository.findById(invoiceId) + // A locally expired invoice can still have been paid before its expiry. Ask the + // processor before retiring it; LNURL and NWC rely on polling for settlement. + if (!invoice || invoice.status !== InvoiceStatus.PENDING) { + return false + } + + try { + const updated = await this.paymentsService.getInvoiceFromPaymentsProcessor(invoice) + if (updated.status === InvoiceStatus.COMPLETED && updated.confirmedAt) { + await this.paymentsService.confirmInvoice({ + ...invoice, + ...updated, + amountPaid: typeof updated.amountPaid === 'bigint' ? updated.amountPaid : invoice.amountRequested, + }) + return true + } + + // Update only the check columns. The processor call yields, and a webhook may + // have settled this peer in the meantime; saving the old row would undo it. + await this.peeringPaymentRepository.recordCheck( + peerPubkey, + now, + updated.status ? `processor status: ${updated.status}` : null, + ) + return false + } catch (error) { + logger.error('unable to recheck peering invoice %s: %o', invoiceId, error) + await this.peeringPaymentRepository.recordCheck( + peerPubkey, + now, + error instanceof Error ? error.message : 'processor check failed', + ) + return false + } + } + + /** + * Ends periods whose paid window has passed, marks each peer lapsed once and + * emits the operator alert. A failed processor recheck makes the lapse wait + * for the next pass instead of revoking a peer that may have just paid. + */ + public async processLapses(now = new Date()): Promise { + let term: PeeringTermSnapshot | undefined + try { + term = resolvePaidPeeringTerm(this.settings()) + } catch (error) { + logger.error('not processing peering lapses: %o', error) + return 0 + } + + if (!term) { + return 0 + } + + return this.sweep( + 'ended', + (limit, offset) => this.peeringPaymentRepository.findPeriodEnded(now, limit, offset), + (payment) => this.handlePeriodEnded(payment.peerPubkey, now), + ) + } + + private async handlePeriodEnded(peerPubkey: Pubkey, now: Date): Promise { + // A webhook may have been lost; check the open invoice before locking the period. + // This is the last check before a lapse, so it bypasses the normal recheck cooldown. + const settled = await this.recheckPendingInvoice(peerPubkey, now, true) + if (settled) { + return true + } + + const transaction = new Transaction(this.dbClient) + let lapsed = false + + await transaction.begin() + try { + const payment = await this.peeringPaymentRepository.lockByPeer(peerPubkey, transaction.transaction) + if (!payment) { + await transaction.rollback() + return false + } + + const stillRunning = payment.periodEnd instanceof Date && payment.periodEnd.getTime() > now.getTime() + if (stillRunning || payment.status === PeeringPaymentStatus.LAPSED) { + await transaction.rollback() + return false + } + + await this.peeringPaymentRepository.save( + { + ...payment, + status: PeeringPaymentStatus.LAPSED, + currentInvoiceId: null, + renewalInvoiceId: null, + lastCheckedAt: now, + lastError: null, + }, + transaction.transaction, + ) + + await this.notificationOutboxRepository.enqueue( + OperatorNotificationEventType.PEERING_ACCESS_LAPSED, + { + pubkey: peerPubkey, + periodEnd: payment.periodEnd?.toISOString(), + }, + transaction.transaction, + ) + + await transaction.commit() + lapsed = true + } catch (error) { + await transaction.rollback() + logger.error('unable to lapse peering access for %s: %o', peerPubkey, error) + return false + } + + logger('peering access lapsed for %s', peerPubkey) + try { + this.revokePeer?.(peerPubkey) + } catch (error) { + logger.error('unable to revoke live peering sockets for %s: %o', peerPubkey, error) + } + + return lapsed + } + + /** Clears a pointer and records the failure after the processor confirms expiry. */ + public async handleInvoiceExpired(invoice: Invoice): Promise { + if (invoice.purpose !== InvoicePurpose.PEERING) { + return + } + + const payment = await this.peeringPaymentRepository.findByPeer(invoice.pubkey) + if (!payment) { + return + } + + const isCurrent = payment.currentInvoiceId === invoice.id + const isRenewal = payment.renewalInvoiceId === invoice.id + if (!isCurrent && !isRenewal) { + return + } + + await this.peeringPaymentRepository.save({ + ...payment, + currentInvoiceId: isCurrent ? null : payment.currentInvoiceId, + renewalInvoiceId: isRenewal ? null : payment.renewalInvoiceId, + status: + isCurrent && payment.status === PeeringPaymentStatus.INVOICED ? PeeringPaymentStatus.UNPAID : payment.status, + lastCheckedAt: new Date(), + }) + + await this.enqueueFailed(invoice, 'expired') + } + + private async sweep( + name: 'renewal' | 'ended', + find: (limit: number, offset: number) => Promise, + handle: (payment: PeeringPayment) => Promise, + ): Promise { + let changed = 0 + let skipped = this.cursors[name] + let reachedEnd = false + + for (let page = 0; page < SWEEP_MAX_PAGES; page++) { + const payments = await find(SWEEP_PAGE_SIZE, skipped) + + for (const payment of payments) { + let handled = false + try { + handled = await handle(payment) + } catch (error) { + logger.error('unable to process peering lifecycle for %s: %o', payment.peerPubkey, error) + } + + if (handled) { + changed++ + } else { + skipped++ + } + } + + if (payments.length < SWEEP_PAGE_SIZE) { + reachedEnd = true + break + } + } + + this.cursors[name] = reachedEnd ? 0 : skipped + + return changed + } + + private async enqueueFailed(invoice: Invoice, reason: string, client?: DatabaseClient): Promise { + try { + await this.notificationOutboxRepository.enqueue( + OperatorNotificationEventType.PEERING_INVOICE_FAILED, + { + invoiceId: invoice.id, + pubkey: invoice.pubkey, + reason, + }, + client, + ) + } catch (error) { + logger.error('unable to enqueue peering invoice failure for %s: %o', invoice.id, error) + } + } + +} diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 7f326f4e..fdad3f41 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -959,6 +959,14 @@ const validatePeeringTerms = (terms: unknown, issues: ValidationIssue[]): void = 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)) { @@ -1078,6 +1086,26 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => validatePeeringTerms(peering.terms, issues) validatePeeringPeers(peering.peers, issues) + const paidTerms = Array.isArray(peering.terms) + ? peering.terms.filter( + (term) => isPlainObject(term) && typeof term.amount === 'number' && term.amount > 0, + ) + : [] + + if (paidTerms.length > 1) { + issues.push({ + path: 'peering.terms', + message: 'only one paid peering term is supported', + }) + } + + if (paidTerms.length > 0 && settings.payments?.enabled !== true) { + issues.push({ + path: 'peering.terms', + message: 'payments must be enabled to charge for peering', + }) + } + if (!enabled) { return } diff --git a/test/integration/features/nip-11/nip-11.feature.ts b/test/integration/features/nip-11/nip-11.feature.ts index 728a830f..ea8ba8ea 100644 --- a/test/integration/features/nip-11/nip-11.feature.ts +++ b/test/integration/features/nip-11/nip-11.feature.ts @@ -97,12 +97,18 @@ Then('the peering object matches the configured peering settings', function(this { kinds: [1, 6], window_seconds: 3600 }, { kinds: [3], since: 1700000000 }, ], - terms: [{ amount: 1000, unit: 'msats', period: 2592000 }], + terms: [], }) }) -const peeringIssuesFor = (peering: unknown) => - validateSettings({ ...createSettings(), peering } as Settings).filter((issue) => issue.path.startsWith('peering')) +const peeringIssuesFor = (peering: unknown) => { + const settings = createSettings() + return validateSettings({ + ...settings, + payments: { ...settings.payments, enabled: true, processor: 'lnbits' }, + peering, + } as Settings).filter((issue) => issue.path.startsWith('peering')) +} When('peering settings are validated with a complete configuration', function(this: World>) { this.parameters.peeringValidationIssues = peeringIssuesFor({ diff --git a/test/integration/settings.yaml b/test/integration/settings.yaml index 79dbe9a6..c7230462 100644 --- a/test/integration/settings.yaml +++ b/test/integration/settings.yaml @@ -15,7 +15,3 @@ peering: windowSeconds: 3600 - kinds: [3] since: 1700000000 - terms: - - amount: 1000 - unit: msats - period: 2592000 diff --git a/test/unit/adapters/web-socket-adapter.spec.ts b/test/unit/adapters/web-socket-adapter.spec.ts index 2b35d28e..979d1b06 100644 --- a/test/unit/adapters/web-socket-adapter.spec.ts +++ b/test/unit/adapters/web-socket-adapter.spec.ts @@ -188,6 +188,103 @@ describe('WebSocketAdapter', () => { }) }) + describe('setSubscriptionExpiry', () => { + let clock: Sinon.SinonFakeTimers + + beforeEach(() => { + clock = Sinon.useFakeTimers({ now: new Date('2026-11-09T12:00:00.000Z') }) + }) + + afterEach(() => { + clock.restore() + }) + + const closedMessage = (subscriptionId: string) => + JSON.stringify(['CLOSED', subscriptionId, 'payment-required: peering access expired']) + + it('closes the subscription when paid access ends', async () => { + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry( + 'sub-1', + new Date('2026-11-09T12:00:01.000Z'), + sandbox.stub().resolves(undefined), + ) + + await clock.tickAsync(1000) + + expect(adapter.getSubscriptions().has('sub-1')).to.be.false + expect(client.send).to.have.been.calledWith(closedMessage('sub-1')) + }) + + it('keeps the subscription open when access becomes free', async () => { + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry( + 'sub-1', + new Date('2026-11-09T12:00:01.000Z'), + sandbox.stub().resolves(null), + ) + + await clock.tickAsync(1000) + + expect(adapter.getSubscriptions().has('sub-1')).to.be.true + expect(client.send).not.to.have.been.calledWith(closedMessage('sub-1')) + }) + + it('clears the timer when the subscription is closed', async () => { + const check = sandbox.stub().resolves(undefined) + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:01.000Z'), check) + adapter.onUnsubscribed('sub-1') + + await clock.tickAsync(1000) + + expect(check).not.to.have.been.called + }) + + it('clears the timer when the subscription id is reused', async () => { + const check = sandbox.stub().resolves(undefined) + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:01.000Z'), check) + adapter.onSubscribed('sub-1', [{ kinds: [2] }]) + + await clock.tickAsync(1000) + + expect(check).not.to.have.been.called + expect(adapter.getSubscriptions().get('sub-1')).to.deep.equal([{ kinds: [2] }]) + }) + + it('does not close a reused subscription when an old expiry check resolves late', async () => { + let releaseCheck: ((periodEnd: Date | undefined) => void) | undefined + const check = () => + new Promise((resolve) => { + releaseCheck = resolve + }) + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:00.000Z'), check) + + clock.tick(1) + expect(releaseCheck).to.be.a('function') + adapter.onSubscribed('sub-1', [{ kinds: [2] }]) + releaseCheck?.(undefined) + await clock.tickAsync(0) + + expect(adapter.getSubscriptions().get('sub-1')).to.deep.equal([{ kinds: [2] }]) + expect(client.send).not.to.have.been.calledWith(closedMessage('sub-1')) + }) + + it('clears all timers when the socket closes', async () => { + const check = sandbox.stub().resolves(undefined) + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:01.000Z'), check) + const closeCall = client.on.getCalls().find((call: any) => call.args[0] === 'close') + closeCall.args[1]() + + await clock.tickAsync(1000) + + expect(check).not.to.have.been.called + }) + }) + describe('onBroadcast', () => { it('emits broadcast event on the WebSocket server adapter', () => { const emitSpy = sandbox.spy(webSocketServer, 'emit') diff --git a/test/unit/app/maintenance-worker.spec.ts b/test/unit/app/maintenance-worker.spec.ts index cbd03e1d..03cd5a4f 100644 --- a/test/unit/app/maintenance-worker.spec.ts +++ b/test/unit/app/maintenance-worker.spec.ts @@ -7,6 +7,7 @@ import sinonChai from 'sinon-chai' import { InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../src/@types/invoice' import { Nip05Verification } from '../../../src/@types/nip05' +import { OperatorNotificationEventType } from '../../../src/@types/operator-notifications' import { IMaintenanceService, INotificationOutboxService, IPaymentsService } from '../../../src/@types/services' import { Settings } from '../../../src/@types/settings' import { applyReverificationOutcome, MaintenanceWorker } from '../../../src/app/maintenance-worker' @@ -32,6 +33,7 @@ describe('MaintenanceWorker', () => { let notificationOutboxService: Sinon.SinonStubbedInstance let notificationDeliveryLogRepository: any let notificationOutboxRepository: any + let peeringBillingService: { processLapses: Sinon.SinonStub; handleInvoiceExpired: Sinon.SinonStub } let verifyStub: Sinon.SinonStub const pendingInvoice = { @@ -109,6 +111,11 @@ describe('MaintenanceWorker', () => { deleteTerminalOlderThan: sandbox.stub().resolves(0), } + peeringBillingService = { + processLapses: sandbox.stub().resolves(0), + handleInvoiceExpired: sandbox.stub().resolves(), + } + // Prevent real timeouts and randomized per-invoice delays. sandbox.stub(misc, 'delayMs').resolves() @@ -121,6 +128,9 @@ describe('MaintenanceWorker', () => { notificationOutboxService, notificationDeliveryLogRepository, notificationOutboxRepository, + undefined, + undefined, + peeringBillingService as any, ) }) @@ -741,6 +751,47 @@ describe('MaintenanceWorker', () => { expect(paymentsService.updateInvoiceStatus).not.to.have.been.called }) + it('uses the peering expiry handler for a pending peering 404', async () => { + const expiredPeering = { + ...pendingInvoice, + purpose: InvoicePurpose.PEERING, + expiresAt: new Date(Date.now() - 60000), + } + settingsState.payments = { enabled: true } as any + paymentsService.getPendingInvoices.resolves([expiredPeering]) + paymentsService.getInvoiceFromPaymentsProcessor.rejects({ response: { status: 404 } }) + + await (worker as any).onSchedule() + + expect(paymentsService.updateInvoiceStatus).to.have.been.calledOnceWithExactly({ + id: expiredPeering.id, + status: InvoiceStatus.EXPIRED, + }) + expect(peeringBillingService.handleInvoiceExpired).to.have.been.calledWith(expiredPeering) + expect(notificationOutboxRepository.enqueue).not.to.have.been.calledWith( + OperatorNotificationEventType.ADMISSION_INVOICE_FAILED, + Sinon.match.any, + ) + }) + + it('runs the peering lapse scan on each pass', async () => { + settingsState.payments = { enabled: true } as any + paymentsService.getPendingInvoices.resolves([]) + peeringBillingService.processLapses.resolves(2) + + await (worker as any).onSchedule() + + expect(peeringBillingService.processLapses).to.have.been.calledOnce + }) + + it('skips the peering lapse scan when payments are disabled', async () => { + settingsState.payments = { enabled: false } as any + + await (worker as any).onSchedule() + + expect(peeringBillingService.processLapses).not.to.have.been.called + }) + it('keeps an expired pending invoice pending when the processor lookup fails without 404', async () => { const expiredInvoice = { ...pendingInvoice, diff --git a/test/unit/factories/message-handler-factory.spec.ts b/test/unit/factories/message-handler-factory.spec.ts index e9c30dd4..a066b91e 100644 --- a/test/unit/factories/message-handler-factory.spec.ts +++ b/test/unit/factories/message-handler-factory.spec.ts @@ -1,4 +1,5 @@ -import { expect } from 'chai' +import chai from 'chai' +import sinonChai from 'sinon-chai' import { IDvmJobRepository, @@ -13,7 +14,7 @@ import { AuthMessageHandler } from '../../../src/handlers/auth-message-handler' import { Event } from '../../../src/@types/event' import { EventMessageHandler } from '../../../src/handlers/event-message-handler' import { IWebSocketAdapter } from '../../../src/@types/adapters' -import { messageHandlerFactory } from '../../../src/factories/message-handler-factory' +import { messageHandlerFactory, peeringBillingServiceFor } from '../../../src/factories/message-handler-factory' import { CountMessageHandler } from '../../../src/handlers/count-message-handler' import { NegCloseMessageHandler } from '../../../src/handlers/neg-close-message-handler' import { NegMsgMessageHandler } from '../../../src/handlers/neg-msg-message-handler' @@ -23,6 +24,9 @@ import { UnsubscribeMessageHandler } from '../../../src/handlers/unsubscribe-mes import * as cacheModule from '../../../src/cache/client' import sinon from 'sinon' +chai.use(sinonChai) +const { expect } = chai + describe('messageHandlerFactory', () => { let event: Event let eventRepository: IEventRepository @@ -127,4 +131,25 @@ describe('messageHandlerFactory', () => { expect(() => factory([message, adapter])).to.throw(Error, 'Unknown message type: undefined') }) + + describe('peeringBillingServiceFor', () => { + it('does not create billing for an ordinary client', () => { + const get = sandbox.stub() + + const result = peeringBillingServiceFor({ getPeerPubkey: () => undefined } as any, get) + + expect(result).to.be.undefined + expect(get).not.to.have.been.called + }) + + it('creates billing for a configured peer', () => { + const service = {} as any + const get = sandbox.stub().returns(service) + + const result = peeringBillingServiceFor({ getPeerPubkey: () => 'a'.repeat(64) } as any, get) + + expect(result).to.equal(service) + expect(get).to.have.been.calledOnce + }) + }) }) diff --git a/test/unit/factories/payments-processor-factory.spec.ts b/test/unit/factories/payments-processor-factory.spec.ts new file mode 100644 index 00000000..9125a54e --- /dev/null +++ b/test/unit/factories/payments-processor-factory.spec.ts @@ -0,0 +1,48 @@ +import chai from 'chai' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import { LazyPaymentsProcessor } from '../../../src/factories/payments-processor-factory' + +chai.use(sinonChai) +const { expect } = chai + +describe('LazyPaymentsProcessor', () => { + it('does not create the processor until a call needs it', async () => { + const createInvoice = Sinon.stub().resolves({ id: 'inv-1' }) + const getInvoice = Sinon.stub() + const factory = Sinon.stub().returns({ createInvoice, getInvoice }) + const processor = new LazyPaymentsProcessor(factory) + + expect(factory).not.to.have.been.called + + const result = await processor.createInvoice({ amount: 1000n }) + + expect(result).to.deep.equal({ id: 'inv-1' }) + expect(factory).to.have.been.calledOnce + expect(createInvoice).to.have.been.calledWith({ amount: 1000n }) + }) + + it('caches the processor across calls', async () => { + const createInvoice = Sinon.stub().resolves({ id: 'inv-1' }) + const factory = Sinon.stub().returns({ createInvoice, getInvoice: Sinon.stub() }) + const processor = new LazyPaymentsProcessor(factory) + + await processor.createInvoice({ amount: 1000n }) + await processor.createInvoice({ amount: 2000n }) + + expect(factory).to.have.been.calledOnce + expect(createInvoice).to.have.been.calledTwice + }) + + it('delegates getInvoice to the real processor', async () => { + const getInvoice = Sinon.stub().resolves({ id: 'inv-1', status: 'completed' }) + const factory = Sinon.stub().returns({ createInvoice: Sinon.stub(), getInvoice }) + const processor = new LazyPaymentsProcessor(factory) + + const result = await processor.getInvoice('inv-1') + + expect(result).to.deep.equal({ id: 'inv-1', status: 'completed' }) + expect(getInvoice).to.have.been.calledWith('inv-1') + }) +}) diff --git a/test/unit/handlers/count-message-handler.spec.ts b/test/unit/handlers/count-message-handler.spec.ts index 172eb011..91afde4c 100644 --- a/test/unit/handlers/count-message-handler.spec.ts +++ b/test/unit/handlers/count-message-handler.spec.ts @@ -68,6 +68,32 @@ describe('CountMessageHandler', () => { webSocket.on(WebSocketAdapterEvent.Message, webSocketOnMessageStub) }) + it('closes a peer count when paid access is not active', async () => { + const peer = 'a'.repeat(64) + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + const billing = { + getAccess: sandbox.stub().resolves({ allowed: false, reason: 'peering payment required' }), + } + handler = new CountMessageHandler( + webSocket, + eventRepository, + () => ({ nip45: { enabled: true }, limits: { peer: { subscription: { maxFilters: 10 } } } }) as Settings, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + + await handler.handleMessage([MessageType.COUNT, 'q1', {}] as any) + + expect(billing.getAccess).to.have.been.calledWith(peer, { recheck: true }) + expect(webSocketOnMessageStub).to.have.been.calledWith([ + MessageType.CLOSED, + 'q1', + 'payment-required: peering payment required', + ]) + expect(eventRepository.countByFilters).not.to.have.been.called + }) + it('returns COUNT with the result when counting works', async () => { const message = [MessageType.COUNT, 'q1', {}] as any diff --git a/test/unit/handlers/neg-open-message-handler.spec.ts b/test/unit/handlers/neg-open-message-handler.spec.ts index 84d51200..0fb02fba 100644 --- a/test/unit/handlers/neg-open-message-handler.spec.ts +++ b/test/unit/handlers/neg-open-message-handler.spec.ts @@ -109,6 +109,67 @@ describe('NegOpenMessageHandler', () => { expect(findReconciliationItems).to.have.been.calledOnceWithExactly({ kinds: [1], limit: 3 }, 101) }) + it('rejects a reconciliation from a peer without paid access', async () => { + const peer = 'a'.repeat(64) + ;(webSocket as any).getPeerPubkey = () => peer + const billing = { + getAccess: sandbox.stub().resolves({ allowed: false, reason: 'peering payment required' }), + } + handler = new NegOpenMessageHandler( + webSocket, + eventRepository, + () => settings, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + + await open() + + expect(billing.getAccess).to.have.been.calledWith(peer, { recheck: true }) + expect(findReconciliationItems).not.to.have.been.called + expect(sessions.getSessionIds()).to.deep.equal([]) + expect(emitted.firstCall.args[0]).to.deep.equal([ + MessageType.NEG_ERR, + 'sync1', + 'payment-required: peering payment required', + ]) + }) + + it('does not close a replacement NEG-OPEN after a stale billing wait', async () => { + const peer = 'a'.repeat(64) + let releaseAccess: ((access: unknown) => void) | undefined + let markGetAccessCalled: (() => void) | undefined + const getAccessCalled = new Promise((resolve) => { + markGetAccessCalled = resolve + }) + ;(webSocket as any).getPeerPubkey = () => peer + const billing = { + getAccess: sandbox.stub().callsFake(() => { + markGetAccessCalled?.() + return new Promise((resolve) => { + releaseAccess = resolve + }) + }), + } + handler = new NegOpenMessageHandler( + webSocket, + eventRepository, + () => settings, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + + const pending = open() + await getAccessCalled + sessions.close('sync1') + releaseAccess?.({ allowed: false, reason: 'peering payment required' }) + await pending + + expect(emitted).not.to.have.been.called + }) + describe('when disabled', () => { it('replies NEG-ERR blocked and does not read events', async () => { settings = { nip77: { enabled: false } } as Settings diff --git a/test/unit/handlers/subscribe-message-handler.spec.ts b/test/unit/handlers/subscribe-message-handler.spec.ts index 389aaa29..72e320a9 100644 --- a/test/unit/handlers/subscribe-message-handler.spec.ts +++ b/test/unit/handlers/subscribe-message-handler.spec.ts @@ -132,6 +132,178 @@ describe('SubscribeMessageHandler', () => { expect(webSocketOnMessageStub).to.have.been.calledOnceWithExactly(['NOTICE', 'Subscription rejected: reason']) }) + it('closes a peer feed request when paid access is not active', async () => { + const peer = 'a'.repeat(64) + const billing = { + getAccess: sandbox.stub().resolves({ allowed: false, reason: 'peering payment required' }), + ensureInvoice: sandbox.stub().resolves(), + } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxFilters: 10, maxLimit: 0 } } }, + }) + handler = new SubscribeMessageHandler( + webSocket, + eventRepository, + settingsFactory, + inviteCodeRepository, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + message = [MessageType.REQ, subscriptionId, { kinds: [1] }] as any + + await handler.handleMessage(message) + + expect(billing.getAccess).to.have.been.calledWith(peer, { recheck: true }) + expect(webSocketOnMessageStub.firstCall.args[0]).to.deep.equal([ + 'CLOSED', + subscriptionId, + 'payment-required: peering payment required', + ]) + expect(fetchAndSendStub).not.to.have.been.called + }) + + it('lets a peer request its invoice without paid access', async () => { + const peer = 'a'.repeat(64) + const billing = { + getAccess: sandbox.stub(), + ensureInvoice: sandbox.stub().resolves(), + } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxFilters: 10, maxLimit: 0 } } }, + }) + handler = new SubscribeMessageHandler( + webSocket, + eventRepository, + settingsFactory, + inviteCodeRepository, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + message = [MessageType.REQ, subscriptionId, { kinds: [402], '#p': [peer], '#t': ['peering'], limit: 1 }] as any + + await handler.handleMessage(message) + + expect(billing.ensureInvoice).to.have.been.calledWith(peer) + expect(billing.getAccess).not.to.have.been.called + expect(fetchAndSendStub).to.have.been.calledOnce + }) + + it('does not exempt a mixed invoice and feed request from the paid gate', async () => { + const peer = 'a'.repeat(64) + const billing = { + getAccess: sandbox.stub().resolves({ allowed: false, reason: 'peering payment required' }), + ensureInvoice: sandbox.stub().resolves(), + } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxFilters: 10, maxLimit: 0 } } }, + }) + handler = new SubscribeMessageHandler( + webSocket, + eventRepository, + settingsFactory, + inviteCodeRepository, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + const invoice = { kinds: [402], '#p': [peer], '#t': ['peering'], limit: 1 } + message = [MessageType.REQ, subscriptionId, invoice, { kinds: [1] }] as any + + await handler.handleMessage(message) + + expect(billing.ensureInvoice).not.to.have.been.called + expect(billing.getAccess).to.have.been.calledWith(peer, { recheck: true }) + expect(webSocketOnMessageStub.firstCall.args[0]).to.deep.equal([ + 'CLOSED', + subscriptionId, + 'payment-required: peering payment required', + ]) + expect(fetchAndSendStub).not.to.have.been.called + }) + + it('does not register a subscription closed while billing is pending', async () => { + const peer = 'a'.repeat(64) + let releaseAccess: ((access: unknown) => void) | undefined + const billing = { + getAccess: sandbox.stub().returns( + new Promise((resolve) => { + releaseAccess = resolve + }), + ), + ensureInvoice: sandbox.stub().resolves(), + } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxFilters: 10, maxLimit: 0 } } }, + }) + handler = new SubscribeMessageHandler( + webSocket, + eventRepository, + settingsFactory, + inviteCodeRepository, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + message = [MessageType.REQ, subscriptionId, { kinds: [1] }] as any + + const pending = handler.handleMessage(message) + await new Promise((resolve) => setImmediate(resolve)) + expect(billing.getAccess).to.have.been.calledOnce + ;(handler as any).abort() + releaseAccess?.({ allowed: true, periodEnd: new Date(Date.now() + 60_000) }) + await pending + + expect(webSocketOnSubscribeStub).not.to.have.been.called + expect(fetchAndSendStub).not.to.have.been.called + }) + + it('schedules a paid feed expiry with the socket adapter', async () => { + const peer = 'a'.repeat(64) + const periodEnd = new Date(Date.now() + 60_000) + const setSubscriptionExpiry = sandbox.stub() + const billing = { + getAccess: sandbox.stub().resolves({ allowed: true, periodEnd }), + ensureInvoice: sandbox.stub().resolves(), + } + ;(webSocket as any).setSubscriptionExpiry = setSubscriptionExpiry + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxFilters: 10, maxLimit: 0 } } }, + }) + handler = new SubscribeMessageHandler( + webSocket, + eventRepository, + settingsFactory, + inviteCodeRepository, + rateLimiterFactory, + requestStats as any, + billing as any, + ) + message = [MessageType.REQ, subscriptionId, { kinds: [1] }] as any + + await handler.handleMessage(message) + + expect(setSubscriptionExpiry).to.have.been.calledWith(subscriptionId, periodEnd, Sinon.match.func) + + const check = setSubscriptionExpiry.firstCall.args[2] as () => Promise + const renewedPeriodEnd = new Date(periodEnd.getTime() + 60_000) + billing.getAccess.resolves({ allowed: true, periodEnd: renewedPeriodEnd }) + expect(await check()).to.equal(renewedPeriodEnd) + expect(billing.getAccess).to.have.been.calledWith(peer, { recheck: true }) + + billing.getAccess.resolves({ allowed: true, status: 'free' }) + expect(await check()).to.be.null + + billing.getAccess.resolves({ allowed: false }) + expect(await check()).to.be.false + }) + it('bounds raw filters before deduplicating them', async () => { settingsFactory.returns({ limits: { client: { subscription: { maxFilters: 10 } } } }) const duplicate = { kinds: [1] } @@ -912,6 +1084,34 @@ describe('SubscribeMessageHandler', () => { expect((handler as any).canSubscribe(subscriptionId, filters)).to.be.undefined }) + it('caps peering invoice subscriptions for a peer', () => { + const peer = 'a'.repeat(64) + const invoice = { kinds: [402], '#p': [peer], '#t': ['peering'], limit: 1 } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxSubscriptions: 10, maxFilters: 10 } } }, + }) + subscriptions.set('invoice-1', [invoice]) + + expect((handler as any).canSubscribe('invoice-2', [invoice])).to.equal( + 'Too many peering invoice subscriptions: close the previous invoice subscription before opening another', + ) + }) + + it('does not exempt a mixed invoice and feed request from maxSubscriptions', () => { + const peer = 'a'.repeat(64) + const invoice = { kinds: [402], '#p': [peer], '#t': ['peering'], limit: 1 } + ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns(peer) + settingsFactory.returns({ + limits: { peer: { subscription: { maxSubscriptions: 1, maxFilters: 10 } } }, + }) + subscriptions.set('other', []) + + expect((handler as any).canSubscribe('mixed', [invoice, { kinds: [1] }])).to.equal( + 'Too many subscriptions: Number of subscriptions must be less than or equal to 1', + ) + }) + it('uses peer limits instead of client limits for a recognized peer', () => { settingsFactory.returns({ limits: { diff --git a/test/unit/repositories/invoice-repository.spec.ts b/test/unit/repositories/invoice-repository.spec.ts index ac92b142..79e85cc7 100644 --- a/test/unit/repositories/invoice-repository.spec.ts +++ b/test/unit/repositories/invoice-repository.spec.ts @@ -1,8 +1,8 @@ import * as chai from 'chai' -import * as sinon from 'sinon' +import chaiAsPromised from 'chai-as-promised' import knex from 'knex' +import * as sinon from 'sinon' import sinonChai from 'sinon-chai' -import chaiAsPromised from 'chai-as-promised' import { DatabaseClient } from '../../../src/@types/base' import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../src/@types/invoice' @@ -71,19 +71,18 @@ describe('InvoiceRepository', () => { await repository.confirmInvoice('invoice-123', 5000n, fixedDate, client) - expect(rawStub).to.have.been.calledOnceWithExactly( - 'select confirm_invoice(?, ?, ?)', - ['invoice-123', '5000', fixedDate.toISOString()], - ) + expect(rawStub).to.have.been.calledOnceWithExactly('select confirm_invoice(?, ?, ?)', [ + 'invoice-123', + '5000', + fixedDate.toISOString(), + ]) }) it('re-throws when raw call rejects', async () => { const dbError = new Error('connection refused') const client = { raw: sandbox.stub().rejects(dbError) } as unknown as DatabaseClient - await expect( - repository.confirmInvoice('invoice-123', 5000n, fixedDate, client), - ).to.be.rejectedWith(dbError) + await expect(repository.confirmInvoice('invoice-123', 5000n, fixedDate, client)).to.be.rejectedWith(dbError) }) }) @@ -114,6 +113,27 @@ describe('InvoiceRepository', () => { expect(result!.amountRequested).to.equal(1000n) }) + it('maps the purpose and peering term snapshot', async () => { + const client = sandbox.stub().returns({ + where: sandbox.stub().returns({ + select: sandbox.stub().resolves([ + { + ...dbInvoiceRow, + purpose: 'peering', + term_amount_msats: '21000', + term_period_seconds: 2592000, + }, + ]), + }), + }) as unknown as DatabaseClient + + const result = await repository.findById('test-invoice-id', client) + + expect(result!.purpose).to.equal('peering') + expect(result!.termAmountMsats).to.equal(21000n) + expect(result!.termPeriodSeconds).to.equal(2592000) + }) + it('maps the subscription plan and period when the invoice has them', async () => { const periodStart = new Date('2026-02-01T00:00:00.000Z') const periodEnd = new Date('2026-03-03T00:00:00.000Z') @@ -154,6 +174,20 @@ describe('InvoiceRepository', () => { }) }) + describe('.updatePeriod', () => { + it('updates the period columns for the invoice', async () => { + const update = sandbox.stub().returns({ where: sandbox.stub().resolves() }) + const client = sandbox.stub().returns({ update }) as unknown as DatabaseClient + const start = new Date('2026-11-01T00:00:00.000Z') + const end = new Date('2026-12-01T00:00:00.000Z') + + await repository.updatePeriod('inv-1', start, end, client) + + expect(client).to.have.been.calledWith('invoices') + expect(update).to.have.been.calledWith(sandbox.match({ period_start: start, period_end: end })) + }) + }) + describe('.findPendingInvoices', () => { function makePendingClient(results: any[]): DatabaseClient { const selectStub = sandbox.stub().resolves(results) @@ -347,6 +381,17 @@ describe('InvoiceRepository', () => { expect(sql).to.include('"period_end"') }) + it('stores the invoice purpose and peering term snapshot', () => { + const sql = repository + .upsert({ ...testInvoice, purpose: 'peering' as any, termAmountMsats: 21000n, termPeriodSeconds: 2592000 }) + .toString() + + expect(sql).to.include('"purpose"') + expect(sql).to.include(`'peering'`) + expect(sql).to.include('"term_amount_msats"') + expect(sql).to.include('"term_period_seconds"') + }) + it('never rewrites the plan or period of an existing invoice', () => { const sql = repository .upsert({ ...testInvoice, planId: 'basic', periodStart: fixedDate, periodEnd: fixedDate }) diff --git a/test/unit/repositories/peering-payment-repository.spec.ts b/test/unit/repositories/peering-payment-repository.spec.ts index 7c13d3a8..20f5b311 100644 --- a/test/unit/repositories/peering-payment-repository.spec.ts +++ b/test/unit/repositories/peering-payment-repository.spec.ts @@ -100,6 +100,20 @@ describe('PeeringPaymentRepository', () => { expect(saved.status).to.equal(PeeringPaymentStatus.LAPSED) }) + it('updates only the processor-check diagnostics', async () => { + const recording = createRecordingKnex() + const repository = new PeeringPaymentRepository(recording.db) + recording.respondWith(1) + + await repository.recordCheck(pubkey, now, 'processor status: pending', recording.db) + + const sql = recording.queries[0].sql + expect(sql).to.include('"last_checked_at"') + expect(sql).to.include('"last_error"') + expect(sql).to.not.include('"status"') + expect(sql).to.not.include('"period_end"') + }) + it('finds periods due for renewal and periods that ended', async () => { const recording = createRecordingKnex() const repository = new PeeringPaymentRepository(recording.db) diff --git a/test/unit/services/peering-billing-service.spec.ts b/test/unit/services/peering-billing-service.spec.ts new file mode 100644 index 00000000..40686468 --- /dev/null +++ b/test/unit/services/peering-billing-service.spec.ts @@ -0,0 +1,536 @@ +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../src/@types/invoice' +import { OperatorNotificationEventType } from '../../../src/@types/operator-notifications' +import { PeeringPayment, PeeringPaymentDirection, PeeringPaymentStatus } from '../../../src/@types/peering' +import { Settings } from '../../../src/@types/settings' +import { PeeringBillingService } from '../../../src/services/peering-billing-service' +import { PeeringInvoiceCooldownError } from '../../../src/utils/peering-billing' + +chai.use(sinonChai) +chai.use(chaiAsPromised) +const { expect } = chai + +describe('PeeringBillingService', () => { + const peer = 'a'.repeat(64) + const now = new Date('2026-11-09T12:00:00.000Z') + + let sandbox: Sinon.SinonSandbox + let service: PeeringBillingService + let mockTrx: { commit: Sinon.SinonStub; rollback: Sinon.SinonStub } + let dbClient: any + let paymentRepository: any + let invoiceRepository: any + let paymentsService: any + let notificationOutboxRepository: any + let settingsState: Settings + let revokePeer: Sinon.SinonStub + + const payment = (overrides: Partial = {}): PeeringPayment => ({ + peerPubkey: peer, + direction: PeeringPaymentDirection.SELL, + status: PeeringPaymentStatus.UNPAID, + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: null, + periodEnd: null, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: null, + lastSettledAt: null, + lastCheckedAt: null, + lastError: null, + createdAt: now, + updatedAt: now, + ...overrides, + }) + + const invoice = (overrides: Partial = {}): Invoice => ({ + id: 'inv-1', + pubkey: peer, + bolt11: 'lnbc...', + amountRequested: 21000n, + unit: InvoiceUnit.MSATS, + status: InvoiceStatus.PENDING, + description: 'peering', + confirmedAt: null, + expiresAt: new Date(now.getTime() + 60_000), + updatedAt: now, + createdAt: now, + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + ...overrides, + }) + + beforeEach(() => { + sandbox = Sinon.createSandbox() + mockTrx = { + commit: sandbox.stub().resolves(), + rollback: sandbox.stub().resolves(), + } + dbClient = { transaction: sandbox.stub().resolves(mockTrx) } + + paymentRepository = { + findByPeer: sandbox.stub(), + ensureRow: sandbox.stub().resolves(), + lockByPeer: sandbox.stub(), + save: sandbox.stub().callsFake(async (value) => value), + recordCheck: sandbox.stub().resolves(), + list: sandbox.stub().resolves([]), + findDueForRenewal: sandbox.stub().resolves([]), + findPeriodEnded: sandbox.stub().resolves([]), + } + + invoiceRepository = { + findById: sandbox.stub().resolves(undefined), + updateStatus: sandbox.stub().resolves(), + updatePeriod: sandbox.stub().resolves(), + } + + paymentsService = { + createPeeringInvoice: sandbox.stub(), + sendPeeringInvoiceNotification: sandbox.stub().resolves(), + ensurePeeringInvoiceNotification: sandbox.stub().resolves(), + getInvoiceFromPaymentsProcessor: sandbox.stub(), + confirmInvoice: sandbox.stub().resolves(), + } + + notificationOutboxRepository = { + enqueue: sandbox.stub().resolves(), + } + + settingsState = { + info: { name: 'Test Relay' }, + payments: { enabled: true }, + peering: { + enabled: true, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + }, + } as Settings + + revokePeer = sandbox.stub() + + service = new PeeringBillingService( + dbClient, + paymentRepository, + invoiceRepository, + paymentsService, + notificationOutboxRepository, + () => settingsState, + revokePeer, + ) + }) + + afterEach(() => sandbox.restore()) + + describe('getAccess', () => { + it('allows settlement-free peering without reading billing state', async () => { + settingsState.peering!.terms = [] + + const access = await service.getAccess(peer, { now }) + + expect(access).to.include({ allowed: true, status: 'free' }) + expect(paymentRepository.findByPeer).not.to.have.been.called + }) + + it('denies a peer with no invoice yet', async () => { + paymentRepository.findByPeer.resolves(undefined) + + const access = await service.getAccess(peer, { now }) + + expect(access.allowed).to.equal(false) + expect(access.status).to.equal(PeeringPaymentStatus.UNPAID) + }) + + it('allows an active period that has not ended', async () => { + paymentRepository.findByPeer.resolves( + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodStart: new Date(now.getTime() - 1000), + periodEnd: new Date(now.getTime() + 1000), + }), + ) + + const access = await service.getAccess(peer, { now }) + + expect(access.allowed).to.equal(true) + expect(access.status).to.equal(PeeringPaymentStatus.ACTIVE) + }) + + it('allows a running renewal-pending period', async () => { + paymentRepository.findByPeer.resolves( + payment({ + status: PeeringPaymentStatus.RENEWAL_PENDING, + periodEnd: new Date(now.getTime() + 1000), + }), + ) + + const access = await service.getAccess(peer, { now }) + + expect(access.allowed).to.equal(true) + expect(access.status).to.equal(PeeringPaymentStatus.RENEWAL_PENDING) + }) + + it('denies a lapsed period', async () => { + paymentRepository.findByPeer.resolves( + payment({ + status: PeeringPaymentStatus.LAPSED, + periodEnd: new Date(now.getTime() - 1000), + }), + ) + + const access = await service.getAccess(peer, { now }) + + expect(access.allowed).to.equal(false) + expect(access.reason).to.include('lapsed') + }) + + it('denies access when the paid term is invalid', async () => { + settingsState.peering!.terms = [{ amount: 1500, unit: 'msats', period: 2592000 }] + + const access = await service.getAccess(peer, { now }) + + expect(access.allowed).to.equal(false) + expect(access.status).to.equal('unconfigured') + }) + + it('rechecks a pending invoice before denying access', async () => { + const invoiced = payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }) + paymentRepository.findByPeer + .onFirstCall() + .resolves(invoiced) + .onSecondCall() + .resolves(invoiced) + .onThirdCall() + .resolves( + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 1000), + }), + ) + invoiceRepository.findById.resolves(invoice()) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ + status: InvoiceStatus.COMPLETED, + confirmedAt: now, + amountPaid: 21000n, + }) + + const access = await service.getAccess(peer, { now, recheck: true }) + + expect(access.allowed).to.equal(true) + expect(paymentsService.confirmInvoice).to.have.been.calledOnce + }) + }) + + describe('ensureInvoice', () => { + it('creates and publishes a first invoice', async () => { + paymentRepository.lockByPeer.resolves(payment()) + paymentsService.createPeeringInvoice.resolves(invoice()) + + const result = await service.ensureInvoice(peer, { now }) + + expect(result?.id).to.equal('inv-1') + expect(paymentsService.createPeeringInvoice).to.have.been.calledWith( + peer, + 21000n, + Sinon.match.string, + 2592000, + mockTrx, + ) + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ + status: PeeringPaymentStatus.INVOICED, + currentInvoiceId: 'inv-1', + renewalInvoiceId: null, + }), + mockTrx, + ) + expect(mockTrx.commit).to.have.been.calledOnce + expect(paymentsService.ensurePeeringInvoiceNotification).to.have.been.calledWith(result) + }) + + it('reuses an open invoice instead of charging the peer twice', async () => { + paymentRepository.lockByPeer.resolves(payment({ currentInvoiceId: 'inv-1' })) + invoiceRepository.findById.resolves(invoice()) + + const result = await service.ensureInvoice(peer, { now }) + + expect(result?.id).to.equal('inv-1') + expect(paymentsService.createPeeringInvoice).not.to.have.been.called + expect(mockTrx.commit).to.have.been.calledOnce + }) + + it('retires an expired invoice and applies the reissue cooldown', async () => { + paymentRepository.lockByPeer.resolves(payment({ currentInvoiceId: 'inv-1' })) + invoiceRepository.findById.resolves(invoice({ expiresAt: new Date(now.getTime() - 1000) })) + + await expect(service.ensureInvoice(peer, { now })).to.be.rejectedWith(PeeringInvoiceCooldownError) + + expect(invoiceRepository.updateStatus).to.have.been.calledWith( + { id: 'inv-1', status: InvoiceStatus.EXPIRED }, + mockTrx, + ) + expect(paymentsService.createPeeringInvoice).not.to.have.been.called + expect(mockTrx.rollback).to.have.been.calledOnce + }) + + it('issues a renewal invoice for a running period', async () => { + paymentRepository.lockByPeer.resolves( + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 86_400_000), + }), + ) + paymentsService.createPeeringInvoice.resolves(invoice({ id: 'renewal-1' })) + + const result = await service.ensureInvoice(peer, { now, renewal: true }) + + expect(result?.id).to.equal('renewal-1') + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ + status: PeeringPaymentStatus.RENEWAL_PENDING, + renewalInvoiceId: 'renewal-1', + }), + mockTrx, + ) + }) + + it('returns no invoice for settlement-free peering', async () => { + settingsState.peering!.terms = [] + + const result = await service.ensureInvoice(peer, { now }) + + expect(result).to.be.undefined + expect(paymentRepository.ensureRow).not.to.have.been.called + }) + + it('fails closed when payments are disabled', async () => { + settingsState.payments!.enabled = false + + await expect(service.ensureInvoice(peer, { now })).to.be.rejectedWith( + 'paid peering requires payments to be enabled', + ) + }) + + it('returns the settled invoice after a recheck', async () => { + paymentRepository.findByPeer + .onFirstCall() + .resolves(payment({ currentInvoiceId: 'inv-1' })) + .onSecondCall() + .resolves(payment({ lastSettledInvoiceId: 'inv-1' })) + invoiceRepository.findById + .onFirstCall() + .resolves(invoice({ status: InvoiceStatus.PENDING })) + .onSecondCall() + .resolves(invoice({ status: InvoiceStatus.COMPLETED, confirmedAt: now })) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ + status: InvoiceStatus.COMPLETED, + confirmedAt: now, + amountPaid: 21000n, + }) + + const result = await service.ensureInvoice(peer, { now }) + + expect(result?.id).to.equal('inv-1') + expect(paymentsService.confirmInvoice).to.have.been.calledOnce + expect(paymentsService.ensurePeeringInvoiceNotification).to.have.been.calledOnce + expect(paymentsService.createPeeringInvoice).not.to.have.been.called + }) + }) + + describe('recheckPendingInvoice', () => { + it('does nothing without a payment row or open invoice', async () => { + paymentRepository.findByPeer.resolves(undefined) + + expect(await service.recheckPendingInvoice(peer, now, true)).to.equal(false) + }) + + it('honours the recheck cooldown', async () => { + paymentRepository.findByPeer.resolves( + payment({ currentInvoiceId: 'inv-1', lastCheckedAt: new Date(now.getTime() - 1000) }), + ) + + expect(await service.recheckPendingInvoice(peer, now)).to.equal(false) + expect(paymentsService.getInvoiceFromPaymentsProcessor).not.to.have.been.called + }) + + it('records only the processor check and leaves settlement columns alone', async () => { + paymentRepository.findByPeer.resolves( + payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }), + ) + invoiceRepository.findById.resolves( + invoice({ status: InvoiceStatus.PENDING, expiresAt: new Date(now.getTime() - 1000) }), + ) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ status: InvoiceStatus.PENDING }) + + const settled = await service.recheckPendingInvoice(peer, now, true) + + expect(settled).to.be.false + expect(paymentRepository.recordCheck).to.have.been.calledWith(peer, now, 'processor status: pending') + expect(paymentRepository.save).not.to.have.been.called + }) + + it('settles a locally expired invoice when the processor reports payment', async () => { + paymentRepository.findByPeer.resolves( + payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }), + ) + invoiceRepository.findById.resolves( + invoice({ status: InvoiceStatus.PENDING, expiresAt: new Date(now.getTime() - 1000) }), + ) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ + status: InvoiceStatus.COMPLETED, + confirmedAt: now, + amountPaid: 21000n, + }) + + const settled = await service.recheckPendingInvoice(peer, now, true) + + expect(settled).to.be.true + expect(paymentsService.confirmInvoice).to.have.been.calledWith( + Sinon.match({ id: 'inv-1', status: InvoiceStatus.COMPLETED }), + ) + expect(paymentRepository.recordCheck).not.to.have.been.called + }) + + it('records a processor failure on the peer row', async () => { + paymentRepository.findByPeer.resolves(payment({ currentInvoiceId: 'inv-1' })) + invoiceRepository.findById.resolves(invoice()) + paymentsService.getInvoiceFromPaymentsProcessor.rejects(new Error('processor down')) + + const settled = await service.recheckPendingInvoice(peer, now, true) + + expect(settled).to.be.false + expect(paymentRepository.recordCheck).to.have.been.calledWith(peer, now, 'processor down') + }) + }) + + describe('processLapses', () => { + it('lapses an expired period after rechecking the pending invoice', async () => { + const expired = payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() - 1000), + }) + paymentRepository.findPeriodEnded.resolves([expired]) + paymentRepository.findByPeer.resolves(expired) + paymentRepository.lockByPeer.resolves(expired) + + const changed = await service.processLapses(now) + + expect(changed).to.equal(1) + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ + status: PeeringPaymentStatus.LAPSED, + currentInvoiceId: null, + renewalInvoiceId: null, + }), + mockTrx, + ) + expect(notificationOutboxRepository.enqueue).to.have.been.calledWith( + OperatorNotificationEventType.PEERING_ACCESS_LAPSED, + Sinon.match({ pubkey: peer }), + mockTrx, + ) + expect(revokePeer).to.have.been.calledWith(peer) + }) + + it('does not lapse while the period is still running', async () => { + paymentRepository.findPeriodEnded.resolves([]) + + const changed = await service.processLapses(now) + + expect(changed).to.equal(0) + expect(paymentRepository.save).not.to.have.been.called + }) + + it('does nothing for settlement-free peering', async () => { + settingsState.peering!.terms = [] + + expect(await service.processLapses(now)).to.equal(0) + expect(paymentRepository.findPeriodEnded).not.to.have.been.called + }) + + it('does not lapse a peer that paid before the recheck', async () => { + const expired = payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() - 1000), + currentInvoiceId: 'inv-1', + }) + paymentRepository.findPeriodEnded.resolves([expired]) + paymentRepository.findByPeer.resolves(expired) + invoiceRepository.findById.resolves(invoice()) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ + status: InvoiceStatus.COMPLETED, + confirmedAt: now, + }) + + const changed = await service.processLapses(now) + + expect(changed).to.equal(1) + expect(paymentRepository.lockByPeer).not.to.have.been.called + expect(notificationOutboxRepository.enqueue).not.to.have.been.calledWith( + OperatorNotificationEventType.PEERING_ACCESS_LAPSED, + Sinon.match.any, + Sinon.match.any, + ) + }) + }) + + describe('handleInvoiceExpired', () => { + it('ignores non-peering invoices', async () => { + await service.handleInvoiceExpired(invoice({ purpose: InvoicePurpose.ADMISSION })) + + expect(paymentRepository.findByPeer).not.to.have.been.called + }) + + it('ignores an invoice that is not the current pointer', async () => { + paymentRepository.findByPeer.resolves(payment({ currentInvoiceId: 'other' })) + + await service.handleInvoiceExpired(invoice()) + + expect(paymentRepository.save).not.to.have.been.called + }) + + it('clears the pointer and records a failure', async () => { + paymentRepository.findByPeer.resolves( + payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }), + ) + + await service.handleInvoiceExpired(invoice()) + + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ + status: PeeringPaymentStatus.UNPAID, + currentInvoiceId: null, + }), + ) + expect(notificationOutboxRepository.enqueue).to.have.been.calledWith( + OperatorNotificationEventType.PEERING_INVOICE_FAILED, + Sinon.match({ invoiceId: 'inv-1', reason: 'expired' }), + ) + }) + + it('clears a renewal pointer without changing the current status', async () => { + paymentRepository.findByPeer.resolves( + payment({ + status: PeeringPaymentStatus.ACTIVE, + currentInvoiceId: 'current', + renewalInvoiceId: 'inv-1', + }), + ) + + await service.handleInvoiceExpired(invoice()) + + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ + status: PeeringPaymentStatus.ACTIVE, + currentInvoiceId: 'current', + renewalInvoiceId: null, + }), + ) + }) + }) +}) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 8bd0cf5e..fc6384e4 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -113,6 +113,7 @@ describe('settings-config', () => { contact: 'test@example.com', }, network: { maxPayloadSize: 1024 }, + payments: { enabled: true, processor: 'lnbits' }, peering, }) as any @@ -244,6 +245,51 @@ describe('settings-config', () => { expect(issues.some((issue) => issue.path === 'peering.terms[0].currency')).to.equal(true) }) + it('rejects a paid msat term that is not a whole number of satoshis', () => { + const issues = peeringIssues({ + ...settlementFreePeering, + terms: [{ amount: 1500, unit: 'msats', period: 2592000 }], + }) + + expect(issues.some((issue) => issue.path === 'peering.terms[0].amount')).to.equal(true) + }) + + it('rejects a paid term in an unsupported unit', () => { + const issues = peeringIssues({ + ...settlementFreePeering, + terms: [{ amount: 1, unit: 'usd', period: 2592000 }], + }) + + expect(issues.some((issue) => issue.path === 'peering.terms[0].unit')).to.equal(true) + }) + + it('rejects more than one paid term', () => { + const issues = peeringIssues({ + ...settlementFreePeering, + terms: [ + { amount: 21000, unit: 'msats', period: 2592000 }, + { amount: 42000, unit: 'msats', period: 2592000 }, + ], + }) + + expect(issues.some((issue) => issue.path === 'peering.terms')).to.equal(true) + expect(issues.find((issue) => issue.path === 'peering.terms')?.message).to.include('only one paid') + }) + + it('rejects paid terms while payments are disabled', () => { + const issues = validateSettings({ + info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, + network: { maxPayloadSize: 1024 }, + peering: { + ...settlementFreePeering, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + }, + } as any) + + expect(issues.some((issue) => issue.path === 'peering.terms')).to.equal(true) + expect(issues.find((issue) => issue.path === 'peering.terms')?.message).to.include('payments must be enabled') + }) + it('rejects a proof-of-work requirement above the NIP-13 maximum', () => { const issues = peeringIssues({ ...settlementFreePeering, minRequestPowDifficulty: 257 }) @@ -376,8 +422,7 @@ describe('settings-config', () => { expect( issues.some( (issue) => - issue.path === 'info.relay_url' && - issue.message === 'relay_url must use ws, wss, http, or https protocol', + issue.path === 'info.relay_url' && issue.message === 'relay_url must use ws, wss, http, or https protocol', ), `expected ${relay_url} to be rejected for protocol`, ).to.equal(true) @@ -476,7 +521,9 @@ describe('settings-config', () => { const settings = baseSettings() settings.limits = { event: { rateLimits: [{ period: 0.5, rate: 10 }] } } - const message = validateSettings(settings).find((issue) => issue.path === 'limits.event.rateLimits[0].period')?.message + const message = validateSettings(settings).find( + (issue) => issue.path === 'limits.event.rateLimits[0].period', + )?.message expect(message).to.contain('milliseconds') }) @@ -858,8 +905,13 @@ describe('settings-config', () => { describe('settings-guided-schema', () => { it('exports guided categories for admin and CLI use', () => { expect(guidedSettingCategories.length).to.be.greaterThan(0) - expect(getGuidedSettingCategory('payments')?.settings.some((entry) => entry.path === 'payments.enabled')).to.equal(true) - expect(getGuidedSettingField('limits', 'limits.rateLimiter.strategy')?.options).to.deep.equal(['ewma', 'sliding_window']) + expect(getGuidedSettingCategory('payments')?.settings.some((entry) => entry.path === 'payments.enabled')).to.equal( + true, + ) + expect(getGuidedSettingField('limits', 'limits.rateLimiter.strategy')?.options).to.deep.equal([ + 'ewma', + 'sliding_window', + ]) }) it('validates guided numeric fields', () => {