Skip to content

Commit cfb265c

Browse files
committed
feat(peering): add the buyer invoice ledger and budget primitives
- add peering_invoices keyed by BOLT11 payment hash plus peering_budgets\n counters for per-peer and global fixed periods\n- decode BOLT11 enough to compare invoice amounts and dedupe on the payment hash\n- add buyer settings and typed payment contracts without wiring the runtime yet
1 parent 026bd00 commit cfb265c

13 files changed

Lines changed: 959 additions & 3 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"nostream": minor
3+
---
4+
5+
feat(peering): add the buyer invoice ledger and budget primitives
6+
7+
Adds the storage and decoding foundation for buying peering: a
8+
`peering_invoices` ledger deduped by BOLT11 payment hash, per-peer/global
9+
`peering_budgets` counters, a narrow BOLT11 decoder, and the buyer settings
10+
contracts. Automatic payment and admin approval ship in the follow-up slices.

‎.knip.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
],
1818
"ignore": [
1919
".nostr/**",
20-
"src/utils/relay-probe/**"
20+
"src/utils/relay-probe/**",
21+
"src/repositories/peering-invoice-repository.ts",
22+
"src/utils/bolt11.ts"
2123
],
2224
"commitlint": false,
2325
"eslint": false,
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
exports.up = async function (knex) {
2+
await knex.schema.createTable('peering_invoices', (table) => {
3+
// The BOLT11 payment hash is the idempotency key: a redelivered kind 402
4+
// event must not create a second payment, and it must survive restarts.
5+
table.text('payment_hash').primary()
6+
table.text('event_id').notNullable().unique()
7+
table.binary('peer_pubkey').notNullable()
8+
table.text('bolt11').notNullable()
9+
table.bigint('amount_msats').unsigned().notNullable()
10+
table
11+
.enum('status', ['received', 'paying', 'paid', 'held', 'rejected', 'failed'])
12+
.notNullable()
13+
.defaultTo('received')
14+
table.text('reason').nullable()
15+
table.boolean('auto_paid').notNullable().defaultTo(false)
16+
table.timestamp('budget_period_start', { useTz: true }).nullable()
17+
table.timestamp('budget_period_end', { useTz: true }).nullable()
18+
table.integer('term_period_seconds').nullable()
19+
table.timestamp('expires_at', { useTz: true }).nullable()
20+
table.integer('seen_count').notNullable().defaultTo(1)
21+
table.timestamp('paid_at', { useTz: true }).nullable()
22+
table.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now())
23+
table.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now())
24+
25+
table.index(['status', 'created_at'], 'idx_peering_invoices_status_created_at')
26+
table.index(['peer_pubkey', 'status'], 'idx_peering_invoices_peer_status')
27+
})
28+
29+
await knex.schema.createTable('peering_budgets', (table) => {
30+
// scope is `global` or `peer:<hex>`. The period is a fixed, epoch-aligned
31+
// window so a renewal inside one period cannot borrow from the next.
32+
table.text('scope').notNullable()
33+
table.timestamp('period_start', { useTz: true }).notNullable()
34+
table.timestamp('period_end', { useTz: true }).notNullable()
35+
table.bigint('spent_msats').unsigned().notNullable().defaultTo(0)
36+
37+
table.primary(['scope', 'period_start'])
38+
})
39+
}
40+
41+
exports.down = async function (knex) {
42+
await knex.schema.dropTable('peering_budgets')
43+
await knex.schema.dropTable('peering_invoices')
44+
}

‎resources/default-settings.yaml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,16 @@ peering:
208208
# - pubkey: replace-with-peer-relay-pubkey-in-hex
209209
# relayUrl: wss://peer.example.com
210210
# enabled: true
211+
# # Reserved for the buyer workflow; not active in this slice.
212+
# budget: { amount: 10000, unit: sats, period: 2592000 }
211213
peers: []
214+
# Reserved for the buyer workflow. This slice stores the policy settings;
215+
# the payment and admin approval paths ship in follow-up slices.
216+
autoPay:
217+
enabled: false
218+
# Optional cap across every peer, per this budget's own period. A zero
219+
# amount means no global cap.
220+
globalBudget: { amount: 0, unit: sats, period: 2592000 }
212221
network:
213222
maxPayloadSize: 524288
214223
# Uncomment only when using a trusted reverse proxy and configuring trustedProxies.

