Accepting Lightning payments without holding anyone's money: how my API checks invoices, proves payment and signs webhooks

2026-11-22来源 dev.toEnglish
Accepting Lightning payments without holding anyone's money: how my API checks invoices, proves payment and signs webhooks

The short version. If your app takes Lightning payments through someone else's API, that someone usually holds the money. I built one that doesn't. Your customer pays straight to your own Lightning address; my server only fetches the invoice, checks it wasn't swapped, waits for proof of payment and tells your app with a signed webhook. This post walks through every check in the real code, the bug I found in my own settlement logic while writing it (and the fix), and a sandbox you can run for free in 15 minutes.

Table of contents

  • Why "no custody" changes the design
  • The flow in one picture
  • Check 1: the address must name itself
  • Check 2: the invoice must be the one you asked for
  • Check 3: paid means a preimage, not a yes
  • Settling exactly once
  • Signed webhooks and how to verify them
  • Try it: the sandbox, with real output
  • Going live and what it costs
  • Honest limits and open questions

GitHub logo altradits / altradits

YeBente is a free Bitcoin Lightning wallet for everyday people. Its AI agency now thinks with Meta Muse.

Altradits

Tests and security checks License: MIT

The code behind altradits.com: free Bitcoin tools and learning for people new to Bitcoin, including Ye₿ente, a custodial Bitcoin Lightning wallet for everyday amounts, and the admin dashboard that runs the Lightning node behind it.

What lives here

  • server.mjs, api/: the website and its API (Node.js, no framework).
  • lib/: shared code: wallets, Lightning, receipts, mail, security.
  • yebente/: the Ye₿ente wallet app (React + Vite). The shipped build in yebente/app is committed with the source that produced it.
  • assets/admin.js, admin.html: the node operator dashboard.
  • test/: the test suite, including the build-stage security guard.
  • docs/: manuals and guides (setup, Lightning, review process).
  • deploy/, .github/: signed-merge tooling, deploy and CI.

Quick start

Requirements: Node.js 20 or newer (CI runs 24).

npm ci --ignore-scripts cp .env.example .env npm run dev

Open http://localhost:3000 (admin: /admin, token dev on a local machine only)…

Why "no custody" changes the design

Most payment APIs work like this: the customer pays the provider, the provider keeps a balance for you, and you withdraw later. That's simple to build. It also means the provider holds other people's money, which in Kenya (where I build) quickly becomes a licensing question, and anywhere becomes a trust question.

I wanted the opposite. The developer's customers pay straight to the developer's own Lightning address. My server never receives those sats, never forwards them, and never takes a cut in flight. Its node key can only create invoices and read whether they were paid.

That one rule moves all the hard work into verification. If I'm not the one being paid, I have to prove three things from the outside:

  1. The address really belongs to the developer, not a typo that lands on a stranger.
  2. The invoice the address returns is for exactly what was asked, and wasn't swapped on the way.
  3. "Paid" really means paid.

Each section below is one of those checks, with the code that does it. All links are pinned to commit 4569720 so the line numbers stay true.

The flow in one picture

 Your app Altradits API Your Lightning address | POST /v1/invoices | | |------------------------>| GET /.well-known/lnurlp/<you> | | |---------------------------------->| | | payRequest (callback, metadata) | | |<----------------------------------| | | GET callback?amount=<msat> | | |---------------------------------->| | | { pr: bolt11, verify: url } | | |<----------------------------------| | | check amount + description hash | | bolt11 (unchanged) | | |<------------------------| | | | Customer pays the bolt11 ---- sats go straight to you ---------->| | | GET verify url (LUD-21) | | |---------------------------------->| | | { settled, preimage } | | |<----------------------------------| | | sha256(preimage) == payment_hash?| | invoice.settled (signed webhook) | |<------------------------| | 

The protocols are all public: LNURL-pay (LUD-06), Lightning addresses (LUD-16) and the verify endpoint (LUD-21). The work is in not trusting any single answer.

Check 1: the address must name itself

