Files
MichilisandClaude Fable 5.1 74f5ae53a7 Add LNURLcash audit and implementation plan
Phase 1 and 2 documents for LUD-25 bearer note support: an audit of the
bot (routing, locking, money paths, LNURL, storage, i18n, jobs, risks)
and of lnurlcash-go v0.3.0 including the btcec/lnd dependency conflict,
plus a step-by-step plan with open questions. No code changes.

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

28 KiB
Raw Permalink Blame History

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<unique>|<data>" 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:<rand10>:<amount>; 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-<tgid>-<amount>-<rand5>, 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 "<user.Name>_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:<uid> 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:<hash> in Bunt (no TTL) to dedupe, loads InvoiceEvent invoice:<hash> 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:<tgid>-<amount>-<rand5>, 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.
  • /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] <lnurl>; 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-<tgid>-<rand5>; 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 <LNURLcash note> 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:<hash>, lnurl-p:<hash>, webhook:<hash>, 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 ReplyMarkups 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=<h> 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.