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) } // markHandled records paymentHash and reports whether this is the first time. func (w *Server) markHandled(paymentHash string) (first bool, err error) { err = w.buntdb.Update(func(tx *buntdb.Tx) error { _, replaced, err := tx.Set("webhook:"+paymentHash, "1", nil) 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 } // Handle every payment once, so a webhook can't be replayed. first, err := w.markHandled(webhookEvent.PaymentHash) 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) // trigger invoice events txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}} err = w.buntdb.Get(txInvoiceEvent) if err != nil { log.Errorln(err) } 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) }