When you register you@wallet.com, the server fetches https://wallet.com/.well-known/lnurlp/you and reads the metadata field. LUD-16 says the metadata should include a text/identifier entry naming the address. I require it, and I require it to match exactly (resolveDestination, lines 277–306):

const id = Array.isArray(meta) ? meta.find((m) => Array.isArray(m) && m[0] === "text/identifier")?.[1] : null; // ... names = `${p.user}@${p.domain}` === canonical; // ... if (!names) throw err("That address doesn't name itself, so it can't be registered.", "address_mismatch", 422); 

Why bother? Without it, a typo like stanely@wallet.com could resolve to somebody else's wallet, and every customer payment would go to them. A self-naming address at least proves the server you reached agrees it is the address you typed.

The callback URL is also fenced: https: only, no user:pass@ in the URL, and never a bare IP address. Requests go through a guard that refuses private and loopback ranges at connect time, so a hostile address can't make my server probe its own network.

Then the developer proves control by paying a 1-sat challenge invoice from the wallet behind the address. Honest scope: Lightning payments carry no sender identity, so this proves "controls a funded wallet and an address that names itself", not cryptographic ownership.

Check 2: the invoice must be the one you asked for

Every new invoice triggers a fresh payRequest, even for a destination registered last month. That re-checks the address still names itself and picks up the current limits (destinationInvoice, lines 469–517). Then two checks on the BOLT11 that comes back:

if (!pr || bolt11Msats(pr) !== msats) { substitution(host, `asked ${msats} msat, got ${bolt11Msats(pr)}`); throw err("The destination returned an invoice for a different amount.", "invoice_mismatch", 502); } const dh = bolt11DescriptionHash(pr); if (dh && typeof pay.metadata === "string" && dh !== sha(pay.metadata)) { substitution(host, "description hash doesn't match the destination's metadata"); throw err("The destination returned an invoice for something else.", "invoice_mismatch", 502); } 
  1. Exact amount. Not "close enough". If you ask for 2,500 sats and get an invoice for 2,501, it's refused.
  2. Description hash. LNURL-pay invoices commit to sha256(metadata) in the h tag. If the hash doesn't match the metadata I just fetched, the invoice was built for a different payRequest. That's the classic invoice-swap attack, where a compromised server or proxy hands back an invoice that pays someone else.

Both failures are recorded as invoice_substitution in my security log, because they shouldn't happen by accident.

Amounts are whole sats from 1 to 100,000,000, or a fiat amount in USD or KES converted at the live rate. The rate is stored on the invoice, so you can always see what price was used. If the price feed doesn't answer, the request fails with 503 rate_unavailable instead of guessing.

Check 3: paid means a preimage, not a yes

This is the section I had to rewrite, because writing it exposed a bug.

On Lightning, the payee picks a random 32-byte preimage and puts sha256(preimage) in the invoice as the payment hash. Paying the invoice is how the payer learns the preimage. So the preimage is the receipt: anyone can check it by hashing it.

LUD-21 lets a wallet expose a verify URL that answers { "settled": true, "preimage": "..." }. At commit 4569720, my code trusted settled: true and stored whatever 64-hex string came with it (lines 627–630):

// Before: trusts the yes, never checks the proof if (d.settled === true) { const preimage = typeof d.preimage === "string" && HASH_RE.test(d.preimage) ? d.preimage.toLowerCase() : null; return { invoice: publicInvoice(await settleInvoice(inv, { preimage })), verifySupported: true }; } 

A misbehaving or hostile verify endpoint could mark an unpaid invoice "settled". The developer would get a signed webhook saying the order was paid, and would ship goods for money that never arrived.

Worse, my sandbox taught the wrong habit. The simulator drew a random payment hash and, on settle, a separate random preimage. I ran it and hashed the result:

paymentHash e6cafd86b671a1f21920ea09609b614520f06cc3c6684cbf9c17f0ff85efc344 preimage 3d4aa3012741bcc80a43e66ef293c888933b556ea0d5904e95ac357c924281b2 sha256(preimage) c46c2bece215f1877a0b16b6fe7450b5c5a3d8f9e76d3bf7bc836d1741b9df3a ✗ 

