diff --git a/.changeset/paid-peering-lifecycle.md b/.changeset/paid-peering-lifecycle.md new file mode 100644 index 00000000..1d1df883 --- /dev/null +++ b/.changeset/paid-peering-lifecycle.md @@ -0,0 +1,12 @@ +--- +"nostream": minor +--- + +feat(peering): renew, lapse and expose paid peering access + +The billing worker now issues renewal invoices before a period ends, rechecks +pending payments before lapsing a peer, closes live peer sockets on lapse, and +keeps stored events and sync state for a later resume. `GET /admin/peering` and +the dashboard show billing status, access end, the open invoice and the last +processor error. NEG-MSG rechecks paid access so an open NIP-77 session cannot +keep syncing after the paid period ends. diff --git a/docs/PEERING.md b/docs/PEERING.md index 7fa82e9d..81872685 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -191,3 +191,39 @@ authenticate the remote relay, because NIP-42 is a client-to-relay proof. The remote relay's identity is established separately by the configured `peering.peers` pubkey (and, in later phases, by discovery and owner attestation). + +## Paid peering + +When `peering.terms` contains exactly one positive term, this relay sells the +feed instead of serving it settlement-free. Terms use the NIP-11 fee-object +shape (`amount`, `unit`, `period`); `unit` must be `msats`, `sats` or `btc`, and +a paid `msats` amount must be a whole number of satoshis so every payment +processor charges the same value. Payments must be enabled. + +The buyer, Relay A, has no relationship with this relay's payment processor. +The invoice travels over the authenticated relay connection: + +1. Relay A authenticates with NIP-42 and sends + `REQ {"kinds":[402],"#p":[""],"#t":["peering"],"limit":1}`. +2. Relay B creates a BOLT11 invoice with its existing payments processor and + persists it with `invoices.purpose = peering` and a snapshot of the term. +3. Relay B publishes a signed `kind 402` event tagged `p` (Relay A), `t` + (`peering`), `bolt11`, `i` (processor invoice id) and `expiration`. +4. Relay A pays the invoice. The processor calls Relay B's existing callback, + or the billing worker finds the payment by polling. Settlement validates the + amount and extends `peering_payments.period_end` exactly once. +5. Feed access is allowed while `period_end` is in the future. An unpaid period + marks the peer `lapsed`, closes its peer sockets, and refuses feed `REQ`, + `COUNT` and `NIP-77`; it does not delete events or sync state. +6. Renewal is the same loop: the billing worker issues a renewal invoice before + the period ends and publishes it on the same `kind 402` path. + +An expired invoice is retired and reissued on request after a short cooldown. +Before denying access, the relay rechecks a pending invoice with the processor, +so a missed webhook heals on its own. A peer can always authenticate and ask for +its invoice, even while lapsed, but cannot read the feed. + +Billing state is stored in `peering_payments`, one row per peer and direction +(`sell` here; `buy` is reserved for the paying side). `GET /admin/peering` +merges it with the sync and request rows, showing status, access end, the open +invoice and the last processor error. diff --git a/resources/admin/assets/admin-ops.js b/resources/admin/assets/admin-ops.js index 6d423ae6..8b6ee39c 100644 --- a/resources/admin/assets/admin-ops.js +++ b/resources/admin/assets/admin-ops.js @@ -118,6 +118,16 @@ return `${Math.round(seconds / 86400)}d` } + const peeringBillingBadge = (billing) => { + if (!billing?.status) { + return 'Not billed' + } + + const status = String(billing.status) + const degraded = status === 'lapsed' || status === 'unpaid' + return `${escapeHtml(status)}` + } + const peeringSignalBadge = (row) => { if (!row.configured || !row.enabled) { return 'Disabled' @@ -145,7 +155,7 @@ const renderPeering = (rows) => { if (!Array.isArray(rows) || !rows.length) { elements.peeringBody.innerHTML = - 'No peering peers configured.' + 'No peering peers configured.' return } @@ -158,6 +168,8 @@ return ` ${escapeHtml(shortPubkey(row.pubkey))} ${escapeHtml(row.relayUrl)} + ${peeringBillingBadge(row.billing)} + ${escapeHtml(formatTime(row.billing?.periodEnd))} ${escapeHtml(formatTime(state?.lastReconciledAt))} ${escapeHtml(formatLag(state?.lagSeconds))} ${escapeHtml(state?.missingEvents ?? '—')} diff --git a/resources/admin/dashboard.html b/resources/admin/dashboard.html index 61b9cf1d..f16a0583 100644 --- a/resources/admin/dashboard.html +++ b/resources/admin/dashboard.html @@ -236,6 +236,8 @@

Peering

Peer Relay + Billing + Access until Last reconciliation Lag Missing @@ -245,7 +247,7 @@

Peering

