Skip to content

Commit d5ebdff

Browse files
authored
feat(peering): ingest and surface auto-paid peer invoices (#1169)
2 parents 9ab9017 + 50b7bc0 commit d5ebdff

48 files changed

Lines changed: 2020 additions & 186 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"nostream": minor
3+
---
4+
5+
feat(peering): surface buyer invoices and budgets in the admin console
6+
7+
Watches the peer's signed kind 402 invoice stream over the authenticated sync
8+
connection, pays through LNbits or NWC, and exposes held invoices with
9+
operator approve/reject actions, budget spend/remaining, and invoice counts.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
"nostream": patch
3+
---
4+
5+
fix(peering): keep wallet payments recoverable and request invoices before the feed
6+
7+
Subscribe to the seller's invoice stream before opening a paid feed, so a feed
8+
rejected until payment no longer closes the connection first. Wallet submits
9+
now report whether they settled; pending, unknown and ambiguous transport
10+
outcomes keep their reservation and stay `PAYING` for recovery, while outgoing
11+
LNbits expiry no longer counts as a failed payment. Each payment attempt owns
12+
its row, may only leave `PAYING` once, and serializes submission against
13+
recovery, so a stale lookup cannot release a charge that is still in flight.
14+
Renewal invoices are only offered inside the period-relative renewal window, so
15+
ordinary reconnects cannot buy extra periods.

‎.knip.json‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,6 @@
1818
"ignore": [
1919
".nostr/**",
2020
"src/utils/relay-probe/**",
21-
"src/repositories/peering-invoice-repository.ts",
22-
"src/utils/bolt11.ts",
23-
"src/services/peering-buyer-service.ts"
2421
],
2522
"commitlint": false,
2623
"eslint": false,

‎docs/PAYMENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ Each processor step ends with `nostream stop` and `nostream start`, which is the
7272
- Your instance must be accessible from the internet and have a valid SSL/TLS certificate
7373
- Get wallet Invoice/read key (in Api docs section of your wallet)
7474
- set `LNBITS_API_KEY` environment variable with the Invoice/read key Key above on your `.env` file
75+
- if this relay buys paid peering feeds, the same key must also allow
76+
**outgoing payments** (spending), otherwise auto-pay cannot pay a peer invoice
7577
7678
```
7779
LNBITS_API_KEY={YOUR_LNBITS_API_KEY_HERE}

‎docs/PEERING.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,55 @@ Billing state is stored in `peering_payments`, one row per peer and direction
227227
(`sell` here; `buy` is reserved for the paying side). `GET /admin/peering`
228228
merges it with the sync and request rows, showing status, access end, the open
229229
invoice and the last processor error.
230+
231+
## Buying side: auto-pay and budgets
232+
233+
The relay can also be the buyer. It subscribes to the `kind 402` invoice stream
234+
of every enabled peer that advertises a paid term, over the same authenticated
235+
peering connection it uses for the feed. Invoices are deduplicated by BOLT11
236+
payment hash, so a redelivered event or a reconnect never pays twice.
237+
238+
Auto-pay is opt-in and requires a per-peer budget:
239+
240+
```yaml
241+
peering:
242+
autoPay:
243+
enabled: true
244+
# Optional cap across every peer, per its own period. Zero means no cap.
245+
globalBudget: { amount: 100000, unit: sats, period: 2592000 }
246+
peers:
247+
- pubkey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
248+
relayUrl: wss://peer.example.com
249+
budget: { amount: 10000, unit: sats, period: 2592000 }
250+
```
251+
252+
An invoice is paid automatically only when all of these hold:
253+
254+
- the event is signed by the configured peer pubkey and p-tagged to this relay;
255+
- its BOLT11 amount equals the single paid term in the peer's NIP-11 document;
256+
- the payment hash has not been seen before;
257+
- the per-peer budget, and the optional global budget, have room in the current
258+
period.
259+
260+
Budget windows are fixed and epoch-aligned. A renewal inside the same window
261+
counts against the same counter, and auto-pay never borrows from the next
262+
window. The counters are updated atomically before the wallet is called, so two
263+
workers cannot both spend the last unit of a budget.
264+
265+
Anything else is stored as a **held** invoice and shown under Operations →
266+
Peering invoices in the admin console. The reason is one of `amount_mismatch`,
267+
`unknown_peer`, `budget_exceeded`, `budget_not_configured`, `auto_pay_disabled`,
268+
`payment_failed` or `expired`. Held invoices can be approved (paid manually) or
269+
rejected. Manual approval is not limited by the auto-pay budget, but its spend is
270+
still recorded. Every hold, payment and budget exhaustion feeds the existing
271+
peering notification switches, so the operator can subscribe to
272+
`peering.invoice.paid` / `peering.invoice.failed`.
273+
274+
Auto-pay uses the configured payments processor as the wallet. LNbits and NWC
275+
can pay BOLT11 invoices; receive-only adapters hold every invoice because they
276+
have no way to spend. The LNbits key must allow
277+
**outgoing payments**, not only invoice creation/read access. An Invoice/read
278+
key can create the relay's own invoices but cannot spend, so every buyer
279+
invoice is held instead of paid. The buyer never credits a user balance and never touches
280+
the seller's payment processor: the payment is a normal Lightning payment from
281+
this relay's wallet to the BOLT11 invoice in the peer's signed event.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
exports.up = async function (knex) {
2+
await knex.schema.alterTable('peering_invoices', (table) => {
3+
table.text('payment_attempt_id').nullable()
4+
})
5+
}
6+
7+
exports.down = async function (knex) {
8+
await knex.schema.alterTable('peering_invoices', (table) => {
9+
table.dropColumn('payment_attempt_id')
10+
})
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
exports.up = async function (knex) {
2+
await knex.schema.alterTable('peering_invoices', (table) => {
3+
table.timestamp('payment_activity_at', { useTz: true }).nullable()
4+
})
5+
}
6+
7+
exports.down = async function (knex) {
8+
await knex.schema.alterTable('peering_invoices', (table) => {
9+
table.dropColumn('payment_activity_at')
10+
})
11+
}

‎resources/admin/assets/admin-ops.js‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
workersBody,
1313
peeringSync: document.getElementById('peering-sync'),
1414
peeringBody: document.getElementById('peering-body'),
15+
peeringInvoicesSync: document.getElementById('peering-invoices-sync'),
16+
peeringInvoicesBody: document.getElementById('peering-invoices-body'),
17+
peeringBudgetsBody: document.getElementById('peering-budgets-body'),
1518
nip05Error: document.getElementById('ops-nip05-error'),
1619
nip05Domain: document.getElementById('ops-nip05-domain'),
1720
nip05Verified: document.getElementById('ops-nip05-verified'),
@@ -152,8 +155,61 @@
152155
}
153156
}
154157

155-
const renderPeering = (rows) => {
156-
if (!Array.isArray(rows) || !rows.length) {
158+
const peeringInvoiceBadge = (status) => {
159+
const degraded = status === 'held' || status === 'failed' || status === 'rejected'
160+
return `<span class="status-badge${degraded ? ' status-degraded' : ''}"><span class="status-led" aria-hidden="true"></span>${escapeHtml(status)}</span>`
161+
}
162+
163+
const renderPeeringInvoices = (invoices) => {
164+
if (!Array.isArray(invoices) || !invoices.length) {
165+
elements.peeringInvoicesBody.innerHTML =
166+
'<tr><td colspan="6" class="admin-muted small">No buyer invoices yet.</td></tr>'
167+
return
168+
}
169+
170+
elements.peeringInvoicesBody.innerHTML = invoices
171+
.map((invoice) => {
172+
const pending = invoice.status === 'held' || invoice.status === 'failed'
173+
const actions = pending
174+
? `<button type="button" class="btn btn-console btn-sm me-1" data-peering-invoice-action="approve" data-payment-hash="${escapeAttr(invoice.paymentHash)}">Approve</button>
175+
<button type="button" class="btn btn-console btn-sm" data-peering-invoice-action="reject" data-payment-hash="${escapeAttr(invoice.paymentHash)}">Reject</button>`
176+
: ''
177+
const title = [invoice.peerPubkey, invoice.reason || '', invoice.expiresAt || ''].filter(Boolean).join(' · ')
178+
return `<tr>
179+
<td><code class="small" title="${escapeAttr(title)}">${escapeHtml(shortPubkey(invoice.peerPubkey))}</code></td>
180+
<td class="small">${escapeHtml(Math.round(Number(BigInt(invoice.amountMsats) / 1000n)))} sats</td>
181+
<td>${peeringInvoiceBadge(invoice.status)}</td>
182+
<td class="small">${escapeHtml(invoice.reason || '—')}</td>
183+
<td class="small">${escapeHtml(formatTime(invoice.createdAt))}</td>
184+
<td>${actions}</td>
185+
</tr>`
186+
})
187+
.join('')
188+
}
189+
190+
const renderPeeringBudgets = (budgets) => {
191+
if (!Array.isArray(budgets) || !budgets.length) {
192+
elements.peeringBudgetsBody.innerHTML =
193+
'<tr><td colspan="5" class="admin-muted small">No buyer budgets configured.</td></tr>'
194+
return
195+
}
196+
197+
elements.peeringBudgetsBody.innerHTML = budgets
198+
.map((budget) => {
199+
const label = budget.scope === 'global' ? 'All peers' : shortPubkey(budget.peerPubkey)
200+
const title = budget.scope === 'global' ? 'global cap' : budget.peerPubkey
201+
return `<tr>
202+
<td class="small" title="${escapeAttr(title)}">${escapeHtml(label)}</td>
203+
<td class="small">${escapeHtml(formatTime(budget.periodStart))} → ${escapeHtml(formatTime(budget.periodEnd))}</td>
204+
<td class="small">${escapeHtml(Math.round(Number(BigInt(budget.spentMsats) / 1000n)))} sats</td>
205+
<td class="small">${escapeHtml(Math.round(Number(BigInt(budget.remainingMsats) / 1000n)))} sats</td>
206+
<td class="small">${escapeHtml(budget.received)} / ${escapeHtml(budget.paid)} / ${escapeHtml(budget.held)}</td>
207+
</tr>`
208+
})
209+
.join('')
210+
}
211+
212+
const renderPeering = (rows) => { if (!Array.isArray(rows) || !rows.length) {
157213
elements.peeringBody.innerHTML =
158214
'<tr><td colspan="10" class="admin-muted small">No peering peers configured.</td></tr>'
159215
return
@@ -291,9 +347,14 @@
291347
}
292348
const payload = await response.json()
293349
renderPeering(payload.peers)
350+
renderPeeringInvoices(payload.invoices)
351+
renderPeeringBudgets(payload.budgets)
294352
if (elements.peeringSync) {
295353
elements.peeringSync.innerHTML = `<span class="prompt-char">&gt;</span> peers: updated ${formatTime(new Date().toISOString())}`
296354
}
355+
if (elements.peeringInvoicesSync) {
356+
elements.peeringInvoicesSync.innerHTML = `<span class="prompt-char">&gt;</span> buyer invoices: updated ${formatTime(new Date().toISOString())}`
357+
}
297358
}
298359

299360
const buildNip05Query = () => {
@@ -375,6 +436,22 @@
375436
await loadNip05()
376437
}
377438

439+
const decidePeeringInvoice = async (paymentHash, action) => {
440+
const response = await adminFetch('/peering/invoices/decision', {
441+
method: 'POST',
442+
headers: { 'content-type': 'application/json' },
443+
body: JSON.stringify({ paymentHash, action }),
444+
})
445+
const payload = await response.json().catch(() => ({}))
446+
if (!response.ok) {
447+
if (elements.peeringInvoicesSync) {
448+
elements.peeringInvoicesSync.innerHTML = `<span class="prompt-char">&gt;</span><span class="text-danger"> invoice: ${escapeHtml(payload.error || 'decision failed')}</span>`
449+
}
450+
return
451+
}
452+
await loadPeering()
453+
}
454+
378455
const refreshAll = async () => {
379456
const results = await Promise.allSettled([loadWorkers(), loadPeering(), loadNip05()])
380457

@@ -431,6 +508,19 @@
431508
void reverify(pubkey)
432509
})
433510

511+
elements.peeringInvoicesBody?.addEventListener('click', (event) => {
512+
const target = event.target
513+
if (!(target instanceof HTMLElement)) {
514+
return
515+
}
516+
const action = target.getAttribute('data-peering-invoice-action')
517+
const paymentHash = target.getAttribute('data-payment-hash')
518+
if (!action || !paymentHash) {
519+
return
520+
}
521+
void decidePeeringInvoice(paymentHash, action)
522+
})
523+
434524
window.__ADMIN_OPS__ = {
435525
load: () => {
436526
nip05Offset = 0

‎resources/admin/dashboard.html‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,46 @@ <h2 class="section-title">Peering</h2>
253253
</div>
254254
</section>
255255

256+
<section class="dashboard-section">
257+
<h2 class="section-title">Peering invoices</h2>
258+
<p id="peering-invoices-sync" class="sync-line mb-2"><span class="prompt-char">&gt;</span> buyer invoices: not loaded</p>
259+
<div class="table-responsive panel-card mb-2">
260+
<table class="table table-sm mb-0" aria-describedby="peering-budgets-caption">
261+
<caption id="peering-budgets-caption" class="visually-hidden">Buyer spend and remaining budget for the current period</caption>
262+
<thead>
263+
<tr>
264+
<th scope="col">Budget</th>
265+
<th scope="col">Period</th>
266+
<th scope="col">Spent</th>
267+
<th scope="col">Remaining</th>
268+
<th scope="col">Received / paid / held</th>
269+
</tr>
270+
</thead>
271+
<tbody id="peering-budgets-body">
272+
<tr><td colspan="5" class="admin-muted small">No buyer budgets configured.</td></tr>
273+
</tbody>
274+
</table>
275+
</div>
276+
<div class="table-responsive panel-card">
277+
<table class="table table-sm mb-0" aria-describedby="peering-invoices-caption">
278+
<caption id="peering-invoices-caption" class="visually-hidden">Invoices received from peering peers and their auto-pay status</caption>
279+
<thead>
280+
<tr>
281+
<th scope="col">Peer</th>
282+
<th scope="col">Amount</th>
283+
<th scope="col">Status</th>
284+
<th scope="col">Reason</th>
285+
<th scope="col">Received</th>
286+
<th scope="col">Actions</th>
287+
</tr>
288+
</thead>
289+
<tbody id="peering-invoices-body">
290+
<tr><td colspan="6" class="admin-muted small">No buyer invoices yet.</td></tr>
291+
</tbody>
292+
</table>
293+
</div>
294+
</section>
295+
256296
<section id="network-health-section" class="dashboard-section">
257297
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
258298
<h2 class="section-title mb-0">Tor / I2P &amp; network probes</h2>

‎resources/default-settings.yaml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,11 +213,13 @@ peering:
213213
# - pubkey: replace-with-peer-relay-pubkey-in-hex
214214
# relayUrl: wss://peer.example.com
215215
# enabled: true
216+
# # Buying side: auto-pay this peer's invoices up to this budget.
217+
# budget: { amount: 10000, unit: sats, period: 2592000 }
216218
peers: []
217219
# Buying side automatic payment. Invoices are paid only when the peer is
218220
# configured above, the amount matches the peer's advertised NIP-11 terms,
219221
# the payment hash has not been seen, and both budgets have room. Anything
220-
# else is held for operator approval.
222+
# else is held for operator approval in the admin console.
221223
autoPay:
222224
enabled: false
223225
# Optional cap across every peer, per this budget's own period.

0 commit comments

Comments
 (0)