Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
cf74f95
feat(peering): decide and pay peer invoices within budgets
Ferryx349 Nov 18, 2026
8c4df0c
fix(peering): restore buyer types and manual budget mutations
Ferryx349 Nov 18, 2026
241072c
Merge branch 'main' into feat/peering-auto-pay-2-policy
Ferryx349 Nov 19, 2026
c8af5b3
fix(peering): allow route-hint invoices and cover buyer policy in int…
Ferryx349 Nov 19, 2026
f39dcf5
fix(peering): expose auto-pay settings and harden budget reservation
Ferryx349 Nov 19, 2026
afd8718
fix(peering): bind both limit operands in the budget upsert
Ferryx349 Nov 19, 2026
9cec3d6
fix(peering): make a zero global budget an explicit no-cap
Ferryx349 Nov 19, 2026
43d485e
test(peering): cover buyer hold paths and payment failures
Ferryx349 Nov 19, 2026
e13d408
chore(peering): add the buyer policy changeset
Ferryx349 Nov 19, 2026
ff9c09b
fix(peering): keep paid charges and recover interrupted payments
Ferryx349 Nov 19, 2026
8c4c6bf
fix(peering): make payment recovery atomic and budget-complete
Ferryx349 Nov 19, 2026
bf301ce
Merge branch 'main' into feat/peering-auto-pay-2-policy
Ferryx349 Nov 19, 2026
4193086
fix(peering): require successful budget accounting before paying
Ferryx349 Nov 19, 2026
caea8df
test(peering): remove unused recovery fixture variables
Ferryx349 Nov 19, 2026
001499b
test(peering): restore the peer key in the auto-pay fixture
Ferryx349 Nov 19, 2026
b5af61a
fix(peering): recover paying invoices on redelivery and approval
Ferryx349 Nov 19, 2026
76a875f
fix(peering): recover a PAYING row when the claim is lost
Ferryx349 Nov 20, 2026
9c5917d
chore(peering): add a changeset for the buyer policy slice
Ferryx349 Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/peering-auto-pay-policy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"nostream": minor
---

feat(peering): enforce buyer budgets before paying peer invoices

Adds the buying-side policy: verify a peer invoice against its advertised
NIP-11 term, dedupe on the payment hash, reserve per-peer and global budget
counters atomically, pay through the configured wallet, and hold anything
outside the envelope for operator approval.
3 changes: 2 additions & 1 deletion .knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
".nostr/**",
"src/utils/relay-probe/**",
"src/repositories/peering-invoice-repository.ts",
"src/utils/bolt11.ts"
"src/utils/bolt11.ts",
"src/services/peering-buyer-service.ts"
],
"commitlint": false,
"eslint": false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
exports.up = async function (knex) {
await knex.schema.alterTable('peering_invoices', (table) => {
table.timestamp('global_budget_period_start', { useTz: true }).nullable()
table.timestamp('global_budget_period_end', { useTz: true }).nullable()
})
}

