Files
MichilisandClaude Opus 5.5 8faab56990 Harden LNURLcash, webhook replay and ticket restarts; add command aliases
- LNURLcash: mint single notes directly when the mint rounds fees to whole
  sats, recover lost direct-note funding, melt to the callback named in the
  note's own withdraw info, and poll for settlement so redeems/reclaims
  finish without waiting on the webhook. Read-only lookups use a pooled
  client; every mutation stays on the no-keep-alive client.
- Webhook: expire replay markers only for payments without an invoice event,
  so an event callback can never run twice.
- Tickets: on restart, enforce tickets that ran out while the bot was down
  unless LNbits says the invoice was paid; drop stale ones without a ban.
- Telegram: register translated /faucet and /tipjar command aliases.
- i18n: load translations from one language list and log broken files.
- Config example: one entry per mint; ignore local docs/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:20:52 +00:00

229 lines
7.8 KiB
Go

package webhook
import (
"encoding/json"
"fmt"
"io"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook/verify"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
"github.com/tidwall/buntdb"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
// maxBodyBytes bounds the webhook request body. A real LNbits payload is a
// few hundred bytes.
const maxBodyBytes = 1 << 20
type Server struct {
httpServer *http.Server
bot *tb.Bot
c *lnbits.Client
database *gorm.DB
buntdb *storage.DB
}
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int64 `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: bot.Client,
database: bot.DB.Users,
bot: bot.Telegram,
httpServer: srv,
buntdb: bot.Bunt,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[Webhook] Server started at %s", internal.Configuration.Lnbits.WebhookServerUrl)
return apiServer
}
func (w *Server) GetUserByWalletId(walletId string) (*lnbits.User, error) {
user := &lnbits.User{}
tx := w.database.Where("wallet_id = ?", walletId).First(user)
if tx.Error != nil {
return user, tx.Error
}
return user, nil
}
// settledAmount returns the amount in msat that LNbits says the user's wallet
// received for paymentHash. It fails unless that payment is settled.
func (w *Server) settledAmount(user *lnbits.User, paymentHash string) (int64, error) {
payment, err := w.c.Payment(*user.Wallet, paymentHash)
// LNbits sends a webhook only once, so a short LNbits hiccup must not
// lose the payment event.
for try := 0; err != nil && try < 2; try++ {
time.Sleep(time.Second)
payment, err = w.c.Payment(*user.Wallet, paymentHash)
}
if err != nil {
return 0, err
}
return verify.SettledIncoming(verify.Payment{
Paid: payment.Paid,
PaymentHash: payment.Details.PaymentHash,
WalletID: payment.Details.WalletID,
AmountMsat: payment.Details.Amount,
}, paymentHash, user.Wallet.ID)
}
// handledTTLWithoutEvent is how long the replay marker of a payment without an
// invoice event is kept. A replay of such a payment only repeats the "you
// received" message, so the marker doesn't need to outlive LNbits' retries.
const handledTTLWithoutEvent = 7 * 24 * time.Hour
// markHandled records paymentHash and reports whether this is the first time.
// A marker with an expiry is only safe when no invoice event exists for the
// payment: invoice events are kept forever, and replaying one after its marker
// expired would run its callback (which may pay out) a second time.
func (w *Server) markHandled(paymentHash string, hasEvent bool) (first bool, err error) {
var opts *buntdb.SetOptions
if !hasEvent {
opts = &buntdb.SetOptions{Expires: true, TTL: handledTTLWithoutEvent}
}
err = w.buntdb.Update(func(tx *buntdb.Tx) error {
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", opts)
first = !replaced
return err
})
return first, err
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
return router
}
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
webhookEvent := Webhook{}
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, maxBodyBytes))
if err != nil {
log.Errorf("[Webhook] Error reading request body: %s", err.Error())
writer.WriteHeader(400)
return
}
if err = json.Unmarshal(body, &webhookEvent); err != nil {
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
writer.WriteHeader(400)
return
}
// The hash becomes part of an LNbits URL and of the replay key, so only
// the form LNbits uses is accepted.
if !verify.ValidPaymentHash(webhookEvent.PaymentHash) {
log.Errorf("[Webhook] Rejecting webhook with malformed payment_hash")
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil || user.Wallet == nil || user.Wallet.ID == "" {
log.Errorf("[Webhook] Error getting user for wallet_id %q: %v", webhookEvent.WalletID, err)
writer.WriteHeader(400)
return
}
// Anyone who can reach this port can send a webhook, so the body is only
// a hint. Ask LNbits whether this wallet really received the payment and
// use the amount LNbits reports.
amountMsat, err := w.settledAmount(user, webhookEvent.PaymentHash)
if err != nil {
log.Errorf("[Webhook] Rejecting webhook for payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
writer.WriteHeader(400)
return
}
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
eventErr := w.buntdb.Get(txInvoiceEvent)
// Handle every payment once, so a webhook can't be replayed. Any lookup
// error other than "not found" counts as an event, which keeps the marker.
first, err := w.markHandled(webhookEvent.PaymentHash, eventErr != buntdb.ErrNotFound)
if err != nil {
log.Errorf("[Webhook] Error storing payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
writer.WriteHeader(500)
return
}
if !first {
log.Infof("[Webhook] Ignoring repeated webhook for payment_hash %s", webhookEvent.PaymentHash)
writer.WriteHeader(200)
return
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, amountMsat/1000))
writer.WriteHeader(200)
if eventErr != nil {
log.Errorln(eventErr)
} else if txInvoiceEvent.User != nil && txInvoiceEvent.User.Wallet != nil && txInvoiceEvent.User.Wallet.ID != user.Wallet.ID {
// the event was registered for another wallet than the one LNbits paid
log.Errorf("[Webhook] Invoice event for payment_hash %s belongs to wallet %s, not %s. Not dispatching.",
webhookEvent.PaymentHash, txInvoiceEvent.User.Wallet.ID, user.Wallet.ID)
return
} else {
// do something with the event
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
if err := telegram.AssertEventType(txInvoiceEvent, c.Type); err != nil {
log.Errorln(err)
return
}
go runCallback(c.Function, txInvoiceEvent)
return
}
}
// fallback: send a message to the user if there is no callback for this invoice
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), amountMsat/1000))
if err != nil {
log.Errorln(err)
}
}
// runCallback runs an invoice callback in its own goroutine. Telegram handlers
// recover from panics, but these callbacks run outside of telebot, so a panic
// in one would otherwise take the whole bot down.
func runCallback(f func(telegram.Event), ev telegram.Event) {
defer func() {
if r := recover(); r != nil {
log.Errorf("[Webhook] panic in invoice callback: %v", r)
}
}()
f(ev)
}