Files
LightningTipBot/internal/telegram/lnurlcash.go
T
MichilisandClaude Fable 5.1 3c2ccf8d83 Add the LNURLcash Telegram commands
/note, /notes (list and batch), /redeem and /lnurlmints with confirm
dialogs, group posting with private receipts, claim notifications,
batch export as PDF/JSON/CSV, and LNURLcash notes detected inside the
existing /lnurl, paste and QR-photo flows. Plain withdraw links behave
as before. Two /lnurl log lines no longer print k1.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 22:12:27 +00:00

393 lines
13 KiB
Go

package telegram
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// InvoiceCallbackLNURLCashSettle is the invoice event callback for reclaim and
// redeem invoices; CallbackData carries the lnurlcash reference.
const InvoiceCallbackLNURLCashSettle = 8
// initLNURLCash wires the note service when the feature is enabled.
func (bot *TipBot) initLNURLCash() {
cfg := &internal.Configuration.LNURLCash
if !cfg.Enabled || bot.DB.LNURLCash == nil {
return
}
cipher, err := lnurlcash.NewCipher(cfg.SecretEncryptionKey)
if err != nil {
panic(err)
}
notifier := &lnurlcashNotifier{bot: bot}
registry := lnurlcash.NewRegistry(cfg, bot.DB.LNURLCash, network.NewNoKeepAliveClient(30*time.Second), notifier.Alert)
bot.LNURLCash = lnurlcash.NewService(cfg, bot.DB.LNURLCash, registry, &lnbitsLedger{bot: bot}, cipher)
bot.lnurlcashJobs = lnurlcash.NewJobs(bot.LNURLCash, notifier)
log.Infof("[lnurlcash] enabled with %d mint(s)", len(cfg.Mints))
}
// startLNURLCashJobs runs the background jobs. The bot has no shutdown
// context; the jobs are restart-safe by design.
func (bot *TipBot) startLNURLCashJobs() {
if bot.lnurlcashJobs != nil {
bot.lnurlcashJobs.Start(context.Background())
}
}
// userByName loads a user by the lnbits.User.Name key (Telegram id as text).
func (bot *TipBot) userByName(name string) (*lnbits.User, error) {
id, err := strconv.ParseInt(name, 10, 64)
if err != nil {
return nil, fmt.Errorf("bad user name %q", name)
}
user, err := GetLnbitsUser(&tb.User{ID: id}, *bot)
if err != nil {
return nil, err
}
if user.Wallet == nil {
return nil, fmt.Errorf("user %s has no wallet", name)
}
return user, nil
}
// ---- Ledger: what the note service needs from LNbits ----
type lnbitsLedger struct{ bot *TipBot }
func (l *lnbitsLedger) CreateInvoice(ctx context.Context, userName string, amountSat int64, memo, ref string) (string, string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", "", err
}
invoice, err := user.Wallet.Invoice(lnbits.InvoiceParams{Out: false, Amount: amountSat, Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer}, l.bot.Client)
if err != nil {
return "", "", err
}
event := InvoiceEvent{
Invoice: &Invoice{PaymentHash: invoice.PaymentHash, PaymentRequest: invoice.PaymentRequest, Amount: amountSat, Memo: memo},
User: user,
Callback: InvoiceCallbackLNURLCashSettle,
CallbackData: ref,
LanguageCode: user.Telegram.LanguageCode,
}
runtime.IgnoreError(l.bot.Bunt.Set(event))
return invoice.PaymentRequest, invoice.PaymentHash, nil
}
func (l *lnbitsLedger) PayInvoice(ctx context.Context, userName, pr string) (string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", err
}
paid, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: pr}, l.bot.Client)
if err != nil {
var lnErr lnbits.Error
if errors.As(err, &lnErr) {
return "", err // LNbits answered: definitive
}
return "", &lnurlcash.AmbiguousLedgerError{Err: err}
}
runtime.IgnoreErrorMultiReturn(l.bot.GetUserBalance(user))
return paid.PaymentHash, nil
}
func (l *lnbitsLedger) InvoicePaid(ctx context.Context, userName, hash string) (bool, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return false, err
}
p, err := l.bot.Client.Payment(*user.Wallet, hash)
if err != nil {
return false, err
}
return p.Paid, nil
}
func (l *lnbitsLedger) PaymentSucceeded(ctx context.Context, userName, hash string) (bool, bool, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return false, false, err
}
p, err := l.bot.Client.Payment(*user.Wallet, hash)
if err != nil {
return false, false, err
}
if p.Paid {
return true, false, nil
}
return false, p.Details.Pending, nil
}
func (l *lnbitsLedger) BalanceMsat(ctx context.Context, userName string) (int64, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return 0, err
}
w, err := l.bot.Client.Info(*user.Wallet)
if err != nil {
return 0, err
}
return w.Balance, nil
}
// lnurlcashSettleEvent runs when a reclaim or redeem invoice was paid.
func (bot *TipBot) lnurlcashSettleEvent(event Event) {
ev := event.(*InvoiceEvent)
if bot.LNURLCash == nil {
return
}
st, err := bot.LNURLCash.SettleInvoice(context.Background(), ev.PaymentHash)
if err != nil {
log.Errorf("[lnurlcash] settle %s: %v", ev.PaymentHash, err)
return
}
if st == nil {
return
}
n := &lnurlcashNotifier{bot: bot}
if st.Note != nil {
n.NoteReclaimed(st.Note)
n.GroupNoteState(st.Note)
}
if st.Redeem != nil {
n.RedeemSettled(st.Redeem)
}
}
// ---- Notifier: how the jobs reach Telegram ----
type lnurlcashNotifier struct{ bot *TipBot }
func recipientOf(userName string) *tb.User {
id, _ := strconv.ParseInt(userName, 10, 64)
return &tb.User{ID: id}
}
func (n *lnurlcashNotifier) send(userName, lang, text string, opts ...interface{}) {
if userName == "bot" || userName == "" {
return
}
n.bot.trySendMessage(recipientOf(userName), text, opts...)
}
func (n *lnurlcashNotifier) NoteClaimed(note *lnurlcash.Note) {
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteClaimedNotifyMessage"),
note.ReportedMsat/1000, lnurlcash.ShortID(note.ID), str.MarkdownEscape(note.Memo)))
}
func (n *lnurlcashNotifier) BatchDigest(b *lnurlcash.Batch, claimed []*lnurlcash.Note) {
notes, _ := n.bot.DB.LNURLCash.NotesInBatch(b.ID)
total, done := 0, 0
for _, x := range notes {
if x.Kind != lnurlcash.KindUser {
continue
}
total++
if x.State == lnurlcash.NoteClaimed {
done++
}
}
n.send(b.UserName, b.LanguageCode, fmt.Sprintf(i18n.Translate(b.LanguageCode, "noteBatchDigestMessage"),
len(claimed), lnurlcash.ShortID(b.ID), done, total))
}
func (n *lnurlcashNotifier) NoteReclaimed(note *lnurlcash.Note) {
if user, err := n.bot.userByName(note.UserName); err == nil {
runtime.IgnoreErrorMultiReturn(n.bot.GetUserBalance(user))
}
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteReclaimedMessage"),
note.ReportedMsat/1000, lnurlcash.ShortID(note.ID)))
}
func (n *lnurlcashNotifier) RedeemSettled(r *lnurlcash.Redeem) {
if user, err := n.bot.userByName(r.UserName); err == nil {
runtime.IgnoreErrorMultiReturn(n.bot.GetUserBalance(user))
}
n.send(r.UserName, r.LanguageCode, fmt.Sprintf(i18n.Translate(r.LanguageCode, "redeemDoneMessage"), r.ReportedMsat/1000))
}
// GroupNoteState edits the caption of a note's group post.
func (n *lnurlcashNotifier) GroupNoteState(note *lnurlcash.Note) {
if note.ChatID == 0 || note.MessageID == "" {
return
}
var key string
switch note.State {
case lnurlcash.NoteClaimed:
key = "noteGroupClaimedMessage"
case lnurlcash.NoteReclaimed, lnurlcash.NoteReclaiming:
key = "noteGroupWithdrawnMessage"
default:
return
}
caption := fmt.Sprintf(i18n.Translate("en", key), note.ReportedMsat/1000)
msg := &tb.StoredMessage{MessageID: note.MessageID, ChatID: note.ChatID}
if _, err := n.bot.Telegram.EditCaption(msg, caption); err != nil {
log.Warnf("[lnurlcash] edit group post of %s: %v", note.ID, err)
}
}
func (n *lnurlcashNotifier) Alert(msg string) {
log.Errorf("[lnurlcash] ALERT: %s", msg)
if id := internal.Configuration.LNURLCash.AdminTelegramID; id != 0 {
n.bot.trySendMessage(&tb.User{ID: id}, "⚠️ "+msg)
}
}
// ---- shared handler helpers ----
// lnurlcashReady tells the user the feature is off and reports false.
func (bot *TipBot) lnurlcashReady(ctx intercept.Context) bool {
if bot.LNURLCash != nil {
return true
}
bot.trySendMessage(ctx.Sender(), Translate(ctx, "lnurlcashDisabledMessage"))
return false
}
// sendPrivate sends to the user's private chat and reports whether Telegram
// accepted it, which it does not when the user never started the bot.
func (bot *TipBot) sendPrivate(user *tb.User, what interface{}, opts ...interface{}) (*tb.Message, bool) {
msg := bot.trySendMessageEditable(user, what, opts...)
return msg, msg != nil
}
// lnurlcashErrorText maps a service error to a user message.
func lnurlcashErrorText(ctx context.Context, err error) string {
cfg := &internal.Configuration.LNURLCash
var own *lnurlcash.ErrOwnNote
switch {
case errors.Is(err, lnurlcash.ErrCapNoteValue):
return fmt.Sprintf(TranslateUser(ctx, "noteCapValueMessage"), cfg.MinNoteSat, cfg.MaxNoteSat, cfg.GroupNoteMaxSat)
case errors.Is(err, lnurlcash.ErrCapBatch):
return fmt.Sprintf(TranslateUser(ctx, "noteCapBatchMessage"), cfg.MaxBatchSize, cfg.MaxBatchTotalSat)
case errors.Is(err, lnurlcash.ErrCapOutstanding):
return fmt.Sprintf(TranslateUser(ctx, "noteCapOutstandingMessage"), cfg.MaxOutstandingNotesPerUser, cfg.MaxOutstandingSatPerUser)
case errors.Is(err, lnurlcash.ErrInsufficientFunds):
return TranslateUser(ctx, "noteInsufficientFundsMessage")
case errors.Is(err, lnurlcash.ErrNoMint), errors.Is(err, lnurlcash.ErrMintUnavailable):
return TranslateUser(ctx, "noteMintUnavailableMessage")
case errors.Is(err, lnurlcash.ErrMintRange):
return TranslateUser(ctx, "noteMintRangeMessage")
case errors.Is(err, lnurlcash.ErrNoteClaimed):
return TranslateUser(ctx, "noteStatusClaimedMessage")
case errors.Is(err, lnurlcash.ErrNotePending):
return TranslateUser(ctx, "redeemPendingMessage")
case errors.Is(err, lnurlcash.ErrNotANote):
return TranslateUser(ctx, "redeemNotANoteMessage")
case errors.Is(err, lnurlcash.ErrFractionalValue):
return TranslateUser(ctx, "redeemFractionalMessage")
case errors.Is(err, lnurlcash.ErrInFlight):
return TranslateUser(ctx, "noteInFlightMessage")
case errors.Is(err, lnurlcash.ErrNothingToReclaim), errors.Is(err, lnurlcash.ErrNoteNotLive):
return TranslateUser(ctx, "noteNothingToReclaimMessage")
case errors.Is(err, lnurlcash.ErrNotOwner):
return TranslateUser(ctx, "noteNotOwnerMessage")
case errors.As(err, &own):
return TranslateUser(ctx, "redeemOwnNoteMessage")
}
log.Warnf("[lnurlcash] %v", err)
return TranslateUser(ctx, "noteErrorMessage")
}
// noteStateText is the translated state label.
func noteStateText(ctx context.Context, state string) string {
switch state {
case lnurlcash.NoteLive:
return TranslateUser(ctx, "noteStateLive")
case lnurlcash.NoteClaimed:
return TranslateUser(ctx, "noteStateClaimed")
case lnurlcash.NoteReclaiming:
return TranslateUser(ctx, "noteStateReclaiming")
case lnurlcash.NoteReclaimed:
return TranslateUser(ctx, "noteStateReclaimed")
case lnurlcash.NoteFailed:
return TranslateUser(ctx, "noteStateFailed")
}
return TranslateUser(ctx, "noteStatePending")
}
// noteViewText renders one note.
func noteViewText(ctx context.Context, n *lnurlcash.Note) string {
value := n.ReportedMsat
if value == 0 {
value = n.ValueMsat
}
memo := ""
if n.Memo != "" {
memo = fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(n.Memo))
}
return fmt.Sprintf(TranslateUser(ctx, "noteViewMessage"), lnurlcash.ShortID(n.ID), value/1000,
noteStateText(ctx, n.State), n.MintID, n.CreatedAt.UTC().Format("2 Jan 06 15:04")) + memo
}
// noteKeyboard builds the buttons under a note: QR, status, reclaim.
func noteKeyboard(ctx context.Context, n *lnurlcash.Note, withQR bool) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
var row []tb.Btn
if withQR && n.State == lnurlcash.NoteLive {
row = append(row, menu.Data(TranslateUser(ctx, "noteShowQrButton"), "lnc_qr", n.ID))
}
if !lnurlcash.IsFinalNoteState(n.State) {
row = append(row, menu.Data(TranslateUser(ctx, "noteStatusButton"), "lnc_status", n.ID))
}
if n.State == lnurlcash.NoteLive {
row = append(row, menu.Data(TranslateUser(ctx, "noteReclaimButton"), "lnc_reclaim", n.ID))
}
if len(row) > 0 {
menu.Inline(menu.Row(row...))
}
return menu
}
// loadOwnNote loads the note behind a callback and checks the presser owns it.
func (bot *TipBot) loadOwnNote(ctx intercept.Context) (*lnurlcash.Note, error) {
n, err := bot.LNURLCash.Store().Note(ctx.Data())
if err != nil {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
if n.UserName != LoadUser(ctx).Name {
return nil, lnurlcash.ErrNotOwner
}
return n, nil
}
// sendNoteQR sends the QR photo of a note with the bech32 LNURL as caption.
func (bot *TipBot) sendNoteQR(to tb.Recipient, n *lnurlcash.Note) *tb.Message {
_, bech, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
log.Errorf("[lnurlcash] note strings %s: %v", n.ID, err)
return nil
}
qr, err := qrcodeEncode(bech)
if err != nil {
return nil
}
return bot.trySendMessageEditable(to, &tb.Photo{File: tb.File{FileReader: qr}, Caption: fmt.Sprintf("`%s`", bech)})
}
// formatSat renders msat as sats for messages.
func formatSat(msat int64) string {
if msat%1000 == 0 {
return strconv.FormatInt(msat/1000, 10)
}
return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.3f", float64(msat)/1000), "0"), ".")
}