A developer who did the right thing and checked the preimage would have seen every sandbox payment fail.

The fix (PR #543) is small:

// Lightning's proof of payment: SHA-256 of the 32-byte preimage is the payment hash. const preimageMatches = (preimage, hash) => crypto.createHash("sha256").update(Buffer.from(String(preimage), "hex")).digest("hex") === String(hash).toLowerCase(); if (d.settled === true) { const preimage = typeof d.preimage === "string" && HASH_RE.test(d.preimage) ? d.preimage.toLowerCase() : null; if (!preimage || !preimageMatches(preimage, inv.paymentHash)) { substitution(u.hostname, preimage ? "verify gave a preimage that doesn't hash to the payment hash" : "verify said settled with no preimage"); return { invoice: publicInvoice(inv), verifySupported: true, note: "The destination says this is paid but gave no valid proof (preimage), so it stays pending here. Confirm in your wallet." }; } return { invoice: publicInvoice(await settleInvoice(inv, { preimage })), verifySupported: true }; } 

And the simulator now does what a real wallet does: preimage first, hash second.

const preimage = crypto.randomBytes(32).toString("hex"); const hash = crypto.createHash("sha256").update(Buffer.from(preimage, "hex")).digest("hex"); 

The same run after the fix:

paymentHash ab940cc8cfbf09d8653a1876b3d03f317e329b1586b2b4be9449b41c5d779e17 preimage d3ff73ddb4674a6670be96bff68e3e195faaa63095e04ab6abf4dc49efd05b5e sha256(preimage) == paymentHash: true ✓ 

There's a new test for the bad cases: a fake wallet that answers settled: true with a wrong preimage, and one with no preimage at all. Both must stay pending, through both GET /invoices/{id} and GET /verify/{hash}. The full suite: 845 pass, 0 fail.

The trade-off: a wallet whose verify endpoint says "settled" but leaves out the preimage now stays pending. LUD-21 returns the preimage once an invoice is settled, so a wallet that follows the spec is unaffected. I chose a false "pending" over a false "paid".

What you should take from this, whatever API you use: check sha256(preimage) == payment_hash yourself before you ship anything. It's one line, and it means you don't have to trust me either.

Settling exactly once

Two requests can check the same invoice at the same moment: your app polling, and the background sweep. Without care, that's two fee deductions and two webhooks. settleInvoice (lines 667–695) takes a lock per invoice, re-reads the record inside it, and returns early if another request already settled it:

const release = await acquireLock(`dev:settle:${inv.id}`, 30); if (!release) return getJSON(`dev:inv:${inv.id}`); try { const cur = await getJSON(`dev:inv:${inv.id}`); if (!cur || cur.status === "settled") return cur; cur.status = "settled"; // ...fee deducted under a second, per-account lock... await queueSettledWebhooks(cur); return cur; } finally { await release(); } 

The fee comes off a prepaid balance under a second lock per account. If several invoices settle at once and together cost more than the balance holds, the balance floors at zero and the shortfall is written on the ledger, instead of going negative or failing a payment your customer already made.

Creating invoices is idempotent too. Send the same Idempotency-Key header with the same body and you get the first reply back, so a retry after a timeout never creates a second invoice.

Signed webhooks and how to verify them

When an invoice settles, every webhook endpoint you registered for invoice.settled gets a POST. The signature follows the Stripe pattern (attemptDelivery, lines 768–809):

X-Dev-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")> 

Failed deliveries retry after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, then stop. Every attempt is kept in a delivery log you can read in the dashboard.

Here's a receiver with no framework, so nothing re-parses the body before you check it:

webhook-receiver.mjs (Node 18+, no dependencies)
import http from "node:http"; import crypto from "node:crypto"; const SECRET = process.env.ALTRADITS_WEBHOOK_SECRET; // shown once when you register the endpoint const WINDOW = 300; // seconds: refuse anything older (replay protection) function verify(raw, header) { const parts = Object.fromEntries(String(header || "").split(",").map((p) => p.split("="))); const t = Number(parts.t); if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > WINDOW) return false; const expected = crypto.createHmac("sha256", SECRET).update(`${t}.${raw}`).digest("hex"); const a = Buffer.from(expected, "hex"); const b = Buffer.from(String(parts.v1 || ""), "hex"); return a.length === b.length && crypto.timingSafeEqual(a, b); // constant time } function provesPayment(inv) { if (!inv.preimage) return false; const h = crypto.createHash("sha256").update(Buffer.from(inv.preimage, "hex")).digest("hex"); return h === inv.paymentHash; } http.createServer((req, res) => { let raw = ""; req.on("data", (c) => { raw += c; if (raw.length > 65536) req.destroy(); }); req.on("end", () => { if (!verify(raw, req.headers["x-dev-signature"])) { res.writeHead(401).end(); return; } const { event, invoice } = JSON.parse(raw); if (event === "invoice.settled" && invoice.status === "settled" && provesPayment(invoice)) { // Mark the order paid. Make this idempotent: the same event can arrive twice. console.log("paid:", invoice.id, invoice.sats, "sats", invoice.memo); } res.writeHead(200).end("ok"); }); }).listen(8787); 

Three habits matter more than the code:

  • Verify against the raw body. If a framework parses JSON and you re-serialise it, key order or whitespace changes and the HMAC won't match.
  • Compare in constant time (timingSafeEqual), and check the timestamp window, so a captured request can't be replayed later.
  • Answer 200 fast and be idempotent. Retries mean you can see the same event twice.

I checked the signature scheme against a real delivery from the sandbox run: the HMAC computed with the endpoint secret matched v1 exactly.

Try it: the sandbox, with real output

The sandbox runs the same code paths with a built-in simulator at dev@sandbox.altradits.com. No network, no node, and invoices use signet encoding (lntb...), so they can't be paid on mainnet by mistake. You get 10,000 test sats of fee credit, and it refills itself.

1. Set up (about 2 minutes). At altradits.com/developer/dashboard, sign in with an email code (no password). Create a key with Test key ticked; it starts with ak_test_ and is shown once. Add the destination dev@sandbox.altradits.com with Sandbox ticked, then click Copy id.

export ALTRADITS_KEY=ak_test_... export ALTRADITS_DEST=<the destination id you copied> 

2. Run this (pay.mjs, Node 18+):

import crypto from "node:crypto"; const API = "https://altradits.com/api/dev/v1"; const headers = { Authorization: `Bearer ${process.env.ALTRADITS_KEY}`, "Content-Type": "application/json", }; async function call(method, path, body, extra = {}) { const res = await fetch(API + path, { method, headers: { ...headers, ...extra }, body: body && JSON.stringify(body) }); const data = await res.json(); if (!res.ok) throw new Error(`${res.status} ${data.code}: ${data.error}`); return data; } // 1. Create an invoice. The Idempotency-Key makes a retry safe. const made = await call("POST", "/invoices", { destinationId: process.env.ALTRADITS_DEST, sats: 2500, memo: "Order 1001" }, { "Idempotency-Key": crypto.randomUUID() }); console.log("invoice:", made.invoice.status, made.invoice.bolt11.slice(0, 24) + "..."); // 2. Play the customer (sandbox only). const paid = await call("POST", "/sandbox/settle", { invoiceId: made.invoice.id }); // 3. Never trust "settled" alone: check the proof yourself. const { paymentHash, preimage, status } = paid.invoice; const proof = crypto.createHash("sha256").update(Buffer.from(preimage, "hex")).digest("hex"); console.log("status:", status, "| proof ok:", proof === paymentHash); 

What the API answers. These are real responses, trimmed for length, from running the same code locally with the fix in place (IDs differ on every run):

Create, check, settle, settle again
// POST /v1/invoices -> 201 { "ok": true, "invoice": { "id": "wcFz9rPYkYsG", "address": "dev@sandbox.altradits.com...

原文:https://www.a8q9.cn/en/article/accepting-lightning-payments-without-holding-anyone-s-money-how-my-api-checks-in-a9f9b5.html

相关文章