exports.down = async function (knex) {
await knex.schema.alterTable('peering_invoices', (table) => {
table.dropColumn('global_budget_period_start')
table.dropColumn('global_budget_period_end')
})
}
12 changes: 6 additions & 6 deletions resources/default-settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -208,15 +208,15 @@ peering:
# - pubkey: replace-with-peer-relay-pubkey-in-hex
# relayUrl: wss://peer.example.com
# enabled: true
# # Reserved for the buyer workflow; not active in this slice.
# budget: { amount: 10000, unit: sats, period: 2592000 }
peers: []
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
# Reserved for the buyer workflow. This slice stores the policy settings;
# the payment and admin approval paths ship in follow-up slices.
# Buying side automatic payment. Invoices are paid only when the peer is
# configured above, the amount matches the peer's advertised NIP-11 terms,
# the payment hash has not been seen, and both budgets have room. Anything
# else is held for operator approval.
autoPay:
enabled: false
# Optional cap across every peer, per this budget's own period. A zero
# amount means no global cap.
# Optional cap across every peer, per this budget's own period.
# A zero amount means no global cap.
globalBudget: { amount: 0, unit: sats, period: 2592000 }
network:
maxPayloadSize: 524288
Expand Down
20 changes: 20 additions & 0 deletions src/@types/clients.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,27 @@ export interface CreateInvoiceRequest {

export type GetInvoiceResponse = Partial<Invoice>

export interface PayInvoiceRequest {
bolt11: string
}

export interface PayInvoiceResponse {
/** BOLT11 payment hash, used as the buyer-side dedupe key. */
paymentHash: string
preimage?: string
}

/** The configured processor only creates/reads incoming invoices; it cannot spend. */
export class PaymentsProcessorCannotPayError extends Error {
public constructor() {
super('the configured payments processor cannot pay a BOLT11 invoice')
this.name = 'PaymentsProcessorCannotPayError'
}
}

export interface IPaymentsProcessor {
createInvoice(request: CreateInvoiceRequest): Promise<CreateInvoiceResponse>
getInvoice(invoice: string | Invoice): Promise<GetInvoiceResponse>
/** Pays a BOLT11 invoice from the processor wallet. Absent on receive-only adapters. */
payInvoice?(request: PayInvoiceRequest): Promise<PayInvoiceResponse>
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved
}
26 changes: 26 additions & 0 deletions src/@types/peering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ export interface PeeringInvoice {
autoPaid: boolean
budgetPeriodStart?: Date | null
budgetPeriodEnd?: Date | null
globalBudgetPeriodStart?: Date | null
globalBudgetPeriodEnd?: Date | null
/** Period this invoice buys from the peer, from the advertised term. */
termPeriodSeconds?: number | null
expiresAt?: Date | null
Expand All @@ -130,6 +132,8 @@ export interface DBPeeringInvoice {
auto_paid: boolean
budget_period_start: Date | null
budget_period_end: Date | null
global_budget_period_start: Date | null
global_budget_period_end: Date | null
term_period_seconds: number | null
expires_at: Date | null
seen_count: number
Expand All @@ -138,6 +142,28 @@ export interface DBPeeringInvoice {
updated_at: Date
}

/** One budget counter, either `global` or `peer:<hex>`. */
export interface PeeringBudgetUsage {
scope: string
periodStart: Date
periodEnd: Date
spentMsats: bigint
}

/** Admin view of one budget window, with invoice counts for its peer. */
export interface PeeringBudgetSummary {
scope: 'peer' | 'global'
peerPubkey?: string
periodStart: Date
periodEnd: Date
limitMsats: bigint
spentMsats: bigint
remainingMsats: bigint
received: number
paid: number
held: number
}

export interface PeeringTermSnapshot {
amountMsats: bigint
periodSeconds: number
Expand Down
34 changes: 32 additions & 2 deletions src/@types/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
NotificationDeliveryStatus,
OperatorNotificationChannelType,
} from './operator-notifications'
import { PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering'
import { PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering'
import { Report } from './report'
import { EventKindsRange } from './settings'
import { SubscriptionFilter } from './subscription'
Expand Down Expand Up @@ -109,7 +109,20 @@ export interface IPeeringInvoiceRepository {
findByHash(paymentHash: string, client?: DatabaseClient): Promise<PeeringInvoice | undefined>
update(
paymentHash: string,
changes: Partial<Pick<PeeringInvoice, 'status' | 'reason' | 'autoPaid' | 'paidAt' | 'budgetPeriodStart' | 'budgetPeriodEnd' | 'termPeriodSeconds'>>,
changes: Partial<
Pick<
PeeringInvoice,
| 'status'
| 'reason'
| 'autoPaid'
| 'paidAt'
| 'budgetPeriodStart'
| 'budgetPeriodEnd'
| 'globalBudgetPeriodStart'
| 'globalBudgetPeriodEnd'
| 'termPeriodSeconds'
>
>,
client?: DatabaseClient,
): Promise<PeeringInvoice | undefined>
/** Atomically moves one row from an allowed state; undefined when another writer won. */
Expand All @@ -129,6 +142,23 @@ export interface IPeeringInvoiceRepository {
limitMsats: bigint,
client: DatabaseClient,
): Promise<bigint | undefined>
/** Adds manual spend even when it exceeds the auto-pay limit. */
addBudgetSpend(
scope: string,
periodStart: Date,
periodEnd: Date,
amountMsats: bigint,
client: DatabaseClient,
): Promise<bigint>
releaseBudget(scope: string, periodStart: Date, amountMsats: bigint, client: DatabaseClient): Promise<void>
/** Current and recent budget counters for the admin console. */
listBudgets(): Promise<PeeringBudgetUsage[]>
/** Invoice counts in one budget window, optionally for one peer. */
countInWindow(
peerPubkey: string | undefined,
start: Date,
end: Date,
): Promise<{ received: number; paid: number; held: number }>
}

export interface IUserSubscriptionRepository {
Expand Down
26 changes: 25 additions & 1 deletion src/@types/services.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { DatabaseTransaction, Pubkey } from './base'
import { Event } from './event'
import { Invoice } from './invoice'
import { NotificationOutboxPayload } from './notification-outbox'
import { PeeringAccess } from './peering'
import { PeeringAccess, PeeringAdvertisement, PeeringBudgetSummary, PeeringInvoice, PeeringInvoiceStatus } from './peering'
import { PeeringPeer } from './settings'

export interface IMaintenanceService {
clearOldEvents(): Promise<void>
Expand Down Expand Up @@ -53,6 +55,8 @@ export interface IPaymentsService {
getPendingInvoices(offset?: number): Promise<Invoice[]>
/** Completed peering invoices whose settlement did not commit, for retry. */
getUnconfirmedPeeringInvoices(limit?: number, offset?: number): Promise<Invoice[]>
/** Pays a BOLT11 invoice from the configured wallet and returns its payment hash. */
payInvoice(bolt11: string): Promise<string>
}

export interface IPeeringBillingService {
Expand All @@ -68,6 +72,26 @@ export interface IPeeringBillingService {
handleInvoiceExpired(invoice: Invoice): Promise<void>
}

export interface IPeeringBuyerService {
/** Validates a kind 402 invoice from a peer, then auto-pays or holds it. */
handleInvoice(
peer: PeeringPeer,
advertisement: PeeringAdvertisement,
event: Event,
now?: Date,
): Promise<PeeringInvoice>
/** Pays a held invoice on operator approval, bypassing the auto-pay budget guard. */
approve(paymentHash: string, now?: Date): Promise<PeeringInvoice>
/** Rejects a held invoice without paying it. */
reject(paymentHash: string): Promise<PeeringInvoice>
/** Recent buyer invoices for the admin console. */
list(statuses?: PeeringInvoiceStatus[], limit?: number): Promise<PeeringInvoice[]>
/** Spend, remaining budget and invoice counts for the current period. */
budgetSummary(now?: Date): Promise<PeeringBudgetSummary[]>
/** Finishes invoices left in PAYING by a restart, before retrying anything. */
recover(now?: Date): Promise<number>
}

export interface ISubscriptionService {
/** One pass of renewal invoices, period ends and grace expiries. Returns how many subscriptions changed. */
processLifecycle(now?: Date): Promise<number>
Expand Down
90 changes: 89 additions & 1 deletion src/repositories/peering-invoice-repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { DatabaseClient } from '../@types/base'
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved
import {
DBPeeringInvoice,
PeeringBudgetUsage,
PeeringInvoice,
PeeringInvoiceReason,
PeeringInvoiceStatus,
Expand All @@ -22,6 +23,8 @@ const toRow = (invoice: PeeringInvoice): DBPeeringInvoice => ({
auto_paid: invoice.autoPaid,
budget_period_start: invoice.budgetPeriodStart ?? null,
budget_period_end: invoice.budgetPeriodEnd ?? null,
global_budget_period_start: invoice.globalBudgetPeriodStart ?? null,
global_budget_period_end: invoice.globalBudgetPeriodEnd ?? null,
term_period_seconds: invoice.termPeriodSeconds ?? null,
expires_at: invoice.expiresAt ?? null,
seen_count: invoice.seenCount,
Expand All @@ -41,6 +44,8 @@ const fromRow = (row: DBPeeringInvoice): PeeringInvoice => ({
autoPaid: Boolean(row.auto_paid),
budgetPeriodStart: row.budget_period_start,
budgetPeriodEnd: row.budget_period_end,
globalBudgetPeriodStart: row.global_budget_period_start,
globalBudgetPeriodEnd: row.global_budget_period_end,
termPeriodSeconds: row.term_period_seconds,
expiresAt: row.expires_at,
seenCount: row.seen_count,
Expand Down Expand Up @@ -112,6 +117,8 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository {
| 'paidAt'
| 'budgetPeriodStart'
| 'budgetPeriodEnd'
| 'globalBudgetPeriodStart'
| 'globalBudgetPeriodEnd'
| 'termPeriodSeconds'
>
>,
Expand All @@ -136,6 +143,12 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository {
if (changes.budgetPeriodEnd !== undefined) {
patch.budget_period_end = changes.budgetPeriodEnd
}
if (changes.globalBudgetPeriodStart !== undefined) {
patch.global_budget_period_start = changes.globalBudgetPeriodStart
}
if (changes.globalBudgetPeriodEnd !== undefined) {
patch.global_budget_period_end = changes.globalBudgetPeriodEnd
}
if (changes.termPeriodSeconds !== undefined) {
patch.term_period_seconds = changes.termPeriodSeconds
}
Expand Down Expand Up @@ -193,7 +206,7 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository {
ON CONFLICT (scope, period_start) DO UPDATE
SET spent_msats = peering_budgets.spent_msats + EXCLUDED.spent_msats,
period_end = EXCLUDED.period_end
WHERE peering_budgets.spent_msats + EXCLUDED.spent_msats <= CAST(? AS bigint)
WHERE peering_budgets.spent_msats <= CAST(? AS bigint) - CAST(? AS bigint)
RETURNING spent_msats`,
[
scope,
Expand All @@ -203,6 +216,7 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository {
amountMsats.toString(),
limitMsats.toString(),
limitMsats.toString(),
amountMsats.toString(),
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
],
)
const row = firstRow(result)
Expand All @@ -214,5 +228,79 @@ export class PeeringInvoiceRepository implements IPeeringInvoiceRepository {
return BigInt(row.spent_msats)
}

public async addBudgetSpend(
scope: string,
periodStart: Date,
periodEnd: Date,
amountMsats: bigint,
client: DatabaseClient,
): Promise<bigint> {
if (amountMsats < 0n) {
throw new Error('budget spend amount must be non-negative')
}

const result = await client.raw(
`INSERT INTO peering_budgets (scope, period_start, period_end, spent_msats)
VALUES (?, ?, ?, ?)
ON CONFLICT (scope, period_start) DO UPDATE
SET spent_msats = peering_budgets.spent_msats + EXCLUDED.spent_msats,
period_end = EXCLUDED.period_end
RETURNING spent_msats`,
[scope, periodStart, periodEnd, amountMsats.toString()],
)

return BigInt(firstRow(result).spent_msats)
}

public async releaseBudget(
scope: string,
periodStart: Date,
amountMsats: bigint,
client: DatabaseClient,
): Promise<void> {
if (amountMsats < 0n) {
throw new Error('budget release amount must be non-negative')
}

await client.raw(
`UPDATE peering_budgets
SET spent_msats = GREATEST(spent_msats - ?, 0)
WHERE scope = ? AND period_start = ?`,
[amountMsats.toString(), scope, periodStart],
)
}

public async countInWindow(
peerPubkey: string | undefined,
start: Date,
end: Date,
): Promise<{ received: number; paid: number; held: number }> {
const result = await this.dbClient.raw(
`SELECT COUNT(*) AS received,
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status IN ('held', 'failed')) AS held
FROM peering_invoices
WHERE created_at >= ? AND created_at < ?
${peerPubkey ? 'AND peer_pubkey = ?' : ''}`,
peerPubkey ? [start, end, toBuffer(peerPubkey)] : [start, end],
)
const row = firstRow(result) ?? {}

return {
received: Number(row.received ?? 0),
paid: Number(row.paid ?? 0),
held: Number(row.held ?? 0),
}
}

public async listBudgets(): Promise<PeeringBudgetUsage[]> {
const rows = await this.dbClient<any>('peering_budgets').orderBy('period_start', 'desc')

return rows.map((row) => ({
scope: row.scope,
periodStart: row.period_start,
periodEnd: row.period_end,
spentMsats: BigInt(row.spent_msats),
}))
}
}
Loading
Loading