diff --git a/docs/lnurlcash/AUDIT.md b/docs/lnurlcash/AUDIT.md new file mode 100644 index 00000000..d0d9689a --- /dev/null +++ b/docs/lnurlcash/AUDIT.md @@ -0,0 +1,373 @@ +# LNURLcash audit of LightningTipBot (branch update-bugfixes @ 5a3b4da) + + +> Audit of `update-bugfixes` @ `5a3b4da` (clean tree) for the LNURLcash feature. Paths are +> relative to the repo root; `t/` means `internal/telegram/`. Every claim names a file and +> function. Where something could not be verified from code, it says so. + +## 1. Structure + +**Entry point** `main.go`: package `init()`s run first (`internal/config.go:72` loads +`config.yaml` with `configor.Load`, panics on error, parses the webhook and LNURL URLs; +`internal/i18n/localize.go:15` loads `translations/*.toml`). Then `main()`: +`setLogger()` (Debug level, unconditionally, `main.go:28`), `price.NewPriceWatcher().Start()`, +`telegram.NewBot()` (`t/bot.go:44`: go-cache, `AutoMigration()`, rate limiter, LNbits +client, two buntdb files, `tb.NewBot` with 60 s long poller and Markdown parse mode), +`startApiServer()` (`main.go:45`: no-op `OnError`, webhook server, public API, admin API), +`bot.Start()` (`t/bot.go:111`: `initBotWallet`, `registerTelegramHandlers`, edit worker, +`initInvoiceEventCallbacks`, `initializeStateCallbackMessage`, `go Telegram.Start()`, +`go restartPersistedTickets()`, then wait for SIGINT and `GracefulShutdown`, which polls +`mutex.IsEmpty()` for at most 10 s). + +**Config**: one global struct `internal.Configuration` (`internal/config.go:13`) with +`Bot`, `Telegram`, `Database`, `Lnbits`, `Generate`, `Nostr`. A new `lnurlcash:` block is a +new struct + field here. configor decodes YAML with yaml.v2, so `time.Duration` fields +accept `5m`/`60s`. `config.yaml.example` lists every key; `http_proxy` in the example has +no struct field. + +**Packages**: `internal` (config), `internal/api` (+`admin`, `userpage`), `internal/database` +(column migrations + user lookups only; it opens no DB), `internal/errors`, `internal/i18n`, +`internal/lnbits` (REST client + `User`/`Wallet`/`Settings` GORM models), `internal/lnbits/webhook` +(+`verify`), `internal/lnurl` (LNURL-pay server, NIP-57), `internal/netguard` (refuses private +IPs), `internal/network` (`GetClientForScheme`: 10 s timeout, netguard dialer, SOCKS/Tor), +`internal/nostr`, `internal/price`, `internal/rate`, `internal/runtime` (+`mutex`, `once`), +`internal/satdress`, `internal/storage` (buntdb wrapper, `Base`), `internal/str`, +`internal/telegram` (+`intercept`), `internal/gpt`, `internal/dalle`, `internal/lndhub`, +`pkg/lightning` (`IsInvoice`, `IsLnurl`, `IsLightningAddress`; string checks only). + +**Versions** (`go.mod`): `go 1.26.0`, `toolchain go1.26.11`; telebot fork +`gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd`; `gorm.io/gorm v1.21.12`; +`gorm.io/driver/sqlite v1.1.4` (mattn/go-sqlite3 v1.14.5, cgo); `tidwall/buntdb v1.2.7`; +`fiatjaf/go-lnurl v1.11.3-0.20220819192234`; `fiatjaf/ln-decodepay v1.1.0` (only use: +`t/pay.go:81`); `skip2/go-qrcode` (2020); `makiuchi-d/gozxing v0.0.2`; `go-i18n/v2 v2.1.2`; +`jinzhu/configor v1.2.1`; `btcsuite/btcd/btcec/v2 v2.2.0` (direct, `internal/lnbits/types.go:160` +for LNURL-auth); `lightningnetwork/lnd v0.15.0-beta` (indirect, via ln-decodepay → zpay32). +There is no LNbits client library dependency: the client is hand-written in `internal/lnbits/lnbits.go`. + +## 2. Handler registration and routing + +- `t/handler.go:19 registerTelegramHandlers` iterates `getHandler()` (`handler.go:85-1316`, + one `InterceptionWrapper{Endpoints, Handler, Interceptor}` per entry) and calls + `registerHandlerWithInterceptor` (`handler.go:41`), which prepends the defaults + `idInterceptor, rejectPlaceholderSenderInterceptor` and wraps with + `intercept.WithHandler`. `handle()` (`handler.go:55`) also registers `/CMD` and `/Cmd` + variants for slash commands. +- Endpoints are strings (`"/faucet"`), telebot events (`tb.OnText`, `tb.OnPhoto`, + `tb.OnQuery`) or `*tb.Btn`. Buttons route by `Unique`: telebot serialises callback data + as `"\f|"` and matches `^\f([-\w]+)(\|(.+))?$`, then hands the handler + `ctx.Callback().Data` = payload. One flat namespace: registering the same `Unique` twice + silently replaces the earlier handler. Existing uniques: `confirm_/cancel_` + + `pay|send|withdraw|login|send_inline|receive_inline|faucet_inline|tipjar_inline`, + `pay_ticket`, `left_transactions`, `right_transactions`, `satdress_check_invoice`, `shop_*`. + Telegram's 64-byte callback limit applies to the whole string. +- telebot runs every update in its own goroutine (fork `util.go:30`); `Synchronous` is not set. +- **Faucet pattern** (`t/faucet.go`): command registered at `handler.go:392` with + `localizer, logMessage, requireUser, lock` + `OnDefer: unlock`; `InlineFaucet` embeds + `*storage.Base`; id `faucet::`; keyboard built per message with a fresh + `&tb.ReplyMarkup{}` and `.Data(label, "confirm_faucet_inline", id)`; persisted with + `obj.Set(obj, bot.Bunt)`. Click handler `acceptInlineFaucetHandler` (`faucet.go:250`): + `tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}`, + `mutex.LockWithContext(ctx, tx.ID)` + deferred unlock, `tx.Get`, checks `Active`, owner, + then acts, edits via `tryEditStack`, `Inactivate`. Registration at `handler.go:788-820` + uses `singletonCallbackInterceptor, localizer, loadUser, answerCallback, lock`. +- **Tipjar** (`t/tipjar.go:178,238,343`): same shape, `confirm_tipjar_inline`/`cancel_tipjar_inline`. +- **/send** (`t/send.go:61 sendHandler`): `SendData` with id `send---`, + saved to Bunt and copied into the user's sqlite state (`SetUserState(... UserStateConfirmSend ...)`); + `confirmSendHandler` (`send.go:274`) locks the object, checks `From.Telegram.ID == sender` + and `Active`, `ResetUserState`, `NewTransaction(...).Send()`, `Inactivate`; in private chat + deletes the confirmation and sends a fresh message, in a group edits it and DMs the sender. + `cancelSendHandler` (`send.go:360`): owner check, `tryDeleteMessage`, `Inactivate`. + Caveat: `sendConfirmationMenu` is a package-level `ReplyMarkup` mutated per request (race). +- **Message disposal**: `NewMessage(m, WithDuration(d, bot))` (`t/message.go:17,24`) deletes + after `d` via goroutine, never in private chats; `WithDuration(0, bot)` deletes at once. + `tryDeleteMessage` (`t/telegram.go:88`) needs admin rights in groups (cached 5 min). + There is no `DisposeMessage`. +- **/transactions pagination** (`t/transactions.go:107`): `TransactionsList` kept in + `bot.Cache` under `"_transactions"` for 1 min (not Bunt); buttons + `left_transactions`/`right_transactions` with the list id as data but lookup is by user + name; `tryEditMessage` on scroll; registered at `handler.go:349-390`. Bugs not to copy: + `printTransactions` start index `pagenr*(tx_per_page-1)` with inclusive end (11 rows, + overlapping pages), hard-coded English footer, shared package-level `transactionsMeno`. +- **Photo/QR** (`t/photo.go:44 photoHandler`, registered `handler.go:598` with + `requirePrivateChat, localizer, logMessage, requireUser, lock`): if the user has a pending + state, that state's callback consumes the photo (no QR decode). Else `bot.Telegram.File`, + `jpeg.Decode` (JPEG only), `TryRecognizeQrCode` (gozxing, accepts only `IsInvoice`/`IsLnurl`), + echoes `photoQrRecognizedMessage`, then rewrites `m.Text` to `/pay …` or `/lnurl …` and + calls `payHandler`/`lnurlHandler` directly. Documents go to `fileHandler` (`t/files.go:11`), + never QR-decoded. +- **Text** (`t/text.go:18 anyTextHandler`, private only, `loadUser` + `lock`): uninitialised + user → `startHandler`; `Balance` prefix → balance; `IsInvoice(lower)` → `/pay`; + `IsLnurl(lower)` → `/lnurl` (note: `m.Text` is lowercased first); else + `stateCallbackMessage[user.StateKey]` (`t/state.go:12`). `IsLnurl` is a prefix check, so a + pasted `lnurlw://…` note already reaches `lnurlHandler` today. +- **Inline queries** (`t/inline_query.go:141`): prefix routing; not needed for notes. + +## 3. Middleware and locking + +- Interceptors (`t/interceptor.go`): `idInterceptor` (random `uid` in ctx, :56), + `rejectPlaceholderSenderInterceptor` (:67), `singletonCallbackInterceptor` (:30, `once`), + `lockInterceptor`/`unlockInterceptor` (:38-55, `mutex.Lock(strconv.FormatInt(sender.ID,10))`), + `answerCallbackInterceptor` (:87), `requireUserInterceptor` (:108, sets `"user"`, errors if + banned or not found), `loadUserInterceptor` (:151, tolerates unknown users: stub with + `Wallet == nil`), `localizerInterceptor` (:181, `publicLocalizer` = English in groups, + user language in private; `userLocalizer` always user language), + `requirePrivateChatInterceptor` (:215, also fails for callbacks since `Message()` is nil), + `logMessageInterceptor` (:227, redacts via `redactForLog`). +- `intercept.WithHandler` (`t/intercept/context.go:59`) runs Before, registers + `defer intercept(h, onDefer)` with the pre-handler context (so a `callback_response` set by + the handler never reaches a deferred `answerCallbackInterceptor`), runs the handler, then After. +- Per-user lock: `internal/runtime/mutex/mutex_lock.go:124 Lock(s)` on a concurrent map keyed + by the decimal Telegram id; not re-entrant. Object locks use `LockWithContext(ctx, id)` + (`mutex.go:57`), whose re-entrancy counter `nLocks:` is keyed by request `uid` only + (`mutex.go:68`): **a second, different object locked in the same request is skipped**. + `UnlockHTTP` (admin `/mutex/unlock/{id}`) can force-unlock any key. +- Users: `GetUser(tbUser, bot)` (`t/database.go:206`, 1-min cache then sqlite by primary key + `Name` = Telegram id; returns a stub + `gorm.ErrRecordNotFound` when absent); + `GetLnbitsUserWithSettings` (:190) preloads `Settings`; `UpdateUserRecord` (:263) re-reads + `banned`/`wallet_adminkey` and saves with `FullSaveAssociations`; + `CreateWalletForTelegramUser` (`t/users.go:102`) creates an LNbits wallet for a recipient + who never started the bot (`Initialized=false`). +- Private vs group: no helper; code uses `m.Chat.Type != tb.ChatPrivate` or `m.Private()`; + `requirePrivateChatInterceptor` for whole endpoints. Sending privately from a group: + `bot.trySendMessage(ctx.Sender() /* or user.Telegram */, …)` (`t/telegram.go:37`); + `trySendMessageEditable` skips the main-menu keyboard. A user who never started the bot: + telebot returns `ErrNotStartedByUser` ("Forbidden: bot can't initiate conversation"); + `trySendMessage` only logs a warning and returns nil, so nothing today detects it. + +## 4. Money paths + +- LNbits client `internal/lnbits/lnbits.go`: `(w Wallet) Invoice(InvoiceParams, *Client)` (:88, + `POST /api/v1/payments` with inkey; `InvoiceParams.Amount` is **int64 sats**, `Webhook`, + `Memo`), `(c Client) Info(w)` (:112, balance in msat), `Payments(w)` (:136, last 60), + `Payment(w, hash)` (:160, `LNbitsPayment{Paid, Preimage, Details.Pending}`), + `(w Wallet) Pay(PaymentParams{Out:true, Bolt11}, *Client)` (:202, adminkey, **24 h request + timeout** at :210). Errors are `lnbits.Error{Detail}`. The client never logs. +- Incoming money: LNbits settles and credits the wallet itself; the bot only learns about it. + Webhook `internal/lnbits/webhook/webhook.go:121 receive`: validates the hash, finds the + user by `wallet_id` (:75), re-checks with `Payment` + `verify.SettledIncoming` (:86), marks + `webhook:` in Bunt (no TTL) to dedupe, loads `InvoiceEvent` `invoice:` from Bunt + and dispatches `telegram.InvoiceCallback[ev.Callback]` in a goroutine (no user lock); + with no event it sends the generic `invoiceReceivedMessage`. **No polling fallback in this + tree** (`kravens/fix/poll-invoices-when-webhook-fails` is unmerged); the only pull path is + `bot.Client.Payment` (used by `/transactions` and the webhook). +- `InvoiceEvent` + callback registry: `t/invoice.go:37 initInvoiceEventCallbacks`, constants + `InvoiceCallbackGeneric … InvoiceCallbackPayJoinTicket` (1–7). `createInvoiceWithEvent` + (`invoice.go:185`) is the helper that creates an invoice with the webhook and stores the + event (it embeds the whole `*lnbits.User`, admin key included, in Bunt JSON). +- Paying: `/pay` (`t/pay.go:55`) decodes with `decodepay.Decodepay`, checks `GetUserBalance` + (sats, writes the balance back into the users DB on every call, `t/users.go:73`), warns + above 98 % of balance, stores `PayData` `pay:--`, and + `confirmPayHandler` (:162) calls `user.Wallet.Pay`; on error the object stays `Active` + (a second tap re-sends the same bolt11). No `Transaction` row for external payments. +- Internal transfers: `t/transaction.go:87 SendTransaction` creates an invoice on the + receiver's wallet (no webhook) and pays it from the sender's wallet; `Transaction` rows go + to `transactions.db`. Not needed for notes. +- `pkg/lightning`: prefix checks only; bolt11 amount decoding lives in `pay.go` via ln-decodepay. + +## 5. Existing LNURL code and what `/lnurl ` does today + +- `/lnurl` registered at `handler.go:516` (`requirePrivateChat, localizer, logMessage, + requireUser, lock`). `lnurlHandler` (`t/lnurl.go:31`): **logs the full raw text at :40**; + bare `/lnurl` → `lnurlReceiveHandler` (own LNURL QR); parses `[amount] `; strips + `lightning:`; `bot.HandleLNURL` (`lnurl.go:181`, a modified copy of go-lnurl 1.8.4): + lightning address → `.well-known/lnurlp`; `http…` verbatim; `lnurlp/w/a://` and + `keyauth://` → https (http for `.onion`); else bech32 `FindLNURLInText` + `LNURLDecodeStrict`. + **:217 `log.Debug` logs the decoded URL including `k1`** (Debug is on). Query `tag=login` + → `lnurl.HandleAuth`; `tag=withdrawRequest` with all params → `HandleFastWithdraw` (no GET). + Otherwise GET via `network.GetClientForScheme` and switch on body `tag`: + `withdrawRequest` → `lnurl.HandleWithdraw(b)` (go-lnurl `LNURLWithdrawResponse`: + `Tag, K1, Callback, MaxWithdrawable, MinWithdrawable, DefaultDescription, BalanceCheck, + PayLink`; **unknown JSON fields such as `mintPubkey` and `c` are dropped**; the raw body + `b` is local and not returned), `payRequest` → `HandlePay`. Type switch at `lnurl.go:79`: + auth → `lnurlAuthHandler` (`:82` logs the callback incl. `k1`), pay → `lnurlPayHandler`, + withdraw → `lnurlWithdrawHandler` (`:107` logs the callback URL). +- `lnurlWithdrawHandler` (`t/lnurl-withdraw.go:78`): `LnurlWithdrawState{*storage.Base, From, + LNURLWithdrawResponse, Amount(msat), …}` id `lnurlw--`; range check only when + min and max are both non-zero; amount from command or `askForAmount(... "LnurlWithdrawState" ...)` + (`t/amounts.go:139`, state `UserEnterAmount`); then `lnurlWithdrawHandlerWithdraw` (:139) + shows `confirmLnurlWithdrawMessage` with `confirm_withdraw`/`cancel_withdraw` (mutating the + package-level `withdrawConfirmationMenu`, :193). `confirmWithdrawHandler` (:208): object + lock, owner check, `Active` check, `user.Wallet.Invoice({Amount: msat/1000, Memo:"Withdraw", + Webhook})` (**no `InvoiceEvent` stored**), GET `callback?pr=&k1=` via `GetClientForScheme`, + `json.Unmarshal` into `lnurl.LNURLResponse` (error ignored); `Status=="OK"` → `Active=false` + + `lnurlWithdrawSuccess`; else `lnurlWithdrawFailed`; on transport error `Active` stays true. + Credit arrives through LNbits + webhook → generic `invoiceReceivedMessage`. +- **So today, `/lnurl ` in private chat** = a plain LUD-03 withdraw of the + note's full value into the user's wallet, with the `k1` logged twice (:40 raw text, :217 + decoded URL), no `mintPubkey` awareness, no "pending" handling (`{"status":"ERROR", + "reason":"pending"}` shows as "Withdrawal failed"), and the note secret persisted in Bunt + (`LnurlWithdrawState`) and, on the direct-amount path, in the sqlite `users.state_data` + column (`lnurl-withdraw.go:126-132`). In a group the command is dropped silently by + `requirePrivateChatInterceptor` (`OnError` is a no-op). A pasted bare note (`lnurlw://…`) + is lowercased and routed the same way by `anyTextHandler`; a QR photo of it likewise, unless + a pending user state swallows the photo first. +- LNURL server (`internal/lnurl/lnurl.go:78 Handle`, routes in `main.go:55-80`): lnurl-pay + for `user@host` (`serveLNURLpSecond` stores an `InvoiceEvent` with + `InvoiceCallbackLNURLPayReceive`), NIP-57, userpage, NIP-05, lndhub proxy, `/api/v1/*`. + Not affected by the feature. + +## 6. Storage + +- Three sqlite files opened in `t/database.go:107 AutoMigration` with + `gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true}`: + users (`database.db_path`, `AutoMigrate(&lnbits.User{})` after `ColumnMigrationTasks`), + transactions (`transactions_path`, `&Transaction{}`), groups (`groupsdb_path`, `&Group{}`); + handles live in `Databases{Users, Transactions, Groups}` (`database.go:32`) as `bot.DB`. + **Adding a table**: define the GORM struct in a package `telegram` can import, add a + path key to `DatabaseConfiguration` (`internal/config.go:55`) and `config.yaml`, open + + `AutoMigrate` in `AutoMigration`, add a field to `Databases`. AutoMigrate adds tables and + columns only; one-off data migrations follow `ColumnMigrationTasks` (`database.go:65`). +- User model `internal/lnbits/types.go:24 User` (`Name` = Telegram id, embedded `Telegram` + and `Wallet` with plaintext `adminkey`/`inkey` columns, `StateKey/StateData`, `Settings` + has-one in table `settings`: `Display.DisplayCurrency`, `Node`, `Nostr`). +- Bunt: `internal/storage/bunt.go` (`Storable{Key()}`, JSON `Set/Get/Delete`, **no TTL ever + set**), `internal/storage/base.go` (`Base{ID, Active, Canceled, CreatedAt, UpdatedAt}`, + `Get/Set/Inactivate` through a 5-min go-cache in front of Bunt). Two files: `buntdb_path` + and `shop_buntdb_path` (`t/bot.go:53`). Keys: `invoice:`, `lnurl-p:`, + `webhook:`, `pay:…`, `faucet:…`, `send-…`, `lnurlw-…`. +- **No encryption helper exists** (`crypto/*` is only sha256/sha1/subtle/tls). Admin keys and + node credentials are plaintext in sqlite and in Bunt JSON. `golang.org/x/crypto v0.58.0` + is already in the graph (indirect); `crypto/aes` + `cipher.NewGCM` from the stdlib suffice. + +## 7. Translations + +`internal/i18n/localize.go`: bundle with English fallback, `MustLoadMessageFile(en.toml)`, +then de, fi, it, es, nl, pl, fr, pt-br, tr, cs, id, ru. Lookups: `Translate(ctx, key)` +(`t/translate.go:10`, public localizer), `TranslateUser(ctx, key)` (:18), and +`i18n.Translate(languageCode, key)` (`localize.go:52`) for code without a ctx (webhooks, +background jobs; the stored `LanguageCode` pattern). Parameters are `fmt` verbs applied +afterwards (`fmt.Sprintf(Translate(ctx,"confirmLnurlWithdrawMessage"), amount)`); TemplateData +is never used; a literal `{{` in a message would break go-i18n's template parse. Format: +TOML triple-quoted strings under `# SECTION` comments, camelCase keys ending in `Message`, +`ButtonMessage`, `CommandStr` (see `translations/en.toml:259-265`). Key counts: en 210, +nl 166 (nl is missing 44 keys and falls back to English; no nl-only keys). Missing keys log a +warning and return the English text. + +## 8. Background work + +No shared stop context anywhere. Existing patterns: `internal/price/price.go:56 Start` +→ `go Watch()` (30 s loop); `t/edit.go:33 startEditWorker` (1 s loop draining a queue, +`tryEditStack`); `t/ticket.go:219 restartPersistedTickets` (startup job that reloads Bunt +objects and starts timers; the closest model for "pending recovery at startup"); +`internal/runtime/function.go ResettableFunction` and `retry.go FunctionRetry` (ticker with +context deadline, used by `t/satdress.go:356`); fire-and-forget goroutines for delayed +deletes. `GracefulShutdown` waits only for the mutex map to empty. No cron, no mint health. + +## 9. Fork-specific things the feature must not break + +Fiat display and `/set` are **upstream** (#496, #497), not fork additions: currency in +`user.Settings.Display.DisplayCurrency` (needs `GetLnbitsUserWithSettings`), formatting via +`SatoshisToFiat` (`t/amounts.go:122`) + `invoiceReceivedCurrencyMessage` (`%d sat (%.2f %s)`), +the only "sat + fiat" pattern (`t/invoice.go:221-232`). Fork commits on top of upstream +(`origin/main..HEAD`, 21 commits): netguard + per-client transports (`internal/network/http.go`: +**every user-supplied URL must go through `network.GetClientForScheme`**), admin API token, +log redaction (`t/redact.go`, only applied in `logMessageInterceptor`), placeholder-sender +rejection, `Active=false` after pay/withdraw, atomic named mutex, webhook verification, +NIP-57 relay filter, satdress crash fixes, `go test ./...` without `config.yaml` +(`internal/config.go:93 isTestBinary`). Cashu was dropped; only `cashuTokenPattern` in +`redact.go` remains (the `kravens/cashu-feature` branch shows a text-handler insertion point +after the LNURL check and before `stateCallbackMessage`). `/node`, `/link`, `/api` +(`t/link.go`) hand users their LNbits admin key, so users can spend outside the bot's locks. + +## 10. Risks for the new code + +1. **Secret leakage into logs**: `t/lnurl.go:40` (raw `/lnurl` text), `:217` (decoded URL with + `k1`), `:82`, `:89`, `:107` (callback URLs), `t/interceptor.go:241` (callback data). + `redactForLog` redacts `lnurl…` tokens in the message log only. Any new path that + re-enters `lnurlHandler` with a note inherits :40 and :217. +2. **Bunt and sqlite state hold secrets in plaintext** (`LnurlWithdrawState`, `users.state_data`). +3. **Double spend / replay**: a failed callback leaves `Active=true` (`lnurl-withdraw.go:290`, + `pay.go:213`), so a second tap re-sends; `LockWithContext` cannot lock two objects in one + request (`mutex.go:68`); webhook callbacks run without the user lock (`webhook.go:192`); + balance check → pay is not atomic and users can spend via `/link`. LNbits' own debit is + the only hard guard. +4. **Long holds of the per-user lock**: `Wallet.Pay` has a 24 h timeout; `GetClientForScheme` + 10 s. The lock serialises one user's handlers only. +5. **Text routing**: `anyTextHandler` lowercases, and a pending `stateCallbackMessage` state + (shop title, enter-user, DALL·E prompt) consumes anything not matched earlier; the photo + handler consumes photos while a state is pending. +6. **Shared package-level `ReplyMarkup`s** mutated per request (`withdrawConfirmationMenu`, + `paymentConfirmationMenu`, `sendConfirmationMenu`, `transactionsMeno`). +7. **No webhook → no settle signal**: without the unmerged poller, a lost webhook means an + invoice settle is never noticed except by polling `Client.Payment`. +8. **No "user never started the bot" detection**: `trySendMessage` returns nil silently. +9. **Shutdown**: no context cancels background goroutines; jobs must tolerate being killed + mid-request (hence persist-before-request and recovery on startup). + +## 11. The library: `github.com/lnurlcash/lnurlcash-go` v0.3.0 (2026-11-05) + +Read: README, llms.txt, client.go, protocol.go, fees.go, errors.go, secrets.go, note.go, +urls.go, bolt11.go, CHANGELOG, THREAT-MODEL, plus the LUD-25 draft (`lnurl/luds` branch +`lnurlcash`, `25.md`). + +- **Go requirement**: `go 1.25` (repo is 1.26.0: fine). Direct deps: `btcec/v2 v2.5.0`, + `btcutil v1.2.0` (for `bech32.DecodeNoLimit`/`Encode`), `decred secp256k1/v4 v4.4.0`; + indirect `chainhash/v2 v2.0.0`, `blake256 v1.1.0`. +- **API used by this feature**: `NewClient()` (keep-alives off, no redirects, 30 s timeout, + `MutationRetries` default 1 for rotate/split/merge, never melt), `FetchPayRequest` + (`PayRequest{Callback, WithdrawLink, MintPubkey, MintFee, HasMintFee, CommentAllowed, + HasCommentAllowed}`, refuses a mint whose `commentAllowed < 64`), `ParseMintFee` / + `GrossUpForMintFee(netMsat, fee)` / `ApplyMintFee` / `DescribeMintFee`, + `GenerateNoteSecret` (32 random bytes hex), `HashK1`, `RequestMintInvoiceWithHash(cb, + msat, h)` (returns `Invoice{PR, VerifyURL}`; `ParseInvoice` already rejects an invoice whose + bolt11 amount differs), `FetchInvoiceStatus(verifyURL)` (LUD-21), `FetchNoteInfoByHash(link, + h)` (`WithdrawInfo{Callback, MaxWithdrawableMsat, MintPubkey, Signature}`; `IsSpent(err)` + for "already in use", `IsUnknownNote`), `FetchNoteInfo(noteURL)` (echo check of `k1`), + `MeltNote(cb, k1, pr)` (success = in flight), `SplitNoteWithHash(cb, k1s, msat, h, h2)`, + `BuildNoteURL(link, k1, msat)`, `ToBech32Lnurl`, `ToLud17w`, `ResolveLnurlInput`, + `ResolveNoteInput` (verifies the spend opens the note at its own domain), `NoteK1`, + `NoteLookupOf`, `ServerOf`, `IsAllowedServiceURL` (https, or http to loopback/.onion only). +- **Error taxonomy** that the service layer must honour: `ErrRequestRefused` (nothing sent), + `*ServiceError` (definitive; `Spent`, `Unknown`, `OutputInUse`), `*AmbiguousError` + (outcome unknown; carries `NewSecrets`), `*UnverifiableError` (mutation landed, no cert), + `*ProtocolError`, `ErrNotePending` (melt in flight: retry, not spent). `IsAmbiguous(err)` + first, `NewSecrets(err)` persisted first (empty from the `*WithHash` calls because the + caller already holds the secrets). `ProbeBurnedNote` → `NoteLive|NoteGone|NoteFateUnknown`. +- **Protocol facts that shape the design** (LUD-25 `25.md`): + - "`minWithdrawable` and `maxWithdrawable` are both the note's value, and a melt whose `pr` + is for any other amount MUST be rejected" (:151). Melt invoices must match to the msat. + - Fee: value = amount − base − floor(amount·ppm/1e6); a split costs `base_fee_msat` on the + change; "insufficient value" if change ≤ 0 (:125-133). + - Informational GET by `?p=` MUST be accepted; a burned note answers "already in use"; + unknown and burned are indistinguishable (:197). + - Melt: the note is "pending" until the payment settles; failure restores it (:182). +- **Default mint, observed live** (`https://lnurl.21mint.me/.well-known/lnurlp/mint`): + `Mint fees: 1000,100` (1 sat + 0.01 %), `commentAllowed: 64`, `withdrawLink + https://lnurl.21mint.me/w`, `minSendable 12000`; `/.well-known/lnurlw/mint` publishes + `mintPubkey 021ab89d…3555`, `minWithdrawable 10000`, node alias "Azzamo". + Consequence: for a gross of G whole sats the credited value is + `G·1000 − 1000 − floor(G/10)` msat, which is **a whole number of sats only for G < 10 or + G a multiple of 10 000**. Bot-minted notes would carry fractional-sat values, and + `lnbits.InvoiceParams.Amount` is whole sats, so a melt of exactly the value would be + impossible for almost every note. The plan handles this (Part 2, design decision D1). +- **What breaks on `go get`** (verified in scratch copies, `go build ./... && go test ./...`): + - Plain `go get github.com/lnurlcash/lnurlcash-go@v0.3.0` raises `btcec/v2` to v2.5.0 + (and btcutil 1.2.0, btcd 0.24.2, secp256k1 4.4.0). **btcec ≥ v2.3.4 changed + `ecdsa.SignCompact` to return `[]byte` instead of `([]byte, error)`**, and + `lnd/keychain` (pulled by `ln-decodepay` → `zpay32`) does not compile: + `keychain/signer.go:88: not enough return values`. This fails for lnd v0.15.0-beta, + v0.16.4-beta, v0.17.5-beta and v0.18.3-beta.rc3 alike. + - Switching to `nbd-wtf/ln-decodepay v1.13.0` (lnd v0.18.3) additionally drags + opentelemetry v1.30 (breaking `eko/gocache v1.2.0` via go-redis v8.8.2), removes + `prometheus/common/log` (used by `internal/nostr/nip05.go:10`), and changes ~1000 go.sum + lines. Not recommended. + - **Working, minimal set** (scratch `pathA/`): add lnurlcash-go v0.3.0 and pin + `replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3` + (the last version with the old `SignCompact` signature, and the one lnd v0.18 builds + against). Result: repo builds, `go vet` clean, `go test ./...` passes, **and + `go test github.com/lnurlcash/lnurlcash-go` passes under the pinned graph** (its + conformance vectors are in the module). go.mod diff: btcec 2.2.0→2.5.0 (required) + + replace, btcutil 1.1.1→1.2.0, btcd 0.23.1→0.24.2, chainhash 1.0.1→1.1.0 + chainhash/v2, + secp256k1 4.0.1→4.4.0, blake256 1.0.0→1.1.0, test deps. The pin also keeps + `internal/lnbits/types.go SignKeyAuth` (uses `ecdsa.Sign`) unchanged. Pinning v2.2.0 + also works; v2.3.3 is newer and still API-compatible with lnd. + - Residual risk of the pin: `go get -u` would fight the replace; document it in go.mod. + The library's secp256k1 v4.4.0 requirement stays (lnd compiles with it). +- **Extra dependency for PDF export**: no PDF code in the repo. Proposed `github.com/go-pdf/fpdf + v0.9.0` (pure Go, `go 1.20`, maintained fork of gofpdf; deps: barcode, gofpdi, pdf417, + x/image). QR PNGs come from the existing `skip2/go-qrcode`. CSV/JSON need the stdlib only. + Documents are sent with `tb.Document{File: tb.File{FileReader: …}, FileName: …}` (telebot + fork `media.go:143`); background edits of group messages use `tb.StoredMessage{MessageID, + ChatID}` (`editable.go:23`) with `bot.Telegram.Edit`. + + diff --git a/docs/lnurlcash/PLAN.md b/docs/lnurlcash/PLAN.md new file mode 100644 index 00000000..3b137765 --- /dev/null +++ b/docs/lnurlcash/PLAN.md @@ -0,0 +1,375 @@ +# LNURLcash implementation plan + + +> Implementation plan for LNURLcash notes. Each step compiles and can be merged alone. +> Amounts are int64 msat inside `internal/lnurlcash`; sats appear only at the Telegram and +> LNbits edges. `k1` is never logged; `h` (sha256 of k1) and the note id are safe to log. + +## Design decisions (deviations from the spec, with reasons) + +- **D1. Every bot-minted note is carved by a split so its value is a whole number of sats.** + LUD-25 requires a melt invoice for exactly the note's value, and LNbits invoices are whole + sats (`InvoiceParams.Amount int64`). With the default mint's fee (`1000,100`) a directly + minted note is almost never whole-sat. So creation always does: pay one mint invoice for the + gross → the funding note (secret `k1_0`, hash `h_0`) → `SplitNoteWithHash(cb, [k1_0], + value_msat, h_1, h_2)` → the user's note `h_1` is exactly `value`; the change `h_2` is dust + owned by the bot. A single note is therefore a batch of one with `batch_strategy: split`. + Gross is computed as the smallest whole-sat invoice whose net after the mint fee is at least + `N·value + N·base_fee_msat + 1 msat` (each split costs `base_fee_msat` on the change and the + change must stay positive). The confirm message shows value, mint fee (both parts), total. + Alternative (open question Q1): if the running LNbits accepts fractional sats + (`amount` as float, `unit: "sat"`), melts could be exact without splits; the split path + stays necessary for externally minted fractional notes anyway. +- **D2. `batch_strategy: invoices` is kept but documented as "one invoice per note, then one + split per note"** (same carving, N invoices). Default remains `split`. +- **D3. Redeeming a note with a fractional-sat value** (possible from other mints): split off + `S = floor(value_msat/1000)` sats to a fresh bot secret (persisted first), retrying with + `S−1`, `S−2` on a definitive `insufficient value` refusal (nothing burned), then melt that + whole-sat note. The dust change stays as a bot-owned `dust` row. Whole-sat notes melt directly. +- **D4. Detection of a note inside the existing `/lnurl` flow happens in `HandleLNURL`'s + `withdrawRequest` branch** by reading `mintPubkey` from the body with gjson; when present + and the feature is enabled it returns a new `LNURLCashNoteParams` value and `lnurlHandler` + hands it to the redeem flow. Withdraw links without `mintPubkey` behave exactly as today. +- **D5. Two log lines in `t/lnurl.go` that print the raw text (:40) and the decoded URL + (:217) are changed to go through `redactForLog` / to drop the query string.** This is a + log change only; command behaviour is untouched. Required by "never log k1". +- **D6. Secrets are stored AES-256-GCM encrypted** (stdlib `crypto/aes`, random 12-byte + nonce, key = `secret_encryption_key` as 64 hex chars). When `lnurlcash.enabled` and the key + is empty or malformed the bot refuses to start with a clear message. The hash `h` is stored + in clear as the lookup key. +- **D7. New sqlite file `database.lnurlcash_path` (default `data/lnurlcash.db`)** holding + the five new tables, opened in `AutoMigration`. Keeps the users DB untouched and lets the + feature be dropped by deleting one file. Models live in `internal/lnurlcash` (imports + `internal/lnbits` for `Wallet`; `telegram` imports `lnurlcash`; no cycle). +- **D8. Idempotent "in-flight" rows instead of Bunt objects**: all state is in GORM rows with + a `state` column; Bunt is used only for the short-lived confirm dialogs (`storage.Base` + pattern, like `/send`). Background jobs read rows, never Bunt. +- **D9. Settle detection = webhook event + polling.** Redeem/reclaim invoices are created + with `createInvoiceWithEvent`-style events (new `InvoiceCallbackLNURLCashSettle`), and the + recovery job also polls `bot.Client.Payment(wallet, hash).Paid`, so a lost webhook cannot + strand a melt. +- **D10. The per-user Telegram lock is held for the whole creation handler** (including + the mint invoice and the LNbits pay), matching `/pay`. Background jobs lock per note id + with `mutex.Lock(noteID)` (plain, not `LockWithContext`, because of the nLocks caveat) and + skip rows whose lock is busy. + +## Step 0: branch, docs, dependency (no behaviour change) + +- `git checkout -b lnurlcash`; add `docs/lnurlcash/AUDIT.md`, `docs/lnurlcash/PLAN.md`. +- `go get github.com/lnurlcash/lnurlcash-go@v0.3.0`; add + `replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3` + with a comment explaining the lnd `SignCompact` incompatibility; `go mod tidy`. +- Test: `go build ./... && go vet ./... && go test ./... && go test github.com/lnurlcash/lnurlcash-go` + (all verified green in the scratch copy). + +## Step 1: config and crypto (`internal/config.go`, `internal/lnurlcash/crypto.go`) + +- Add to `internal/config.go`: `LNURLCash LnurlcashConfiguration \`yaml:"lnurlcash"\`` with + fields mirroring the spec block (`Enabled bool`, `Mints []MintConfiguration{Name, URL, + Default bool}`, `MinNoteSat, MaxNoteSat, MaxOutstandingSatPerUser, MaxOutstandingNotesPerUser, + MaxBatchSize, MaxBatchTotalSat, GroupNoteMaxSat, MaxMintFeePpm int64`, `AutoReclaimDays int`, + `StatusPollInterval, InvoiceWaitTimeout time.Duration`, `BatchStrategy string`, + `BatchFormats []string`, `SecretEncryptionKey string`) and + `DatabaseConfiguration.LNURLCashPath \`yaml:"lnurlcash_path"\``. Add the block to + `config.yaml.example` (disabled by default). Add `Validate() error` (defaults for zero + values: poll 5m, wait 60s, strategy split, formats pdf,json,csv; exactly one default mint; + URLs must pass `lnurlcash.IsAllowedServiceURL`; key hex of 32 bytes when enabled). Call it + from `checkLnbitsConfiguration` (skipped in tests by `isTestBinary`). +- `internal/lnurlcash/crypto.go`: `type Cipher struct{aead cipher.AEAD}`, `NewCipher(hexKey)`, + `Seal(plain string) ([]byte, error)`, `Open([]byte) (string, error)`. +- Tests: `crypto_test.go` round-trip, wrong key fails, tamper fails; `config_test.go` for + `Validate`. + +## Step 2: models and store (`internal/lnurlcash/models.go`, `store.go`; `t/database.go`) + +Tables (GORM, table names via `TableName()`): +- `lnurlcash_notes`: `ID string` (pk, `note-`), `BatchID *string` (index), `UserName + string` (index; Telegram id as in `lnbits.User.Name`), `MintID string`, `MintURL string` + (withdraw link), `MintPubkey string`, `Hash string` (unique index; `h`), `SecretEnc []byte`, + `ValueMsat int64` (requested), `ReportedMsat int64` (from the mint), `GrossMsat int64`, + `FeeMsat int64`, `Memo string`, `State string` (index), `Kind string` (`user`, `funding`, + `dust`, `redeem_split`), `InvoicePR string`, `InvoiceHash string`, `VerifyURL string`, + `Certificate string`, `ChatID int64`, `MessageID string` (group post, for edits), + `ReceiptMessageID string`, `LanguageCode string`, `LastProbe time.Time`, `LastError + string`, `ClaimedAt, ReclaimedAt *time.Time`, `CreatedAt, UpdatedAt`. +- `lnurlcash_batches`: `ID` (`batch-`), `UserName`, `MintID`, `Memo`, `Count`, + `ValueMsat`, `TotalGrossMsat`, `FeeMsat`, `State` (`pending_invoice|pending_settle|carving| + live|partial|claimed|reclaimed`), `FundingNoteID`, `InvoiceHash`, `LastDigestAt`, + timestamps. +- `lnurlcash_redeems`: `ID` (`redeem-`), `UserName`, `MintHost`, `NoteID string` + (hex Q from `NoteIDOf`), `NoteURLEnc []byte` (full note URL incl. k1, encrypted), + `ReportedMsat`, `State` (`info|confirmed|invoiced|melting|settled|failed|split_pending`), + `InvoicePR`, `InvoiceHash`, `SplitNoteID *string`, `LastError`, timestamps, `LanguageCode`. +- `lnurlcash_user_prefs`: `UserName` (pk), `DefaultMintID`, `UpdatedAt`. +- `lnurlcash_mints`: `ID` (config name), `URL`, `PayURL`, `WithdrawLink`, `PinnedPubkey`, + `LastSeenPubkey`, `FeeBaseMsat`, `FeePpm`, `CommentAllowed`, `Healthy bool`, `Disabled + bool`, `LastCheck`, `LastError`, `MinSendableMsat`, `MaxSendableMsat`. +- `store.go`: `type Store struct{db *gorm.DB}`; `Open(path) (*Store, error)` with the same + `gorm.Config` as the other files + `AutoMigrate` of the five models; typed accessors + (`CreateNotes(tx, []Note)`, `UpdateNoteState(id, from, to, patch)` as a conditional + UPDATE `WHERE state = from` so two workers cannot both advance a row, `NotesByState`, + `OutstandingByUser(user) (count, sumMsat)`, `ListNotes(user, page, size)`, pagination + helpers, `NotesInBatch`, `Redeem*`, `Mint*`, `Pref*`). +- `t/database.go AutoMigration`: open `lnurlcash.Open(cfg.LNURLCashPath)` when enabled; add + `Databases.LNURLCash *lnurlcash.Store`. +- Tests: `store_test.go` with an in-memory sqlite (`file::memory:?cache=shared`), covering + conditional state transitions and outstanding sums. + +## Step 3: mint registry (`internal/lnurlcash/mints.go`) + +- `type Registry struct{cfg, store, client *lnurlcash.Client, alert func(string), mu}`. + `NewRegistry(...)`; `Check(ctx, mint)`: `ResolveMintInput(url)` → `FetchPayRequest` → + require `NamesMintOutput()`, `WithdrawLink != ""`, `HasMintFee` with `FeePpm ≤ + max_mint_fee_ppm` (absent fee = 0), then `FetchNoteInfoByHash` is not possible without a + note, so the pubkey is read from the payRequest's `MintPubkey` and, when empty, from the + mint address at `MintAddressURL(payURL)` (`FetchMintAddress`, best effort), and finally + verified on the first real note info (`WithdrawInfo.MintPubkey`). Pin on first non-empty + value; a later different value → `Disabled=true`, `alert("mint X changed pubkey …")`. +- `Default() *Mint`, `ByID`, `Enabled() []Mint`, `ForUser(user)` (pref → default). +- `RunHealth(ctx)`: at startup and every 5 min (`time.NewTicker`), each mint checked with a + 10 s context; logs host + outcome only. +- HTTP client: `lnurlcash.NewClient()` but with `HTTP.Transport` built from + `network.directTransport()`-equivalent (netguard dialer, SOCKS proxy from config) **plus + `DisableKeepAlives: true`, no redirects**; expose `newHTTPClient()` in `internal/network` + (`NewNoKeepAliveClient(timeout)`), so netguard and the proxy apply to mint traffic. +- Tests: `mints_test.go` with `httptest.Server` serving payRequest JSON: fee cap, comment + size, pubkey pin and change detection. + +## Step 4: note service, creation and status (`internal/lnurlcash/service.go`) + +- Interfaces so the service is testable without LNbits: + `type Ledger interface { Invoice(w lnbits.Wallet, sat int64, memo, webhook string) + (lnbits.Invoice, error); Pay(w lnbits.Wallet, bolt11 string) (lnbits.Invoice, error); + Paid(w lnbits.Wallet, hash string) (bool, error); BalanceMsat(w lnbits.Wallet) (int64, error) }` + implemented in `t/lnurlcash.go` by a thin adapter around `bot.Client`. +- `type Service struct{cfg, store, mints, ledger, cipher, client, log}`. +- `Quote(ctx, mint, valueMsat, count) (Quote{GrossMsat, FeeMsat, PerNoteMsat, + FundingNeededMsat, Mint}, error)`: `FetchPayRequest` → fee → needed = `count·value + + count·base + 1000` → `GrossUpForMintFee(needed, fee)` → round up to whole sat → check + `MinSendable/MaxSendable`. +- `Create(ctx, user *lnbits.User, q Quote, memo, chat, lang) (*Batch, []Note, error)` + (one note = batch of one): + 1. caps: `min/max_note_sat`, outstanding count/sum per user (live + pending rows), + `max_batch_size`, `max_batch_total_sat`, balance ≥ gross (via `BalanceMsat`). + 2. In one DB transaction: generate `k1_0` (funding) and `k1_1..N` (+ one dust secret per + split, N of them) with `GenerateNoteSecret`, hash them, insert the batch + (`pending_invoice`) and all N+1+N rows (funding `pending_invoice`, user notes + `pending_carve`, dust `pending_carve`) with encrypted secrets. **Commit before any + network call.** + 3. `RequestMintInvoiceWithHash(payCallback, grossMsat, h_0)`; store PR + verify URL on the + funding note and the batch → `pending_settle` (conditional update). + 4. `ledger.Pay(user.Wallet, pr)`; on a definitive LNbits error → batch `failed`, rows + `failed`, return the error; on ambiguous error (timeout) → leave `pending_settle` for + recovery. + 5. Wait up to `invoice_wait_timeout`: loop `FetchInvoiceStatus(verifyURL)` (if present) and + `FetchNoteInfoByHash(withdrawLink, h_0)`; found → funding `live`, store `ReportedMsat`. + Timeout → leave for recovery and tell the user "still settling". + 6. `Carve(ctx, batch)`: for i in 1..N: `SplitNoteWithHash(cb, [k1_current], valueMsat, + h_i, h_dust_i)`; on success note i → `live`, verify by `FetchNoteInfoByHash(h_i)` + (ReportedMsat), current = dust_i; last dust → `dust` state `live`. Partial failure: keep + the live ones, the remainder stays in the current change note (bot-owned, `funding` + state `live` with its reported value) and the batch is `partial`; the un-carved value is + returned to the user by melting that change note into a fresh LNbits invoice for the + user (whole-sat part; sub-sat remainder stays as dust), via the reclaim path. + 7. Build `NoteURL = BuildNoteURL(withdrawLink, k1_i, ReportedMsat)`; `ToBech32Lnurl` for + display; `ToLud17w` for the lnurlw form; QR via `qrcode.Encode`. The URL is built on + demand from the decrypted secret and never stored. +- `Status(ctx, note) (NoteStatus, error)`: `FetchNoteInfoByHash` → `live` with value; `IsSpent` + → mark `claimed` (conditional update) and return `claimed`; `IsUnknownNote` on a note that + was `live` → `claimed` as well (LUD-25: unknown and burned are one answer); transport + errors → unchanged. +- On any mutation error: `IsAmbiguous` → row state `unknown` with `LastError`; the secrets + were persisted in step 2 so `NewSecrets` is empty by construction, but the code still calls + it and logs a warning if non-empty. `ProbeBurnedNote` is used by recovery only. +- Tests: `service_test.go` with a fake mint (`httptest`) implementing payRequest, mint + invoice, `?p=` lookup, split, melt (including "pending", "already in use", dropped + connection after apply) and a fake ledger. Covers: secrets persisted before the first + request, gross-up math against the live fee `1000,100`, carve partial failure, status + transitions, the ambiguity path. + +## Step 5: reclaim and redeem (`internal/lnurlcash/melt.go`) + +- `Reclaim(ctx, note)`: lock `mutex.Lock(note.ID)`; `Status` first (claimed → stop); + `ledger.Invoice(user.Wallet, ReportedMsat/1000, "LNURLcash reclaim ", webhook)` (whole + sat by D1; otherwise D3 split first); store PR/hash on the note; `live → reclaiming` + (conditional); `MeltNote(cb, k1, pr)`: `ErrNotePending` → stay `reclaiming` (another melt + is in flight; recovery resolves); `IsSpent` → `claimed`; definitive refusal → back to `live` + with `LastError`; ambiguous → `unknown`. Success → stay `reclaiming` until the invoice is + paid (`InvoiceCallbackLNURLCashSettle` or poll) → `reclaimed`. +- `RedeemInfo(ctx, input string) (RedeemPreview, error)`: `ResolveNoteInput` (also accepts + `lightning:`), `FetchNoteInfo(noteURL)` (echo check), require `MintPubkey`; preview = + value, host, whether the host is an admin mint, `NoteIDOf(k1)`; insert `lnurlcash_redeems` + (`info`) with the encrypted note URL; no secret in the preview message. +- `Redeem(ctx, redeemID, user)`: `info → confirmed` (owner), invoice for the whole-sat value + (or D3), `invoiced → melting`, `MeltNote`; same error mapping; settle → `settled` and the + balance is simply LNbits' new balance. +- Never auto-retry a melt. A second `MeltNote` on the same note only after recovery has + classified the first (`ProbeBurnedNote` → `NoteLive` and no LNbits payment). +- Tests: fake-mint melt happy path, `pending`, spent, ambiguous; redeem of a fractional note + (D3) and of a note from an unknown mint. + +## Step 6: background jobs (`internal/lnurlcash/jobs.go`) + +- `type Notifier interface { NoteClaimed(note); BatchDigest(batch, claimedSince []Note); + GroupNoteState(note, state); Alert(msg) }` implemented in `t/lnurlcash.go`. +- `Jobs.Start(ctx)`: goroutines with `time.NewTicker`, each run guarded by a `sync.Mutex` so + runs never overlap, each row under `mutex.Lock(id)`/`Unlock`: + - **claim watcher** (`status_poll_interval`): `Status` for every `live` user note, oldest + `LastProbe` first, capped per run; on `claimed`: `Notifier.NoteClaimed` (single notes), + `GroupNoteState(claimed)` if `MessageID != ""`, batches collected into one + `BatchDigest` per batch per hour (`LastDigestAt`). + - **pending recovery** (startup + 1 min): `pending_settle` → check `ledger.Paid` / + verify URL / `FetchNoteInfoByHash`, finish `Carve` or mark `failed` after the LNbits + payment is known to have failed; `pending_carve` with a live funding/change note → + `Carve` resumes from the last live change; `reclaiming`/`melting` → `ledger.Paid(hash)` + settled → `reclaimed`/`settled`; not settled and the note `Status` is live again → melt + failed → `live`/`failed`; still "pending" → wait; `unknown` → `ProbeBurnedNote` + (`NoteGone` + payment settled → final; `NoteLive` → back to the previous state). + - **mint health**: Step 3's `RunHealth`. + - **auto reclaim** (daily, only when `auto_reclaim_days > 0`): `Reclaim` for live notes older + than N days, notifying the owner. +- Started from `bot.Start()` after `initInvoiceEventCallbacks` with a `context.Background()` + (the bot has no shutdown context; jobs are restart-safe by design). +- Tests: table tests driving `RunOnce()` of each job against the fake mint and the in-memory + store. + +## Step 7: Telegram wiring, single note (`t/lnurlcash.go`, `t/note.go`) + +- `t/lnurlcash.go`: `TipBot.LNURLCash *lnurlcash.Service` (nil when disabled; every handler + starts with `if bot.LNURLCash == nil { send lnurlcashDisabledMessage; return }`), the + `Ledger` adapter, the `Notifier` (uses `i18n.Translate(note.LanguageCode, …)`, `bot.Telegram.Edit` + with `tb.StoredMessage` for group posts, `trySendMessage(&tb.User{ID:…})` for DMs), the + invoice callback `InvoiceCallbackLNURLCashSettle = 8` registered in `initInvoiceEventCallbacks` + (the event's `CallbackData` carries the note/redeem id), and `mustHavePrivateChat(ctx)`: + send a probe-free DM via `trySendMessageEditable(user.Telegram, …)`; if the returned message + is nil (telebot `ErrNotStartedByUser`/`ErrBlockedByUser`, now surfaced by extending + `trySendMessage` to also return the error through a new `trySendMessageErr`), reply in the + group with `lnurlcashStartPrivateFirstMessage` and create nothing. +- `/note [memo]` (`noteHandler`): registered like `/send` (`localizer, logMessage, + requireUser, lock` + `unlock`); amount via `GetAmount`; memo via `GetMemoFromCommand(m.Text, 2)`. + Private: `Quote` → confirm message (value, mint fee, total, mint name, memo) with + `NoteConfirm{*storage.Base, UserName, Quote, Memo, LanguageCode}` in Bunt (id + `lnurlcash-note--`) and buttons `lnc_create`, `lnc_mint`, `lnc_cancel` + built on a fresh `&tb.ReplyMarkup{}`. `lnc_create` handler: object lock, owner, `Active`, + `Inactivate`, `Create`, then send the QR photo (caption = bech32 LNURL in backticks, like + `invoice.go:180`) and a second message with the `lnurlw://` text and buttons `lnc_reclaim`, + `lnc_status` (data = note id). `lnc_mint`: cycles through enabled mints and re-quotes. + Group: `group_note_max_sat` check first, `mustHavePrivateChat`, no confirm, `Create` with + `ChatID`, post QR + LNURL in the group (`tryReplyMessage`), store `MessageID`, DM the + receipt with fee and the two buttons. Errors go to the DM; the group command is deleted + with `NewMessage(m, WithDuration(0, bot))` only on error. +- `lnc_status`: `Status` → edit the receipt line; `lnc_reclaim`: `Reclaim` → message + "reclaim requested"; settle notification via callback 8. +- Translations: add an `# LNURLCASH` section to `en.toml` and `nl.toml` (keys below). + +## Step 8: /lnurlmints (`t/lnurlmints.go`) + +- Lists enabled mints with fee (`DescribeMintFee`), health and a `lnc_setmint` button per + mint (data = mint id); writes `lnurlcash_user_prefs`. In a group: delete the command (admin + permitting), answer privately. + +## Step 9: /notes list and batches (`t/notes_list.go`, `t/notes_batch.go`, `internal/lnurlcash/export/`) + +- `/notes` (private; in a group answered privately): paginated list (10 per page) of the + user's single notes and batches, newest first, state emoji + value + memo + short id; + buttons `lnc_page` (data `|`), `lnc_open` (note id) and `lnc_openb` (batch + id). The list object is `NotesList{*storage.Base, UserName, Page, …}` in Bunt keyed by its + own id (not by user name) and keyboards are built fresh per message; page math fixed + (`start = page*size`, exclusive end). +- Note view: value (reported), state, mint, memo, created; buttons `lnc_qr`, `lnc_status`, + `lnc_reclaim`. Batch view: counts by state, buttons `lnc_exp_pdf`, `lnc_exp_json`, + `lnc_exp_csv`, `lnc_refresh`, `lnc_reclaimb`. +- `/notes x [memo]`: parse `x`/`×`; caps; `Quote(count)`; confirm with the + total; progress message edited through `tryEditStack` after each carve step (progress + callback on `Create`); then a format picker with the configured `batch_formats`. +- `export/pdf.go` (go-pdf/fpdf, A4, 2×4 grid = 8 notes per page: QR PNG from + `qrcode.Encode` via `ImageOptions` with a `bytes.Reader`, value, memo, mint name, short + id), `export/csv.go` (`index,id,amount_sat,lnurl,lnurlw_url,mint,memo,created_at`), + `export/json.go` (`{batch_id, mint_url, mint_pubkey, memo, created_at, notes:[{index, id, + amount_msat, lnurl, lnurlw, certificate}]}`); all take `[]ExportNote` (decrypted URLs built + in memory by the service, `claimed` notes excluded) and write to an `io.Writer`. Sent with + `tb.Document{File: tb.File{FileReader: buf}, FileName: "notes-."}` in private + chat only. Re-export regenerates from the DB. +- Tests: golden tests for CSV/JSON; PDF test checks page count and that the file starts with + `%PDF`. + +## Step 10: redeem entry points (`t/note_redeem.go`, `t/lnurl.go`, `t/text.go`, `t/photo.go`) + +- `/redeem `: private → `RedeemInfo` → preview (value, mint host, warning if not an + admin mint) with `lnc_redeem_ok` / `lnc_cancel`; `lnc_redeem_ok` → `Redeem`. Group → delete + the command immediately (`tryDeleteMessage`; if the bot lacks delete rights, still + continue privately and tell the user the message could not be removed), then the same + flow in the DM via `mustHavePrivateChat`. +- `HandleLNURL` (`t/lnurl.go:267`): in the `withdrawRequest` body branch, if + `j.Get("mintPubkey").String() != ""` and `bot.LNURLCash != nil`, return + `LNURLCashNoteParams{URL: rawurl, Body: b}`; `lnurlHandler` adds a case that calls the + redeem preview with the original input. Everything else unchanged; feature disabled → old + path. D5 log fixes: `:40` → `redactForLog(m.Text)`, `:217` → log scheme+host only. +- `anyTextHandler`: nothing to add (pasted `lnurlw://…` and `LNURL1…` already route to + `lnurlHandler`); add a case-preserving pass: when `IsLnurl` matches, pass the original + `m.Text` (not `anyText`) for the note path so paths keep their case. Groups: unchanged + (the text handler is private-only already). +- `photoHandler`: unchanged (hands to `lnurlHandler`); groups unchanged (private-only). + +## Step 11: hardening and docs + +- `redactForLog`: also redact `lnurlw://`, `lnurlp://` and `?k1=` tokens (regex). +- README section; `botfather-setcommands.txt` entries for `/note`, `/notes`, `/redeem`, + `/lnurlmints`; help text keys. +- Admin alerts: `Alert` DMs `lnbits.admin_id`'s Telegram user if resolvable, else logs at + Error level (open question Q4). + +## Translation keys (en + nl, all under `# LNURLCASH`) + +`lnurlcashDisabledMessage`, `lnurlcashStartPrivateFirstMessage`, `noteHelpMessage`, +`noteConfirmMessage` (value, fee, total, mint, memo), `noteCreateButton`, `noteChangeMintButton`, +`noteCancelButton`, `noteCreatingMessage`, `noteCreatedMessage`, `noteGroupMessage`, +`noteGroupClaimedMessage`, `noteGroupWithdrawnMessage`, `noteReceiptMessage`, +`noteReclaimButton`, `noteStatusButton`, `noteShowQrButton`, `noteStatusLiveMessage`, +`noteStatusClaimedMessage`, `noteStatusPendingMessage`, `noteReclaimRequestedMessage`, +`noteReclaimedMessage`, `noteClaimedNotifyMessage`, `noteBatchDigestMessage`, +`noteCapMessage` (several: min/max/outstanding/group/batch), `noteInsufficientFundsMessage`, +`noteMintUnavailableMessage`, `noteErrorMessage`, `notesListHeader`, `notesListEmpty`, +`notesListItem`, `notesBatchItem`, `notesOpenMessage`, `notesBatchOpenMessage`, +`notesExportPdfButton`, `notesExportJsonButton`, `notesExportCsvButton`, +`notesRefreshButton`, `notesReclaimUnclaimedButton`, `notesBatchConfirmMessage`, +`notesBatchProgressMessage`, `notesBatchPartialMessage`, `notesBatchFormatMessage`, +`redeemHelpMessage`, `redeemPreviewMessage`, `redeemUnknownMintWarning`, +`redeemAddButton`, `redeemInFlightMessage`, `redeemDoneMessage`, `redeemSpentMessage`, +`redeemPendingMessage`, `redeemFailedMessage`, `redeemGroupDeletedMessage`, +`lnurlmintsHeader`, `lnurlmintsItem`, `lnurlmintsSetButton`, `lnurlmintsSetMessage`, +`lnurlcashMintPubkeyChangedAlert`. + +## Testing strategy overall + +- Unit: `internal/lnurlcash/**` with a fake mint (`httptest`) and a fake ledger; no Telegram. +- Integration (manual, documented in PLAN.md): a testnet/regtest LNbits + the live default + mint with 10–20 sat notes: create single (private and group), claim with lnurl-wallet, + observe the group edit and DM; reclaim; batch of 3 with PDF/CSV/JSON; redeem a note minted + by another wallet; kill the bot during `pending_settle` and during `reclaiming` and check + recovery; change the mint pubkey in config to see the disable + alert. +- `go test ./...` stays green at every step; `go vet` clean. + +## Open questions for the user + +1. **Fractional values vs LNbits (D1/D3)**: does the production LNbits accept a fractional + `amount` in sats (LNbits ≥ 0.12 `CreateInvoice.amount: float`)? If yes, do you prefer + msat-exact melts over the split carving? The configured LNbits (`100.64.131.43:5000`) was + not reachable from this machine, so the version is unknown. Carving is the safe default. +2. **Dust**: the per-split base fee and sub-sat remainders leave small bot-owned `dust` + notes. Accept and ignore, or add a periodic merge/melt into the bot wallet (`initBotWallet`)? +3. **Dependency pin**: accept the `replace … btcec/v2 v2.3.3` pin (recommended, tested), or + remove `ln-decodepay`/lnd by decoding bolt11 amounts another way (changes `/pay` internals)? +4. **Admin alerts**: DM to the Telegram user behind `lnbits.admin_id` is not derivable + (admin_id is an LNbits user id). Add `lnurlcash.admin_telegram_id` to config, or log only? +5. **New sqlite file** (`database.lnurlcash_path`) vs tables inside `bot.db`? +6. **Group `/redeem` without delete rights**: continue privately anyway (proposed) or refuse? +7. **PDF library**: `github.com/go-pdf/fpdf v0.9.0` acceptable (adds 4 small deps)? +8. **Minimum note value**: the default mint's `minWithdrawable` is 10 sat and `minSendable` + 12 sat; `min_note_sat: 1` cannot be honoured there. Clamp to the mint's minimum at quote + time (proposed) or reject? +9. **`/lnurl ` log fixes (D5)**: OK to change those two existing log lines? +10. **Batch strategy `invoices`**: keep (N invoices + N splits) or drop from the first + version? + +