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>
28 KiB
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/meansinternal/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 registerTelegramHandlersiteratesgetHandler()(handler.go:85-1316, oneInterceptionWrapper{Endpoints, Handler, Interceptor}per entry) and callsregisterHandlerWithInterceptor(handler.go:41), which prepends the defaultsidInterceptor, rejectPlaceholderSenderInterceptorand wraps withintercept.WithHandler.handle()(handler.go:55) also registers/CMDand/Cmdvariants for slash commands.- Endpoints are strings (
"/faucet"), telebot events (tb.OnText,tb.OnPhoto,tb.OnQuery) or*tb.Btn. Buttons route byUnique: telebot serialises callback data as"\f<unique>|<data>"and matches^\f([-\w]+)(\|(.+))?$, then hands the handlerctx.Callback().Data= payload. One flat namespace: registering the sameUniquetwice 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);Synchronousis not set. - Faucet pattern (
t/faucet.go): command registered athandler.go:392withlocalizer, logMessage, requireUser, lock+OnDefer: unlock;InlineFaucetembeds*storage.Base; idfaucet:<rand10>:<amount>; keyboard built per message with a fresh&tb.ReplyMarkup{}and.Data(label, "confirm_faucet_inline", id); persisted withobj.Set(obj, bot.Bunt). Click handleracceptInlineFaucetHandler(faucet.go:250):tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))},mutex.LockWithContext(ctx, tx.ID)+ deferred unlock,tx.Get, checksActive, owner, then acts, edits viatryEditStack,Inactivate. Registration athandler.go:788-820usessingletonCallbackInterceptor, 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):SendDatawith idsend-<tgid>-<amount>-<rand5>, saved to Bunt and copied into the user's sqlite state (SetUserState(... UserStateConfirmSend ...));confirmSendHandler(send.go:274) locks the object, checksFrom.Telegram.ID == senderandActive,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:sendConfirmationMenuis a package-levelReplyMarkupmutated per request (race). - Message disposal:
NewMessage(m, WithDuration(d, bot))(t/message.go:17,24) deletes afterdvia 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 noDisposeMessage. - /transactions pagination (
t/transactions.go:107):TransactionsListkept inbot.Cacheunder"<user.Name>_transactions"for 1 min (not Bunt); buttonsleft_transactions/right_transactionswith the list id as data but lookup is by user name;tryEditMessageon scroll; registered athandler.go:349-390. Bugs not to copy:printTransactionsstart indexpagenr*(tx_per_page-1)with inclusive end (11 rows, overlapping pages), hard-coded English footer, shared package-leveltransactionsMeno. - Photo/QR (
t/photo.go:44 photoHandler, registeredhandler.go:598withrequirePrivateChat, localizer, logMessage, requireUser, lock): if the user has a pending state, that state's callback consumes the photo (no QR decode). Elsebot.Telegram.File,jpeg.Decode(JPEG only),TryRecognizeQrCode(gozxing, accepts onlyIsInvoice/IsLnurl), echoesphotoQrRecognizedMessage, then rewritesm.Textto/pay …or/lnurl …and callspayHandler/lnurlHandlerdirectly. Documents go tofileHandler(t/files.go:11), never QR-decoded. - Text (
t/text.go:18 anyTextHandler, private only,loadUser+lock): uninitialised user →startHandler;Balanceprefix → balance;IsInvoice(lower)→/pay;IsLnurl(lower)→/lnurl(note:m.Textis lowercased first); elsestateCallbackMessage[user.StateKey](t/state.go:12).IsLnurlis a prefix check, so a pastedlnurlw://…note already reacheslnurlHandlertoday. - Inline queries (
t/inline_query.go:141): prefix routing; not needed for notes.
3. Middleware and locking
- Interceptors (
t/interceptor.go):idInterceptor(randomuidin 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 withWallet == nil),localizerInterceptor(:181,publicLocalizer= English in groups, user language in private;userLocalizeralways user language),requirePrivateChatInterceptor(:215, also fails for callbacks sinceMessage()is nil),logMessageInterceptor(:227, redacts viaredactForLog). intercept.WithHandler(t/intercept/context.go:59) runs Before, registersdefer intercept(h, onDefer)with the pre-handler context (so acallback_responseset by the handler never reaches a deferredanswerCallbackInterceptor), 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 useLockWithContext(ctx, id)(mutex.go:57), whose re-entrancy counternLocks:<uid>is keyed by requestuidonly (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 keyName= Telegram id; returns a stub +gorm.ErrRecordNotFoundwhen absent);GetLnbitsUserWithSettings(:190) preloadsSettings;UpdateUserRecord(:263) re-readsbanned/wallet_adminkeyand saves withFullSaveAssociations;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.ChatPrivateorm.Private();requirePrivateChatInterceptorfor whole endpoints. Sending privately from a group:bot.trySendMessage(ctx.Sender() /* or user.Telegram */, …)(t/telegram.go:37);trySendMessageEditableskips the main-menu keyboard. A user who never started the bot: telebot returnsErrNotStartedByUser("Forbidden: bot can't initiate conversation");trySendMessageonly 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/paymentswith inkey;InvoiceParams.Amountis 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 arelnbits.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 bywallet_id(:75), re-checks withPayment+verify.SettledIncoming(:86), markswebhook:<hash>in Bunt (no TTL) to dedupe, loadsInvoiceEventinvoice:<hash>from Bunt and dispatchestelegram.InvoiceCallback[ev.Callback]in a goroutine (no user lock); with no event it sends the genericinvoiceReceivedMessage. No polling fallback in this tree (kravens/fix/poll-invoices-when-webhook-failsis unmerged); the only pull path isbot.Client.Payment(used by/transactionsand the webhook). InvoiceEvent+ callback registry:t/invoice.go:37 initInvoiceEventCallbacks, constantsInvoiceCallbackGeneric … 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 withdecodepay.Decodepay, checksGetUserBalance(sats, writes the balance back into the users DB on every call,t/users.go:73), warns above 98 % of balance, storesPayDatapay:<tgid>-<amount>-<rand5>, andconfirmPayHandler(:162) callsuser.Wallet.Pay; on error the object staysActive(a second tap re-sends the same bolt11). NoTransactionrow for external payments. - Internal transfers:
t/transaction.go:87 SendTransactioncreates an invoice on the receiver's wallet (no webhook) and pays it from the sender's wallet;Transactionrows go totransactions.db. Not needed for notes. pkg/lightning: prefix checks only; bolt11 amount decoding lives inpay.govia ln-decodepay.
5. Existing LNURL code and what /lnurl <withdraw link> does today
/lnurlregistered athandler.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>; stripslightning:;bot.HandleLNURL(lnurl.go:181, a modified copy of go-lnurl 1.8.4): lightning address →.well-known/lnurlp;http…verbatim;lnurlp/w/a://andkeyauth://→ https (http for.onion); else bech32FindLNURLInText+LNURLDecodeStrict. :217log.Debuglogs the decoded URL includingk1(Debug is on). Querytag=login→lnurl.HandleAuth;tag=withdrawRequestwith all params →HandleFastWithdraw(no GET). Otherwise GET vianetwork.GetClientForSchemeand switch on bodytag:withdrawRequest→lnurl.HandleWithdraw(b)(go-lnurlLNURLWithdrawResponse:Tag, K1, Callback, MaxWithdrawable, MinWithdrawable, DefaultDescription, BalanceCheck, PayLink; unknown JSON fields such asmintPubkeyandcare dropped; the raw bodybis local and not returned),payRequest→HandlePay. Type switch atlnurl.go:79: auth →lnurlAuthHandler(:82logs the callback incl.k1), pay →lnurlPayHandler, withdraw →lnurlWithdrawHandler(:107logs the callback URL).lnurlWithdrawHandler(t/lnurl-withdraw.go:78):LnurlWithdrawState{*storage.Base, From, LNURLWithdrawResponse, Amount(msat), …}idlnurlw-<tgid>-<rand5>; range check only when min and max are both non-zero; amount from command oraskForAmount(... "LnurlWithdrawState" ...)(t/amounts.go:139, stateUserEnterAmount); thenlnurlWithdrawHandlerWithdraw(:139) showsconfirmLnurlWithdrawMessagewithconfirm_withdraw/cancel_withdraw(mutating the package-levelwithdrawConfirmationMenu, :193).confirmWithdrawHandler(:208): object lock, owner check,Activecheck,user.Wallet.Invoice({Amount: msat/1000, Memo:"Withdraw", Webhook})(noInvoiceEventstored), GETcallback?pr=&k1=viaGetClientForScheme,json.Unmarshalintolnurl.LNURLResponse(error ignored);Status=="OK"→Active=falselnurlWithdrawSuccess; elselnurlWithdrawFailed; on transport errorActivestays true. Credit arrives through LNbits + webhook → genericinvoiceReceivedMessage.
- 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 thek1logged twice (:40 raw text, :217 decoded URL), nomintPubkeyawareness, 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 sqliteusers.state_datacolumn (lnurl-withdraw.go:126-132). In a group the command is dropped silently byrequirePrivateChatInterceptor(OnErroris a no-op). A pasted bare note (lnurlw://…) is lowercased and routed the same way byanyTextHandler; a QR photo of it likewise, unless a pending user state swallows the photo first. - LNURL server (
internal/lnurl/lnurl.go:78 Handle, routes inmain.go:55-80): lnurl-pay foruser@host(serveLNURLpSecondstores anInvoiceEventwithInvoiceCallbackLNURLPayReceive), 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 AutoMigrationwithgorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true}: users (database.db_path,AutoMigrate(&lnbits.User{})afterColumnMigrationTasks), transactions (transactions_path,&Transaction{}), groups (groupsdb_path,&Group{}); handles live inDatabases{Users, Transactions, Groups}(database.go:32) asbot.DB. Adding a table: define the GORM struct in a packagetelegramcan import, add a path key toDatabaseConfiguration(internal/config.go:55) andconfig.yaml, open +AutoMigrateinAutoMigration, add a field toDatabases. AutoMigrate adds tables and columns only; one-off data migrations followColumnMigrationTasks(database.go:65). - User model
internal/lnbits/types.go:24 User(Name= Telegram id, embeddedTelegramandWalletwith plaintextadminkey/inkeycolumns,StateKey/StateData,Settingshas-one in tablesettings:Display.DisplayCurrency,Node,Nostr). - Bunt:
internal/storage/bunt.go(Storable{Key()}, JSONSet/Get/Delete, no TTL ever set),internal/storage/base.go(Base{ID, Active, Canceled, CreatedAt, UpdatedAt},Get/Set/Inactivatethrough a 5-min go-cache in front of Bunt). Two files:buntdb_pathandshop_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.0is already in the graph (indirect);crypto/aes+cipher.NewGCMfrom 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
- Secret leakage into logs:
t/lnurl.go:40(raw/lnurltext),:217(decoded URL withk1),:82,:89,:107(callback URLs),t/interceptor.go:241(callback data).redactForLogredactslnurl…tokens in the message log only. Any new path that re-enterslnurlHandlerwith a note inherits :40 and :217. - Bunt and sqlite state hold secrets in plaintext (
LnurlWithdrawState,users.state_data). - Double spend / replay: a failed callback leaves
Active=true(lnurl-withdraw.go:290,pay.go:213), so a second tap re-sends;LockWithContextcannot 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. - Long holds of the per-user lock:
Wallet.Payhas a 24 h timeout;GetClientForScheme10 s. The lock serialises one user's handlers only. - Text routing:
anyTextHandlerlowercases, and a pendingstateCallbackMessagestate (shop title, enter-user, DALL·E prompt) consumes anything not matched earlier; the photo handler consumes photos while a state is pending. - Shared package-level
ReplyMarkups mutated per request (withdrawConfirmationMenu,paymentConfirmationMenu,sendConfirmationMenu,transactionsMeno). - No webhook → no settle signal: without the unmerged poller, a lost webhook means an
invoice settle is never noticed except by polling
Client.Payment. - No "user never started the bot" detection:
trySendMessagereturns nil silently. - 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(forbech32.DecodeNoLimit/Encode),decred secp256k1/v4 v4.4.0; indirectchainhash/v2 v2.0.0,blake256 v1.1.0. - API used by this feature:
NewClient()(keep-alives off, no redirects, 30 s timeout,MutationRetriesdefault 1 for rotate/split/merge, never melt),FetchPayRequest(PayRequest{Callback, WithdrawLink, MintPubkey, MintFee, HasMintFee, CommentAllowed, HasCommentAllowed}, refuses a mint whosecommentAllowed < 64),ParseMintFee/GrossUpForMintFee(netMsat, fee)/ApplyMintFee/DescribeMintFee,GenerateNoteSecret(32 random bytes hex),HashK1,RequestMintInvoiceWithHash(cb, msat, h)(returnsInvoice{PR, VerifyURL};ParseInvoicealready 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 ofk1),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; carriesNewSecrets),*UnverifiableError(mutation landed, no cert),*ProtocolError,ErrNotePending(melt in flight: retry, not spent).IsAmbiguous(err)first,NewSecrets(err)persisted first (empty from the*WithHashcalls because the caller already holds the secrets).ProbeBurnedNote→NoteLive|NoteGone|NoteFateUnknown. - Protocol facts that shape the design (LUD-25
25.md):- "
minWithdrawableandmaxWithdrawableare both the note's value, and a melt whosepris 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_msaton 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/mintpublishesmintPubkey 021ab89d…3555,minWithdrawable 10000, node alias "Azzamo". Consequence: for a gross of G whole sats the credited value isG·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, andlnbits.InvoiceParams.Amountis 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.0raisesbtcec/v2to v2.5.0 (and btcutil 1.2.0, btcd 0.24.2, secp256k1 4.4.0). btcec ≥ v2.3.4 changedecdsa.SignCompactto return[]byteinstead of([]byte, error), andlnd/keychain(pulled byln-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 (breakingeko/gocache v1.2.0via go-redis v8.8.2), removesprometheus/common/log(used byinternal/nostr/nip05.go:10), and changes ~1000 go.sum lines. Not recommended. - Working, minimal set (scratch
pathA/): add lnurlcash-go v0.3.0 and pinreplace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3(the last version with the oldSignCompactsignature, and the one lnd v0.18 builds against). Result: repo builds,go vetclean,go test ./...passes, andgo test github.com/lnurlcash/lnurlcash-gopasses 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 keepsinternal/lnbits/types.go SignKeyAuth(usesecdsa.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 -uwould fight the replace; document it in go.mod. The library's secp256k1 v4.4.0 requirement stays (lnd compiles with it).
- Plain
- 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 existingskip2/go-qrcode. CSV/JSON need the stdlib only. Documents are sent withtb.Document{File: tb.File{FileReader: …}, FileName: …}(telebot forkmedia.go:143); background edits of group messages usetb.StoredMessage{MessageID, ChatID}(editable.go:23) withbot.Telegram.Edit.