From 3c2ccf8d836e3ffb7c18b540f2a73c77b85cce9e Mon Sep 17 00:00:00 2001 From: Michilis Date: Fri, 13 Nov 2026 22:12:27 +0000 Subject: [PATCH] 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 --- README.md | 4 + botfather-setcommands.txt | 6 +- internal/lnurlcash/service_export.go | 108 ++++++++ internal/network/http.go | 17 ++ internal/telegram/bot.go | 8 + internal/telegram/handler.go | 316 +++++++++++++++++++++ internal/telegram/invoice.go | 2 + internal/telegram/lnurl.go | 34 ++- internal/telegram/lnurlcash.go | 392 +++++++++++++++++++++++++++ internal/telegram/lnurlcash_qr.go | 17 ++ internal/telegram/lnurlcash_test.go | 62 +++++ internal/telegram/lnurlmints.go | 87 ++++++ internal/telegram/note.go | 348 ++++++++++++++++++++++++ internal/telegram/note_redeem.go | 117 ++++++++ internal/telegram/notes_batch.go | 233 ++++++++++++++++ internal/telegram/notes_list.go | 205 ++++++++++++++ internal/telegram/redact.go | 3 + internal/telegram/text.go | 15 +- translations/en.toml | 81 +++++- translations/nl.toml | 80 ++++++ 20 files changed, 2128 insertions(+), 7 deletions(-) create mode 100644 internal/lnurlcash/service_export.go create mode 100644 internal/telegram/lnurlcash.go create mode 100644 internal/telegram/lnurlcash_qr.go create mode 100644 internal/telegram/lnurlcash_test.go create mode 100644 internal/telegram/lnurlmints.go create mode 100644 internal/telegram/note.go create mode 100644 internal/telegram/note_redeem.go create mode 100644 internal/telegram/notes_batch.go create mode 100644 internal/telegram/notes_list.go diff --git a/README.md b/README.md index 3ff70176..88ba1ed5 100644 --- a/README.md +++ b/README.md @@ -148,3 +148,7 @@ A complete guide to install and run LightningTipBot + LNBITS (on docker with Pos - [gozxing](https://github.com/makiuchi-d/gozxing) – barcode image processing library in Go. - [ln-decodepay](https://github.com/fiatjaf/ln-decodepay) – Lightning Network BOLT11 invoice decoder. - [go-lnurl](https://github.com/fiatjaf/go-lnurl) - Helpers for building lnurl support into services. + +## LNURLcash notes (optional) + +The bot can mint [LNURLcash](https://github.com/lnurl/luds/pull/301) bearer notes at admin-listed mints: `/note [memo]`, `/notes x [memo]`, `/notes`, `/redeem ` and `/lnurlmints`. The balance stays in LNbits; note secrets are stored AES-256-GCM encrypted in `data/lnurlcash.db`. Enable it with the `lnurlcash:` block in `config.yaml` (see `config.yaml.example`; a `secret_encryption_key` is required). Design and audit notes live in `docs/lnurlcash/`. diff --git a/botfather-setcommands.txt b/botfather-setcommands.txt index 5e61ae0f..a15232e3 100644 --- a/botfather-setcommands.txt +++ b/botfather-setcommands.txt @@ -14,4 +14,8 @@ invoice - Receive with Lightning: /invoice 1000 pay - Pay with Lightning: /pay lnbc10n1ps... donate - Donate: /donate 1000 faucet - Create a faucet: /faucet 2100 21 -advanced - Advanced help \ No newline at end of file +advanced - Advanced help +note - Create an LNURLcash note: /note 1000 [memo] +notes - List your notes, or create a batch: /notes 100 x 10 +redeem - Redeem a received note: /redeem lnurlw://... +lnurlmints - Show the LNURLcash mints and pick a default diff --git a/internal/lnurlcash/service_export.go b/internal/lnurlcash/service_export.go new file mode 100644 index 00000000..55bb82a0 --- /dev/null +++ b/internal/lnurlcash/service_export.go @@ -0,0 +1,108 @@ +package lnurlcash + +import ( + "context" + "errors" + "sort" + + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export" +) + +// ExportBatch builds the export of a batch for its owner: live notes only, +// so a re-export after some were claimed leaves those out. The note strings +// are built in memory and never stored. +func (s *Service) ExportBatch(batchID, user string) (export.Batch, error) { + b, err := s.store.Batch(batchID) + if err != nil { + return export.Batch{}, err + } + if b.UserName != user { + return export.Batch{}, ErrNotOwner + } + notes, err := s.store.NotesInBatch(b.ID) + if err != nil { + return export.Batch{}, err + } + mint, _ := s.mints.Get(b.MintID) + out := export.Batch{ID: b.ID, Memo: b.Memo, CreatedAt: b.CreatedAt, MintName: b.MintID} + if mint != nil { + out.MintURL, out.MintPubkey = mint.WithdrawLink, mint.PinnedPubkey + } + for _, n := range notes { + if n.Kind != KindUser || n.State != NoteLive { + continue + } + lnurlw, bech, err := s.NoteStrings(n) + if err != nil { + return export.Batch{}, err + } + out.Notes = append(out.Notes, export.Note{Index: n.Index, ID: n.ID, ShortID: ShortID(n.ID), AmountMsat: n.ReportedMsat, + LNURL: bech, LNURLW: lnurlw, Mint: b.MintID, Memo: n.Memo, Cert: n.Certificate, CreatedAt: n.CreatedAt}) + } + sort.Slice(out.Notes, func(i, j int) bool { return out.Notes[i].Index < out.Notes[j].Index }) + return out, nil +} + +// BatchSummary counts a batch's user notes by state. +type BatchSummary struct { + Total, Live, Claimed, Reclaimed, Failed, Pending int +} + +// Summarize counts the notes of a batch. +func (s *Service) Summarize(batchID string) (BatchSummary, error) { + notes, err := s.store.NotesInBatch(batchID) + if err != nil { + return BatchSummary{}, err + } + var sum BatchSummary + for _, n := range notes { + if n.Kind != KindUser { + continue + } + sum.Total++ + switch n.State { + case NoteLive: + sum.Live++ + case NoteClaimed: + sum.Claimed++ + case NoteReclaimed: + sum.Reclaimed++ + case NoteFailed: + sum.Failed++ + default: + sum.Pending++ + } + } + return sum, nil +} + +// ReclaimBatch reclaims every live note of a batch. It returns how many +// melts were sent and the first error. +func (s *Service) ReclaimBatch(ctx context.Context, batchID, user string) (int, error) { + b, err := s.store.Batch(batchID) + if err != nil { + return 0, err + } + if b.UserName != user { + return 0, ErrNotOwner + } + notes, err := s.store.NotesInBatch(b.ID) + if err != nil { + return 0, err + } + sent := 0 + var first error + for _, n := range notes { + if n.Kind != KindUser || n.State != NoteLive { + continue + } + if _, err := s.Reclaim(ctx, n.ID); err != nil { + if !errors.Is(err, ErrNoteClaimed) && first == nil { + first = err + } + continue + } + sent++ + } + return sent, first +} diff --git a/internal/network/http.go b/internal/network/http.go index 83a5121e..5c0071ac 100644 --- a/internal/network/http.go +++ b/internal/network/http.go @@ -107,3 +107,20 @@ func GetClient(clientType ClientType) (*http.Client, error) { client.Transport = specialTransport return &client, nil } + +// NewNoKeepAliveClient returns a client for LNURLcash mints: the same proxy +// and netguard rules as GetClient, but keep-alives off and redirects refused, +// because every LNURLcash mutation is a non-idempotent GET that net/http +// would otherwise retry on a reused connection. +func NewNoKeepAliveClient(timeout time.Duration) *http.Client { + client, err := GetClient(ClientTypeClearNet) + if err != nil || client == nil { + client = &http.Client{Transport: directTransport()} + } + if t, ok := client.Transport.(*http.Transport); ok { + t.DisableKeepAlives = true + } + client.Timeout = timeout + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return client +} diff --git a/internal/telegram/bot.go b/internal/telegram/bot.go index c65d29e5..48c5f3a2 100644 --- a/internal/telegram/bot.go +++ b/internal/telegram/bot.go @@ -16,6 +16,7 @@ import ( "github.com/LightningTipBot/LightningTipBot/internal" "github.com/LightningTipBot/LightningTipBot/internal/lnbits" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" "github.com/LightningTipBot/LightningTipBot/internal/storage" gocache "github.com/patrickmn/go-cache" log "github.com/sirupsen/logrus" @@ -30,6 +31,9 @@ type TipBot struct { Client *lnbits.Client limiter map[string]limiter.Limiter Cache + // LNURLCash is nil unless the lnurlcash feature is enabled. + LNURLCash *lnurlcash.Service + lnurlcashJobs *lnurlcash.Jobs } type Cache struct { *store.GoCacheStore @@ -116,6 +120,9 @@ func (bot *TipBot) Start() { log.Errorf("Could not initialize bot wallet: %s", err.Error()) } + // LNURLcash notes (optional feature) + bot.initLNURLCash() + // register telegram handlers bot.registerTelegramHandlers() @@ -136,6 +143,7 @@ func (bot *TipBot) Start() { go bot.Telegram.Start() go bot.restartPersistedTickets() + bot.startLNURLCashJobs() // gracefully shutdown exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked // we need to catch SIGTERM and SIGSTOP diff --git a/internal/telegram/handler.go b/internal/telegram/handler.go index d94a9bc5..7a0c3ec0 100644 --- a/internal/telegram/handler.go +++ b/internal/telegram/handler.go @@ -84,6 +84,322 @@ func (bot TipBot) register(h InterceptionWrapper) { // getHandler returns a list of all handlers, that need to be registered with Telegram func (bot TipBot) getHandler() []InterceptionWrapper { return []InterceptionWrapper{ + // LNURLcash notes (docs/lnurlcash) + { + Endpoints: []interface{}{"/note"}, + Handler: bot.noteHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.logMessageInterceptor, + bot.loadUserInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{"/notes"}, + Handler: bot.notesHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.logMessageInterceptor, + bot.loadUserInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{"/redeem"}, + Handler: bot.redeemHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.logMessageInterceptor, + bot.loadUserInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{"/lnurlmints"}, + Handler: bot.lnurlmintsHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.logMessageInterceptor, + bot.loadUserInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteCreate}, + Handler: bot.noteCreateHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteMint}, + Handler: bot.noteMintHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteCancel}, + Handler: bot.noteCancelHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteStatus}, + Handler: bot.noteStatusHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteReclaim}, + Handler: bot.noteReclaimHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNoteQR}, + Handler: bot.noteQRHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNotesPage}, + Handler: bot.notesPageHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNotesOpen}, + Handler: bot.notesOpenHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnNotesOpenB}, + Handler: bot.notesOpenBatchHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnBatchExportPDF}, + Handler: bot.batchExportHandler("pdf"), + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnBatchExportJSON}, + Handler: bot.batchExportHandler("json"), + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnBatchExportCSV}, + Handler: bot.batchExportHandler("csv"), + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnBatchRefresh}, + Handler: bot.batchRefreshHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnBatchReclaim}, + Handler: bot.batchReclaimHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnSetMint}, + Handler: bot.setMintHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnRedeemOK}, + Handler: bot.redeemConfirmHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, + { + Endpoints: []interface{}{&btnRedeemCancel}, + Handler: bot.redeemCancelHandler, + Interceptor: &Interceptor{ + Before: []intercept.Func{ + bot.localizerInterceptor, + bot.requireUserInterceptor, + bot.answerCallbackInterceptor, + bot.lockInterceptor, + }, + OnDefer: []intercept.Func{ + bot.unlockInterceptor, + }, + }, + }, { Endpoints: []interface{}{"/start"}, Handler: bot.startHandler, diff --git a/internal/telegram/invoice.go b/internal/telegram/invoice.go index eac162be..a0939f31 100644 --- a/internal/telegram/invoice.go +++ b/internal/telegram/invoice.go @@ -43,6 +43,7 @@ func initInvoiceEventCallbacks(bot *TipBot) { InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice}, InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice}, InvoiceCallbackPayJoinTicket: EventHandler{Function: bot.stopJoinTicketTimer, Type: EventTypeInvoice}, + InvoiceCallbackLNURLCashSettle: EventHandler{Function: bot.lnurlcashSettleEvent, Type: EventTypeInvoice}, } } @@ -56,6 +57,7 @@ const ( InvoiceCallbackSatdressProxy InvoiceCallbackGenerateDalle InvoiceCallbackPayJoinTicket + // InvoiceCallbackLNURLCashSettle (8) is declared in lnurlcash.go ) const ( diff --git a/internal/telegram/lnurl.go b/internal/telegram/lnurl.go index a2291c8b..653227a2 100644 --- a/internal/telegram/lnurl.go +++ b/internal/telegram/lnurl.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + goerrors "errors" "fmt" "io/ioutil" "net/url" @@ -18,7 +19,9 @@ import ( "github.com/tidwall/gjson" "github.com/LightningTipBot/LightningTipBot/internal/lnbits" + lnurlcashpkg "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" lnurl "github.com/fiatjaf/go-lnurl" + lnurlcash "github.com/lnurlcash/lnurlcash-go" log "github.com/sirupsen/logrus" "github.com/skip2/go-qrcode" tb "gopkg.in/lightningtipbot/telebot.v3" @@ -37,7 +40,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error if m.Chat.Type != tb.ChatPrivate { return ctx, errors.Create(errors.NoPrivateChatError) } - log.Infof("[lnurlHandler] %s", m.Text) + log.Infof("[lnurlHandler] %s", redactForLog(m.Text)) user := LoadUser(ctx) if user.Wallet == nil { return ctx, errors.Create(errors.UserNoWalletError) @@ -67,6 +70,16 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error // get rid of the URI prefix lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:") + // an LNURLcash note is a withdraw link whose k1 is the money: redeem it + // directly. A withdraw link without mintPubkey falls through below. + if bot.LNURLCash != nil && lnurlcash.ResolveNoteInput(lnurlSplit) != "" { + ctx, err := bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, lnurlSplit, false) + if !goerrors.Is(err, lnurlcashpkg.ErrNotANote) { + bot.tryDeleteMessage(statusMsg) + return ctx, err + } + } + // log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit) // HandleLNURL by fiatjaf/go-lnurl _, params, err := bot.HandleLNURL(lnurlSplit) @@ -79,7 +92,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error switch params.(type) { case lnurl.LNURLAuthParams: authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)} - log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback) + log.Infof("[LNURL-auth] %s", lnurlcash.ServerOf(authParams.LNURLAuthParams.Callback)) bot.tryDeleteMessage(statusMsg) ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams) return ctx, err @@ -102,9 +115,17 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error // ask whether to make payment bot.lnurlPayHandler(ctx, payParams) + case LNURLCashNoteParams: + bot.tryDeleteMessage(statusMsg) + if bot.LNURLCash == nil { + return ctx, errors.Create(errors.UnknownError) + } + log.Infof("[LNURL-cash] note from %s", lnurlcash.ServerOf(params.(LNURLCashNoteParams).URL)) + return bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, lnurlSplit, false) + case lnurl.LNURLWithdrawResponse: withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)} - log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback) + log.Infof("[LNURL-w] %s", lnurlcash.ServerOf(withdrawParams.LNURLWithdrawResponse.Callback)) bot.tryDeleteMessage(statusMsg) bot.lnurlWithdrawHandler(ctx, withdrawParams) default: @@ -214,11 +235,12 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro return "", nil, err } } - log.Debug("[HandleLNURL] rawurl: ", rawurl) parsed, err := url.Parse(rawurl) if err != nil { return rawurl, nil, err } + // host only: the query string of a withdraw or login link carries k1 + log.Debug("[HandleLNURL] host: ", parsed.Host) query := parsed.Query() @@ -266,6 +288,10 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro switch j.Get("tag").String() { case "withdrawRequest": + if bot.LNURLCash != nil && j.Get("mintPubkey").String() != "" { + // an LNURLcash note (LUD-25): the withdraw link publishes a mintPubkey + return rawurl, LNURLCashNoteParams{URL: rawurl}, nil + } value, err := lnurl.HandleWithdraw(b) return rawurl, value, err case "payRequest": diff --git a/internal/telegram/lnurlcash.go b/internal/telegram/lnurlcash.go new file mode 100644 index 00000000..7f387215 --- /dev/null +++ b/internal/telegram/lnurlcash.go @@ -0,0 +1,392 @@ +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"), ".") +} diff --git a/internal/telegram/lnurlcash_qr.go b/internal/telegram/lnurlcash_qr.go new file mode 100644 index 00000000..e0b9caf3 --- /dev/null +++ b/internal/telegram/lnurlcash_qr.go @@ -0,0 +1,17 @@ +package telegram + +import ( + "bytes" + "io" + + "github.com/skip2/go-qrcode" +) + +// qrcodeEncode renders a PNG QR code for Telegram. +func qrcodeEncode(data string) (io.Reader, error) { + png, err := qrcode.Encode(data, qrcode.Medium, 256) + if err != nil { + return nil, err + } + return bytes.NewReader(png), nil +} diff --git a/internal/telegram/lnurlcash_test.go b/internal/telegram/lnurlcash_test.go new file mode 100644 index 00000000..5b0bb110 --- /dev/null +++ b/internal/telegram/lnurlcash_test.go @@ -0,0 +1,62 @@ +package telegram + +import "testing" + +func TestParseBatchCommand(t *testing.T) { + amount, count, memo, ok := parseBatchCommand("/notes 100 x 10 party time") + if !ok || amount != 100 || count != 10 || memo != "party time" { + t.Fatalf("got %d %d %q %v", amount, count, memo, ok) + } + if _, _, _, ok := parseBatchCommand("/notes"); ok { + t.Fatal("bare /notes is a list") + } + if _, _, _, ok := parseBatchCommand("/notes 100 y 10"); ok { + t.Fatal("wrong separator") + } + if _, _, _, ok := parseBatchCommand("/notes 100 x 0"); ok { + t.Fatal("zero count") + } + if _, c, _, ok := parseBatchCommand("/notes 1k × 3"); !ok || c != 3 { + t.Fatal("unicode times and 1k amounts must parse") + } +} + +func TestRedactNoteURLs(t *testing.T) { + in := "/redeem lnurlw://mint.example/w?k1=" + "ab" + "cd" + if got := redactForLog(in); got == in || !contains(got, "/redeem <") { + t.Fatalf("note not redacted: %q", got) + } + in = "/lnurl https://mint.example/w?k1=abcd&amount=1000" + if got := redactForLog(in); got == in { + t.Fatalf("withdraw link with k1 not redacted: %q", got) + } + if got := redactForLog("/note 100 hello"); got != "/note 100 hello" { + t.Fatalf("plain command changed: %q", got) + } + if got := formatSat(1000_900); got != "1000.9" { + t.Fatalf("formatSat: %q", got) + } + if got := formatSat(21_000); got != "21" { + t.Fatalf("formatSat: %q", got) + } +} + +func contains(s, sub string) bool { + return len(s) >= len(sub) && (func() bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false + })() +} + +func TestPreserveNoteCase(t *testing.T) { + if got := preserveNoteCase("LNURLW://Mint.Example/W/Abc?k1=AB"); got != "lnurlw://Mint.Example/W/Abc?k1=AB" { + t.Fatalf("got %q", got) + } + if got := preserveNoteCase("LIGHTNING:LNURL1ABC"); got != "lightning:lnurl1abc" { + t.Fatalf("got %q", got) + } +} diff --git a/internal/telegram/lnurlmints.go b/internal/telegram/lnurlmints.go new file mode 100644 index 00000000..63932e80 --- /dev/null +++ b/internal/telegram/lnurlmints.go @@ -0,0 +1,87 @@ +package telegram + +import ( + "fmt" + + "github.com/LightningTipBot/LightningTipBot/internal" + tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + lnurlcashgo "github.com/lnurlcash/lnurlcash-go" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +var btnSetMint = (&tb.ReplyMarkup{}).Data("", "lnc_setmint") + +func bot_lnurlcash_cfg() *lnurlcash.Config { return &internal.Configuration.LNURLCash } + +// lnurlmintsHandler lists the admin mints and lets the user pick a default. +func (bot *TipBot) lnurlmintsHandler(ctx intercept.Context) (intercept.Context, error) { + if !bot.lnurlcashReady(ctx) { + return ctx, nil + } + m := ctx.Message() + user, ok := bot.noteCommandUser(ctx) + if !ok { + return ctx, tiperrors.Create(tiperrors.UserNoWalletError) + } + if !m.Private() { + NewMessage(m, WithDuration(0, bot)) + } + text, kb := bot.mintsText(ctx, user.Name) + if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + } + return ctx, nil +} + +func (bot *TipBot) mintsText(ctx intercept.Context, user string) (string, *tb.ReplyMarkup) { + reg := bot.LNURLCash.Mints() + current, _ := reg.ForUser(user) + menu := &tb.ReplyMarkup{} + var rows []tb.Row + text := TranslateUser(ctx, "lnurlmintsHeader") + for _, mnt := range reg.All() { + state := "🟢" + switch { + case mnt.Disabled: + state = "⛔️" + case !mnt.Healthy: + state = "🔴" + } + mark := "" + if current != nil && current.ID == mnt.ID { + mark = " ⭐️" + } + fee := TranslateUser(ctx, "lnurlmintsNoFee") + if mnt.FeeBaseMsat > 0 || mnt.FeePpm > 0 { + fee = lnurlcashgo.DescribeMintFee(mnt.Fee()) + } + text += fmt.Sprintf(TranslateUser(ctx, "lnurlmintsItem"), state, mnt.ID, mark, lnurlcashgo.ServerOf(mnt.PayURL), fee) + if mnt.Usable() { + rows = append(rows, menu.Row(menu.Data(fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetButton"), mnt.ID), "lnc_setmint", mnt.ID))) + } + } + menu.Inline(rows...) + return text, menu +} + +// setMintHandler stores the user's default mint. +func (bot *TipBot) setMintHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + user := LoadUser(ctx) + mnt, ok := bot.LNURLCash.Mints().Get(ctx.Data()) + if !ok || !mnt.Usable() { + bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteMintUnavailableMessage")) + return ctx, nil + } + if err := bot.LNURLCash.Store().SetPref(user.Name, mnt.ID); err != nil { + return ctx, err + } + bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetMessage"), mnt.ID)) + text, kb := bot.mintsText(ctx, user.Name) + bot.tryEditMessage(ctx.Callback().Message, text, kb) + return ctx, nil +} diff --git a/internal/telegram/note.go b/internal/telegram/note.go new file mode 100644 index 00000000..74784761 --- /dev/null +++ b/internal/telegram/note.go @@ -0,0 +1,348 @@ +package telegram + +import ( + "context" + "errors" + "fmt" + "strconv" + + tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" + "github.com/LightningTipBot/LightningTipBot/internal/lnbits" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" + "github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex" + "github.com/LightningTipBot/LightningTipBot/internal/storage" + "github.com/LightningTipBot/LightningTipBot/internal/str" + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + log "github.com/sirupsen/logrus" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +// NoteConfirm is the pending "create a note" dialog in private chat. +type NoteConfirm struct { + *storage.Base + UserName string `json:"user_name"` + Quote lnurlcash.Quote `json:"quote"` + Memo string `json:"memo"` + LanguageCode string `json:"languagecode"` + ValueMsat int64 `json:"value_msat"` + Count int `json:"count"` +} + +var ( + btnNoteCreate = (&tb.ReplyMarkup{}).Data("", "lnc_create") + btnNoteMint = (&tb.ReplyMarkup{}).Data("", "lnc_mint") + btnNoteCancel = (&tb.ReplyMarkup{}).Data("", "lnc_cancel") + btnNoteStatus = (&tb.ReplyMarkup{}).Data("", "lnc_status") + btnNoteReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_reclaim") + btnNoteQR = (&tb.ReplyMarkup{}).Data("", "lnc_qr") +) + +// noteCommandUser resolves the sender for a note command. In a group a user +// without a wallet is told to start a private chat; in private chat the +// start flow runs. +func (bot *TipBot) noteCommandUser(ctx intercept.Context) (*lnbits.User, bool) { + user := LoadUser(ctx) + m := ctx.Message() + if user == nil || user.Wallet == nil || !user.Initialized { + if m.Private() { + _, _ = bot.startHandler(ctx) + return nil, false + } + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + return nil, false + } + return user, true +} + +// noteHandler handles /note [memo]. +func (bot *TipBot) noteHandler(ctx intercept.Context) (intercept.Context, error) { + if !bot.lnurlcashReady(ctx) { + return ctx, nil + } + m := ctx.Message() + user, ok := bot.noteCommandUser(ctx) + if !ok { + return ctx, tiperrors.Create(tiperrors.UserNoWalletError) + } + amount, err := decodeAmountFromCommand(m.Text) + if err != nil || amount <= 0 { + if m.Private() { + bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteHelpMessage")) + } else { + NewMessage(m, WithDuration(0, bot)) + bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteHelpMessage")) + } + return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError) + } + memo := GetMemoFromCommand(m.Text, 2) + svc := bot.LNURLCash + mint, ok := svc.Mints().ForUser(user.Name) + if !ok { + bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage")) + return ctx, tiperrors.Create(tiperrors.UnknownError) + } + q, err := svc.Quote(ctx, mint, amount*1000, 1) + if err == nil { + err = svc.CheckCaps(ctx, user.Name, q, !m.Private()) + } + if err != nil { + text := lnurlcashErrorText(ctx, err) + if m.Private() { + bot.trySendMessage(m.Sender, text) + } else { + NewMessage(m, WithDuration(0, bot)) + bot.sendPrivate(m.Sender, text) + } + return ctx, err + } + if !m.Private() { + return bot.createNoteInGroup(ctx, user, q, memo) + } + confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))), + UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: 1} + bot.trySendMessageEditable(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)) + return ctx, confirm.Set(confirm, bot.Bunt) +} + +func noteConfirmText(ctx context.Context, c *NoteConfirm) string { + q := c.Quote + text := fmt.Sprintf(TranslateUser(ctx, "noteConfirmMessage"), q.Count, formatSat(q.ValueMsat), formatSat(q.FeeMsat), formatSat(q.GrossMsat), q.MintName) + if c.Memo != "" { + text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(c.Memo)) + } + return text +} + +func noteConfirmKeyboard(ctx context.Context, id string) *tb.ReplyMarkup { + menu := &tb.ReplyMarkup{} + menu.Inline( + menu.Row(menu.Data(TranslateUser(ctx, "noteCreateButton"), "lnc_create", id)), + menu.Row(menu.Data(TranslateUser(ctx, "noteChangeMintButton"), "lnc_mint", id), + menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_cancel", id)), + ) + return menu +} + +// loadNoteConfirm loads the dialog behind a callback and checks ownership. +func (bot *TipBot) loadNoteConfirm(ctx intercept.Context) (*NoteConfirm, error) { + tx := &NoteConfirm{Base: storage.New(storage.ID(ctx.Data()))} + got, err := tx.Get(tx, bot.Bunt) + if err != nil { + return nil, err + } + c := got.(*NoteConfirm) + if c.UserName != LoadUser(ctx).Name { + return nil, tiperrors.Create(tiperrors.UnknownError) + } + if !c.Active { + return nil, tiperrors.Create(tiperrors.NotActiveError) + } + return c, nil +} + +// noteCreateHandler runs when the user pressed Create. +func (bot *TipBot) noteCreateHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + mutex.LockWithContext(ctx, ctx.Data()) + defer mutex.UnlockWithContext(ctx, ctx.Data()) + c, err := bot.loadNoteConfirm(ctx) + if err != nil { + return ctx, err + } + _ = c.Inactivate(c, bot.Bunt) + user := LoadUser(ctx) + msg := ctx.Callback().Message + bot.tryEditMessage(msg, TranslateUser(ctx, "noteCreatingMessage"), &tb.ReplyMarkup{}) + params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: c.Quote, Memo: c.Memo} + if c.Count > 1 { + return bot.createBatchFromConfirm(ctx, c, params, msg) + } + _, live, err := bot.LNURLCash.Create(ctx, params) + if err != nil && len(live) == 0 { + bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{}) + return ctx, err + } + bot.tryDeleteMessage(msg) + bot.sendNoteCreated(ctx, user.Telegram, live[0]) + return ctx, nil +} + +// sendNoteCreated sends the QR and the note text with its buttons. +func (bot *TipBot) sendNoteCreated(ctx context.Context, to *tb.User, n *lnurlcash.Note) { + bot.sendNoteQR(to, n) + lnurlw, _, err := bot.LNURLCash.NoteStrings(n) + if err != nil { + log.Errorf("[lnurlcash] note strings: %v", err) + return + } + text := fmt.Sprintf(TranslateUser(ctx, "noteCreatedMessage"), formatSat(n.ReportedMsat), lnurlcash.ShortID(n.ID), lnurlw) + bot.trySendMessageEditable(to, text, noteKeyboard(ctx, n, false)) +} + +// noteMintHandler cycles the dialog to the next usable mint and re-quotes. +func (bot *TipBot) noteMintHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + mutex.LockWithContext(ctx, ctx.Data()) + defer mutex.UnlockWithContext(ctx, ctx.Data()) + c, err := bot.loadNoteConfirm(ctx) + if err != nil { + return ctx, err + } + mints := bot.LNURLCash.Mints().All() + var usable []*lnurlcash.Mint + for _, m := range mints { + if m.Usable() { + usable = append(usable, m) + } + } + if len(usable) < 2 { + bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteOnlyOneMintMessage")) + return ctx, nil + } + next := usable[0] + for i, m := range usable { + if m.ID == c.Quote.MintID { + next = usable[(i+1)%len(usable)] + break + } + } + q, err := bot.LNURLCash.Quote(ctx, next, c.ValueMsat, c.Count) + if err != nil { + bot.trySendMessage(ctx.Sender(), lnurlcashErrorText(ctx, err)) + return ctx, err + } + c.Quote = q + bot.tryEditMessage(ctx.Callback().Message, noteConfirmText(ctx, c), noteConfirmKeyboard(ctx, c.ID)) + return ctx, c.Set(c, bot.Bunt) +} + +// noteCancelHandler runs when the user pressed Cancel. +func (bot *TipBot) noteCancelHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + mutex.LockWithContext(ctx, ctx.Data()) + defer mutex.UnlockWithContext(ctx, ctx.Data()) + c, err := bot.loadNoteConfirm(ctx) + if err != nil { + return ctx, err + } + bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "noteCancelledMessage"), &tb.ReplyMarkup{}) + return ctx, c.Inactivate(c, bot.Bunt) +} + +// createNoteInGroup creates a note without a confirm step, posts it in the +// group and sends the receipt privately. +func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q lnurlcash.Quote, memo string) (intercept.Context, error) { + m := ctx.Message() + receipt, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteCreatingMessage")) + if !ok { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) + } + params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: q, Memo: memo, ChatID: m.Chat.ID} + _, live, err := bot.LNURLCash.Create(ctx, params) + if err != nil && len(live) == 0 { + bot.tryEditMessage(receipt, lnurlcashErrorText(ctx, err)) + return ctx, err + } + n := live[0] + _, bech, err := bot.LNURLCash.NoteStrings(n) + if err != nil { + return ctx, err + } + qr, err := qrcodeEncode(bech) + if err != nil { + return ctx, err + } + caption := fmt.Sprintf(Translate(ctx, "noteGroupMessage"), formatSat(n.ReportedMsat), GetUserStrMd(m.Sender), bech) + if memo != "" { + caption += fmt.Sprintf(Translate(ctx, "noteViewMemo"), str.MarkdownEscape(memo)) + } + post := bot.tryReplyMessage(m, &tb.Photo{File: tb.File{FileReader: qr}, Caption: caption}) + if post != nil { + _ = bot.LNURLCash.Store().UpdateNote(n.ID, map[string]interface{}{"chat_id": post.Chat.ID, "message_id": strconv.Itoa(post.ID)}) + } + lnurlw, _, _ := bot.LNURLCash.NoteStrings(n) + text := fmt.Sprintf(TranslateUser(ctx, "noteReceiptMessage"), formatSat(n.ReportedMsat), formatSat(q.FeeMsat), q.MintName, lnurlcash.ShortID(n.ID), lnurlw) + bot.tryEditMessage(receipt, text, noteKeyboard(ctx, n, false)) + log.Infof("[lnurlcash] %s created group note %s (%d msat) in chat %d", GetUserStr(m.Sender), n.ID, n.ReportedMsat, m.Chat.ID) + return ctx, nil +} + +// noteStatusHandler answers the Check status button. +func (bot *TipBot) noteStatusHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + n, err := bot.loadOwnNote(ctx) + if err != nil { + return ctx, err + } + state, value, err := bot.LNURLCash.Status(ctx, n) + var text string + switch { + case errors.Is(err, lnurlcashgoPending()): + text = TranslateUser(ctx, "noteStatusPendingMessage") + case err != nil: + text = TranslateUser(ctx, "noteMintUnavailableMessage") + case state == lnurlcash.NoteClaimed: + text = TranslateUser(ctx, "noteStatusClaimedMessage") + case state == lnurlcash.NoteLive: + text = fmt.Sprintf(TranslateUser(ctx, "noteStatusLiveMessage"), formatSat(value)) + default: + text = fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, state)) + } + bot.trySendMessageEditable(ctx.Sender(), text) + if ctx.Callback().Message != nil { + _, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false)) + } + return ctx, nil +} + +// noteReclaimHandler answers the Reclaim button. +func (bot *TipBot) noteReclaimHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + n, err := bot.loadOwnNote(ctx) + if err != nil { + return ctx, err + } + n, err = bot.LNURLCash.Reclaim(ctx, n.ID) + if err != nil { + bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err)) + return ctx, err + } + bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteReclaimRequestedMessage"), formatSat(n.ReportedMsat))) + if ctx.Callback().Message != nil { + _, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false)) + } + (&lnurlcashNotifier{bot: bot}).GroupNoteState(n) + return ctx, nil +} + +// noteQRHandler answers the Show QR button. +func (bot *TipBot) noteQRHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + n, err := bot.loadOwnNote(ctx) + if err != nil { + return ctx, err + } + if n.State != lnurlcash.NoteLive { + bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, n.State))) + return ctx, nil + } + bot.sendNoteCreated(ctx, ctx.Sender(), n) + return ctx, nil +} + +// lnurlcashgoPending is the library's pending sentinel, kept behind a +// function so this file does not import the library for one value. +func lnurlcashgoPending() error { return lnurlcash.ErrNotePending } diff --git a/internal/telegram/note_redeem.go b/internal/telegram/note_redeem.go new file mode 100644 index 00000000..d71893af --- /dev/null +++ b/internal/telegram/note_redeem.go @@ -0,0 +1,117 @@ +package telegram + +import ( + "errors" + "fmt" + "strings" + + tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" + "github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex" + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + log "github.com/sirupsen/logrus" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +// LNURLCashNoteParams is what HandleLNURL returns for a withdraw link that +// publishes a mintPubkey: an LNURLcash note rather than a plain withdraw. +type LNURLCashNoteParams struct { + URL string +} + +var ( + btnRedeemOK = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_ok") + btnRedeemCancel = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_no") +) + +// redeemHandler handles /redeem . In a group the command is deleted +// at once because it carries the secret, and the flow continues privately. +func (bot *TipBot) redeemHandler(ctx intercept.Context) (intercept.Context, error) { + if !bot.lnurlcashReady(ctx) { + return ctx, nil + } + m := ctx.Message() + if !m.Private() { + bot.tryDeleteMessage(m) + } + user, ok := bot.noteCommandUser(ctx) + if !ok { + return ctx, tiperrors.Create(tiperrors.UserNoWalletError) + } + parts := strings.Fields(m.Text) + if len(parts) < 2 { + if _, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "redeemHelpMessage")); !ok && !m.Private() { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + } + return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError) + } + return bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, parts[1], !m.Private()) +} + +// redeemInput previews a pasted note and offers to add it to the balance. +// Everything goes to the user's private chat. +func (bot *TipBot) redeemInput(ctx intercept.Context, userName, lang, input string, fromGroup bool) (intercept.Context, error) { + sender := ctx.Sender() + preview, err := bot.LNURLCash.RedeemInfo(ctx, userName, lang, input) + if err != nil { + if errors.Is(err, lnurlcash.ErrNotANote) && !fromGroup { + // the caller decides (the /lnurl flow falls back to a plain withdraw) + return ctx, err + } + text := lnurlcashErrorText(ctx, err) + if _, ok := bot.sendPrivate(sender, text); !ok && fromGroup { + bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + } + return ctx, err + } + text := fmt.Sprintf(TranslateUser(ctx, "redeemPreviewMessage"), formatSat(preview.ValueMsat), preview.MintHost) + if !preview.KnownMint { + text += "\n\n" + TranslateUser(ctx, "redeemUnknownMintWarning") + } + menu := &tb.ReplyMarkup{} + menu.Inline(menu.Row( + menu.Data(TranslateUser(ctx, "redeemAddButton"), "lnc_redeem_ok", preview.Redeem.ID), + menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_redeem_no", preview.Redeem.ID))) + if _, ok := bot.sendPrivate(sender, text, menu); !ok && fromGroup { + bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) + } + return ctx, nil +} + +// redeemConfirmHandler runs when Add to balance was pressed. +func (bot *TipBot) redeemConfirmHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + mutex.LockWithContext(ctx, ctx.Data()) + defer mutex.UnlockWithContext(ctx, ctx.Data()) + user := LoadUser(ctx) + msg := ctx.Callback().Message + bot.tryEditMessage(msg, TranslateUser(ctx, "redeemInFlightMessage"), &tb.ReplyMarkup{}) + r, err := bot.LNURLCash.Redeem(ctx, ctx.Data(), user.Name) + if err != nil { + bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{}) + return ctx, err + } + log.Infof("[lnurlcash] %s redeems %s (%d msat)", GetUserStr(ctx.Sender()), r.ID, r.ReportedMsat) + bot.tryEditMessage(msg, fmt.Sprintf(TranslateUser(ctx, "redeemRequestedMessage"), formatSat(r.ReportedMsat)), &tb.ReplyMarkup{}) + return ctx, nil +} + +// redeemCancelHandler runs when Cancel was pressed on a preview. +func (bot *TipBot) redeemCancelHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + r, err := bot.LNURLCash.Store().Redeem(ctx.Data()) + if err != nil || r.UserName != LoadUser(ctx).Name { + return ctx, tiperrors.Create(tiperrors.UnknownError) + } + _ = bot.LNURLCash.Store().TransitionRedeem(r.ID, lnurlcash.RedeemInfo, lnurlcash.RedeemFailed, map[string]interface{}{"last_error": "cancelled"}) + bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "redeemCancelledMessage"), &tb.ReplyMarkup{}) + return ctx, nil +} + +// LNURLKind satisfies go-lnurl's LNURLParams so HandleLNURL can return a note. +func (LNURLCashNoteParams) LNURLKind() string { return "lnurlcash-note" } diff --git a/internal/telegram/notes_batch.go b/internal/telegram/notes_batch.go new file mode 100644 index 00000000..c9b5fffa --- /dev/null +++ b/internal/telegram/notes_batch.go @@ -0,0 +1,233 @@ +package telegram + +import ( + "bytes" + "context" + "fmt" + "strings" + + tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" + "github.com/LightningTipBot/LightningTipBot/internal/lnbits" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export" + "github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex" + "github.com/LightningTipBot/LightningTipBot/internal/storage" + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + log "github.com/sirupsen/logrus" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +var ( + btnBatchExportPDF = (&tb.ReplyMarkup{}).Data("", "lnc_exp_pdf") + btnBatchExportJSON = (&tb.ReplyMarkup{}).Data("", "lnc_exp_json") + btnBatchExportCSV = (&tb.ReplyMarkup{}).Data("", "lnc_exp_csv") + btnBatchRefresh = (&tb.ReplyMarkup{}).Data("", "lnc_brefresh") + btnBatchReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_breclaim") +) + +// parseBatchCommand reads "/notes x [memo]". ok is false +// when the text is not a batch command. +func parseBatchCommand(text string) (amount int64, count int, memo string, ok bool) { + parts := strings.Fields(text) + if len(parts) < 4 { + return 0, 0, "", false + } + sep := strings.ToLower(parts[2]) + if sep != "x" && sep != "×" && sep != "*" { + return 0, 0, "", false + } + amount, err := GetAmount(parts[1]) + if err != nil { + return 0, 0, "", false + } + var n int + if _, err := fmt.Sscanf(parts[3], "%d", &n); err != nil || n < 1 { + return 0, 0, "", false + } + return amount, n, GetMemoFromCommand(text, 4), true +} + +// noteBatchStart quotes a batch and shows the confirm dialog privately. +func (bot *TipBot) noteBatchStart(ctx intercept.Context, user *lnbits.User, amount int64, count int, memo string) (intercept.Context, error) { + m := ctx.Message() + svc := bot.LNURLCash + if !m.Private() { + NewMessage(m, WithDuration(0, bot)) + } + mint, ok := svc.Mints().ForUser(user.Name) + if !ok { + bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage")) + return ctx, tiperrors.Create(tiperrors.UnknownError) + } + q, err := svc.Quote(ctx, mint, amount*1000, count) + if err == nil { + err = svc.CheckCaps(ctx, user.Name, q, false) + } + if err != nil { + if _, ok := bot.sendPrivate(m.Sender, lnurlcashErrorText(ctx, err)); !ok && !m.Private() { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + } + return ctx, err + } + confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))), + UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: count} + if _, ok := bot.sendPrivate(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)); !ok { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) + } + return ctx, confirm.Set(confirm, bot.Bunt) +} + +// createBatchFromConfirm runs after Create was pressed on a batch dialog. +func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) (intercept.Context, error) { + total := c.Count + key := "lnc-progress-" + c.ID + params.Progress = func(done, total int) { + bot.tryEditStack(msg, key, fmt.Sprintf(TranslateUser(ctx, "notesBatchProgressMessage"), done, total, MakeProgressbar(int64(done), int64(total)))) + } + batch, live, err := bot.LNURLCash.Create(ctx, params) + if err != nil && len(live) == 0 { + bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{}) + return ctx, err + } + text := fmt.Sprintf(TranslateUser(ctx, "notesBatchCreatedMessage"), len(live), total, lnurlcash.ShortID(batch.ID)) + if err != nil { + text += "\n" + fmt.Sprintf(TranslateUser(ctx, "notesBatchPartialMessage"), lnurlcashErrorText(ctx, err)) + } + text += "\n\n" + TranslateUser(ctx, "notesBatchFormatMessage") + bot.tryEditMessage(msg, text, batchKeyboard(ctx, batch.ID)) + return ctx, nil +} + +// batchKeyboard offers the export formats and the batch actions. +func batchKeyboard(ctx context.Context, batchID string) *tb.ReplyMarkup { + menu := &tb.ReplyMarkup{} + cfg := bot_lnurlcash_cfg() + var formats []tb.Btn + if cfg.HasFormat("pdf") { + formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportPdfButton"), "lnc_exp_pdf", batchID)) + } + if cfg.HasFormat("json") { + formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportJsonButton"), "lnc_exp_json", batchID)) + } + if cfg.HasFormat("csv") { + formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportCsvButton"), "lnc_exp_csv", batchID)) + } + rows := []tb.Row{} + if len(formats) > 0 { + rows = append(rows, menu.Row(formats...)) + } + rows = append(rows, menu.Row( + menu.Data(TranslateUser(ctx, "notesRefreshButton"), "lnc_brefresh", batchID), + menu.Data(TranslateUser(ctx, "notesReclaimUnclaimedButton"), "lnc_breclaim", batchID))) + menu.Inline(rows...) + return menu +} + +// batchViewText renders a batch with its counts. +func (bot *TipBot) batchViewText(ctx context.Context, b *lnurlcash.Batch) string { + sum, _ := bot.LNURLCash.Summarize(b.ID) + text := fmt.Sprintf(TranslateUser(ctx, "notesBatchOpenMessage"), lnurlcash.ShortID(b.ID), b.Count, formatSat(b.ValueMsat), b.MintID, + b.CreatedAt.UTC().Format("2 Jan 06 15:04"), sum.Live, sum.Claimed, sum.Reclaimed, sum.Failed+sum.Pending) + if b.Memo != "" { + text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), b.Memo) + } + return text +} + +// loadOwnBatch loads the batch behind a callback and checks ownership. +func (bot *TipBot) loadOwnBatch(ctx intercept.Context) (*lnurlcash.Batch, error) { + b, err := bot.LNURLCash.Store().Batch(ctx.Data()) + if err != nil { + return nil, tiperrors.Create(tiperrors.NotActiveError) + } + if b.UserName != LoadUser(ctx).Name { + return nil, lnurlcash.ErrNotOwner + } + return b, nil +} + +func (bot *TipBot) batchExportHandler(format string) intercept.Func { + return func(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + if !bot_lnurlcash_cfg().HasFormat(format) { + return ctx, nil + } + b, err := bot.loadOwnBatch(ctx) + if err != nil { + return ctx, err + } + // files only ever go to the private chat + if msg := ctx.Callback().Message; msg != nil && !msg.Private() { + return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) + } + data, err := bot.LNURLCash.ExportBatch(b.ID, LoadUser(ctx).Name) + if err != nil { + bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err)) + return ctx, err + } + var buf bytes.Buffer + var mime string + switch format { + case "pdf": + err, mime = export.PDF(&buf, data), "application/pdf" + case "json": + err, mime = export.JSON(&buf, data), "application/json" + case "csv": + err, mime = export.CSV(&buf, data), "text/csv" + } + if err != nil { + log.Errorf("[lnurlcash] export %s of %s: %v", format, b.ID, err) + bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteErrorMessage")) + return ctx, err + } + doc := &tb.Document{File: tb.File{FileReader: &buf}, FileName: fmt.Sprintf("notes-%s.%s", lnurlcash.ShortID(b.ID), format), MIME: mime, + Caption: fmt.Sprintf(TranslateUser(ctx, "notesExportCaption"), len(data.Notes), lnurlcash.ShortID(b.ID))} + bot.trySendMessageEditable(ctx.Sender(), doc) + return ctx, nil + } +} + +// batchRefreshHandler probes every live note of the batch and re-renders it. +func (bot *TipBot) batchRefreshHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + b, err := bot.loadOwnBatch(ctx) + if err != nil { + return ctx, err + } + notes, _ := bot.LNURLCash.Store().NotesInBatch(b.ID) + for _, n := range notes { + if n.Kind == lnurlcash.KindUser && n.State == lnurlcash.NoteLive { + _, _, _ = bot.LNURLCash.Status(ctx, n) + } + } + b, _ = bot.LNURLCash.Store().Batch(b.ID) + bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID)) + return ctx, nil +} + +// batchReclaimHandler reclaims every unclaimed note of the batch. +func (bot *TipBot) batchReclaimHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + mutex.LockWithContext(ctx, ctx.Data()) + defer mutex.UnlockWithContext(ctx, ctx.Data()) + b, err := bot.loadOwnBatch(ctx) + if err != nil { + return ctx, err + } + sent, err := bot.LNURLCash.ReclaimBatch(ctx, b.ID, LoadUser(ctx).Name) + text := fmt.Sprintf(TranslateUser(ctx, "notesBatchReclaimMessage"), sent) + if err != nil { + text += "\n" + lnurlcashErrorText(ctx, err) + } + bot.trySendMessageEditable(ctx.Sender(), text) + b, _ = bot.LNURLCash.Store().Batch(b.ID) + bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID)) + return ctx, nil +} diff --git a/internal/telegram/notes_list.go b/internal/telegram/notes_list.go new file mode 100644 index 00000000..a2af9124 --- /dev/null +++ b/internal/telegram/notes_list.go @@ -0,0 +1,205 @@ +package telegram + +import ( + "context" + "fmt" + "sort" + "strconv" + "strings" + "time" + + tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" + "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" + "github.com/LightningTipBot/LightningTipBot/internal/storage" + "github.com/LightningTipBot/LightningTipBot/internal/str" + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +const notesPerPage = 8 + +var ( + btnNotesPage = (&tb.ReplyMarkup{}).Data("", "lnc_page") + btnNotesOpen = (&tb.ReplyMarkup{}).Data("", "lnc_open") + btnNotesOpenB = (&tb.ReplyMarkup{}).Data("", "lnc_openb") +) + +// NotesList is a user's open /notes list; pages are computed from the DB. +type NotesList struct { + *storage.Base + UserName string `json:"user_name"` +} + +type notesEntry struct { + id string + batch bool + created time.Time + label string +} + +// notesHandler handles /notes and /notes x [memo]. +func (bot *TipBot) notesHandler(ctx intercept.Context) (intercept.Context, error) { + if !bot.lnurlcashReady(ctx) { + return ctx, nil + } + m := ctx.Message() + user, ok := bot.noteCommandUser(ctx) + if !ok { + return ctx, tiperrors.Create(tiperrors.UserNoWalletError) + } + if amount, count, memo, isBatch := parseBatchCommand(m.Text); isBatch { + return bot.noteBatchStart(ctx, user, amount, count, memo) + } + if len(strings.Fields(m.Text)) > 1 { + bot.sendPrivate(m.Sender, TranslateUser(ctx, "notesHelpMessage")) + return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError) + } + if !m.Private() { + NewMessage(m, WithDuration(0, bot)) + } + list := &NotesList{Base: storage.New(storage.ID(fmt.Sprintf("lncl-%d-%s", m.Sender.ID, RandStringRunes(6)))), UserName: user.Name} + text, kb := bot.notesPage(ctx, list, 0) + if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() { + bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) + return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) + } + return ctx, list.Set(list, bot.Bunt) +} + +// notesEntries lists single notes and batches, newest first. +func (bot *TipBot) notesEntries(ctx context.Context, user string) []notesEntry { + store := bot.LNURLCash.Store() + var entries []notesEntry + batches, _ := store.UserBatches(user) + inBatch := map[string]bool{} + for _, b := range batches { + inBatch[b.ID] = true + sum, _ := bot.LNURLCash.Summarize(b.ID) + entries = append(entries, notesEntry{id: b.ID, batch: true, created: b.CreatedAt, + label: fmt.Sprintf(TranslateUser(ctx, "notesBatchItem"), b.Count, formatSat(b.ValueMsat), sum.Live, sum.Claimed, lnurlcash.ShortID(b.ID))}) + } + notes, _ := store.UserNotes(user, nil) + for _, n := range notes { + if n.BatchID != nil && inBatch[*n.BatchID] { + continue + } + value := n.ReportedMsat + if value == 0 { + value = n.ValueMsat + } + memo := n.Memo + if len(memo) > 20 { + memo = memo[:19] + "…" + } + entries = append(entries, notesEntry{id: n.ID, created: n.CreatedAt, + label: fmt.Sprintf(TranslateUser(ctx, "notesListItem"), noteStateEmoji(n.State), formatSat(value), lnurlcash.ShortID(n.ID), memo)}) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].created.After(entries[j].created) }) + return entries +} + +func noteStateEmoji(state string) string { + switch state { + case lnurlcash.NoteLive: + return "🟢" + case lnurlcash.NoteClaimed: + return "✅" + case lnurlcash.NoteReclaimed: + return "↩️" + case lnurlcash.NoteReclaiming: + return "🔄" + case lnurlcash.NoteFailed: + return "🚫" + } + return "⏳" +} + +// notesPage renders one page of the list with its buttons. +func (bot *TipBot) notesPage(ctx context.Context, list *NotesList, page int) (string, *tb.ReplyMarkup) { + entries := bot.notesEntries(ctx, list.UserName) + menu := &tb.ReplyMarkup{} + if len(entries) == 0 { + return TranslateUser(ctx, "notesListEmpty"), menu + } + pages := (len(entries) + notesPerPage - 1) / notesPerPage + if page < 0 { + page = 0 + } + if page >= pages { + page = pages - 1 + } + start := page * notesPerPage + end := start + notesPerPage + if end > len(entries) { + end = len(entries) + } + var rows []tb.Row + text := fmt.Sprintf(TranslateUser(ctx, "notesListHeader"), len(entries), page+1, pages) + "\n" + for i, e := range entries[start:end] { + text += fmt.Sprintf("\n%d. %s", start+i+1, str.MarkdownEscape(e.label)) + unique := "lnc_open" + if e.batch { + unique = "lnc_openb" + } + rows = append(rows, menu.Row(menu.Data(fmt.Sprintf("%d · %s", start+i+1, lnurlcash.ShortID(e.id)), unique, e.id))) + } + var nav []tb.Btn + if page > 0 { + nav = append(nav, menu.Data("◀️", "lnc_page", list.ID+":"+strconv.Itoa(page-1))) + } + if page < pages-1 { + nav = append(nav, menu.Data("▶️", "lnc_page", list.ID+":"+strconv.Itoa(page+1))) + } + if len(nav) > 0 { + rows = append(rows, menu.Row(nav...)) + } + menu.Inline(rows...) + return text, menu +} + +// notesPageHandler scrolls the list. +func (bot *TipBot) notesPageHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + id, pageStr, _ := strings.Cut(ctx.Data(), ":") + page, _ := strconv.Atoi(pageStr) + tx := &NotesList{Base: storage.New(storage.ID(id))} + got, err := tx.Get(tx, bot.Bunt) + if err != nil { + return ctx, err + } + list := got.(*NotesList) + if list.UserName != LoadUser(ctx).Name { + return ctx, tiperrors.Create(tiperrors.UnknownError) + } + text, kb := bot.notesPage(ctx, list, page) + bot.tryEditMessage(ctx.Callback().Message, text, kb) + return ctx, nil +} + +// notesOpenHandler shows one note with its actions. +func (bot *TipBot) notesOpenHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + n, err := bot.loadOwnNote(ctx) + if err != nil { + return ctx, err + } + bot.trySendMessageEditable(ctx.Sender(), noteViewText(ctx, n), noteKeyboard(ctx, n, true)) + return ctx, nil +} + +// notesOpenBatchHandler shows one batch with its actions. +func (bot *TipBot) notesOpenBatchHandler(ctx intercept.Context) (intercept.Context, error) { + if bot.LNURLCash == nil { + return ctx, nil + } + b, err := bot.loadOwnBatch(ctx) + if err != nil { + return ctx, err + } + bot.trySendMessageEditable(ctx.Sender(), bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID)) + return ctx, nil +} diff --git a/internal/telegram/redact.go b/internal/telegram/redact.go index 69974a44..96c0c755 100644 --- a/internal/telegram/redact.go +++ b/internal/telegram/redact.go @@ -31,6 +31,9 @@ func redactForLog(text string) string { fields[i] = fmt.Sprintf("", len(f)) case cashuTokenPattern.MatchString(f): fields[i] = fmt.Sprintf("", len(f)) + case strings.Contains(lower, "k1="): + // an LNURLcash note or withdraw link in URL form: the spend is in the query + fields[i] = fmt.Sprintf("", len(f)) } } return strings.Join(fields, " ") diff --git a/internal/telegram/text.go b/internal/telegram/text.go index dc74376e..a0c2320f 100644 --- a/internal/telegram/text.go +++ b/internal/telegram/text.go @@ -43,7 +43,7 @@ func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, err return bot.payHandler(ctx) } if lightning.IsLnurl(anyText) { - m.Text = "/lnurl " + anyText + m.Text = "/lnurl " + preserveNoteCase(m.Text) return bot.lnurlHandler(ctx) } if c := stateCallbackMessage[user.StateKey]; c != nil { @@ -124,3 +124,16 @@ func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, e return ctx, errors.Create(errors.InvalidSyntaxError) } } + +// preserveNoteCase lowercases pasted LNURL text the way it always was, except +// for an lnurlw:// link, whose path may be case-sensitive at the mint. Only +// the scheme is lowercased there. +func preserveNoteCase(text string) string { + lower := strings.ToLower(text) + for _, prefix := range []string{"lightning:lnurlw://", "lnurlw://"} { + if strings.HasPrefix(lower, prefix) { + return prefix + text[len(prefix):] + } + } + return lower +} diff --git a/translations/en.toml b/translations/en.toml index d1f2ab0c..f11aafe7 100644 --- a/translations/en.toml +++ b/translations/en.toml @@ -409,4 +409,83 @@ For users (in private chat): `/join `\nExample: `/join TheBestBitcoi # DALLE GENERATE generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate `\nPrice: 1000 sat""" generateDallePayInvoiceMessage = """Pay this invoice to generate four images 👇""" -generateDalleGeneratingMessage = """Your images are being generated. Please wait...""" \ No newline at end of file +generateDalleGeneratingMessage = """Your images are being generated. Please wait...""" +# LNURLCASH +lnurlcashDisabledMessage = """🚫 LNURLcash notes are not enabled on this bot.""" +lnurlcashStartPrivateFirstMessage = """👋 Start a private chat with me first, then try again.""" +noteHelpMessage = """🎫 *LNURLcash notes*\n\nA note is a bearer link worth a fixed number of sats. Whoever scans it first gets the sats.\n\n`/note [memo]` creates one note.\n`/notes` lists your notes and batches.\n`/notes x [memo]` creates a batch.\n`/redeem ` adds a received note to your balance (or just paste it).\n`/lnurlmints` shows the mints and sets your default.""" +notesHelpMessage = """📖 Usage: `/notes` or `/notes x [memo]`""" +redeemHelpMessage = """📖 Usage: `/redeem ` — or paste the note or send a photo of its QR code in private chat.""" +noteConfirmMessage = """🎫 *Create %d note(s)?*\n\n💸 Value: %s sat each\n🏦 Mint fee: %s sat\n💰 Total: %s sat\n🏭 Mint: %s""" +noteViewMemo = """\n✉️ %s""" +noteCreateButton = """✅ Create""" +noteChangeMintButton = """🏭 Change mint""" +noteCancelButton = """🚫 Cancel""" +noteCancelledMessage = """🚫 Cancelled.""" +noteCreatingMessage = """🧮 Creating your note, this can take a moment...""" +noteCreatedMessage = """🎫 Note of *%s sat* created (id `%s`).\n\nShare the QR code or this link. The first scan wins:\n`%s`""" +noteGroupMessage = """🎫 A note worth *%s sat* from %s. First scan wins!\n\n`%s`""" +noteGroupClaimedMessage = """✅ This %s sat note has been claimed.""" +noteGroupWithdrawnMessage = """↩️ This %s sat note was withdrawn by its creator.""" +noteReceiptMessage = """🧾 *Note posted in the group*\n\n💸 Value: %s sat\n🏦 Mint fee: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`""" +noteReclaimButton = """↩️ Reclaim""" +noteStatusButton = """🔎 Check status""" +noteShowQrButton = """🔳 Show QR""" +noteStatusLiveMessage = """🟢 The note is unclaimed and worth %s sat.""" +noteStatusClaimedMessage = """✅ The note has been claimed.""" +noteStatusPendingMessage = """⏳ The mint is still settling an operation on this note. Try again in a moment.""" +noteStatusOtherMessage = """ℹ️ Note status: %s""" +noteInFlightMessage = """⏳ Still in progress. I will finish it in the background and let you know.""" +noteReclaimRequestedMessage = """↩️ Reclaim requested for %s sat. You will be notified when it arrives.""" +noteReclaimedMessage = """↩️ %s sat from note `%s` are back in your balance.""" +noteClaimedNotifyMessage = """✅ Your %s sat note `%s` has been claimed. %s""" +noteBatchDigestMessage = """✅ %d note(s) of batch `%s` were claimed (%d of %d so far).""" +noteNothingToReclaimMessage = """ℹ️ There is nothing to reclaim on this note.""" +noteNotOwnerMessage = """🚫 That is not your note.""" +noteOnlyOneMintMessage = """ℹ️ Only one mint is available.""" +noteCapValueMessage = """🚫 A note must be between %d and %d sat (at most %d sat in a group).""" +noteCapBatchMessage = """🚫 A batch may hold at most %d notes and %d sat in total.""" +noteCapOutstandingMessage = """🚫 You already have too many unclaimed notes (limit: %d notes or %d sat).""" +noteInsufficientFundsMessage = """🚫 Your balance does not cover the note and the mint fee.""" +noteMintUnavailableMessage = """🚫 The mint is not available right now. Try again later.""" +noteMintRangeMessage = """🚫 The mint does not accept this amount.""" +noteErrorMessage = """🚫 Something went wrong. Try again later.""" +noteStateLive = """unclaimed""" +noteStateClaimed = """claimed""" +noteStateReclaiming = """being reclaimed""" +noteStateReclaimed = """reclaimed""" +noteStateFailed = """failed""" +noteStatePending = """pending""" +noteViewMessage = """🎫 *Note* `%s`\n\n💸 Value: %s sat\n📍 Status: %s\n🏭 Mint: %s\n🕓 Created: %s""" +notesListHeader = """🎫 *Your notes and batches* (%d, page %d/%d)""" +notesListEmpty = """You have no notes yet. Create one with `/note `.""" +notesListItem = """%s %s sat · %s %s""" +notesBatchItem = """📦 %d × %s sat · %d unclaimed, %d claimed · %s""" +notesBatchOpenMessage = """📦 *Batch* `%s`\n\n🎫 %d notes of %s sat\n🏭 Mint: %s\n🕓 Created: %s\n\n🟢 Unclaimed: %d\n✅ Claimed: %d\n↩️ Reclaimed: %d\n⏳ Other: %d""" +notesExportPdfButton = """📄 PDF""" +notesExportJsonButton = """🧾 JSON""" +notesExportCsvButton = """📊 CSV""" +notesExportCaption = """%d unclaimed note(s) of batch `%s`. Keep this file private: it holds the notes themselves.""" +notesRefreshButton = """🔄 Refresh status""" +notesReclaimUnclaimedButton = """↩️ Reclaim unclaimed""" +notesBatchProgressMessage = """🧮 Creating notes... %d/%d\n%s""" +notesBatchCreatedMessage = """📦 %d of %d notes created (batch `%s`).""" +notesBatchPartialMessage = """⚠️ Some notes could not be created: %s\nThe remaining funds are returned to your balance.""" +notesBatchFormatMessage = """Pick a format to export the notes:""" +notesBatchReclaimMessage = """↩️ Reclaim requested for %d note(s).""" +redeemPreviewMessage = """🎫 This note is worth *%s sat* at `%s`.\n\nAdd it to your balance?""" +redeemUnknownMintWarning = """⚠️ This mint is not on this bot's list. Redeem at your own risk.""" +redeemAddButton = """💰 Add to balance""" +redeemInFlightMessage = """⏳ Redeeming...""" +redeemRequestedMessage = """⏳ The mint is paying out %s sat. You will be notified when it arrives.""" +redeemDoneMessage = """✅ %s sat from the note were added to your balance.""" +redeemPendingMessage = """⏳ The mint is still settling an operation on this note. Try again in a moment.""" +redeemNotANoteMessage = """🚫 That is not an LNURLcash note.""" +redeemFractionalMessage = """🚫 This note's value is not a whole number of sats and could not be split.""" +redeemOwnNoteMessage = """ℹ️ That is one of your own notes. Use its Reclaim button instead.""" +redeemCancelledMessage = """🚫 Redeem cancelled.""" +lnurlmintsHeader = """🏭 *LNURLcash mints*\n""" +lnurlmintsItem = """\n%s *%s*%s\n `%s` · fee: %s""" +lnurlmintsNoFee = """none""" +lnurlmintsSetButton = """Use %s""" +lnurlmintsSetMessage = """⭐️ %s is now your default mint.""" diff --git a/translations/nl.toml b/translations/nl.toml index ab73b7ee..c4635839 100644 --- a/translations/nl.toml +++ b/translations/nl.toml @@ -316,3 +316,83 @@ inlineReceiveCreateWalletMessage = """Chat met %s 👈 om uw wallet te beheren." inlineReceiveYourselfMessage = """📖 Je kunt niet aan jezelf betalen.""" inlineReceiveFailedMessage = """🚫 Ontvangst mislukt.""" inlineReceiveCancelledMessage = """🚫 Ontvangen geannuleerd.""" + +# LNURLCASH +lnurlcashDisabledMessage = """🚫 LNURLcash-notes zijn op deze bot niet ingeschakeld.""" +lnurlcashStartPrivateFirstMessage = """👋 Start eerst een privéchat met mij en probeer het dan opnieuw.""" +noteHelpMessage = """🎫 *LNURLcash-notes*\n\nEen note is een link aan toonder ter waarde van een vast aantal sats. Wie hem het eerst scant, krijgt de sats.\n\n`/note [memo]` maakt één note.\n`/notes` toont je notes en batches.\n`/notes x [memo]` maakt een batch.\n`/redeem ` voegt een ontvangen note toe aan je saldo (of plak hem gewoon).\n`/lnurlmints` toont de mints en kiest je standaard.""" +notesHelpMessage = """📖 Gebruik: `/notes` of `/notes x [memo]`""" +redeemHelpMessage = """📖 Gebruik: `/redeem ` — of plak de note of stuur een foto van de QR-code in een privéchat.""" +noteConfirmMessage = """🎫 *%d note(s) maken?*\n\n💸 Waarde: %s sat per stuk\n🏦 Mintkosten: %s sat\n💰 Totaal: %s sat\n🏭 Mint: %s""" +noteViewMemo = """\n✉️ %s""" +noteCreateButton = """✅ Maken""" +noteChangeMintButton = """🏭 Andere mint""" +noteCancelButton = """🚫 Annuleren""" +noteCancelledMessage = """🚫 Geannuleerd.""" +noteCreatingMessage = """🧮 Je note wordt gemaakt, dit kan even duren...""" +noteCreatedMessage = """🎫 Note van *%s sat* gemaakt (id `%s`).\n\nDeel de QR-code of deze link. De eerste scan wint:\n`%s`""" +noteGroupMessage = """🎫 Een note van *%s sat* van %s. De eerste scan wint!\n\n`%s`""" +noteGroupClaimedMessage = """✅ Deze note van %s sat is opgeëist.""" +noteGroupWithdrawnMessage = """↩️ Deze note van %s sat is door de maker ingetrokken.""" +noteReceiptMessage = """🧾 *Note geplaatst in de groep*\n\n💸 Waarde: %s sat\n🏦 Mintkosten: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`""" +noteReclaimButton = """↩️ Terughalen""" +noteStatusButton = """🔎 Status""" +noteShowQrButton = """🔳 Toon QR""" +noteStatusLiveMessage = """🟢 De note is nog niet opgeëist en is %s sat waard.""" +noteStatusClaimedMessage = """✅ De note is opgeëist.""" +noteStatusPendingMessage = """⏳ De mint is nog bezig met deze note. Probeer het zo opnieuw.""" +noteStatusOtherMessage = """ℹ️ Status van de note: %s""" +noteInFlightMessage = """⏳ Nog bezig. Ik maak het op de achtergrond af en laat het je weten.""" +noteReclaimRequestedMessage = """↩️ Terughalen van %s sat aangevraagd. Je krijgt bericht zodra het binnen is.""" +noteReclaimedMessage = """↩️ %s sat van note `%s` staan weer op je saldo.""" +noteClaimedNotifyMessage = """✅ Je note `%s` van %s sat is opgeëist. %s""" +noteBatchDigestMessage = """✅ %d note(s) van batch `%s` zijn opgeëist (%d van %d tot nu toe).""" +noteNothingToReclaimMessage = """ℹ️ Er valt op deze note niets terug te halen.""" +noteNotOwnerMessage = """🚫 Dat is niet jouw note.""" +noteOnlyOneMintMessage = """ℹ️ Er is maar één mint beschikbaar.""" +noteCapValueMessage = """🚫 Een note moet tussen %d en %d sat zijn (in een groep maximaal %d sat).""" +noteCapBatchMessage = """🚫 Een batch mag maximaal %d notes en %d sat in totaal bevatten.""" +noteCapOutstandingMessage = """🚫 Je hebt al te veel openstaande notes (limiet: %d notes of %d sat).""" +noteInsufficientFundsMessage = """🚫 Je saldo dekt de note en de mintkosten niet.""" +noteMintUnavailableMessage = """🚫 De mint is nu niet beschikbaar. Probeer het later opnieuw.""" +noteMintRangeMessage = """🚫 De mint accepteert dit bedrag niet.""" +noteErrorMessage = """🚫 Er ging iets mis. Probeer het later opnieuw.""" +noteStateLive = """niet opgeëist""" +noteStateClaimed = """opgeëist""" +noteStateReclaiming = """wordt teruggehaald""" +noteStateReclaimed = """teruggehaald""" +noteStateFailed = """mislukt""" +noteStatePending = """in behandeling""" +noteViewMessage = """🎫 *Note* `%s`\n\n💸 Waarde: %s sat\n📍 Status: %s\n🏭 Mint: %s\n🕓 Gemaakt: %s""" +notesListHeader = """🎫 *Je notes en batches* (%d, pagina %d/%d)""" +notesListEmpty = """Je hebt nog geen notes. Maak er een met `/note `.""" +notesListItem = """%s %s sat · %s %s""" +notesBatchItem = """📦 %d × %s sat · %d open, %d opgeëist · %s""" +notesBatchOpenMessage = """📦 *Batch* `%s`\n\n🎫 %d notes van %s sat\n🏭 Mint: %s\n🕓 Gemaakt: %s\n\n🟢 Open: %d\n✅ Opgeëist: %d\n↩️ Teruggehaald: %d\n⏳ Overig: %d""" +notesExportPdfButton = """📄 PDF""" +notesExportJsonButton = """🧾 JSON""" +notesExportCsvButton = """📊 CSV""" +notesExportCaption = """%d open note(s) van batch `%s`. Houd dit bestand privé: het bevat de notes zelf.""" +notesRefreshButton = """🔄 Status verversen""" +notesReclaimUnclaimedButton = """↩️ Open notes terughalen""" +notesBatchProgressMessage = """🧮 Notes maken... %d/%d\n%s""" +notesBatchCreatedMessage = """📦 %d van %d notes gemaakt (batch `%s`).""" +notesBatchPartialMessage = """⚠️ Sommige notes konden niet worden gemaakt: %s\nHet resterende bedrag gaat terug naar je saldo.""" +notesBatchFormatMessage = """Kies een formaat om de notes te exporteren:""" +notesBatchReclaimMessage = """↩️ Terughalen aangevraagd voor %d note(s).""" +redeemPreviewMessage = """🎫 Deze note is *%s sat* waard bij `%s`.\n\nToevoegen aan je saldo?""" +redeemUnknownMintWarning = """⚠️ Deze mint staat niet op de lijst van deze bot. Inwisselen op eigen risico.""" +redeemAddButton = """💰 Toevoegen aan saldo""" +redeemInFlightMessage = """⏳ Inwisselen...""" +redeemRequestedMessage = """⏳ De mint betaalt %s sat uit. Je krijgt bericht zodra het binnen is.""" +redeemDoneMessage = """✅ %s sat van de note zijn aan je saldo toegevoegd.""" +redeemPendingMessage = """⏳ De mint is nog bezig met deze note. Probeer het zo opnieuw.""" +redeemNotANoteMessage = """🚫 Dat is geen LNURLcash-note.""" +redeemFractionalMessage = """🚫 De waarde van deze note is geen heel aantal sats en kon niet worden gesplitst.""" +redeemOwnNoteMessage = """ℹ️ Dat is een van je eigen notes. Gebruik de knop Terughalen.""" +redeemCancelledMessage = """🚫 Inwisselen geannuleerd.""" +lnurlmintsHeader = """🏭 *LNURLcash-mints*\n""" +lnurlmintsItem = """\n%s *%s*%s\n `%s` · kosten: %s""" +lnurlmintsNoFee = """geen""" +lnurlmintsSetButton = """Gebruik %s""" +lnurlmintsSetMessage = """⭐️ %s is nu je standaardmint."""