- No peering peers configured. + No peering peers configured. diff --git a/src/@types/negentropy.ts b/src/@types/negentropy.ts index 011fe9a8..00b1ab1f 100644 --- a/src/@types/negentropy.ts +++ b/src/@types/negentropy.ts @@ -34,6 +34,8 @@ export interface INegentropySessions { ): boolean /** The live session for an id, with its idle timer restarted. */ touch(subscriptionId: SubscriptionId): NegentropySession | undefined + /** The live session for an id, without restarting its idle timer. */ + peek(subscriptionId: SubscriptionId): NegentropySession | undefined /** Drops a reservation that never became a session; a no-op if it has since been replaced. */ release(subscriptionId: SubscriptionId, token: NegentropySessionToken): void close(subscriptionId: SubscriptionId): boolean diff --git a/src/@types/services.ts b/src/@types/services.ts index dd81e14c..5c2d68f7 100644 --- a/src/@types/services.ts +++ b/src/@types/services.ts @@ -62,6 +62,8 @@ export interface IPeeringBillingService { ensureInvoice(peerPubkey: Pubkey, options?: { now?: Date; renewal?: boolean }): Promise /** Ends expired periods once, marking them lapsed and alerting the operator. */ processLapses(now?: Date): Promise + /** Renewal window, period end/lapse, and invoice expiry bookkeeping. */ + processLifecycle(now?: Date): Promise /** Clears a pointer and updates status after the processor confirms an invoice expired. */ handleInvoiceExpired(invoice: Invoice): Promise } diff --git a/src/adapters/web-socket-adapter.ts b/src/adapters/web-socket-adapter.ts index 48551bd3..767519e3 100644 --- a/src/adapters/web-socket-adapter.ts +++ b/src/adapters/web-socket-adapter.ts @@ -197,10 +197,12 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter check: () => Promise, ): Promise { let nextPeriodEnd: Date | null | false = false + let checkFailed = false try { nextPeriodEnd = await check() } catch (error) { + checkFailed = true logger.error('unable to check paid subscription expiry for %s: %o', subscriptionId, error) } @@ -222,7 +224,14 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter this.clearSubscriptionExpiry(subscriptionId) this.endSubscription(subscriptionId) - this.sendMessage(createClosedMessage(subscriptionId, 'payment-required: peering access expired')) + this.sendMessage( + createClosedMessage( + subscriptionId, + checkFailed + ? 'error: unable to check peering access' + : 'payment-required: peering access expired', + ), + ) } private clearSubscriptionExpiry(subscriptionId: SubscriptionId): void { diff --git a/src/adapters/web-socket-server-adapter.ts b/src/adapters/web-socket-server-adapter.ts index c85fd57d..cb7ea202 100644 --- a/src/adapters/web-socket-server-adapter.ts +++ b/src/adapters/web-socket-server-adapter.ts @@ -55,6 +55,7 @@ export class WebSocketServerAdapter extends WebServerAdapter implements IWebSock this.webSocketsAdapters = new WeakMap() this.on(WebSocketServerAdapterEvent.Broadcast, this.onBroadcast.bind(this)) + this.on(WebSocketServerAdapterEvent.PeeringRevoke, this.onPeeringRevoke.bind(this)) this.webSocketServer .on(WebSocketServerAdapterEvent.Connection, this.onConnection.bind(this)) @@ -123,6 +124,23 @@ export class WebSocketServerAdapter extends WebServerAdapter implements IWebSock }) } + private onPeeringRevoke(payload: { pubkey?: unknown }) { + const pubkey = typeof payload?.pubkey === 'string' ? payload.pubkey : undefined + if (!pubkey) { + return + } + + this.webSocketServer.clients.forEach((webSocket: WebSocket) => { + const webSocketAdapter = this.webSocketsAdapters.get(webSocket) + if (webSocketAdapter?.getPeerPubkey() !== pubkey) { + return + } + + logger('closing peer %s: peering access ended', pubkey) + webSocket.close(4001, 'payment-required: peering access expired') + }) + } + private onBroadcast(event: Event) { this.webSocketServer.clients.forEach((webSocket: WebSocket) => { if (!propEq('readyState', OPEN)(webSocket)) { diff --git a/src/app/maintenance-worker.ts b/src/app/maintenance-worker.ts index a049f7ce..28be7cc9 100644 --- a/src/app/maintenance-worker.ts +++ b/src/app/maintenance-worker.ts @@ -272,10 +272,13 @@ export class MaintenanceWorker implements IRunnable { mergeDeepLeft({ amountPaid }), )(invoice) - await Promise.all([ - this.paymentsService.confirmInvoice(update), - this.paymentsService.sendInvoiceUpdateNotification(update), - ]) + await this.paymentsService.confirmInvoice(update) + + // Peering settlement is complete once confirmInvoice applies the period; + // a generic “invoice paid” notice would not match the peer's peering filter. + if (invoice.purpose !== InvoicePurpose.PEERING) { + await this.paymentsService.sendInvoiceUpdateNotification(update) + } await delay() } @@ -313,7 +316,7 @@ export class MaintenanceWorker implements IRunnable { } await this.processSubscriptions() - await this.processPeeringLapses() + await this.processPeering() await clearOldEventsPromise await this.publishOpsHeartbeat({ @@ -333,14 +336,14 @@ export class MaintenanceWorker implements IRunnable { } } - private async processPeeringLapses(): Promise { + private async processPeering(): Promise { try { - const changed = await this.peeringBillingService?.processLapses() + const changed = await this.peeringBillingService?.processLifecycle() if (changed) { - logger('lapsed %d peering relationship(s)', changed) + logger('moved %d peering relationship(s) through their lifecycle', changed) } } catch (error) { - logger.error('Unable to process peering lapses', error) + logger.error('Unable to process peering billing', error) } } diff --git a/src/constants/adapter.ts b/src/constants/adapter.ts index 74a280d0..9bb44853 100644 --- a/src/constants/adapter.ts +++ b/src/constants/adapter.ts @@ -10,4 +10,6 @@ export enum WebSocketAdapterEvent { export enum WebSocketServerAdapterEvent { Broadcast = 'broadcast', Connection = 'connection', + /** Close any socket currently authenticated as a peer whose paid access ended. */ + PeeringRevoke = 'peering-revoke', } diff --git a/src/controllers/admin/get-admin-peering-controller.ts b/src/controllers/admin/get-admin-peering-controller.ts index 4bd00f11..0606103d 100644 --- a/src/controllers/admin/get-admin-peering-controller.ts +++ b/src/controllers/admin/get-admin-peering-controller.ts @@ -1,6 +1,7 @@ import { Request, Response } from 'express' import { IController } from '../../@types/controllers' +import { IPeeringPaymentRepository } from '../../@types/repositories' import { Settings } from '../../@types/settings' import { mergePeeringRows } from '../../utils/admin-peering' import { PeeringRequestStatsStore } from '../../utils/peering-request-stats' @@ -12,15 +13,17 @@ export class GetAdminPeeringController implements IController { private readonly stateStore: PeeringSyncStateStore, private readonly getSettings: () => Settings = loadMergedSettings, private readonly requestStatsStore?: PeeringRequestStatsStore, + private readonly peeringPaymentRepository?: IPeeringPaymentRepository, ) {} public async handleRequest(_request: Request, response: Response): Promise { - const [states, settings, requestStats] = await Promise.all([ + const [states, settings, requestStats, billing] = await Promise.all([ this.stateStore.list(), this.getSettings(), this.requestStatsStore?.list() ?? [], + this.peeringPaymentRepository?.list() ?? [], ]) - const peers = mergePeeringRows(settings, states, undefined, requestStats) + const peers = mergePeeringRows(settings, states, undefined, requestStats, billing) response.status(200).setHeader('content-type', 'application/json').send({ peers }) } diff --git a/src/factories/controllers/get-admin-peering-controller-factory.ts b/src/factories/controllers/get-admin-peering-controller-factory.ts index 7eb74ac6..3676e72f 100644 --- a/src/factories/controllers/get-admin-peering-controller-factory.ts +++ b/src/factories/controllers/get-admin-peering-controller-factory.ts @@ -2,6 +2,8 @@ import { IController } from '../../@types/controllers' import { RedisAdapter } from '../../adapters/redis-adapter' import { getCacheClient } from '../../cache/client' import { GetAdminPeeringController } from '../../controllers/admin/get-admin-peering-controller' +import { getMasterDbClient } from '../../database/client' +import { PeeringPaymentRepository } from '../../repositories/peering-payment-repository' import { PeeringRequestStatsStore } from '../../utils/peering-request-stats' import { PeeringSyncStateStore } from '../../utils/peering-sync-state' @@ -13,7 +15,12 @@ export const createGetAdminPeeringController = (): IController => { const cache = new RedisAdapter(getCacheClient()) const stateStore = new PeeringSyncStateStore(cache) const requestStatsStore = new PeeringRequestStatsStore(cache) - sharedController = new GetAdminPeeringController(stateStore, undefined, requestStatsStore) + sharedController = new GetAdminPeeringController( + stateStore, + undefined, + requestStatsStore, + new PeeringPaymentRepository(getMasterDbClient()), + ) } return sharedController diff --git a/src/factories/message-handler-factory.ts b/src/factories/message-handler-factory.ts index 3147ee0d..51bf8781 100644 --- a/src/factories/message-handler-factory.ts +++ b/src/factories/message-handler-factory.ts @@ -137,7 +137,7 @@ export const messageHandlerFactory = peeringBillingServiceFor(adapter), ) case MessageType.NEG_MSG: - return new NegMsgMessageHandler(adapter, createSettings) + return new NegMsgMessageHandler(adapter, createSettings, peeringBillingServiceFor(adapter)) case MessageType.NEG_CLOSE: return new NegCloseMessageHandler(adapter) default: diff --git a/src/factories/peering-billing-service-factory.ts b/src/factories/peering-billing-service-factory.ts index 3955875e..51b31199 100644 --- a/src/factories/peering-billing-service-factory.ts +++ b/src/factories/peering-billing-service-factory.ts @@ -1,3 +1,5 @@ +import cluster from 'cluster' +import { WebSocketServerAdapterEvent } from '../constants/adapter' import { getMasterDbClient } from '../database/client' import { InvoiceRepository } from '../repositories/invoice-repository' import { NotificationOutboxRepository } from '../repositories/notification-outbox-repository' @@ -6,6 +8,21 @@ import { PeeringBillingService } from '../services/peering-billing-service' import { createPaymentsService } from './payments-service-factory' import { createSettings } from './settings-factory' +/** + * A worker cannot reach another worker's sockets. The primary fans this message out + * to every client worker, and WebSocketServerAdapter closes the matching peer sockets. + */ +const revokePeer = (pubkey: string): void => { + if (!cluster.isWorker || typeof process.send !== 'function') { + return + } + + process.send({ + eventName: WebSocketServerAdapterEvent.PeeringRevoke, + event: { pubkey }, + }) +} + export const createPeeringBillingService = (): PeeringBillingService => { const dbClient = getMasterDbClient() @@ -16,5 +33,6 @@ export const createPeeringBillingService = (): PeeringBillingService => { createPaymentsService(), new NotificationOutboxRepository(dbClient), createSettings, + revokePeer, ) } diff --git a/src/handlers/count-message-handler.ts b/src/handlers/count-message-handler.ts index 7e6aba8d..133825db 100644 --- a/src/handlers/count-message-handler.ts +++ b/src/handlers/count-message-handler.ts @@ -17,6 +17,7 @@ import { createClosedMessage, createCountResultMessage } from '../utils/messages import { isCountAuthorized } from '../utils/nip42' import { subscriptionLimitsFor } from '../utils/peer-limits' import { getPeerRequestRetryAfterMs } from '../utils/peer-requests' +import { peeringPaymentRequiredReason } from '../utils/peering-billing' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' const debug = createLogger('count-message-handler') @@ -70,9 +71,7 @@ export class CountMessageHandler implements IMessageHandler { } 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'}` + const reason = peeringPaymentRequiredReason(access) this.webSocket.emit(WebSocketAdapterEvent.Message, createClosedMessage(queryId, reason)) return } diff --git a/src/handlers/neg-msg-message-handler.ts b/src/handlers/neg-msg-message-handler.ts index 15853624..c4bb1d29 100644 --- a/src/handlers/neg-msg-message-handler.ts +++ b/src/handlers/neg-msg-message-handler.ts @@ -2,11 +2,14 @@ import { createNegErrMessage, createNegMsgMessage } from '../utils/messages' import { IMessageHandler } from '../@types/message-handlers' import { IWebSocketAdapter } from '../@types/adapters' import { NegMsgMessage, OutgoingMessage } from '../@types/messages' +import { PeeringAccess } from '../@types/peering' +import { IPeeringBillingService } from '../@types/services' import { Settings } from '../@types/settings' import { WebSocketAdapterEvent } from '../constants/adapter' import { createLogger } from '../factories/logger-factory' import { isNip77Active } from '../utils/nip77' import { isReconciliationAuthorized } from '../utils/nip42' +import { peeringPaymentRequiredReason } from '../utils/peering-billing' const logger = createLogger('neg-msg-message-handler') @@ -14,6 +17,7 @@ export class NegMsgMessageHandler implements IMessageHandler { public constructor( private readonly webSocket: IWebSocketAdapter, private readonly settings: () => Settings, + private readonly peeringBillingService?: IPeeringBillingService, ) {} public async handleMessage(message: NegMsgMessage): Promise { @@ -42,6 +46,37 @@ export class NegMsgMessageHandler implements IMessageHandler { return } + // NEG-OPEN checks payment once. A running sync must re-read it so a lapsed peer + // cannot keep pulling events until the maintenance worker closes its socket. + const peerPubkey = this.webSocket.getPeerPubkey?.() + if (peerPubkey && this.peeringBillingService) { + let access: PeeringAccess + try { + access = await this.peeringBillingService.getAccess(peerPubkey) + } catch (error) { + logger.error('unable to check peering access for %s: %o', peerPubkey, error) + // A replacement NEG-OPEN may own this id now; the old check must not close it. + if (sessions.peek(subscriptionId) !== session) { + return + } + sessions.close(subscriptionId) + this.reply(createNegErrMessage(subscriptionId, 'error: unable to check peering access')) + return + } + + // NEG-CLOSE or a replacement NEG-OPEN can land while billing is pending. + // Never answer or close a session this message no longer owns. + if (sessions.peek(subscriptionId) !== session) { + return + } + + if (!access.allowed) { + sessions.close(subscriptionId) + this.reply(createNegErrMessage(subscriptionId, peeringPaymentRequiredReason(access))) + return + } + } + try { const { output } = session.negentropy.reconcile(Buffer.from(message[2], 'hex')) diff --git a/src/handlers/neg-open-message-handler.ts b/src/handlers/neg-open-message-handler.ts index f49a2756..102d236f 100644 --- a/src/handlers/neg-open-message-handler.ts +++ b/src/handlers/neg-open-message-handler.ts @@ -18,6 +18,7 @@ import { isReconciliationAuthorized } from '../utils/nip42' import { getNip77Limits, isNip77Active, NEGENTROPY_FRAME_SIZE_LIMIT } from '../utils/nip77' import { subscriptionLimitsFor } from '../utils/peer-limits' import { getPeerRequestRetryAfterMs } from '../utils/peer-requests' +import { peeringPaymentRequiredReason } from '../utils/peering-billing' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' const logger = createLogger('neg-open-message-handler') @@ -110,10 +111,7 @@ export class NegOpenMessageHandler implements IMessageHandler { 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) + this.reject(sessions, subscriptionId, peeringPaymentRequiredReason(access)) return } } diff --git a/src/handlers/subscribe-message-handler.ts b/src/handlers/subscribe-message-handler.ts index aa6ed2de..0b910e78 100644 --- a/src/handlers/subscribe-message-handler.ts +++ b/src/handlers/subscribe-message-handler.ts @@ -27,7 +27,7 @@ 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 { isPeeringInvoiceRequest, PeeringInvoiceCooldownError, peeringPaymentRequiredReason } from '../utils/peering-billing' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' import { streamEachAsync, streamEnd, streamFilter, streamMap } from '../utils/stream' @@ -209,9 +209,7 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { 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'}` + const reason = peeringPaymentRequiredReason(access) logger('subscription %s with %o rejected for peer %s: %s', subscriptionId, filters, peerPubkey, reason) this.webSocket.emit(WebSocketAdapterEvent.Message, createClosedMessage(subscriptionId, reason)) diff --git a/src/services/peering-billing-service.ts b/src/services/peering-billing-service.ts index 9913a437..8442ea4a 100644 --- a/src/services/peering-billing-service.ts +++ b/src/services/peering-billing-service.ts @@ -11,6 +11,7 @@ import { InvalidPeeringTermError, PEERING_RECHECK_COOLDOWN_SECONDS, PEERING_REISSUE_COOLDOWN_SECONDS, + PEERING_RENEWAL_LEAD_SECONDS, PeeringInvoiceCooldownError, peeringInvoiceDescription, resolvePaidPeeringTerm, @@ -333,6 +334,56 @@ export class PeeringBillingService implements IPeeringBillingService { ) } + /** + * One pass of the renewal window followed by the ended-period lapse scan. + * Lapses are handled by processLapses so they keep their own cursor and alert. + */ + public async processLifecycle(now = new Date()): Promise { + let term: PeeringTermSnapshot | undefined + try { + term = resolvePaidPeeringTerm(this.settings()) + } catch (error) { + logger.error('not processing peering lifecycle: %o', error) + return 0 + } + + if (!term) { + return 0 + } + + const renewalChanged = await this.sweep( + 'renewal', + (limit, offset) => + this.peeringPaymentRepository.findDueForRenewal( + new Date(now.getTime() + PEERING_RENEWAL_LEAD_SECONDS * 1000), + limit, + offset, + ), + async (payment) => { + // The ended-period sweep owns already-ended rows; issuing a renewal for one + // here would create an invoice and immediately lapse the relationship. + if (payment.periodEnd && payment.periodEnd.getTime() <= now.getTime()) { + return false + } + + try { + await this.ensureInvoice(payment.peerPubkey, { now, renewal: true }) + return true + } catch (error) { + if (error instanceof PeeringInvoiceCooldownError) { + return false + } + logger.error('unable to issue renewal for %s: %o', payment.peerPubkey, error) + return false + } + }, + ) + + const endedChanged = await this.processLapses(now) + + return renewalChanged + endedChanged + } + 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. diff --git a/src/utils/admin-peering.ts b/src/utils/admin-peering.ts index b35ab09c..dbc777bc 100644 --- a/src/utils/admin-peering.ts +++ b/src/utils/admin-peering.ts @@ -1,9 +1,22 @@ -import { PeeringPeerSyncState } from '../@types/peering' +import { PeeringPayment, PeeringPeerSyncState } from '../@types/peering' import { Settings } from '../@types/settings' import { parsePeeringPeerPubkey } from './peering-auth' import { PeeringRequestStats } from './peering-request-stats' import { isPeeringSyncStateStale, PEERING_SYNC_STATE_STALE_AFTER_SECONDS } from './peering-sync-state' +export interface AdminPeeringBilling { + status: PeeringPayment['status'] + periodStart?: Date | null + periodEnd?: Date | null + currentInvoiceId?: string | null + renewalInvoiceId?: string | null + termAmountMsats?: bigint | null + termPeriodSeconds?: number | null + lastSettledAt?: Date | null + lastCheckedAt?: Date | null + lastError?: string | null +} + export interface AdminPeeringRow { pubkey: string relayUrl: string @@ -12,16 +25,32 @@ export interface AdminPeeringRow { stale: boolean state?: PeeringPeerSyncState requests?: PeeringRequestStats + billing?: AdminPeeringBilling } +const toAdminBilling = (payment: PeeringPayment): AdminPeeringBilling => ({ + status: payment.status, + periodStart: payment.periodStart, + periodEnd: payment.periodEnd, + currentInvoiceId: payment.currentInvoiceId, + renewalInvoiceId: payment.renewalInvoiceId, + termAmountMsats: payment.termAmountMsats, + termPeriodSeconds: payment.termPeriodSeconds, + lastSettledAt: payment.lastSettledAt, + lastCheckedAt: payment.lastCheckedAt, + lastError: payment.lastError, +}) + export const mergePeeringRows = ( settings: Settings, states: PeeringPeerSyncState[], staleAfterSeconds = PEERING_SYNC_STATE_STALE_AFTER_SECONDS, requestStats: PeeringRequestStats[] = [], + billing: PeeringPayment[] = [], ): AdminPeeringRow[] => { const statesByPubkey = new Map(states.map((state) => [state.pubkey.toLowerCase(), state])) const requestsByPubkey = new Map(requestStats.map((stats) => [stats.pubkey.toLowerCase(), stats])) + const billingByPubkey = new Map(billing.map((payment) => [payment.peerPubkey.toLowerCase(), payment])) const rows: AdminPeeringRow[] = [] const matched = new Set() @@ -41,6 +70,7 @@ export const mergePeeringRows = ( stale: enabled && (!state || isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds)), state, requests: requestsByPubkey.get(normalized), + billing: billingByPubkey.get(normalized) ? toAdminBilling(billingByPubkey.get(normalized)!) : undefined, }) } @@ -59,6 +89,29 @@ export const mergePeeringRows = ( stale: isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds), state, requests: requestsByPubkey.get(state.pubkey.toLowerCase()), + billing: billingByPubkey.get(state.pubkey.toLowerCase()) + ? toAdminBilling(billingByPubkey.get(state.pubkey.toLowerCase())!) + : undefined, + }) + } + + // A billing row can outlive the peer's sync state; show it so a removed peer with + // an unpaid or active period is not invisible to the operator. + for (const payment of billing) { + if (matched.has(payment.peerPubkey.toLowerCase())) { + continue + } + if (rows.some((row) => row.pubkey.toLowerCase() === payment.peerPubkey.toLowerCase())) { + continue + } + + rows.push({ + pubkey: payment.peerPubkey, + relayUrl: '', + configured: false, + enabled: false, + stale: true, + billing: toAdminBilling(payment), }) } diff --git a/src/utils/negentropy-sessions.ts b/src/utils/negentropy-sessions.ts index 952a213f..88adeaad 100644 --- a/src/utils/negentropy-sessions.ts +++ b/src/utils/negentropy-sessions.ts @@ -71,6 +71,10 @@ export class NegentropySessions implements INegentropySessions { return entry.session } + public peek(subscriptionId: SubscriptionId): NegentropySession | undefined { + return this.entries.get(subscriptionId)?.session + } + public release(subscriptionId: SubscriptionId, token: NegentropySessionToken): void { if (this.entries.get(subscriptionId)?.token === token) { this.close(subscriptionId) diff --git a/src/utils/peering-billing.ts b/src/utils/peering-billing.ts index 9ce024d5..ea3ac26a 100644 --- a/src/utils/peering-billing.ts +++ b/src/utils/peering-billing.ts @@ -1,4 +1,4 @@ -import { PeeringTermSnapshot } from '../@types/peering' +import { PeeringAccess, PeeringTermSnapshot } from '../@types/peering' import { Settings } from '../@types/settings' import { SubscriptionFilter } from '../@types/subscription' import { EventKinds } from '../constants/base' @@ -15,6 +15,12 @@ export const PEERING_REISSUE_COOLDOWN_SECONDS = 15 /** Do not ask the processor about the same unpaid peer more often than this. */ export const PEERING_RECHECK_COOLDOWN_SECONDS = 30 +/** NIP-01 rejection reason for a denied peering access check. */ +export const peeringPaymentRequiredReason = (access: Pick): string => + access.reason?.startsWith('payment-required:') + ? access.reason + : `payment-required: ${access.reason ?? 'peering payment required; request the kind 402 peering invoice'}` + const UNIT_MULTIPLIER: Record = { msats: 1n, sats: 1000n, diff --git a/test/integration/features/peering/paid-peering-ledger.feature b/test/integration/features/peering/paid-peering-ledger.feature index b62534f6..169bcd9c 100644 --- a/test/integration/features/peering/paid-peering-ledger.feature +++ b/test/integration/features/peering/paid-peering-ledger.feature @@ -15,6 +15,15 @@ Feature: Paid peering billing ledger When the peer underpays a 21000 msat peering invoice with 1000 msats Then the underpayment is recorded without activating the peer + Scenario: A running paid period is offered a renewal + When the peer pays a 21000 msat peering invoice + Then the lifecycle offers a renewal without moving the paid period + + Scenario: An ended paid period is lapsed, alerted and revoked once + When the peer pays a 21000 msat peering invoice + And the paid peering period ends + Then the lifecycle lapses the peer, alerts once and revokes the socket + Scenario: A completed but unconfirmed peering invoice is retryable When a peering invoice is marked completed without a confirmation Then the unconfirmed peering invoice is returned for retry diff --git a/test/integration/features/peering/paid-peering-ledger.feature.ts b/test/integration/features/peering/paid-peering-ledger.feature.ts index 6318e0d8..e6a0f565 100644 --- a/test/integration/features/peering/paid-peering-ledger.feature.ts +++ b/test/integration/features/peering/paid-peering-ledger.feature.ts @@ -6,9 +6,11 @@ import Sinon from 'sinon' import { adminNotificationsPatchBodySchema } from '../../../../src/schemas/admin-notifications-schema' import { getMasterDbClient } from '../../../../src/database/client' import { InvoiceStatus, InvoiceUnit } from '../../../../src/@types/invoice' +import { OperatorNotificationEventType } from '../../../../src/@types/operator-notifications' import { InvoiceRepository } from '../../../../src/repositories/invoice-repository' import { PeeringPaymentRepository } from '../../../../src/repositories/peering-payment-repository' import { PaymentsService } from '../../../../src/services/payments-service' +import { PeeringBillingService } from '../../../../src/services/peering-billing-service' import { SettingsStatic } from '../../../../src/utils/settings' import * as eventUtils from '../../../../src/utils/event' import { @@ -59,7 +61,10 @@ const createService = (world: World>): void => { } as any const notificationOutboxRepository = { - enqueue: async () => ({}), + enqueue: async (type: string, payload: unknown) => { + world.parameters.peeringNotifications.push({ type, payload }) + return {} + }, } as any const paymentsProcessor = { @@ -96,6 +101,16 @@ const createService = (world: World>): void => { undefined, peeringPaymentRepository, ) + world.parameters.peeringRevokePeer = Sinon.stub() + world.parameters.peeringBillingService = new PeeringBillingService( + db, + peeringPaymentRepository, + invoiceRepository, + world.parameters.peeringService, + notificationOutboxRepository, + () => SettingsStatic._settings, + world.parameters.peeringRevokePeer, + ) } const createInvoice = async ( @@ -153,6 +168,7 @@ Before({ tags: '@paid-peering-ledger' }, function (this: World>) { + const billing = this.parameters.peeringBillingService as PeeringBillingService + const db = this.parameters.peeringDb + const peer = this.parameters.peeringPeer as string + const before = await peerRow(this, peer) + + const changed = await billing.processLifecycle(new Date()) + expect(changed).to.be.greaterThan(0) + + const row = await peerRow(this, peer) + expect(row.status).to.equal('renewal_pending') + expect(row.renewal_invoice_id).to.be.a('string') + expect(row.period_end.getTime()).to.equal(before.period_end.getTime()) + + const renewal = await db('invoices').where('id', row.renewal_invoice_id).first() + expect(renewal).to.exist + expect(renewal.purpose).to.equal('peering') + expect(renewal.status).to.equal('pending') + + const access = await billing.getAccess(peer) + expect(access.allowed).to.equal(true) + expect(access.status).to.equal('renewal_pending') + }, +) + +When('the paid peering period ends', async function (this: World>) { + const db = this.parameters.peeringDb + const peer = this.parameters.peeringPeer as string + + await db('peering_payments') + .where('peer_pubkey', Buffer.from(peer, 'hex')) + .update({ period_end: new Date(Date.now() - 1000) }) +}) + +Then( + 'the lifecycle lapses the peer, alerts once and revokes the socket', + async function (this: World>) { + const billing = this.parameters.peeringBillingService as PeeringBillingService + const revokePeer = this.parameters.peeringRevokePeer as Sinon.SinonStub + const notifications: { type: string; payload: any }[] = this.parameters.peeringNotifications + const peer = this.parameters.peeringPeer as string + const lapseAlerts = () => + notifications.filter( + (notification) => + notification.type === OperatorNotificationEventType.PEERING_ACCESS_LAPSED && + notification.payload?.pubkey === peer, + ) + + expect(lapseAlerts()).to.have.length(0) + + const changed = await billing.processLapses(new Date()) + expect(changed).to.be.greaterThan(0) + + const row = await peerRow(this, peer) + expect(row.status).to.equal('lapsed') + expect(row.current_invoice_id).to.equal(null) + expect(row.renewal_invoice_id).to.equal(null) + expect(row.last_error).to.equal(null) + expect(lapseAlerts()).to.have.length(1) + Sinon.assert.calledWith(revokePeer, peer) + + const access = await billing.getAccess(peer) + expect(access.allowed).to.equal(false) + expect(access.status).to.equal('lapsed') + + expect(await billing.processLapses(new Date())).to.equal(0) + expect(lapseAlerts()).to.have.length(1) + }, +) + When( 'the peer underpays a {int} msat peering invoice with {int} msats', async function (this: World>, amount: number, paid: number) { diff --git a/test/unit/adapters/web-socket-adapter.spec.ts b/test/unit/adapters/web-socket-adapter.spec.ts index 979d1b06..b0dd8def 100644 --- a/test/unit/adapters/web-socket-adapter.spec.ts +++ b/test/unit/adapters/web-socket-adapter.spec.ts @@ -216,6 +216,25 @@ describe('WebSocketAdapter', () => { expect(client.send).to.have.been.calledWith(closedMessage('sub-1')) }) + it('closes with an error reason when the expiry check fails', async () => { + adapter.onSubscribed('sub-1', [{ kinds: [1] }]) + adapter.setSubscriptionExpiry( + 'sub-1', + new Date('2026-11-09T12:00:01.000Z'), + sandbox.stub().rejects(new Error('db down')), + ) + + await clock.tickAsync(1000) + + expect(adapter.getSubscriptions().has('sub-1')).to.be.false + const closed = client.send + .getCalls() + .map((call: any) => JSON.parse(call.args[0])) + .find((message: any) => message[0] === 'CLOSED') + expect(closed).to.deep.equal(['CLOSED', 'sub-1', 'error: unable to check peering access']) + expect(client.send).not.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( diff --git a/test/unit/adapters/web-socket-server-adapter.spec.ts b/test/unit/adapters/web-socket-server-adapter.spec.ts index 91fa93ad..bb0ac6e1 100644 --- a/test/unit/adapters/web-socket-server-adapter.spec.ts +++ b/test/unit/adapters/web-socket-server-adapter.spec.ts @@ -111,6 +111,10 @@ describe('WebSocketServerAdapter', () => { it('registers error event listener on webSocketServer', () => { expect(webSocketServer.on).to.have.been.calledWith('error') }) + + it('registers the peering revoke listener on itself', () => { + expect(adapter.listenerCount(WebSocketServerAdapterEvent.PeeringRevoke)).to.be.greaterThan(0) + }) }) describe('getConnectedClients', () => { @@ -282,6 +286,47 @@ describe('WebSocketServerAdapter', () => { }) }) + describe('onPeeringRevoke', () => { + const peer = 'a'.repeat(64) + const adapters = () => (adapter as any).webSocketsAdapters as WeakMap + + it('closes only the sockets authenticated as the revoked peer', () => { + const matching = createMockClient() + const other = createMockClient() + const anonymous = createMockClient() + webSocketServer.clients = new Set([matching, other, anonymous] as any) + adapters().set(matching, { getPeerPubkey: () => peer }) + adapters().set(other, { getPeerPubkey: () => 'b'.repeat(64) }) + adapters().set(anonymous, { getPeerPubkey: () => undefined }) + + adapter.emit(WebSocketServerAdapterEvent.PeeringRevoke, { pubkey: peer }) + + expect(matching.close).to.have.been.calledOnceWithExactly(4001, 'payment-required: peering access expired') + expect(other.close).not.to.have.been.called + expect(anonymous.close).not.to.have.been.called + }) + + it('ignores a payload without a usable pubkey', () => { + const client = createMockClient() + webSocketServer.clients = new Set([client] as any) + adapters().set(client, { getPeerPubkey: () => peer }) + + adapter.emit(WebSocketServerAdapterEvent.PeeringRevoke, {}) + adapter.emit(WebSocketServerAdapterEvent.PeeringRevoke, { pubkey: 42 }) + adapter.emit(WebSocketServerAdapterEvent.PeeringRevoke, undefined as any) + + expect(client.close).not.to.have.been.called + }) + + it('skips clients that were never adapted', () => { + const client = createMockClient() + webSocketServer.clients = new Set([client] as any) + + expect(() => adapter.emit(WebSocketServerAdapterEvent.PeeringRevoke, { pubkey: peer })).not.to.throw + expect(client.close).not.to.have.been.called + }) + }) + describe('onHeartbeat', () => { it('emits heartbeat to connected adapters on the heartbeat interval', async () => { const emitStub = sandbox.stub() diff --git a/test/unit/app/maintenance-worker.spec.ts b/test/unit/app/maintenance-worker.spec.ts index 03cd5a4f..f2b23210 100644 --- a/test/unit/app/maintenance-worker.spec.ts +++ b/test/unit/app/maintenance-worker.spec.ts @@ -33,7 +33,7 @@ describe('MaintenanceWorker', () => { let notificationOutboxService: Sinon.SinonStubbedInstance let notificationDeliveryLogRepository: any let notificationOutboxRepository: any - let peeringBillingService: { processLapses: Sinon.SinonStub; handleInvoiceExpired: Sinon.SinonStub } + let peeringBillingService: { processLifecycle: Sinon.SinonStub; handleInvoiceExpired: Sinon.SinonStub } let verifyStub: Sinon.SinonStub const pendingInvoice = { @@ -112,7 +112,7 @@ describe('MaintenanceWorker', () => { } peeringBillingService = { - processLapses: sandbox.stub().resolves(0), + processLifecycle: sandbox.stub().resolves(0), handleInvoiceExpired: sandbox.stub().resolves(), } @@ -371,6 +371,57 @@ describe('MaintenanceWorker', () => { expect(paymentsService.getPendingInvoices).not.to.have.been.called }) + describe('peering lifecycle', () => { + it('runs the peering lifecycle once per pass', async () => { + await (worker as any).onSchedule() + + expect(peeringBillingService.processLifecycle).to.have.been.calledOnce + }) + + it('still finishes the pass when the peering lifecycle fails', async () => { + peeringBillingService.processLifecycle.rejects(new Error('database down')) + + await (worker as any).onSchedule() + + expect(maintenanceService.clearOldEvents).to.have.been.calledOnce + }) + + it('settles a peering invoice without sending the generic paid notice', async () => { + settingsState.payments = { enabled: true } as any + const invoice = { ...pendingInvoice, purpose: InvoicePurpose.PEERING } + paymentsService.getPendingInvoices.resolves([invoice]) + paymentsService.getInvoiceFromPaymentsProcessor.resolves({ + id: 'inv-1', + status: InvoiceStatus.COMPLETED, + confirmedAt: new Date(), + }) + + await (worker as any).onSchedule() + + expect(paymentsService.confirmInvoice).to.have.been.calledOnce + expect(paymentsService.sendInvoiceUpdateNotification).not.to.have.been.called + }) + + it('hands an expired peering invoice to the billing service', async () => { + settingsState.payments = { enabled: true } as any + const invoice = { + ...pendingInvoice, + purpose: InvoicePurpose.PEERING, + expiresAt: new Date('2020-01-01T00:00:00.000Z'), + } + paymentsService.getPendingInvoices.resolves([invoice]) + paymentsService.getInvoiceFromPaymentsProcessor.rejects({ response: { status: 404 } }) + + await (worker as any).onSchedule() + + expect(peeringBillingService.handleInvoiceExpired).to.have.been.calledWith(invoice) + expect(notificationOutboxRepository.enqueue).not.to.have.been.calledWith( + 'admission.invoice.failed', + Sinon.match.any, + ) + }) + }) + describe('subscription lifecycle', () => { let subscriptionService: { processLifecycle: Sinon.SinonStub } @@ -774,24 +825,6 @@ describe('MaintenanceWorker', () => { ) }) - 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/controllers/admin/get-admin-peering-controller.spec.ts b/test/unit/controllers/admin/get-admin-peering-controller.spec.ts index 50c58b25..d229cca7 100644 --- a/test/unit/controllers/admin/get-admin-peering-controller.spec.ts +++ b/test/unit/controllers/admin/get-admin-peering-controller.spec.ts @@ -39,7 +39,24 @@ describe('GetAdminPeeringController', () => { peers: [{ pubkey: state.pubkey, relayUrl: state.relayUrl }], }, } as Settings - const controller = new GetAdminPeeringController(stateStore as any, () => settings, requestStatsStore as any) + const peeringPaymentRepository = { + list: Sinon.stub().resolves([ + { + peerPubkey: state.pubkey, + direction: 'sell', + status: 'active', + periodEnd: new Date('2026-12-01T00:00:00.000Z'), + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }, + ]), + } + const controller = new GetAdminPeeringController( + stateStore as any, + () => settings, + requestStatsStore as any, + peeringPaymentRepository as any, + ) const response = { status: Sinon.stub().returnsThis(), setHeader: Sinon.stub().returnsThis(), @@ -64,5 +81,10 @@ describe('GetAdminPeeringController', () => { lastRequestAt: '2026-01-01T00:00:00.000Z', lastRequestType: 'REQ', }) + expect(payload.peers[0].billing).to.include({ + status: 'active', + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }) }) }) diff --git a/test/unit/handlers/neg-msg-message-handler.spec.ts b/test/unit/handlers/neg-msg-message-handler.spec.ts index 925fe21d..d808a5b2 100644 --- a/test/unit/handlers/neg-msg-message-handler.spec.ts +++ b/test/unit/handlers/neg-msg-message-handler.spec.ts @@ -189,4 +189,129 @@ describe('NegMsgMessageHandler', () => { expect(emitted).to.have.been.calledOnceWithExactly([MessageType.NEG_MSG, 'sync1', '61']) }) + + describe('paid access is checked on every message', () => { + const peer = 'a'.repeat(64) + let billing: { getAccess: Sinon.SinonStub } + + beforeEach(() => { + billing = { getAccess: sandbox.stub().resolves({ allowed: true }) } + ;(webSocket as any).getPeerPubkey = () => peer + handler = new NegMsgMessageHandler(webSocket, () => settings, billing as any) + }) + + it('keeps answering while the peer still has an active period', async () => { + openSession('sync1') + + await send('sync1', validMessageHex) + + expect(billing.getAccess).to.have.been.calledWith(peer) + expect(emitted.firstCall.args[0][0]).to.equal(MessageType.NEG_MSG) + }) + + it('closes the session when the paid period lapses mid-sync', async () => { + openSession('sync1') + billing.getAccess.resolves({ allowed: false, reason: 'peering access lapsed; request a new invoice' }) + + await send('sync1', validMessageHex) + + expect(emitted).to.have.been.calledOnceWithExactly([ + MessageType.NEG_ERR, + 'sync1', + 'payment-required: peering access lapsed; request a new invoice', + ]) + expect(sessions.getSessionIds()).to.deep.equal([]) + }) + + it('does not double-prefix a payment-required reason', async () => { + openSession('sync1') + billing.getAccess.resolves({ allowed: false, reason: 'payment-required: settle the invoice' }) + + await send('sync1', validMessageHex) + + expect(emitted.firstCall.args[0][2]).to.equal('payment-required: settle the invoice') + }) + + it('fails closed when the billing check errors', async () => { + openSession('sync1') + billing.getAccess.rejects(new Error('database down')) + + await send('sync1', validMessageHex) + + expect(emitted).to.have.been.calledOnceWithExactly([ + MessageType.NEG_ERR, + 'sync1', + 'error: unable to check peering access', + ]) + expect(sessions.getSessionIds()).to.deep.equal([]) + }) + + it('does not consult billing for a connection without a peer identity', async () => { + ;(webSocket as any).getPeerPubkey = () => undefined + openSession('sync1') + + await send('sync1', validMessageHex) + + expect(billing.getAccess).not.to.have.been.called + expect(emitted.firstCall.args[0][0]).to.equal(MessageType.NEG_MSG) + }) + + it('does not answer or close a replacement session after the billing wait', async () => { + openSession('sync1') + let settle!: (access: unknown) => void + billing.getAccess.returns( + new Promise((resolve) => { + settle = resolve + }), + ) + + const pending = send('sync1', validMessageHex) + // The peer replaces sync1 while the billing check is still running. + openSession('sync1') + settle({ allowed: false, reason: 'peering access lapsed' }) + + await pending + + expect(emitted).not.to.have.been.called + expect(sessions.getSessionIds()).to.deep.equal(['sync1']) + }) + + it('does not close a replacement session when the billing check fails', async () => { + openSession('sync1') + let fail!: (error: unknown) => void + billing.getAccess.returns( + new Promise((_resolve, reject) => { + fail = reject + }), + ) + + const pending = send('sync1', validMessageHex) + openSession('sync1') + fail(new Error('database down')) + + await pending + + expect(emitted).not.to.have.been.called + expect(sessions.getSessionIds()).to.deep.equal(['sync1']) + }) + + it('does not answer a session that was closed during the billing wait', async () => { + openSession('sync1') + let settle!: (access: unknown) => void + billing.getAccess.returns( + new Promise((resolve) => { + settle = resolve + }), + ) + + const pending = send('sync1', validMessageHex) + sessions.close('sync1') + settle({ allowed: false, reason: 'peering access lapsed' }) + + await pending + + expect(emitted).not.to.have.been.called + expect(sessions.getSessionIds()).to.deep.equal([]) + }) + }) }) diff --git a/test/unit/services/peering-billing-service.spec.ts b/test/unit/services/peering-billing-service.spec.ts index 40686468..3c825b8e 100644 --- a/test/unit/services/peering-billing-service.spec.ts +++ b/test/unit/services/peering-billing-service.spec.ts @@ -477,6 +477,34 @@ describe('PeeringBillingService', () => { Sinon.match.any, ) }) + + it('keeps the peer active when the lapse transaction fails', async () => { + const expired = payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() - 1000), + }) + paymentRepository.findPeriodEnded.resolves([expired]) + paymentRepository.findByPeer.resolves(expired) + paymentRepository.lockByPeer.rejects(new Error('deadlock')) + + expect(await service.processLapses(now)).to.equal(0) + expect(mockTrx.rollback).to.have.been.calledOnce + expect(notificationOutboxRepository.enqueue).not.to.have.been.called + expect(revokePeer).not.to.have.been.called + }) + + it('does not fail the pass when revoking the live sockets throws', 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) + revokePeer.throws(new Error('cluster down')) + + expect(await service.processLapses(now)).to.equal(1) + }) }) describe('handleInvoiceExpired', () => { @@ -494,6 +522,26 @@ describe('PeeringBillingService', () => { expect(paymentRepository.save).not.to.have.been.called }) + it('ignores an invoice when the peer has no billing row', async () => { + paymentRepository.findByPeer.resolves(undefined) + + await service.handleInvoiceExpired(invoice()) + + expect(paymentRepository.save).not.to.have.been.called + expect(notificationOutboxRepository.enqueue).not.to.have.been.called + }) + + it('does not fail the worker when the failure alert cannot be enqueued', async () => { + paymentRepository.findByPeer.resolves( + payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }), + ) + notificationOutboxRepository.enqueue.rejects(new Error('outbox down')) + + await service.handleInvoiceExpired(invoice()) + + expect(paymentRepository.save).to.have.been.called + }) + it('clears the pointer and records a failure', async () => { paymentRepository.findByPeer.resolves( payment({ status: PeeringPaymentStatus.INVOICED, currentInvoiceId: 'inv-1' }), @@ -533,4 +581,109 @@ describe('PeeringBillingService', () => { ) }) }) + + describe('processLifecycle', () => { + it('issues renewals and then lapses ended periods', async () => { + const running = payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 86_400_000), + }) + paymentRepository.findDueForRenewal.resolves([running]) + paymentRepository.findPeriodEnded.resolves([]) + sandbox.stub(service, 'ensureInvoice').resolves(invoice({ id: 'renewal-1' })) + + const changed = await service.processLifecycle(now) + + expect(changed).to.equal(1) + expect(service.ensureInvoice).to.have.been.calledWith(peer, { now, renewal: true }) + }) + + it('runs the ended-period sweep', async () => { + const expired = payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() - 1000), + }) + paymentRepository.findDueForRenewal.resolves([]) + paymentRepository.findPeriodEnded.resolves([expired]) + paymentRepository.findByPeer.resolves(expired) + paymentRepository.lockByPeer.resolves(expired) + + const changed = await service.processLifecycle(now) + + expect(changed).to.equal(1) + expect(paymentRepository.save).to.have.been.calledWith( + Sinon.match({ status: PeeringPaymentStatus.LAPSED }), + mockTrx, + ) + }) + + it('does nothing when the paid term is invalid', async () => { + settingsState.peering!.terms = [{ amount: 1500, unit: 'msats', period: 2592000 }] + + expect(await service.processLifecycle(now)).to.equal(0) + expect(paymentRepository.findDueForRenewal).not.to.have.been.called + expect(paymentRepository.findPeriodEnded).not.to.have.been.called + }) + + it('does nothing for settlement-free peering', async () => { + settingsState.peering!.terms = [] + + expect(await service.processLifecycle(now)).to.equal(0) + expect(paymentRepository.findDueForRenewal).not.to.have.been.called + }) + + it('does not renew a row whose period already ended', async () => { + paymentRepository.findDueForRenewal.resolves([ + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() - 1000), + }), + ]) + paymentRepository.findPeriodEnded.resolves([]) + const ensureInvoice = sandbox.stub(service, 'ensureInvoice').resolves(invoice()) + + expect(await service.processLifecycle(now)).to.equal(0) + expect(ensureInvoice).not.to.have.been.called + }) + + it('treats a reissue cooldown as handled without failing the pass', async () => { + paymentRepository.findDueForRenewal.resolves([ + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 1000), + }), + ]) + paymentRepository.findPeriodEnded.resolves([]) + sandbox.stub(service, 'ensureInvoice').rejects(new PeeringInvoiceCooldownError(15)) + + expect(await service.processLifecycle(now)).to.equal(0) + }) + + it('keeps the pass alive when issuing one renewal fails', async () => { + paymentRepository.findDueForRenewal.resolves([ + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 1000), + }), + ]) + paymentRepository.findPeriodEnded.resolves([]) + sandbox.stub(service, 'ensureInvoice').rejects(new Error('invoice provider down')) + + expect(await service.processLifecycle(now)).to.equal(0) + }) + + it('adds renewals and lapses into one count', async () => { + paymentRepository.findDueForRenewal.resolves([ + payment({ + status: PeeringPaymentStatus.ACTIVE, + periodEnd: new Date(now.getTime() + 1000), + }), + ]) + paymentRepository.findPeriodEnded.resolves([]) + sandbox.stub(service, 'ensureInvoice').resolves(invoice({ id: 'renewal-1' })) + sandbox.stub(service, 'processLapses').resolves(2) + + expect(await service.processLifecycle(now)).to.equal(3) + }) + }) }) diff --git a/test/unit/utils/admin-peering.spec.ts b/test/unit/utils/admin-peering.spec.ts index 8cc03d55..7ec24cc9 100644 --- a/test/unit/utils/admin-peering.spec.ts +++ b/test/unit/utils/admin-peering.spec.ts @@ -92,4 +92,147 @@ describe('admin peering rows', () => { eventsServed: 7, }) }) + + it('attaches paid peering billing state by peer pubkey', () => { + const periodEnd = new Date('2026-12-01T00:00:00.000Z') + const rows = mergePeeringRows( + { + peering: { + enabled: true, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [state()], + undefined, + [], + [ + { + peerPubkey: 'a'.repeat(64), + direction: 'sell', + status: 'active', + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: new Date('2026-11-01T00:00:00.000Z'), + periodEnd, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: 'inv-1', + lastSettledAt: new Date('2026-11-01T00:00:00.000Z'), + lastCheckedAt: null, + lastError: null, + createdAt: new Date('2026-11-01T00:00:00.000Z'), + updatedAt: new Date('2026-11-01T00:00:00.000Z'), + } as any, + ], + ) + + expect(rows[0].billing).to.include({ + status: 'active', + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }) + expect(rows[0].billing?.periodEnd).to.equal(periodEnd) + }) + + it('shows a billing row for a peer removed from settings', () => { + const rows = mergePeeringRows( + {} as Settings, + [], + undefined, + [], + [ + { + peerPubkey: 'b'.repeat(64), + direction: 'sell', + status: 'lapsed', + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: null, + periodEnd: null, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: null, + lastSettledAt: null, + lastCheckedAt: null, + lastError: null, + createdAt: new Date(), + updatedAt: new Date(), + } as any, + ], + ) + + expect(rows).to.have.length(1) + expect(rows[0]).to.include({ configured: false, enabled: false }) + expect(rows[0].billing?.status).to.equal('lapsed') + }) + + it('keeps one row when a configured peer has billing but no sync state', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [], + undefined, + [], + [ + { + peerPubkey: 'a'.repeat(64), + direction: 'sell', + status: 'unpaid', + currentInvoiceId: 'inv-1', + renewalInvoiceId: null, + periodStart: null, + periodEnd: null, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: null, + lastSettledAt: null, + lastCheckedAt: null, + lastError: null, + createdAt: new Date(), + updatedAt: new Date(), + } as any, + ], + ) + + expect(rows).to.have.length(1) + expect(rows[0]).to.include({ configured: true, stale: true }) + expect(rows[0].billing?.status).to.equal('unpaid') + }) + + it('does not add a second row for a removed peer that still has a sync state', () => { + const pubkey = 'c'.repeat(64) + const rows = mergePeeringRows( + {} as Settings, + [state({ pubkey })], + undefined, + [], + [ + { + peerPubkey: pubkey, + direction: 'sell', + status: 'lapsed', + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: null, + periodEnd: null, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: null, + lastSettledAt: null, + lastCheckedAt: null, + lastError: null, + createdAt: new Date(), + updatedAt: new Date(), + } as any, + ], + ) + + expect(rows).to.have.length(1) + expect(rows[0]).to.include({ configured: false, enabled: false }) + expect(rows[0].billing?.status).to.equal('lapsed') + }) }) diff --git a/test/unit/utils/peering-billing.spec.ts b/test/unit/utils/peering-billing.spec.ts index 233e7d30..55d8adc2 100644 --- a/test/unit/utils/peering-billing.spec.ts +++ b/test/unit/utils/peering-billing.spec.ts @@ -4,6 +4,7 @@ import { Settings } from '../../../src/@types/settings' import { InvalidPeeringTermError, isPeeringInvoiceRequest, + peeringPaymentRequiredReason, resolvePaidPeeringTerm, } from '../../../src/utils/peering-billing' @@ -82,3 +83,23 @@ describe('resolvePaidPeeringTerm', () => { expect(isPeeringInvoiceRequest([], peer)).to.be.false }) }) + +describe('peeringPaymentRequiredReason', () => { + it('prefixes an unprefixed denial reason', () => { + expect(peeringPaymentRequiredReason({ reason: 'peering access lapsed' })).to.equal( + 'payment-required: peering access lapsed', + ) + }) + + it('keeps an already-prefixed reason unchanged', () => { + expect(peeringPaymentRequiredReason({ reason: 'payment-required: settle the invoice' })).to.equal( + 'payment-required: settle the invoice', + ) + }) + + it('falls back to the invoice hint when there is no reason', () => { + expect(peeringPaymentRequiredReason({})).to.equal( + 'payment-required: peering payment required; request the kind 402 peering invoice', + ) + }) +})