Repository navigation
feat: pay bolt11 Lightning invoices via /api/v1/send - #72
Conversation
0xMadie
left a comment
There was a problem hiding this comment.
BackendBanda Code Review — PR #72: bolt11 Lightning invoice payments
Review effort: 4/5 | Reviewer: backend-banda | Date: 2026-10-14
Summary
Solid, well-structured feature. The core correctness concerns (double-spend, false settlement confirmation, replay attacks) are all addressed. A few things need fixing or a decision before merge.
✅ What's good
HMAC single-use enforcement (middleware.go)
signatureSet.claim()with in-memory map + TTL = correct approach. Eviction on each call avoids unbounded growth. The TTL is2 * toleranceseconds — wide enough to cover the full valid window.- Future-timestamp rejection (
age < -tolerance) closes the captured-request replay window. Breaking change called out clearly in PR description.
Settlement polling (settlement.go)
WaitForOutgoingPayment→ polling loop with exponential backoff (500ms → 3s cap × 1.5). Correctly stays inside the 90s write timeout viasettlementBudgettrimming against elapsed time since request start.classifyPaymentis appropriately conservative:paid:falsewith no status →PaymentStateUnknown, never failure. This avoids falsely telling callers their sats came back.- Settlement preimage zero-value guard (
strings.Trim(preimage, "0") == "") is correct — lnbits returns all-zero preimage for unsettled payments. - Test coverage of all lnbits response shapes including public-key response (no
status) →PaymentStateUnknown. Good.
Balance reservation under concurrency (balance_reservation.go)
- Per-sender
sync.Mutexserialises the check-then-reserve step.once.DoinRelease()prevents double-release. The concurrent stress test (50 goroutines × 100 sat from 1000 balance → exactly 10 granted) is clean and passes. - Reservation released immediately after
lnbits.Payaccepts, not after settlement polling: correct — lnbits already reflects the deduction once accepted, so holding longer would double-count.
Idempotency (two-layer)
- Short MemoCache lock (concurrent requests, ~5 min) + durable
InvoiceApprovalLockin Bunt (24h, for re-submitted approvals) — the gap between them is documented and addressed. - Invoice payment hash validated as
^[0-9a-f]{64}$before use in lnbits URL. ✅
Approval flow (api_approval.go)
- Per-request
apiApprovalMarkupavoids the race between concurrent approval messages overwriting shared callback data. - Expiry check at approve-time (
time.Now().After(approvalData.expiresAt())) with backwards-compat fallback for old approvals (CreatedAt + PendingTxExpiry). Correct. - Failed Telegram delivery → immediate error + rollback (
abandonPendingTransaction), not a silent 202. ✅
🔴 Must-fix before merge
1. signatureSet is process-local — multi-instance deployments allow replay
var usedSignatures = &signatureSet{...} lives in Go process memory. If the bot runs as more than one instance (e.g. two pods, or a restart mid-tolerance-window), a captured signature can be replayed against the second instance.
For a single-process bot this is fine; for any scaled deployment it is not. Either:
- Document explicitly that the bot must run as a single instance, and add a startup log warning if that changes, OR
- Move the seen-signature store to Bunt (same pattern as
InvoiceApprovalLock) with a TTL-based cleanup.
Action needed: at minimum, a comment in signatureSet stating the single-instance assumption. If multi-instance is in the roadmap, make it Bunt-backed now.
2. MemoCache TTL for the concurrent invoice lock is undocumented / unclear
s.MemoCache.SetNX(lockKey, "locked") is used without a TTL here (in sendToInvoice). The comment says "short lock...expires after 5 minutes" but I don't see where that TTL is set. If MemoCache entries never expire, the lock is permanent: a request that dies after SetNX but before defer Delete (e.g. server crash, panic) would permanently block that invoice from being paid.
Please confirm: does MemoCache have a global TTL? If not, add an explicit TTL to this SetNX call (e.g. 10 minutes), or document the GC/restart recovery path.
3. SendPaymentStatus (GET /api/v1/send/payment/{hash}) has a zero-timeout single lookup
settlement := s.Bot.Client.WaitForOutgoingPayment(*fromUser.Wallet, paymentHash, 0)With timeout=0, WaitForOutgoingPayment does at most one rate-limited check. If lnbits is slow or the rate limiter is busy, this could return PaymentStateUnknown for a payment that would resolve within 1s. The caller gets unknown and has to retry anyway — so the endpoint is not saving them a round trip.
Suggest: a short timeout (e.g. 5s) so a single poll has a chance to land, while still returning promptly. Or document that callers should expect unknown and retry with backoff.
🟡 Non-blocking observations (address in follow-up or now, author's call)
4. lnbc... / lightning: prefix lowercased before invoice check
strings.ToLower(req.To) before lightning.IsInvoice — fine for the prefix, but bolt11 invoices themselves use bech32 which is case-insensitive. decodepay handles upper/lower, so this is safe. Just noting it's intentional.
5. Approval-flow invoice path: reservation acquired in approveAPITransactionHandler but not in executeApprovedInvoicePayment?
In the non-invoice approval path, ReserveBalance is called before the transfer and deferred-released. In executeApprovedInvoicePayment, I don't see an equivalent reservation — the approval handler reserves, but does it hold through the pay call? Please verify the reservation is not released before lnbits.Pay returns, or add one inside executeApprovedInvoicePayment.
6. payment_hash in pending transaction ID is included in plain text
id := fmt.Sprintf("pending-%s-invoice-%s-%d", ...) — the payment hash is part of the bunt key. Payment hashes are public on the Lightning network so this is not a secret, but if bunt keys are ever logged or exposed, it ties a username to a specific payment. Minor.
7. Test for SendPaymentStatus endpoint is missing
The settlement_test.go covers classifyPayment well. The HTTP handler itself (SendPaymentStatus) has no test. At minimum an integration-style test that exercises the auth check and the hash validation would catch regressions.
Verdict
Approve with blocking comments resolved. Issues 1 and 2 need a documented answer or a code fix; issue 3 needs at minimum a comment. Non-blocking items can go in a follow-up.
go build ./... and go test ./... are reported clean; I cannot run them locally (no repo access) but the test coverage on the new packages is solid.
⚠️ Note for merge: this PR changes the HMAC auth contract for ALL existing/send,/userbalance,/usertransactions, and status callers. Any client that retries with the same timestamp+signature will receive401 Request already processed. Make sure existing integrations (CeyFi, DCA bot) sign fresh timestamps on every request including retries before merging to main.
— backend-banda (T-0025)
9136a98 to
b89da36
Compare
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configuration
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
/api/v1/send now accepts a bolt11 invoice (lnbc..., optionally with a
lightning: prefix) as `to` and pays it externally. The amount comes from
the invoice; amountless invoices are rejected.
- Validate invoice amount against min/max limits and the admin approval
threshold, and require a 2% routing-fee reserve.
- Reserve sender balance per user so concurrent sends cannot overspend.
- Idempotency on the payment hash: short in-memory lock plus a durable
24h approval lock, so the same invoice is never paid twice.
- Wait for the payment to settle (settlement_timeout) before reporting
success; unsettled payments return 202 pending, never a false failure.
- Add GET /api/v1/send/payment/{payment_hash} to resolve in-flight
payments (waits up to 5s per call).
- Telegram approval flow supports invoices, with expiry checks and
rollback when the approval message cannot be delivered.
- HMAC: each signed request is single-use and future timestamps are
rejected. Clients must sign a fresh timestamp on every retry. The
used-signature set is in memory, so the bot must run as one instance.
- Docs: docs/invoice-payments-api.md and updated referral-api.md.
- HMAC: valid, expired, future, wrong secret, tampered body/path, missing headers, replay rejected, fresh-timestamp retry allowed. - /send: bad JSON, auth, unknown wallet, undecodable and amountless invoices, amount taken from the invoice for min/max checks. - /send/payment: hash validation and auth.
|
@0xMadie thanks for the review. Fixes are in Must-fix
Non-blocking
Merge note: agreed. CeyFi and the DCA bot must sign a fresh timestamp on every request, including retries, before this is deployed. |
rayaanr
left a comment
There was a problem hiding this comment.
Thoughtful change: the settlement classification, in_flight status, balance reservation and single-use signatures are all well considered. Since this moves real sats, I'd want the four "Should fix" items below addressed before merge. Details are in the inline comments.
Should fix
- Re-submitting an already-paid or in-flight invoice returns a misleading
400(no durable dedup on the direct path), and the docs define that400as "safe to pay a different invoice". - Any
Wallet.Payerror is treated as a definitive failure, including transport errors where the payment may be in flight. - Approval path status bookkeeping: the transaction stays
pendingduringPayand the settlement wait (neverapproved), so a restart mid-wait ends inexpired. A failedPayor an insufficient-balance approval also stayspendingand blocks the invoice for 24h. - Invoice expiry is never checked (
Decodepaydoesn't reject expired invoices), which matters most for the 24h approval window.
Worth discussing: replay protection collides on identical same-second requests (e.g. parallel status polls) and the restart comment understates the window.
Verification
go build ./...passes.internal/lnbitsandinternal/utilstests pass.- The new
internal/apitests pass under-race, but only after symlinkingtranslations/into the package dir. Without it,internal/apipanics at i18n init (open translations/en.toml), asinternal/telegramdoes. The PR description only mentions telegram. - With
translations/symlinked,internal/telegramstill failsTestReferralLookupQueryand two tooltip tests, in files this PR doesn't touch. I didn't check whether they also fail onmain. - The only checks on this PR are CodeQL, so no
go testgates the merge. A CI test step (plus aTestMainchdir for the i18n path) would help. - No tests cover the
WaitForOutgoingPaymentpoll loop (anhttptestserver would do) or thesendToInvoicesettlement branches.
Generated by Claude Code
| // Pay the invoice | ||
| log.Infof("[api/send] Paying invoice for %s (%d sat)", fromUsername, amount) | ||
| payStart := time.Now() | ||
| inv, err := fromUser.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: paymentRequest}, s.Bot.Client) |
There was a problem hiding this comment.
Should fix (1/2): re-submitting an invoice that was already paid or is in flight returns a misleading 400.
The direct-pay path has no durable dedup. The MemoCache lock (line 493) is deleted when the handler returns, which is after the 200/202 has already gone out. A retry of the same invoice goes straight to Wallet.Pay, and lnbits presumably rejects the duplicate, so the caller gets 400 "Invoice payment failed".
The docs define a 400 payment failure as "the sats were not sent… safe to pay a different invoice for the same order". A client that retries after a timeout can conclude failure and pay a second invoice for the same order.
Suggested fix: before calling Pay, look the hash up (Client.Payment). If a payment already exists, answer with its settled or pending result (200/202, same body shape) instead of calling Pay again.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in b0a29aa. Before paying, sendToInvoice now looks up the hash in the sender wallet (Client.PriorPayment). If a payment exists and is settled or still pending, it answers 200/202 with the same body shape and does not call Pay. Only a failed earlier payment is paid again. If the lookup itself fails, it returns 400 saying nothing was paid by this request and to retry the same invoice.
| } | ||
| // Keep the raw error in the logs only — it can carry the internal | ||
| // lnbits host/port, which must not reach the API caller. | ||
| RespondError(w, "Invoice payment failed") |
There was a problem hiding this comment.
Should fix (2/2): any error from Wallet.Pay is reported as a definitive failure.
Wallet.Pay (internal/lnbits/lnbits.go:257) returns one err for both an lnbits rejection (non-2xx) and a transport failure, and its client timeout is 24h. A connection reset or an lnbits restart mid-request would be answered with 400 Invoice payment failed, even though the payment may be in flight. The same applies to executeApprovedInvoicePayment in internal/telegram/api_approval.go.
Suggested fix: when the error is not a parsed lnbits HTTP error, check the hash (known from the invoice) with WaitForOutgoingPayment and answer pending/unknown rather than failed.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in b0a29aa. Added lnbits.IsPaymentRejected: only a 4xx from lnbits counts as a definitive failure. Transport errors and 5xx answers fall through to WaitForOutgoingPayment on the invoice hash, so the caller gets settled/failed/pending/unknown from the real state. Same change in executeApprovedInvoicePayment.
| RespondError(w, "Invalid Lightning invoice") | ||
| return | ||
| } | ||
| amount := int64(bolt11.MSatoshi / 1000) |
There was a problem hiding this comment.
Should fix: invoice expiry is never checked.
decodepay.Decodepay does not reject expired invoices. The PR's own fixtures in send_test.go are described as "long expired" and still decode and reach the amount checks. That makes the docs line "Expired or malformed invoices are rejected (either at decode time with 400…)" inaccurate.
This matters most for the approval flow. Invoices typically live about an hour, but an approval stays actionable for 24h, so an operator can be asked to approve a payment that can no longer succeed.
Suggested fix: reject if bolt11.CreatedAt + Expiry is in the past at submit time, and re-check it in executeApprovedInvoicePayment before calling Pay.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in b0a29aa. Expired invoices are now rejected with 400 Invoice has expired before anything is paid. The pending transaction expiry is capped at the invoice expiry, so the approval closes with the invoice. executeApprovedInvoicePayment re-checks expiry before Pay (covers approvals created before this change) and marks the transaction failed. Docs updated.
| if bot.ErrorLogger != nil { | ||
| bot.ErrorLogger.LogPaymentError(err, approvalData.Amount, approvalData.Memo, approvalData.Invoice, from.Telegram) | ||
| } | ||
| bot.tryEditMessage(ctx.Callback().Message, "❌ Invoice payment failed", &tb.ReplyMarkup{}) |
There was a problem hiding this comment.
Should fix (1/2): a dead approval stays pending and keeps blocking the invoice.
This branch and the insufficient-balance branch (if reservation == nil, line 261) edit the message (buttons gone) and return without updating the PendingTransaction. Consequences:
/api/v1/send/statuskeeps reportingpendingfor 24h and thenexpired. The docs sayfailedcovers "approved and attempted", but aPayrejection never produces it.FindPendingInvoiceApprovalstill sees a live approval (CanBeApproved()is true while status ispending), so resubmitting the same invoice is rejected with "already has an approval request awaiting confirmation" for 24h, even though nothing can approve it.
Suggested fix: call storage.UpdatePendingTxStatusFn(approvalData.TransactionID, storage.TxStatusFailed, ...) on both branches. For the transient insufficient-balance case, consider leaving the buttons in place so the operator can retry.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in b0a29aa. A rejected Pay now marks the transaction failed, so it no longer blocks a resubmission. For insufficient balance and a failed balance check I took your second suggestion: the Approve/Cancel buttons stay and the transaction stays pending, since it is still approvable. The operator can top up and approve again, or cancel. Docs updated.
| // lnbits answers as soon as it has handed the payment to its backend, which | ||
| // is not the same as the sats reaching the destination node. Follow the | ||
| // payment to a terminal state before reporting it as paid. | ||
| settlement := bot.Client.WaitForOutgoingPayment(*from.Wallet, paymentHash, internal.APISendSettlementTimeout()) |
There was a problem hiding this comment.
Should fix (2/2): the transaction is still pending while Pay and the settlement wait run.
approved is only set by pt.Approve(), which the Telegram path never calls. So from approval until the wait ends (up to settlement_timeout), /send/status reports pending. If the process restarts during that window, the record stays pending and is later reported expired. That is the exact failure in_flight was introduced to prevent. It also means the documented approved status is never emitted.
Suggested fix: right after Pay succeeds (before this WaitForOutgoingPayment), set TxStatusInFlight. Then move it to executed or failed once the wait resolves.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in b0a29aa. Status now goes approved (right before Pay, after the approval is inactivated) -> in_flight (right after Pay returns, before the settlement wait) -> executed / failed. A restart mid-wait leaves it in_flight, never expired. The docs now say an approved that lasts longer than settlement_timeout should be resolved via /send/payment/{payment_hash}.
| // A valid signature is single use. Without this, a captured /send | ||
| // request could be replayed inside the tolerance window to move the | ||
| // same sats again. | ||
| if !usedSignatures.claim(signature, time.Duration(2*tolerance)*time.Second) { |
There was a problem hiding this comment.
Worth discussing: replay protection compatibility and restart behaviour.
- Timestamps have one-second resolution. Two identical requests in the same second produce the same signature, and the second gets
401 Request already processed. That affects parallel or retried status polls (GETwith empty body) and repeated/userbalancecalls. The PR description calls out the behaviour change; please confirm the existing consumers (e.g. the referral lookup client) already sign each request freshly. A client-supplied nonce included in the signed message would remove the collision. - The comment at line 157 says a restart is safe because the set is empty for at most one timestamp window. That understates it: after a restart, any captured request whose timestamp is still inside the tolerance window can be replayed once. Invoice payments are protected by lnbits, but internal
/sendhas no equivalent. Acceptable for a single instance, but I'd reword the comment to say so.
Generated by Claude Code
| | **Amountless invoices** | **Not supported** — rejected with `400`. The invoice must encode an amount. | | ||
| | **Minimum amount** | Invoice amount must be greater than `min_amount` (default **1 sat**). | | ||
| | **Maximum amount** | Invoice amount must not exceed the wallet's `max_amount` (global default **1,000,000 sats**; may be set lower per wallet). | | ||
| | **Admin approval threshold** | Amounts above `admin_approval_threshold` (global default **50,000 sats**; may be per wallet) are held for operator approval and return `202` instead of paying immediately. | |
There was a problem hiding this comment.
Nit: the default approval threshold is wrong here. The doc says a global default of 50,000 sats, and the sample awaiting_approval response uses threshold: 50000. internal/config.go defaults AdminApprovalThreshold to 100,000 and config.yaml.example sets 100000.
Also, the "Invoice validity" row (line 348) says expired invoices are rejected at decode time. That isn't true today, see my comment on send.go.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 0f6c5c5. The docs now say the global default is 100,000 sats, and the sample awaiting_approval / status responses use threshold: 100000 with a 150,000 sat amount.
| // the import graph (lnbits -> satdress -> network -> internal), so without it | ||
| // a unit test that never talks to lnbits still cannot run unless a full | ||
| // operator config.yaml sits in its package directory. | ||
| func underTest() bool { |
There was a problem hiding this comment.
Nit: underTest() weakens a production guard for test convenience. Sniffing os.Args to skip the "please configure a lnbits url" panic means production config validation now depends on how the binary was invoked. I'd prefer fixing the cause: the lnbits → satdress → network → internal import chain shouldn't need a full operator config at init. Alternatively, have tests opt in explicitly (e.g. an env var set in TestMain) instead of detecting go test from the process arguments.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 0f6c5c5. Removed underTest(). The lnbits url check is now internal.CheckLnbitsConfiguration(), which main() calls at startup, so it no longer runs from package init. Production still panics without a url; tests just no longer need a full config to load the import chain.
|
|
||
| // RateLimiter enforces a shared rate limit of 150 req/min (safely below LNbits' | ||
| // 200/min limit) across every caller that polls lnbits in a loop. | ||
| var RateLimiter = rate.NewLimiter(rate.Every(400*time.Millisecond), 1) |
There was a problem hiding this comment.
Nit: settlement polls now compete with analytics for the same 150/min budget. Under heavy analytics load, a settlement check can wait on the limiter until its deadline and come back unknown, so a payment that actually settled is reported as a 202. Not wrong, since unknown is handled safely, but a separate limiter (or priority) for settlement would keep payment answers from depending on analytics traffic.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 0f6c5c5. Settlement checks (WaitForOutgoingPayment, PriorPayment) now use their own limiter: 60/min with a burst of 3. Analytics keeps RateLimiter, lowered from 150/min to 120/min so the two together stay under the 200/min lnbits limit.
- Look up an invoice's existing payment before paying it, so a retry of a paid or in-flight invoice gets its real result instead of a 400. - Treat only a 4xx from lnbits as a rejected payment; follow the payment hash after transport errors and 5xx answers. - Track approval status through approved, in_flight and executed/failed. Mark rejected payments failed, and keep the buttons when the balance is too low so the operator can retry. - Reject expired invoices, close the approval window at invoice expiry and re-check expiry before paying an approved invoice.
|
@rayaanr thanks for the review. All four "Should fix" items are fixed in Not addressed yet: the replay-protection discussion, the three nits (default threshold in docs, Verification: |
Summary
Adds external bolt11 Lightning invoice payments to the existing
/api/v1/sendendpoint. Whentois alnbc...payment request (optionallylightning:-prefixed), the bot pays it externally via lnbits instead of doing an internal transfer.What changed
Invoice payments
tomatching a bolt11 invoice routes tosendToInvoice; the amount comes from the invoice (amountless invoices are rejected).Settlement confirmation
settlement_timeout, default 60s, kept inside the 90s server write timeout).200 settled(withpreimageand realfee),400 failed(withpayment_hash), or202 pending(do not retry).GET /api/v1/send/payment/{payment_hash}to resolve a pending payment; approved payments that stay unresolved are recorded asin_flight, neverexpired.Concurrent payments
Security / review fixes
payment_hashis validated (64 hex chars) before it reaches an lnbits URL.202./api/v1/send/status.lnbits 1.x
timeaccepts RFC3339 strings; paymentstatus(success/pending/failed) is read. Branch is up to date withmain(lnbits 1.x account API)./send,/userbalance,/usertransactions,/referral/lookup, status endpoints) now reject a reused signature (401 Request already processed). Clients must sign every request, including retries, with a freshX-Timestamp.Docs
docs/invoice-payments-api.mddocs/referral-api.mdandREADME.md.api.send.settlement_timeout(seconds, default 60).Testing
go build ./...cleango test ./internal/lnbits/ ./internal/utils/passtelegrampackage tests run from the repo root (i18n loadstranslations/relative to the working directory).🤖 Generated with Claude Code