‎src/@types/peering.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,94 @@ export interface PeeringAccess {
7272
reason?: string
7373
}
7474

75+
/** A buying-side invoice received over the peer connection. */
76+
export enum PeeringInvoiceStatus {
77+
RECEIVED = 'received',
78+
PAYING = 'paying',
79+
PAID = 'paid',
80+
HELD = 'held',
81+
REJECTED = 'rejected',
82+
FAILED = 'failed',
83+
}
84+
85+
/** Why a buyer invoice was held, failed, or paid by an operator instead of auto-pay. */
86+
export enum PeeringInvoiceReason {
87+
BUDGET_EXCEEDED = 'budget_exceeded',
88+
BUDGET_NOT_CONFIGURED = 'budget_not_configured',
89+
AUTO_PAY_DISABLED = 'auto_pay_disabled',
90+
AMOUNT_MISMATCH = 'amount_mismatch',
91+
UNKNOWN_PEER = 'unknown_peer',
92+
DUPLICATE = 'duplicate',
93+
UNSUPPORTED_PROCESSOR = 'unsupported_processor',
94+
PAYMENT_FAILED = 'payment_failed',
95+
EXPIRED = 'expired',
96+
INVALID_INVOICE = 'invalid_invoice',
97+
}
98+
99+
export interface PeeringInvoice {
100+
/** BOLT11 payment hash; dedupe key across events and restarts. */
101+
paymentHash: string
102+
/** Kind 402 event that delivered this invoice. */
103+
eventId: string
104+
peerPubkey: Pubkey
105+
bolt11: string
106+
amountMsats: bigint
107+
status: PeeringInvoiceStatus
108+
reason?: PeeringInvoiceReason | null
109+
/** True only for an automatic payment; manual approvals are not auto-spend. */
110+
autoPaid: boolean
111+
budgetPeriodStart?: Date | null
112+
budgetPeriodEnd?: Date | null
113+
/** Period this invoice buys from the peer, from the advertised term. */
114+
termPeriodSeconds?: number | null
115+
expiresAt?: Date | null
116+
seenCount: number
117+
paidAt?: Date | null
118+
createdAt: Date
119+
updatedAt: Date
120+
}
121+
122+
export interface DBPeeringInvoice {
123+
payment_hash: string
124+
event_id: string
125+
peer_pubkey: Buffer
126+
bolt11: string
127+
amount_msats: string
128+
status: PeeringInvoiceStatus
129+
reason: PeeringInvoiceReason | null
130+
auto_paid: boolean
131+
budget_period_start: Date | null
132+
budget_period_end: Date | null
133+
term_period_seconds: number | null
134+
expires_at: Date | null
135+
seen_count: number
136+
paid_at: Date | null
137+
created_at: Date
138+
updated_at: Date
139+
}
140+
141+
/** One budget counter, either `global` or `peer:<hex>`. */
142+
export interface PeeringBudgetUsage {
143+
scope: string
144+
periodStart: Date
145+
periodEnd: Date
146+
spentMsats: bigint
147+
}
148+
149+
/** Admin view of one budget window, with invoice counts for its peer. */
150+
export interface PeeringBudgetSummary {
151+
scope: 'peer' | 'global'
152+
peerPubkey?: string
153+
periodStart: Date
154+
periodEnd: Date
155+
limitMsats: bigint
156+
spentMsats: bigint
157+
remainingMsats: bigint
158+
received: number
159+
paid: number
160+
held: number
161+
}
162+
75163
export interface PeeringTermSnapshot {
76164
amountMsats: bigint
77165
periodSeconds: number

‎src/@types/repositories.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
NotificationDeliveryStatus,
1313
OperatorNotificationChannelType,
1414
} from './operator-notifications'
15-
import { PeeringPayment } from './peering'
15+
import { PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering'
1616
import { Report } from './report'
1717
import { EventKindsRange } from './settings'
1818
import { SubscriptionFilter } from './subscription'
@@ -99,6 +99,48 @@ export interface IPeeringPaymentRepository {
9999
findPeriodEnded(now: Date, limit: number, offset: number): Promise<PeeringPayment[]>
100100
}
101101

102+
export interface IPeeringInvoiceRepository {
103+
/** Inserts once per payment hash; returns the stored row and whether it was new. */
104+
insertIfNew(
105+
invoice: PeeringInvoice,
106+
client?: DatabaseClient,
107+
): Promise<{ inserted: boolean; invoice: PeeringInvoice }>
108+
findByHash(paymentHash: string, client?: DatabaseClient): Promise<PeeringInvoice | undefined>
109+
update(
110+
paymentHash: string,
111+
changes: Partial<Pick<PeeringInvoice, 'status' | 'reason' | 'autoPaid' | 'paidAt' | 'budgetPeriodStart' | 'budgetPeriodEnd' | 'termPeriodSeconds'>>,
112+
client?: DatabaseClient,
113+
): Promise<PeeringInvoice | undefined>
114+
/** Atomically moves one row from an allowed state; undefined when another writer won. */
115+
claim(
116+
paymentHash: string,
117+
from: PeeringInvoiceStatus[],
118+
to: PeeringInvoiceStatus,
119+
client?: DatabaseClient,
120+
): Promise<PeeringInvoice | undefined>
121+
list(statuses?: PeeringInvoiceStatus[], limit?: number): Promise<PeeringInvoice[]>
122+
/** Atomically adds `amount` when the resulting spend stays inside `limit`. */
123+
reserveBudget(
124+
scope: string,
125+
periodStart: Date,
126+
periodEnd: Date,
127+
amountMsats: bigint,
128+
limitMsats: bigint,
129+
client: DatabaseClient,
130+
): Promise<bigint | undefined>
131+
/** Adds manual spend even when it exceeds the auto-pay limit. */
132+
addBudgetSpend(
133+
scope: string,
134+
periodStart: Date,
135+
periodEnd: Date,
136+
amountMsats: bigint,
137+
client: DatabaseClient,
138+
): Promise<bigint>
139+
releaseBudget(scope: string, periodStart: Date, amountMsats: bigint, client: DatabaseClient): Promise<void>
140+
/** Current and recent budget counters for the admin console. */
141+
listBudgets(): Promise<PeeringBudgetUsage[]>
142+
}
143+
102144
export interface IUserSubscriptionRepository {
103145
findByPubkey(pubkey: Pubkey, client?: DatabaseClient): Promise<UserSubscription | undefined>
104146
upsert(subscription: Omit<UserSubscription, 'createdAt' | 'updatedAt'>, client?: DatabaseClient): Promise<number>

‎src/@types/settings.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,19 @@ export interface PeeringPeer {
579579
relayUrl: string
580580
/** Whether this configured peer is active. Defaults to true. */
581581
enabled?: boolean
582+
/**
583+
* Buying side only: how much this relay may auto-pay to this peer per budget
584+
* period. Absent means invoices from this peer are held for an operator.
585+
*/
586+
budget?: PeeringTerm
587+
}
588+
589+
/** Buying-side automatic payment policy. */
590+
export interface PeeringAutoPaySettings {
591+
/** Master switch. Per-peer budgets still decide which peers can be paid. */
592+
enabled: boolean
593+
/** Optional cap across every peer, per its own period. */
594+
globalBudget?: PeeringTerm
582595
}
583596

584597
export interface PeeringSettings {
@@ -617,6 +630,11 @@ export interface PeeringSettings {
617630
* pubkey receives no peer recognition, even with a valid signature.
618631
*/
619632
peers?: PeeringPeer[]
633+
/**
634+
* Buying side: pay invoices from configured peers automatically while they
635+
* stay inside the per-peer budget (and the optional global cap).
636+
*/
637+
autoPay?: PeeringAutoPaySettings
620638
}
621639

622640
export interface Settings {

0 commit comments

Comments
 (0)