Compare commits

..
8 Commits
Author SHA1 Message Date
gohumble 8ff8340001 log 2022-12-11 19:12:11 +01:00
gohumble 1a059d511c no reply in private chat. 2022-12-11 19:09:34 +01:00
callebtc a5cfc97e0f add command to help 2022-12-11 18:47:54 +01:00
gohumble b3e91e6e2f minor updates 2022-12-11 18:46:08 +01:00
gohumble d7dff06ee2 added /chat command 2022-12-11 18:40:47 +01:00
gohumble 369f627794 remove unwanted stuff 2022-12-11 18:40:23 +01:00
gohumble 65a6cddd35 added config example 2022-12-11 18:38:01 +01:00
gohumble b783f202b1 added chat gpt 2022-12-11 18:31:21 +01:00
128 changed files with 811 additions and 12912 deletions
+1 -7
View File
@@ -1,10 +1,4 @@
config.yaml
config.yaml*
data/*
!data/.placeholder
# build artefacts and vendored toolchains must not be committed
/LightningTipBot
*.tar.gz
cashu/node_modules/
trace_*.txt
/docs/
!data/.placeholder
-9
View File
@@ -56,7 +56,6 @@ You can either use your own LNbits instance (recommended) or create an account a
- `transactions_path`: Transaction database file path.
- `buntdb_path`: Object storage database file path.
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
- `admin_api_token`: Secret for the admin API on `admin_api_host` (ban, unban, mutex, pprof). Send it as `Authorization: Bearer <token>`. Without it the admin API rejects every request.
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zeus support, optional).
@@ -137,10 +136,6 @@ To pay a Lightning invoice, you can snap a photo of a QR code and send it direct
To minimize the clutter all the heavy tipping can cause in a group chat, the bot will remove all failed commands (for example due to a syntax error) from the chat immediately. All successful commands will stay visible for `message_dispose_duration` seconds (default 10s) and then be removed. The tips will sill be visible for everyone in the Live tooltip. This feature only works, if the bot is made admin of the group.
## Full Guide to Install and run on a VPS
A complete guide to install and run LightningTipBot + LNBITS (on docker with PostgreSQL) on the same VPS with an external LND funding source has been prepared by Massimo Musumeci (@massmux) and it is available: [LightningTipBot full install](https://www.massmux.com/howto-complete-lightningtipbot-lnbits-setup-vps/)
## Made with
- [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
@@ -148,7 +143,3 @@ A complete guide to install and run LightningTipBot + LNBITS (on docker with Pos
- [gozxing](https://github.com/makiuchi-d/gozxing) – barcode image processing library in Go.
- [ln-decodepay](https://github.com/fiatjaf/ln-decodepay) – Lightning Network BOLT11 invoice decoder.
- [go-lnurl](https://github.com/fiatjaf/go-lnurl) - Helpers for building lnurl support into services.
## LNURLcash notes (optional)
The bot can mint [LNURLcash](https://github.com/lnurl/luds/pull/301) bearer notes at admin-listed mints: `/note <amount> [memo]`, `/notes <amount> x <count> [memo]`, `/notes`, `/redeem <note>` and `/lnurlmints`. The balance stays in LNbits; note secrets are stored AES-256-GCM encrypted in `data/lnurlcash.db`. Enable it with the `lnurlcash:` block in `config.yaml` (see `config.yaml.example`; a `secret_encryption_key` is required). Design and audit notes live in `docs/lnurlcash/`.
+1 -6
View File
@@ -14,9 +14,4 @@ invoice - Receive with Lightning: /invoice 1000
pay - Pay with Lightning: /pay lnbc10n1ps...
donate - Donate: /donate 1000
faucet - Create a faucet: /faucet 2100 21
advanced - Advanced help
note - Create an LNURLcash note: /note 1000 [memo]
notes - List your notes, or create a batch: /notes 100 x 10
redeem - Redeem a received note: /redeem lnurlw://...
lnurlmints - Show the LNURLcash mints and pick a default
lnurlhelp - Help for LNURLcash notes
advanced - Advanced help
+3 -33
View File
@@ -6,11 +6,10 @@ bot:
tor_proxy:
host: 127.0.0.1:9050
http_proxy: ""
lnurl_public_host_name: "https://mylnurl.com"
lnurl_server: "http://127.0.0.1:5454" # or http://0.0.0.0:5454 depending on your configuration
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_image: true
admin_api_host: localhost:6060
admin_api_token: "" # required for the admin API: send it as "Authorization: Bearer <token>"
telegram:
message_dispose_duration: 10
api_key: "1234"
@@ -26,37 +25,8 @@ database:
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
groupsdb_path: "data/groups.db"
lnurlcash_path: "data/lnurlcash.db"
generate:
open_ai_bearer_token: "token_here"
dalle_key: "asd"
dalle_price: 1000
worker: 2
nostr:
private_key: "hex private key here"
lnurlcash: # LUD-25 bearer notes, see docs/lnurlcash/PLAN.md
enabled: false
mints:
# One entry per mint. The name is the mint's id in the database, so do not
# rename a mint that already has notes. Users pick their own default with
# /lnurlmints; the single `default: true` entry is the fallback.
- name: 21mint
url: https://lnurl.21mint.me
default: true
- name: mint.600.wtf
url: https://mint.600.wtf
min_note_sat: 1
max_note_sat: 100000
max_outstanding_sat_per_user: 500000
max_outstanding_notes_per_user: 200
max_batch_size: 100
max_batch_total_sat: 500000
group_note_max_sat: 1000
max_mint_fee_ppm: 20000
auto_reclaim_days: 0
status_poll_interval: 5m
invoice_wait_timeout: 60s
batch_strategy: split # or: invoices
batch_formats: [pdf, json, csv]
secret_encryption_key: "" # 64 hex chars, e.g. `openssl rand -hex 32`; required when enabled
admin_telegram_id: 0 # optional: Telegram user id that receives mint alerts
worker: 2
-373
View File
@@ -1,373 +0,0 @@
# 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.
## 5. Existing LNURL code and what `/lnurl <withdraw link>` 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] <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 `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=<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`.
-375
View File
@@ -1,375 +0,0 @@
# 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-<rand10>`), `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-<rand10>`), `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-<rand10>`), `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 <id>", 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 <amount> [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-<tgid>-<rand5>`) 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 `<listid>|<page>`), `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 <amount> x <count> [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-<batchid>.<ext>"}` 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 <note>`: 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 <note>` 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?
+14 -35
View File
@@ -1,28 +1,23 @@
module github.com/LightningTipBot/LightningTipBot
go 1.26.0
toolchain go1.26.11
go 1.17
require (
github.com/BurntSushi/toml v0.3.1
github.com/PuerkitoBio/goquery v1.8.0
github.com/btcsuite/btcd/btcec/v2 v2.5.0
github.com/PullRequestInc/go-gpt3 v1.1.10
github.com/btcsuite/btcd/btcec/v2 v2.2.0
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/go-pdf/fpdf v0.9.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/lnurlcash/lnurlcash-go v0.3.0
github.com/makiuchi-d/gozxing v0.0.2
github.com/nbd-wtf/go-nostr v0.13.0
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/prometheus/common v0.26.0
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.7.0
@@ -30,8 +25,8 @@ require (
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4
golang.org/x/net v0.62.0
golang.org/x/text v0.43.0
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
golang.org/x/text v0.3.7
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd
gorm.io/driver/sqlite v1.1.4
@@ -39,25 +34,14 @@ require (
)
require (
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
require (
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 // indirect
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/btcsuite/btcd v0.24.2 // indirect
github.com/btcsuite/btcd/btcutil v1.2.0 // indirect
github.com/btcsuite/btcd v0.23.1 // indirect
github.com/btcsuite/btcd/btcutil v1.1.1 // indirect
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
github.com/btcsuite/btcwallet v0.15.1 // indirect
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
@@ -70,13 +54,12 @@ require (
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/decred/dcrd/lru v1.0.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-redis/redis/v8 v8.8.2 // indirect
github.com/gorilla/websocket v1.5.3
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
@@ -99,16 +82,14 @@ require (
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/rtred v0.1.2 // indirect
github.com/tidwall/tinyqueue v0.1.1 // indirect
github.com/valyala/fastjson v1.6.3 // indirect
go.opentelemetry.io/otel v0.20.0 // indirect
go.opentelemetry.io/otel/metric v0.20.0 // indirect
go.opentelemetry.io/otel/trace v0.20.0 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/term v0.47.0 // indirect
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/alecthomas/kingpin.v2 v2.2.6 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
@@ -117,5 +98,3 @@ require (
)
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3
+39 -53
View File
@@ -46,8 +46,8 @@ github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0g
github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 h1:Xa6tp8DPDhdV+k23uiTC/GrAYOe4IdyJVKtob4KW3GA=
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8/go.mod h1:ihkm1viTbO/LOsgdGoFPBSvzqvx7ibvkMzYp3CgtHik=
github.com/PullRequestInc/go-gpt3 v1.1.10 h1:Z2fYKq7oGrr4Cs0yDmuq25FYR4hgvCowIR9sENHmSZ0=
github.com/PullRequestInc/go-gpt3 v1.1.10/go.mod h1:F9yzAy070LhkqHS2154/IH0HVj5xq5g83gLTj7xzyfw=
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
@@ -61,11 +61,9 @@ github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d h1:UQZhZ2O0vMHr2cI+DC1Mbh0TJxzA3RcLoMsFw+aXw7E=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/allegro/bigcache/v2 v2.2.5 h1:mRc8r6GQjuJsmSKQNPsR5jQVXc8IJ1xsW5YXUYMLfqI=
github.com/allegro/bigcache/v2 v2.2.5/go.mod h1:FppZsIO+IZk7gCuj5FiIDHGygD9xvWQcqg1uIPMb6tY=
@@ -104,22 +102,22 @@ github.com/btcsuite/btcd v0.22.0-beta.0.20220204213055-eaf0459ff879/go.mod h1:os
github.com/btcsuite/btcd v0.22.0-beta.0.20220207191057-4dc4ff7963b4/go.mod h1:7alexyj/lHlOtr2PJK7L/+HDJZpcGDn/pAU98r7DY08=
github.com/btcsuite/btcd v0.22.0-beta.0.20220316175102-8d5c75c28923/go.mod h1:taIcYprAW2g6Z9S0gGUxyR+zDwimyDMK5ePOX+iJ2ds=
github.com/btcsuite/btcd v0.23.0/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY=
github.com/btcsuite/btcd v0.23.1 h1:IB8cVQcC2X5mHbnfirLG5IZnkWYNTPlLZVrxUYSotbE=
github.com/btcsuite/btcd v0.23.1/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY=
github.com/btcsuite/btcd v0.24.2 h1:aLmxPguqxza+4ag8R1I2nnJjSu2iFn/kqtHTIImswcY=
github.com/btcsuite/btcd v0.24.2/go.mod h1:5C8ChTkl5ejr3WHj8tkQSCmydiMEPB0ZhQhehpq7Dgg=
github.com/btcsuite/btcd/btcec/v2 v2.3.3 h1:6+iXlDKE8RMtKsvK0gshlXIuPbyWM/h84Ensb7o3sC0=
github.com/btcsuite/btcd/btcec/v2 v2.3.3/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA=
github.com/btcsuite/btcd/btcec/v2 v2.1.1/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
github.com/btcsuite/btcd/btcec/v2 v2.2.0 h1:fzn1qaOt32TuLjFlkzYSsBC35Q3KUjT1SwPxiMSCF5k=
github.com/btcsuite/btcd/btcec/v2 v2.2.0/go.mod h1:U7MHm051Al6XmscBQ0BoNydpOTsFAn707034b5nY8zU=
github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A=
github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE=
github.com/btcsuite/btcd/btcutil v1.1.1 h1:hDcDaXiP0uEzR8Biqo2weECKqEw0uHDZ9ixIWevVQqY=
github.com/btcsuite/btcd/btcutil v1.1.1/go.mod h1:nbKlBMNm9FGsdvKvu0essceubPiAcI57pYBNnsLAa34=
github.com/btcsuite/btcd/btcutil v1.2.0 h1:p3+S2g3Q+7G5NOh4Ji+2UrBOrg5Z0Q4ykzShWG1Dhgs=
github.com/btcsuite/btcd/btcutil v1.2.0/go.mod h1:/Taflm113pYjUpbWKKQEfa6XOtI/+WS8awxeMZpY75k=
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 h1:Edx4AfBn+YPam2KP5AobDitulGp4r1Oibm8oruzkMdI=
github.com/btcsuite/btcd/btcutil/psbt v1.1.4/go.mod h1:9AyU6EQVJ9Iw9zPyNT1lcdHd6cnEZdno5wLu5FY74os=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f h1:bAs4lUbRJpnnkd9VhRV3jjAVU7DJVjMaK+IsvSeZvFo=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
@@ -161,6 +159,7 @@ github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtE
github.com/btcsuite/winsvc v1.0.0 h1:J9B4L7e3oqhXOcm+2IuNApwzQec85lE+QaikUcCs+dk=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
@@ -210,12 +209,10 @@ github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/decred/dcrd/lru v1.0.0 h1:Kbsb1SFDsIlaupWPwsPp+dkxiBY1frcS07PCPgotKz8=
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
github.com/dgraph-io/ristretto v0.0.3 h1:jh22xisGBjrEVnRZ1DVTpBVQm0Xndu8sMl0CWDzSIBI=
@@ -293,8 +290,6 @@ github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk=
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw=
github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
@@ -370,8 +365,8 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
@@ -398,9 +393,8 @@ github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw=
@@ -504,6 +498,8 @@ github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/joefitzgerald/rainbow-reporter v0.1.0/go.mod h1:481CNgqmVHQZzdIbN52CupLJyoVwB10FQ/IQlF1pdL8=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
@@ -557,8 +553,6 @@ github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23/go.mod h1:Ljlbryh9
github.com/julienschmidt/httprouter v1.1.1-0.20151013225520-77a895ad01eb/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee h1:FPP9HDkBbPyniu+u7FHZg+kKFX1WW0gxOGteJ0h3AJk=
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee/go.mod h1:N6sz6HwJAenJ6d+/xmSl0ikfV05ZrVGmjt1ryy/WOtE=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
@@ -635,8 +629,6 @@ github.com/lightningnetwork/lnd/tor v1.0.1 h1:A11FrpU0Y//g+fA827W4VnjOeoIvExONdc
github.com/lightningnetwork/lnd/tor v1.0.1/go.mod h1:RDtaAdwfAm+ONuPYwUhNIH1RAvKPv+75lHPOegUcz64=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/lnurlcash/lnurlcash-go v0.3.0 h1:12LUZJXqvyDfvZ1uWbk1kFh9le7vOIMKiraQiUqvZ1A=
github.com/lnurlcash/lnurlcash-go v0.3.0/go.mod h1:tBFpb7fqLeX0zcLqjNqqa9R9ogH2q5QM8m/rUZMFz1s=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY=
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
@@ -671,6 +663,7 @@ github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KK
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/maxbrunsfeld/counterfeiter/v6 v6.2.3/go.mod h1:1ftk08SazyElaaNvmqAfZWGwJzshjCfBXDLoQtPAMNk=
github.com/mholt/archiver/v3 v3.5.0 h1:nE8gZIrw66cu4osS/U7UW7YDuGMHssxKutU8IfWxwWE=
github.com/mholt/archiver/v3 v3.5.0/go.mod h1:qqTTPUK/HZPFgFQ/TJ3BzvTpF/dPtFVJXdQbCmeMxwc=
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
@@ -703,8 +696,6 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nbd-wtf/go-nostr v0.13.0 h1:3OcUknuSLm8prTk2u/kUvbMQYtaSjLKemADRQ8TBIXk=
github.com/nbd-wtf/go-nostr v0.13.0/go.mod h1:qFFTIxh15H5GGN0WsBI/P73DteqsevnhSEW/yk8nEf4=
github.com/nbd-wtf/ln-decodepay v1.5.1 h1:i/SMR94AXIL21KxE/CyWLg/1kKUOVfxHD4QJswaNRDc=
github.com/nbd-wtf/ln-decodepay v1.5.1/go.mod h1:xzBXPaCj/7oRRaui+iYSIxy5LYUjoPfAyAGq2WCyNKk=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
@@ -724,6 +715,7 @@ github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:v
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
@@ -734,6 +726,7 @@ github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ=
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
@@ -823,6 +816,8 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sclevine/spec v1.2.0/go.mod h1:W4J29eT/Kzv7/b9IWLB055Z+qvVC9vt0Arko24q7p+U=
github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
@@ -863,10 +858,8 @@ github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
@@ -874,10 +867,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
@@ -921,8 +912,6 @@ github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijb
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/valyala/fastjson v1.6.3 h1:tAKFnnwmeMGPbwJ7IwxcTPCNr3uIzoIj3/Fh90ra4xc=
github.com/valyala/fastjson v1.6.3/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
@@ -1029,9 +1018,8 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -1042,8 +1030,7 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 h1:Fq7F/w7MAa1KJ5bt2aJ62ihqp9HDcRuyILskkpIAurw=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/exp v0.0.0-20220426173459-3bcf042a4bf5/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -1068,6 +1055,7 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180406214816-61147c48b25b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -1118,9 +1106,8 @@ golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1138,8 +1125,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde h1:ejfdSekXMDxDLbRrJMwUk6KnSLZ2McaUCVcIKM+N6jc=
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180816055513-1c9583448a9c/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1161,6 +1148,7 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -1213,12 +1201,11 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 h1:fqTvyMIIj+HRzMmnzr9NtpHP6uVpvB5fkHcgPDC4nu8=
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -1228,9 +1215,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1279,6 +1265,7 @@ golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapK
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200301222351-066e0c02454c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
@@ -1294,6 +1281,7 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1400,7 +1388,6 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y=
gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI=
@@ -1446,9 +1433,8 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
+2 -2
View File
@@ -26,7 +26,7 @@ func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
user.Banned = false
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
err = telegram.UpdateUserBan(user, *s.bot)
err = telegram.UpdateUserRecord(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
@@ -52,7 +52,7 @@ func (s Service) BanUser(w http.ResponseWriter, r *http.Request) {
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", reason, user.Wallet.Adminkey)
}
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", "banned", user.Wallet.Adminkey)
err = telegram.UpdateUserBan(user, *s.bot)
err = telegram.UpdateUserRecord(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
+21 -65
View File
@@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -58,7 +58,6 @@ func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
Out: false,
DescriptionHash: createInvoiceRequest.DescriptionHash,
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
Memo: createInvoiceRequest.Memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
s.Bot.Client)
if err != nil {
@@ -141,43 +140,8 @@ type InvoiceStream struct {
WebhookStatus interface{} `json:"webhook_status"`
}
// maxStreamsPerWallet bounds the SSE connections one wallet can hold open. Each
// one keeps a goroutine and a connection to LNbits alive.
const maxStreamsPerWallet = 3
var (
streamsMu sync.Mutex
streams = map[string]int{}
)
// acquireStream reserves a stream slot for the wallet.
func acquireStream(walletID string) bool {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] >= maxStreamsPerWallet {
return false
}
streams[walletID]++
return true
}
func releaseStream(walletID string) {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] <= 1 {
delete(streams, walletID)
return
}
streams[walletID]--
}
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
if !acquireStream(user.Wallet.ID) {
http.Error(w, "Too many streams", http.StatusTooManyRequests)
return
}
defer releaseStream(user.Wallet.ID)
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
@@ -195,37 +159,29 @@ func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
out:
for {
select {
case <-r.Context().Done():
// the client went away: do not wait for the next payment event
break out
case msg := <-c:
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
select {
case <-r.Context().Done():
client.Unsubscribe(c)
break out
default:
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
}
// Unsubscribe once. It blocks until the subscription goroutine takes the
// request, and that goroutine may be sending an event, so keep draining.
done := make(chan struct{})
go func() {
client.Unsubscribe(c)
close(done)
}()
for {
select {
case <-c:
case <-done:
return
}
}
close(c)
time.Sleep(time.Second * 5)
}
-21
View File
@@ -1,21 +0,0 @@
package api
import "testing"
func TestStreamSlotsAreBoundedPerWallet(t *testing.T) {
for i := 0; i < maxStreamsPerWallet; i++ {
if !acquireStream("w1") {
t.Fatalf("slot %d refused", i)
}
}
if acquireStream("w1") {
t.Error("slot beyond the limit was granted")
}
if !acquireStream("w2") {
t.Error("another wallet must not be affected")
}
releaseStream("w1")
if !acquireStream("w1") {
t.Error("released slot was not reusable")
}
}
+1 -28
View File
@@ -2,7 +2,6 @@ package api
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"net/http"
@@ -11,7 +10,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
@@ -65,7 +63,7 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
w.WriteHeader(401)
log.Warnf("[api] Request with a banned key. Not forwarding request")
log.Warnf("[api] Banned user %s. Not forwarding request", password)
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
@@ -87,14 +85,6 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
return
}
// The ban rewrites only the admin key, so a banned user's invoice key
// still matches above. Refuse every key of a banned user.
if user.Banned || user.Wallet == nil || strings.HasPrefix(user.Wallet.Adminkey, "banned") || strings.Contains(user.Wallet.Adminkey, "_") {
w.WriteHeader(401)
log.Warnf("[api] Request with a key of a banned user. Not forwarding request")
return
}
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
r = r.WithContext(context.WithValue(r.Context(), "user", user))
next.ServeHTTP(w, r)
@@ -135,20 +125,3 @@ func dump(r *http.Request) string {
}
return string(x)
}
// AdminTokenMiddleware only lets requests through that carry the token as
// "Authorization: Bearer <token>". With an empty token it rejects everything.
func AdminTokenMiddleware(token string) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
got := strings.TrimPrefix(auth, "Bearer ")
if token == "" || got == auth || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
log.Warnf("[ADMIN] unauthorized request to %s", r.URL.Path)
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
-56
View File
@@ -1,56 +0,0 @@
package api
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// The ban rewrites only the admin key. Every key of a banned user must be
// refused, the invoice key included, and a normal user must still pass.
func TestAuthorizationMiddlewareRefusesBannedUsersKeys(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared&_banmw=1"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&lnbits.User{}); err != nil {
t.Fatal(err)
}
users := []*lnbits.User{
{ID: "u1", Name: "111", Banned: true, Wallet: &lnbits.Wallet{ID: "w1", Adminkey: "banned_aaaaaaaaaaaaaaaa", Inkey: "bbbbbbbbbbbbbbbb"}},
{ID: "u2", Name: "222", Wallet: &lnbits.Wallet{ID: "w2", Adminkey: "cccccccccccccccc", Inkey: "dddddddddddddddd"}},
}
for _, u := range users {
if err := db.Create(u).Error; err != nil {
t.Fatal(err)
}
}
call := func(access AccessKeyType, key string) int {
h := AuthorizationMiddleware(db, AuthTypeBasic, access, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
req := httptest.NewRequest("GET", "/api/v1/balance", nil)
req.Header.Set("Authorization", "Basic "+key)
rr := httptest.NewRecorder()
h(rr, req)
return rr.Code
}
for _, c := range []struct {
access AccessKeyType
key string
want int
}{
{AccessKeyTypeInvoice, "bbbbbbbbbbbbbbbb", 401}, // banned user's invoice key
{AccessKeyTypeInvoice, "aaaaaaaaaaaaaaaa", 401}, // banned user's old admin key
{AccessKeyTypeAdmin, "aaaaaaaaaaaaaaaa", 401},
{AccessKeyTypeInvoice, "dddddddddddddddd", 200}, // normal user still works
{AccessKeyTypeAdmin, "cccccccccccccccc", 200},
} {
if got := call(c.access, c.key); got != c.want {
t.Errorf("%s key %s: got %d, want %d", c.access.Type, c.key, got, c.want)
}
}
}
-19
View File
@@ -32,7 +32,6 @@ func NewServer(address string) *Server {
httpServer: srv,
}
apiServer.router = mux.NewRouter()
apiServer.router.Use(securityHeaders)
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[api] Server started at %s", address)
@@ -42,11 +41,6 @@ func NewServer(address string) *Server {
func (w *Server) ListenAndServe() {
go w.httpServer.ListenAndServe()
}
// Use adds a middleware that runs for every route of the server.
func (w *Server) Use(middleware mux.MiddlewareFunc) {
w.router.Use(middleware)
}
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
@@ -77,16 +71,3 @@ func WriteResponse(writer http.ResponseWriter, response interface{}) error {
_, err = writer.Write(jsonResponse)
return err
}
// securityHeaders sets the headers that need no change to the pages. A
// stricter Content-Security-Policy would need the inline scripts of the
// userpage templates to move out first.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Content-Security-Policy", "object-src 'none'; base-uri 'none'")
next.ServeHTTP(w, r)
})
}
+3 -3
View File
@@ -243,7 +243,7 @@
<div class="wrapper">
<label class="sr-only" for="inlineFormInputGroup">Username</label>
<div class="input-group">
<input type="number" class="form-control" min="1" inputmode="decimal" step="any" pattern="\d+(\.\d*)?" id="invoiceAmount" placeholder="amount">
<input type="number" class="form-control" min="1" inputmode="numeric" pattern="[0-9]*" id="invoiceAmount" placeholder="amount">
<div class="input-group-append">
<div class="input-group-text" id="inputCurrency"></div>
</div>
@@ -270,7 +270,7 @@
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').textContent = "{{.Username}}@ln.tips";
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
@@ -368,7 +368,7 @@
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').textContent = "Pay " + invoiceAmount + " " + currencies[curr_idx];
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
-14
View File
@@ -6,7 +6,6 @@ import (
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"time"
@@ -28,11 +27,6 @@ func New(b *telegram.TipBot) Service {
}
}
// validUsername matches Telegram usernames and the anon id forms (numeric,
// 0x... and 1x...) the LNURL server accepts. The path variable is reflected
// into a page that handles payments, so nothing else is rendered.
var validUsername = regexp.MustCompile(`^[a-z0-9_]{1,64}$`)
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
//go:embed static
@@ -76,10 +70,6 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/@<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering page of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
@@ -105,10 +95,6 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/app/<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering webapp of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
-42
View File
@@ -1,42 +0,0 @@
package userpage
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/mux"
)
func serve(path string) *httptest.ResponseRecorder {
r := mux.NewRouter()
r.HandleFunc("/app/@{username}", Service{}.UserWebAppHandler)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec
}
func TestWebAppRejectsMarkupInUsername(t *testing.T) {
for _, p := range []string{
"/app/@%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E",
"/app/@a%22%3Balert(1)%2F%2F",
"/app/@" + strings.Repeat("a", 65),
} {
rec := serve(p)
if rec.Code == http.StatusOK || strings.Contains(rec.Body.String(), "onerror") {
t.Errorf("%s: code %d, body %q", p, rec.Code, rec.Body.String())
}
}
}
func TestWebAppRendersValidUsernameAsText(t *testing.T) {
rec := serve("/app/@alice_1")
if rec.Code != http.StatusOK {
t.Fatalf("code %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, `textContent = "alice_1@ln.tips"`) || strings.Contains(body, "#greeting').innerHTML") {
t.Errorf("greeting is not set as text")
}
}
-34
View File
@@ -3,10 +3,8 @@ package internal
import (
"fmt"
"net/url"
"os"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/jinzhu/configor"
log "github.com/sirupsen/logrus"
)
@@ -17,15 +15,8 @@ var Configuration = struct {
Database DatabaseConfiguration `yaml:"database"`
Lnbits LnbitsConfiguration `yaml:"lnbits"`
Generate GenerateConfiguration `yaml:"generate"`
Nostr NostrConfiguration `yaml:"nostr"`
// LNURLCash is the optional LUD-25 bearer note feature (see docs/lnurlcash).
LNURLCash lnurlcash.Config `yaml:"lnurlcash"`
}{}
type NostrConfiguration struct {
PrivateKey string `yaml:"private_key"`
}
type GenerateConfiguration struct {
OpenAiBearerToken string `yaml:"open_ai_bearer_token"`
DalleKey string `yaml:"dalle_key"`
@@ -48,7 +39,6 @@ type BotConfiguration struct {
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
AdminAPIToken string `yaml:"admin_api_token"`
}
type TelegramConfiguration struct {
@@ -61,8 +51,6 @@ type DatabaseConfiguration struct {
BuntDbPath string `yaml:"buntdb_path"`
TransactionsPath string `yaml:"transactions_path"`
GroupsDbPath string `yaml:"groupsdb_path"`
// LNURLCashPath is the sqlite file holding LNURLcash notes, batches and mints.
LNURLCashPath string `yaml:"lnurlcash_path"`
}
type LnbitsConfiguration struct {
@@ -95,29 +83,7 @@ func init() {
panic(err)
}
Configuration.Bot.LNURLHostUrl = hostname
if isTestBinary() {
// go test has no config.yaml; a missing LNbits URL must not stop
// unit tests of packages that import this one.
return
}
checkLnbitsConfiguration()
checkLNURLCashConfiguration()
}
// checkLNURLCashConfiguration refuses to start with a broken lnurlcash block:
// a half-configured note feature would mint money it cannot keep track of.
func checkLNURLCashConfiguration() {
if err := Configuration.LNURLCash.Validate(); err != nil {
panic(err)
}
if Configuration.LNURLCash.Enabled && Configuration.Database.LNURLCashPath == "" {
Configuration.Database.LNURLCashPath = "data/lnurlcash.db"
}
}
// isTestBinary reports whether the process is a go test binary.
func isTestBinary() bool {
return strings.HasSuffix(os.Args[0], ".test") || strings.HasSuffix(os.Args[0], ".test.exe")
}
func checkLnbitsConfiguration() {
+1 -1
View File
@@ -13,7 +13,7 @@ func MigrateAnonIdInt32Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
log.Infof("[MigrateAnonIdInt32Hash] %s -> %d", u.ID, str.Int32Hash(u.ID))
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
tx := db.Save(u)
if tx.Error != nil {
-42
View File
@@ -1,42 +0,0 @@
package database
import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/gorm"
)
func FindUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
func FindUserSettings(user *lnbits.User, settingsTx *gorm.DB) (*lnbits.User, error) {
// tx := bot.DB.Users.Preload("Settings").First(user)
tx := settingsTx.First(user)
if tx.Error != nil {
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
-55
View File
@@ -1,55 +0,0 @@
package i18n
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
)
var lnurlcashLanguages = []string{"en", "nl", "de", "es", "fr", "it", "pt-br", "ru", "tr", "pl", "cs", "fi", "id"}
// Every LNURLcash key must localize in every language without falling back,
// and must format with the English argument list without a "%!" error.
func TestLNURLCashKeysInEveryLanguage(t *testing.T) {
en := goi18n.NewLocalizer(Bundle, "en")
verb := regexp.MustCompile(`%(?:\[\d+\])?([sd])`)
// the key list comes from en.toml itself: the bundle does not expose its ids
raw, err := os.ReadFile(filepath.Join(translationsDir(), "en.toml"))
if err != nil {
t.Fatal(err)
}
var keys []string
for _, m := range regexp.MustCompile(`(?m)^(\w+)\s*=`).FindAllStringSubmatch(string(raw[strings.Index(string(raw), "# LNURLCASH"):]), -1) {
keys = append(keys, m[1])
}
if len(keys) < 70 {
t.Fatalf("expected the LNURLcash keys, found %d", len(keys))
}
for _, lang := range lnurlcashLanguages {
loc := goi18n.NewLocalizer(Bundle, lang)
for _, key := range keys {
text, err := loc.Localize(&goi18n.LocalizeConfig{MessageID: key})
if err != nil {
t.Errorf("%s %s: %v", lang, key, err)
continue
}
enText, _ := en.Localize(&goi18n.LocalizeConfig{MessageID: key})
var args []interface{}
for _, m := range verb.FindAllStringSubmatch(strings.ReplaceAll(enText, "%%", ""), -1) {
if m[1] == "d" {
args = append(args, 7)
} else {
args = append(args, "x")
}
}
if out := fmt.Sprintf(text, args...); strings.Contains(out, "%!") {
t.Errorf("%s %s formats badly: %q", lang, key, out)
}
}
}
}
+12 -29
View File
@@ -1,9 +1,6 @@
package i18n
import (
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
@@ -16,35 +13,21 @@ func init() {
Bundle = RegisterLanguages()
}
// translationsDir finds the translations directory. The bot runs from the
// repository root; go test runs from the package directory, so walk up.
func translationsDir() string {
dir := "translations"
for i := 0; i < 6; i++ {
if st, err := os.Stat(dir); err == nil && st.IsDir() {
return dir
}
dir = filepath.Join("..", dir)
}
return "translations"
}
// Languages lists every translation file the bundle loads. English comes
// first: it is the default and the fallback for missing keys.
var Languages = []string{"en", "de", "fi", "it", "es", "nl", "pl", "fr", "pt-br", "tr", "cs", "id", "ru"}
func RegisterLanguages() *i18n.Bundle {
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
dir := translationsDir()
bundle.MustLoadMessageFile(filepath.Join(dir, "en.toml"))
for _, lang := range Languages[1:] {
// a broken file must not stop the bot, but it silently turns
// that language into English, so say so
if _, err := bundle.LoadMessageFile(filepath.Join(dir, lang+".toml")); err != nil {
log.Errorf("[i18n] could not load %s translations: %v", lang, err)
}
}
bundle.MustLoadMessageFile("translations/en.toml")
bundle.LoadMessageFile("translations/de.toml")
bundle.LoadMessageFile("translations/it.toml")
bundle.LoadMessageFile("translations/es.toml")
bundle.LoadMessageFile("translations/nl.toml")
bundle.LoadMessageFile("translations/pl.toml")
bundle.LoadMessageFile("translations/fr.toml")
bundle.LoadMessageFile("translations/pt-br.toml")
bundle.LoadMessageFile("translations/tr.toml")
bundle.LoadMessageFile("translations/cs.toml")
bundle.LoadMessageFile("translations/id.toml")
bundle.LoadMessageFile("translations/ru.toml")
return bundle
}
func Translate(languageCode string, MessgeID string) string {
-22
View File
@@ -1,22 +0,0 @@
package i18n
import (
"path/filepath"
"testing"
"github.com/BurntSushi/toml"
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
// RegisterLanguages only logs a file that fails to load, and that language
// then falls back to English everywhere. Fail the build instead.
func TestEveryTranslationFileLoads(t *testing.T) {
bundle := goi18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
for _, lang := range Languages {
if _, err := bundle.LoadMessageFile(filepath.Join(translationsDir(), lang+".toml")); err != nil {
t.Errorf("%s: %v", lang, err)
}
}
}
+2 -10
View File
@@ -39,18 +39,10 @@ type User struct {
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
Display DisplaySettings `gorm:"embedded;embeddedPrefix:display_"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
ID string `json:"id" gorm:"primarykey"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
}
type DisplaySettings struct {
DisplayCurrency string `json:"displaycurrency"`
}
type NostrSettings struct {
PubKey string `json:"pubkey"`
}
type NodeSettings struct {
NodeType string `json:"nodetype"`
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
-49
View File
@@ -1,49 +0,0 @@
// Package verify holds the checks the LNbits webhook listener applies before
// it treats a request as proof of payment. It has no dependency on the bot
// configuration, so it can be unit tested.
package verify
import (
"fmt"
"regexp"
)
// paymentHashFormat is the only form LNbits uses for a payment hash. The hash
// becomes part of an LNbits URL and of the replay key, so nothing else is
// accepted (a suffix such as "?x=1" would reach the same payment but be a new
// replay key).
var paymentHashFormat = regexp.MustCompile("^[0-9a-f]{64}$")
// ValidPaymentHash reports whether h is 64 lowercase hex characters.
func ValidPaymentHash(h string) bool {
return paymentHashFormat.MatchString(h)
}
// Payment is what LNbits reports for a payment hash, reduced to the fields
// the webhook needs.
type Payment struct {
Paid bool
PaymentHash string
WalletID string
AmountMsat int64
}
// SettledIncoming returns the amount in msat of a settled incoming payment of
// walletID with paymentHash, or an error when p is not that. LNbits only
// returns the details to the wallet that owns the payment; an outgoing payment
// of the same wallet has a negative amount.
func SettledIncoming(p Payment, paymentHash, walletID string) (int64, error) {
if !p.Paid {
return 0, fmt.Errorf("payment %s is not settled", paymentHash)
}
if p.PaymentHash != paymentHash {
return 0, fmt.Errorf("payment hash mismatch: got %s, want %s", p.PaymentHash, paymentHash)
}
if p.WalletID != walletID {
return 0, fmt.Errorf("payment %s does not belong to wallet %s", paymentHash, walletID)
}
if p.AmountMsat <= 0 {
return 0, fmt.Errorf("payment %s is not an incoming payment", paymentHash)
}
return p.AmountMsat, nil
}
@@ -1,52 +0,0 @@
package verify
import (
"strings"
"testing"
)
func TestValidPaymentHash(t *testing.T) {
ok := strings.Repeat("ab", 32)
cases := map[string]bool{
ok: true,
strings.ToUpper(ok): false, // LNbits uses lowercase
ok + "?x=1": false, // would reach the same payment under a new replay key
ok[:62]: false,
ok + "a": false,
"": false,
strings.Repeat("g", 64): false,
"../" + ok[3:]: false,
strings.Repeat("ab", 31) + "a\n": false,
}
for in, want := range cases {
if got := ValidPaymentHash(in); got != want {
t.Errorf("ValidPaymentHash(%q) = %v, want %v", in, got, want)
}
}
}
func TestSettledIncoming(t *testing.T) {
hash := strings.Repeat("01", 32)
good := Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: 21000}
if got, err := SettledIncoming(good, hash, "w1"); err != nil || got != 21000 {
t.Fatalf("settled payment rejected: amount=%d err=%v", got, err)
}
bad := []struct {
name string
p Payment
}{
{"unpaid", Payment{Paid: false, PaymentHash: hash, WalletID: "w1", AmountMsat: 21000}},
{"other hash", Payment{Paid: true, PaymentHash: strings.Repeat("02", 32), WalletID: "w1", AmountMsat: 21000}},
{"other wallet", Payment{Paid: true, PaymentHash: hash, WalletID: "w2", AmountMsat: 21000}},
{"outgoing", Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: -21000}},
{"zero", Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: 0}},
{"empty", Payment{}},
}
for _, c := range bad {
if got, err := SettledIncoming(c.p, hash, "w1"); err == nil || got != 0 {
t.Errorf("%s: accepted with amount=%d err=%v", c.name, got, err)
}
}
}
+13 -115
View File
@@ -3,12 +3,10 @@ package webhook
import (
"encoding/json"
"fmt"
"io"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook/verify"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
@@ -19,16 +17,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
"github.com/tidwall/buntdb"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
// maxBodyBytes bounds the webhook request body. A real LNbits payload is a
// few hundred bytes.
const maxBodyBytes = 1 << 20
type Server struct {
httpServer *http.Server
bot *tb.Bot
@@ -81,49 +74,6 @@ func (w *Server) GetUserByWalletId(walletId string) (*lnbits.User, error) {
return user, nil
}
// settledAmount returns the amount in msat that LNbits says the user's wallet
// received for paymentHash. It fails unless that payment is settled.
func (w *Server) settledAmount(user *lnbits.User, paymentHash string) (int64, error) {
payment, err := w.c.Payment(*user.Wallet, paymentHash)
// LNbits sends a webhook only once, so a short LNbits hiccup must not
// lose the payment event.
for try := 0; err != nil && try < 2; try++ {
time.Sleep(time.Second)
payment, err = w.c.Payment(*user.Wallet, paymentHash)
}
if err != nil {
return 0, err
}
return verify.SettledIncoming(verify.Payment{
Paid: payment.Paid,
PaymentHash: payment.Details.PaymentHash,
WalletID: payment.Details.WalletID,
AmountMsat: payment.Details.Amount,
}, paymentHash, user.Wallet.ID)
}
// handledTTLWithoutEvent is how long the replay marker of a payment without an
// invoice event is kept. A replay of such a payment only repeats the "you
// received" message, so the marker doesn't need to outlive LNbits' retries.
const handledTTLWithoutEvent = 7 * 24 * time.Hour
// markHandled records paymentHash and reports whether this is the first time.
// A marker with an expiry is only safe when no invoice event exists for the
// payment: invoice events are kept forever, and replaying one after its marker
// expired would run its callback (which may pay out) a second time.
func (w *Server) markHandled(paymentHash string, hasEvent bool) (first bool, err error) {
var opts *buntdb.SetOptions
if !hasEvent {
opts = &buntdb.SetOptions{Expires: true, TTL: handledTTLWithoutEvent}
}
err = w.buntdb.Update(func(tx *buntdb.Tx) error {
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", opts)
first = !replaced
return err
})
return first, err
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
@@ -133,69 +83,29 @@ func (w *Server) newRouter() *mux.Router {
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
webhookEvent := Webhook{}
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, maxBodyBytes))
// need to delete the header otherwise the Decode will fail
request.Header.Del("content-length")
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
if err != nil {
log.Errorf("[Webhook] Error reading request body: %s", err.Error())
writer.WriteHeader(400)
return
}
if err = json.Unmarshal(body, &webhookEvent); err != nil {
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
writer.WriteHeader(400)
return
}
// The hash becomes part of an LNbits URL and of the replay key, so only
// the form LNbits uses is accepted.
if !verify.ValidPaymentHash(webhookEvent.PaymentHash) {
log.Errorf("[Webhook] Rejecting webhook with malformed payment_hash")
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil || user.Wallet == nil || user.Wallet.ID == "" {
log.Errorf("[Webhook] Error getting user for wallet_id %q: %v", webhookEvent.WalletID, err)
if err != nil {
log.Errorf("[Webhook] Error getting user: %s", err.Error())
writer.WriteHeader(400)
return
}
// Anyone who can reach this port can send a webhook, so the body is only
// a hint. Ask LNbits whether this wallet really received the payment and
// use the amount LNbits reports.
amountMsat, err := w.settledAmount(user, webhookEvent.PaymentHash)
if err != nil {
log.Errorf("[Webhook] Rejecting webhook for payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
writer.WriteHeader(400)
return
}
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
eventErr := w.buntdb.Get(txInvoiceEvent)
// Handle every payment once, so a webhook can't be replayed. Any lookup
// error other than "not found" counts as an event, which keeps the marker.
first, err := w.markHandled(webhookEvent.PaymentHash, eventErr != buntdb.ErrNotFound)
if err != nil {
log.Errorf("[Webhook] Error storing payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
writer.WriteHeader(500)
return
}
if !first {
log.Infof("[Webhook] Ignoring repeated webhook for payment_hash %s", webhookEvent.PaymentHash)
writer.WriteHeader(200)
return
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, amountMsat/1000))
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
writer.WriteHeader(200)
if eventErr != nil {
log.Errorln(eventErr)
} else if txInvoiceEvent.User != nil && txInvoiceEvent.User.Wallet != nil && txInvoiceEvent.User.Wallet.ID != user.Wallet.ID {
// the event was registered for another wallet than the one LNbits paid
log.Errorf("[Webhook] Invoice event for payment_hash %s belongs to wallet %s, not %s. Not dispatching.",
webhookEvent.PaymentHash, txInvoiceEvent.User.Wallet.ID, user.Wallet.ID)
return
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
err = w.buntdb.Get(txInvoiceEvent)
if err != nil {
log.Errorln(err)
} else {
// do something with the event
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
@@ -203,26 +113,14 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Errorln(err)
return
}
go runCallback(c.Function, txInvoiceEvent)
go c.Function(txInvoiceEvent)
return
}
}
// fallback: send a message to the user if there is no callback for this invoice
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), amountMsat/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
}
// runCallback runs an invoice callback in its own goroutine. Telegram handlers
// recover from panics, but these callbacks run outside of telebot, so a panic
// in one would otherwise take the whole bot down.
func runCallback(f func(telegram.Event), ev telegram.Event) {
defer func() {
if r := recover(); r != nil {
log.Errorf("[Webhook] panic in invoice callback: %v", r)
}
}()
f(ev)
}
-44
View File
@@ -1,44 +0,0 @@
package webhook
import (
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
)
func TestMarkHandled(t *testing.T) {
w := &Server{buntdb: storage.NewBunt(":memory:")}
for _, c := range []struct {
hash string
hasEvent bool
expires bool
}{
{"aa", true, false},
{"bb", false, true},
} {
first, err := w.markHandled(c.hash, c.hasEvent)
if err != nil || !first {
t.Fatalf("%s: first mark: %v %v", c.hash, first, err)
}
first, err = w.markHandled(c.hash, c.hasEvent)
if err != nil || first {
t.Fatalf("%s: second mark must be a repeat: %v %v", c.hash, first, err)
}
err = w.buntdb.View(func(tx *buntdb.Tx) error {
ttl, err := tx.TTL("webhook:" + c.hash)
if err != nil {
return err
}
// buntdb reports -1 for a key without expiry
if expires := ttl >= 0; expires != c.expires {
t.Errorf("%s: expires %t, want %t (ttl %s)", c.hash, expires, c.expires, ttl)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}
+61 -192
View File
@@ -19,13 +19,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"gorm.io/gorm"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
"github.com/nbd-wtf/go-nostr"
log "github.com/sirupsen/logrus"
)
@@ -34,19 +32,17 @@ const (
Endpoint = ".well-known/lnurlp"
MinSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 2000
CommentAllowed = 500
)
type Invoice struct {
*telegram.Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Nip57Receipt nostr.Event `json:"nip57_receipt"`
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
}
type Lnurl struct {
telegram *tb.Bot
@@ -56,7 +52,6 @@ type Lnurl struct {
buntdb *storage.DB
WebhookServer string
cache telegram.Cache
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Lnurl {
@@ -68,7 +63,6 @@ func New(bot *telegram.TipBot) Lnurl {
buntdb: bot.Bunt,
telegram: bot.Telegram,
cache: bot.Cache,
bot: bot,
}
}
func (lnurlInvoice Invoice) Key() string {
@@ -109,39 +103,14 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
// payer data
payerdata := request.FormValue("payerdata")
var payerData lnurl.PayerDataValues
if len(payerdata) > 0 {
err = json.Unmarshal([]byte(payerdata), &payerData)
if err != nil {
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
}
err = json.Unmarshal([]byte(payerdata), &payerData)
if err != nil {
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
}
// nostr NIP-57
// the "nostr" query param has a zap request which is a nostr event
// that specifies which nostr note has been zapped.
// here we check wheter its present, the event signature is valid
// and whether the event has the necessary tags that we need (p and relays are necessary, e is optional)
zapEventQuery := request.FormValue("nostr")
var zapEvent nostr.Event
if len(zapEventQuery) > 0 {
// A request that does not decode cleanly can still carry a pubkey, tags
// and sig (the library keeps the fields it read before the error), so
// it must never reach the zap path unverified.
if err = json.Unmarshal([]byte(zapEventQuery), &zapEvent); err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse nostr event: %v", err))
return
}
valid, err := zapEvent.CheckSignature()
if !valid || err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Nostr NIP-57 zap event signature invalid: %v", err))
return
}
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData, zapEvent)
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
}
// check if error was returned from first or second handlers
if err != nil {
@@ -176,7 +145,7 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
// load the user profile picture
if internal.Configuration.Bot.LNURLSendImage {
// get the user from the database
user, tx := db.FindUser(w.database, username)
user, tx := findUser(w.database, username)
if tx.Error == nil && user.Telegram != nil {
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
}
@@ -187,25 +156,9 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
return metadata
}
// we have our custom LNURLPayParams response object here because we want to
// add nostr nip57 fields to it
type LNURLPayParamsCustom struct {
lnurl.LNURLResponse
Callback string `json:"callback"`
Tag string `json:"tag"`
MaxSendable int64 `json:"maxSendable"`
MinSendable int64 `json:"minSendable"`
EncodedMetadata string `json:"metadata"`
CommentAllowed int64 `json:"commentAllowed"`
PayerData *lnurl.PayerDataSpec `json:"payerData,omitempty"`
AllowNostr bool `json:"allowsNostr,omitempty"`
NostrPubKey string `json:"nostrPubkey,omitempty"`
Metadata lnurl.Metadata `json:"-"`
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error) {
func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
log.Infof("[LNURL] Serving endpoint for user %s", username)
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
if err != nil {
@@ -215,18 +168,7 @@ func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error)
// produce the metadata including the image
metadata := w.getMetaDataCached(username)
// check if the user has added a nostr key for nip57
var allowNostr bool = false
var nostrPubkey string = ""
// if the bot has a nostr private key
if len(internal.Configuration.Nostr.PrivateKey) > 0 {
allowNostr = true
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nostrPubkey = pub
}
return &LNURLPayParamsCustom{
return &lnurl.LNURLPayParams{
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
Tag: PayRequestTag,
Callback: callbackURL.String(),
@@ -239,13 +181,11 @@ func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error)
LightningAddress: &lnurl.PayerDataItemSpec{},
Email: &lnurl.PayerDataItemSpec{},
},
AllowNostr: allowNostr,
NostrPubKey: nostrPubkey,
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues, zapEvent nostr.Event) (*lnurl.LNURLPayValues, error) {
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
log.Infof("[LNURL] Serving invoice for user %s", username)
if amount_msat < MinSendable || amount_msat > MaxSendable {
// amount is not ok
@@ -263,11 +203,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
// get rid of LNURL spam
if amount_msat < 21_000 {
comment = ""
}
user, tx := db.FindUser(w.database, username)
user, tx := findUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
@@ -282,91 +218,28 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
}
// get user settings
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
if err != nil {
log.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
} else {
user = user2
}
// A zap request is only honoured if it names this user (NIP-57, appendix D).
// The receipt is signed with the bot's key and is valid for any p tag, so
// the recipient must be bound to the paid user here.
if zapEvent.Sig != "" {
recipient := ""
if user.Settings != nil {
recipient = user.Settings.Nostr.PubKey
}
if err := validateZapRequest(zapEvent, amount_msat, recipient); err != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Invalid zap request."},
}, fmt.Errorf("[serveLNURLpSecond] %v", err)
}
}
// user is ok now create invoice
// set wallet lnbits client
var resp *lnurl.LNURLPayValues
var descriptionHash string
// NIP57 ZAPs
// TODO: refactor all this into nip57.go
var nip57Receipt nostr.Event
var zapEventSerializedStr string
var nip57ReceiptRelays []string
// for nip57 use the nostr event as the descriptionHash
if zapEvent.Sig != "" {
log.Infof("[LNURL] nostr zap for user %s", username)
// we calculate the descriptionHash here, create an invoice with it
// and store the invoice in the zap receipt later down the line
zapEventSerialized, err := json.Marshal(zapEvent)
zapEventSerializedStr = fmt.Sprintf("%s", zapEventSerialized)
if err != nil {
log.Println(err)
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Couldn't serialize zap event."},
}, err
}
// we extract the relays from the zap request
nip57ReceiptRelaysTags := zapEvent.Tags.GetFirst([]string{"relays"})
if len(fmt.Sprintf("%s", nip57ReceiptRelaysTags)) > 0 {
nip57ReceiptRelays = strings.Split(fmt.Sprintf("%s", nip57ReceiptRelaysTags), " ")
// this tirty method returns slice [ "[relays", "wss...", "wss...", "wss...]" ] – we need to clean it up
if len(nip57ReceiptRelays) > 1 {
// remove the first entry
nip57ReceiptRelays = nip57ReceiptRelays[1:]
// clean up the last entry
len_last_entry := len(nip57ReceiptRelays[len(nip57ReceiptRelays)-1])
nip57ReceiptRelays[len(nip57ReceiptRelays)-1] = nip57ReceiptRelays[len(nip57ReceiptRelays)-1][:len_last_entry-1]
}
// now the relay list is clean!
}
// calculate description hash from the serialized nostr event
descriptionHash = w.Nip57DescriptionHash(zapEventSerializedStr)
} else {
// calculate normal LNURL descriptionhash
// the same description_hash needs to be built in the second request
metadata := w.getMetaDataCached(username)
// the same description_hash needs to be built in the second request
metadata := w.getMetaDataCached(username)
var payerDataByte []byte
var err error
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
payerDataByte, err = json.Marshal(payerData)
if err != nil {
return nil, err
}
} else {
payerDataByte = []byte("")
}
descriptionHash, err = w.DescriptionHash(metadata, string(payerDataByte))
var payerDataByte []byte
var err error
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
payerDataByte, err = json.Marshal(payerData)
if err != nil {
return nil, err
}
} else {
payerDataByte = []byte("")
}
descriptionHash, err := w.DescriptionHash(metadata, string(payerDataByte))
if err != nil {
return nil, err
}
invoice, err := user.Wallet.Invoice(
@@ -390,46 +263,21 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// nip57 - we need to store the newly created invoice in the zap receipt
if zapEvent.Sig != "" {
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nip57Receipt = nostr.Event{
PubKey: pub,
CreatedAt: time.Now(),
Kind: 9735,
Tags: nostr.Tags{
*zapEvent.Tags.GetFirst([]string{"p"}),
[]string{"bolt11", invoice.PaymentRequest},
[]string{"description", zapEventSerializedStr},
},
}
if zapEvent.Tags.GetFirst([]string{"e"}) != nil {
nip57Receipt.Tags = nip57Receipt.Tags.AppendUnique(*zapEvent.Tags.GetFirst([]string{"e"}))
}
nip57Receipt.Sign(pk)
}
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
// also holds Nip57 Zap receipt to send to nostr when invoice is paid
runtime.IgnoreError(w.buntdb.Set(
Invoice{
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
Nip57Receipt: nip57Receipt,
Nip57ReceiptRelays: nip57ReceiptRelays,
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
}))
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
telegram.InvoiceEvent{
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
UserCurrency: user.Settings.Display.DisplayCurrency,
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
}))
return &lnurl.LNURLPayValues{
@@ -462,7 +310,7 @@ func (w Lnurl) metaData(username string) lnurl.Metadata {
// we actually want to find the users username so it looks nicer in the
// metadata description
if strings.HasPrefix(username, "1x") {
user, _ := db.FindUser(w.database, username)
user, _ := findUser(w.database, username)
if user.Telegram.Username != "" {
username = user.Telegram.Username
}
@@ -503,6 +351,27 @@ func isAnonUsername(username string) bool {
}
}
func findUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
func extractSenderFromPayerdata(payer lnurl.PayerDataValues) string {
if payer.LightningAddress != "" {
return payer.LightningAddress
-66
View File
@@ -1,66 +0,0 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
"github.com/nbd-wtf/go-nostr"
)
type Tag []string
type Tags []Tag
type NostrEvent struct {
ID string `json:"id"`
PubKey string `json:"pubkey"`
CreatedAt time.Time `json:"created_at"`
Kind int `json:"kind"`
Tags Tags `json:"tags"`
Content string `json:"content"`
Sig string `json:"sig"`
}
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) Nip57DescriptionHash(zapEventSerialized string) string {
hash := sha256.Sum256([]byte(zapEventSerialized))
hashString := hex.EncodeToString(hash[:])
return hashString
}
// validateZapRequest checks a NIP-57 zap request against the payment it is
// for: kind 9734, exactly one p tag naming the recipient, at most one e tag,
// and an amount tag (if present) equal to the amount of the payment.
// recipientPubkey is the nostr pubkey the paid user registered with the bot;
// without one the request cannot be bound to the user and is refused.
func validateZapRequest(ev nostr.Event, amountMsat int64, recipientPubkey string) error {
if ev.Kind != 9734 {
return fmt.Errorf("zap request has kind %d", ev.Kind)
}
var pTags, eTags int
for _, t := range ev.Tags {
if len(t) < 2 {
continue
}
switch t[0] {
case "p":
pTags++
if recipientPubkey == "" || t[1] != recipientPubkey {
return fmt.Errorf("zap request p tag does not name the paid user")
}
case "e":
eTags++
case "amount":
if v, err := strconv.ParseInt(t[1], 10, 64); err != nil || v != amountMsat {
return fmt.Errorf("zap request amount %q does not match %d msat", t[1], amountMsat)
}
}
}
if pTags != 1 || eTags > 1 {
return fmt.Errorf("zap request has %d p tags and %d e tags", pTags, eTags)
}
return nil
}
-37
View File
@@ -1,37 +0,0 @@
package lnurl
import (
"testing"
"github.com/nbd-wtf/go-nostr"
)
func zap(kind int, tags ...nostr.Tag) nostr.Event {
return nostr.Event{Kind: kind, Tags: nostr.Tags(tags)}
}
func TestValidateZapRequest(t *testing.T) {
const me, other = "aa", "bb"
p := func(k string) nostr.Tag { return nostr.Tag{"p", k} }
for _, c := range []struct {
name string
ev nostr.Event
rcpt string
ok bool
}{
{"valid", zap(9734, p(me), nostr.Tag{"e", "n1"}, nostr.Tag{"amount", "1000"}), me, true},
{"no amount tag", zap(9734, p(me)), me, true},
{"other recipient", zap(9734, p(other)), me, false},
{"user has no pubkey", zap(9734, p(me)), "", false},
{"wrong kind", zap(1, p(me)), me, false},
{"two p tags", zap(9734, p(me), p(me)), me, false},
{"no p tag", zap(9734), me, false},
{"two e tags", zap(9734, p(me), nostr.Tag{"e", "1"}, nostr.Tag{"e", "2"}), me, false},
{"amount mismatch", zap(9734, p(me), nostr.Tag{"amount", "100000000"}), me, false},
{"amount not a number", zap(9734, p(me), nostr.Tag{"amount", "x"}), me, false},
} {
if err := validateZapRequest(c.ev, 1000, c.rcpt); (err == nil) != c.ok {
t.Errorf("%s: err=%v, want ok=%v", c.name, err, c.ok)
}
}
}
-232
View File
@@ -1,232 +0,0 @@
// Package lnurlcash implements LNURLcash (LUD-25) bearer notes for the bot:
// notes are minted at admin-listed mints, their secrets are stored encrypted,
// and the balance stays in LNbits. Amounts inside this package are int64
// millisatoshi everywhere.
package lnurlcash
import (
"encoding/hex"
"fmt"
"strings"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
)
// MintConfig is one admin-listed mint.
type MintConfig struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
Default bool `yaml:"default"`
}
// Config is the `lnurlcash:` block of config.yaml.
type Config struct {
Enabled bool `yaml:"enabled"`
Mints []MintConfig `yaml:"mints"`
MinNoteSat int64 `yaml:"min_note_sat"`
MaxNoteSat int64 `yaml:"max_note_sat"`
MaxOutstandingSatPerUser int64 `yaml:"max_outstanding_sat_per_user"`
MaxOutstandingNotesPerUser int64 `yaml:"max_outstanding_notes_per_user"`
MaxBatchSize int64 `yaml:"max_batch_size"`
MaxBatchTotalSat int64 `yaml:"max_batch_total_sat"`
GroupNoteMaxSat int64 `yaml:"group_note_max_sat"`
MaxMintFeePpm int64 `yaml:"max_mint_fee_ppm"`
AutoReclaimDays int `yaml:"auto_reclaim_days"`
StatusPollInterval time.Duration `yaml:"status_poll_interval"`
InvoiceWaitTimeout time.Duration `yaml:"invoice_wait_timeout"`
BatchStrategy string `yaml:"batch_strategy"`
BatchFormats []string `yaml:"batch_formats"`
SecretEncryptionKey string `yaml:"secret_encryption_key"`
// AdminTelegramID receives mint alerts when set; otherwise alerts are logged only.
AdminTelegramID int64 `yaml:"admin_telegram_id"`
}
const (
StrategySplit = "split"
StrategyInvoices = "invoices"
)
var knownFormats = map[string]bool{"pdf": true, "json": true, "csv": true}
// Normalize fills defaults for zero values. It is safe to call more than once.
func (c *Config) Normalize() {
c.Mints = expandMints(c.Mints)
if c.MinNoteSat <= 0 {
c.MinNoteSat = 1
}
if c.MaxNoteSat <= 0 {
c.MaxNoteSat = 100_000
}
if c.MaxOutstandingSatPerUser <= 0 {
c.MaxOutstandingSatPerUser = 500_000
}
if c.MaxOutstandingNotesPerUser <= 0 {
c.MaxOutstandingNotesPerUser = 200
}
if c.MaxBatchSize <= 0 {
c.MaxBatchSize = 100
}
if c.MaxBatchTotalSat <= 0 {
c.MaxBatchTotalSat = 500_000
}
if c.GroupNoteMaxSat <= 0 {
c.GroupNoteMaxSat = 1000
}
if c.MaxMintFeePpm <= 0 {
c.MaxMintFeePpm = 20_000
}
if c.StatusPollInterval <= 0 {
c.StatusPollInterval = 5 * time.Minute
}
if c.InvoiceWaitTimeout <= 0 {
c.InvoiceWaitTimeout = 60 * time.Second
}
if c.BatchStrategy == "" {
c.BatchStrategy = StrategySplit
}
if len(c.BatchFormats) == 0 {
c.BatchFormats = []string{"pdf", "json", "csv"}
}
}
// Validate checks the block. It only complains when the feature is enabled.
func (c *Config) Validate() error {
c.Normalize()
if !c.Enabled {
return nil
}
if len(c.Mints) == 0 {
return fmt.Errorf("lnurlcash: at least one mint is required")
}
defaults := 0
seen := map[string]bool{}
for i, m := range c.Mints {
if strings.TrimSpace(m.Name) == "" {
return fmt.Errorf("lnurlcash: mint %d has no name", i)
}
if seen[m.Name] {
return fmt.Errorf("lnurlcash: mint name %q is listed twice", m.Name)
}
seen[m.Name] = true
if ResolveMintURL(m.URL) == "" {
return fmt.Errorf("lnurlcash: mint %q has an invalid url %q (https URL, lightning address or bare domain)", m.Name, m.URL)
}
if m.Default {
defaults++
}
}
if defaults != 1 {
return fmt.Errorf("lnurlcash: exactly one mint must be marked default (found %d)", defaults)
}
if c.BatchStrategy != StrategySplit && c.BatchStrategy != StrategyInvoices {
return fmt.Errorf("lnurlcash: batch_strategy must be %q or %q", StrategySplit, StrategyInvoices)
}
for _, f := range c.BatchFormats {
if !knownFormats[f] {
return fmt.Errorf("lnurlcash: unknown batch format %q", f)
}
}
if c.MinNoteSat > c.MaxNoteSat {
return fmt.Errorf("lnurlcash: min_note_sat is above max_note_sat")
}
if c.MaxMintFeePpm >= 1_000_000 {
return fmt.Errorf("lnurlcash: max_mint_fee_ppm must be below 1000000")
}
key, err := hex.DecodeString(strings.TrimSpace(c.SecretEncryptionKey))
if err != nil || len(key) != 32 {
return fmt.Errorf("lnurlcash: secret_encryption_key must be 32 bytes as 64 hex characters (generate one with `openssl rand -hex 32`)")
}
return nil
}
// DefaultMint returns the mint marked default, or the first one.
func (c *Config) DefaultMint() *MintConfig {
for i := range c.Mints {
if c.Mints[i].Default {
return &c.Mints[i]
}
}
if len(c.Mints) > 0 {
return &c.Mints[0]
}
return nil
}
// HasFormat reports whether a batch export format is enabled.
func (c *Config) HasFormat(format string) bool {
for _, f := range c.BatchFormats {
if f == format {
return true
}
}
return false
}
// ResolveMintURL turns a configured mint reference into its payRequest URL.
// Accepted forms: a bare domain or lightning address (lnurlcash-go's
// ResolveMintInput), a bech32 LNURL, a payRequest URL, or a plain https base
// URL of a mint, which uses lnurl-mint's default "mint" identifier.
func ResolveMintURL(input string) string {
trimmed := strings.TrimSpace(input)
lower := strings.ToLower(trimmed)
if strings.HasPrefix(lower, "https://") || strings.HasPrefix(lower, "http://") {
if !lnurlcash.IsAllowedServiceURL(trimmed) {
return ""
}
if strings.Contains(trimmed, "/.well-known/lnurlp/") {
return trimmed
}
host := strings.TrimRight(strings.SplitN(trimmed[strings.Index(trimmed, "://")+3:], "/", 2)[0], "/")
if host == "" {
return ""
}
return lnurlcash.ResolveMintInput("mint@" + host)
}
return lnurlcash.ResolveMintInput(trimmed)
}
// expandMints turns an entry whose url lists several mints, comma separated,
// into one entry per mint. The first keeps the configured name and default
// flag, so notes minted under that name stay attached to it; the others are
// named after their host. It is idempotent.
func expandMints(in []MintConfig) []MintConfig {
var out []MintConfig
for _, m := range in {
parts := strings.Split(m.URL, ",")
if len(parts) == 1 {
out = append(out, m)
continue
}
first := true
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
continue
}
e := MintConfig{Name: mintNameFromURL(part), URL: part}
if first {
e.Name, e.Default = m.Name, m.Default
first = false
}
out = append(out, e)
}
if first { // only commas: keep the entry so Validate reports it
out = append(out, m)
}
}
return out
}
// mintNameFromURL names a mint after its host: "https://mint.600.wtf/x" and
// "mint@mint.600.wtf" both give "mint.600.wtf".
func mintNameFromURL(u string) string {
u = strings.TrimSpace(u)
if i := strings.Index(u, "://"); i >= 0 {
u = u[i+3:]
}
if i := strings.LastIndex(u, "@"); i >= 0 {
u = u[i+1:]
}
return strings.SplitN(u, "/", 2)[0]
}
-13
View File
@@ -1,13 +0,0 @@
package lnurlcash
import "testing"
func TestCommaSeparatedMints(t *testing.T) {
c := &Config{Mints: []MintConfig{{Name: "21mint", URL: "lnurl.21mint.me, https://mint.600.wtf/", Default: true}}}
c.Normalize()
c.Normalize()
if len(c.Mints) != 2 || c.Mints[0].Name != "21mint" || !c.Mints[0].Default || c.Mints[0].URL != "lnurl.21mint.me" ||
c.Mints[1].Name != "mint.600.wtf" || c.Mints[1].Default || c.Mints[1].URL != "https://mint.600.wtf/" {
t.Fatalf("got %+v", c.Mints)
}
}
-64
View File
@@ -1,64 +0,0 @@
package lnurlcash
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
)
// Cipher seals note secrets at rest with AES-256-GCM. The ciphertext is
// nonce || sealed, so every call to Seal gives a different value for the
// same secret.
type Cipher struct {
aead cipher.AEAD
}
// NewCipher takes the key as 64 hex characters.
func NewCipher(hexKey string) (*Cipher, error) {
key, err := hex.DecodeString(strings.TrimSpace(hexKey))
if err != nil || len(key) != 32 {
return nil, errors.New("lnurlcash: encryption key must be 32 bytes of hex")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &Cipher{aead: aead}, nil
}
// Seal encrypts a secret.
func (c *Cipher) Seal(plain string) ([]byte, error) {
if c == nil {
return nil, errors.New("lnurlcash: no cipher configured")
}
nonce := make([]byte, c.aead.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("lnurlcash: could not draw a nonce: %w", err)
}
return append(nonce, c.aead.Seal(nil, nonce, []byte(plain), nil)...), nil
}
// Open decrypts a value produced by Seal.
func (c *Cipher) Open(sealed []byte) (string, error) {
if c == nil {
return "", errors.New("lnurlcash: no cipher configured")
}
n := c.aead.NonceSize()
if len(sealed) < n+c.aead.Overhead() {
return "", errors.New("lnurlcash: sealed secret is too short")
}
plain, err := c.aead.Open(nil, sealed[:n], sealed[n:], nil)
if err != nil {
return "", errors.New("lnurlcash: sealed secret does not open with this key")
}
return string(plain), nil
}
-97
View File
@@ -1,97 +0,0 @@
package lnurlcash
import (
"strings"
"testing"
)
const testKey = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
func TestCipherRoundTrip(t *testing.T) {
c, err := NewCipher(testKey)
if err != nil {
t.Fatal(err)
}
secret := strings.Repeat("ab", 32)
sealed, err := c.Seal(secret)
if err != nil {
t.Fatal(err)
}
again, err := c.Seal(secret)
if err != nil {
t.Fatal(err)
}
if string(sealed) == string(again) {
t.Fatal("two seals of the same secret must differ (random nonce)")
}
got, err := c.Open(sealed)
if err != nil || got != secret {
t.Fatalf("open: %v %q", err, got)
}
sealed[len(sealed)-1] ^= 1
if _, err := c.Open(sealed); err == nil {
t.Fatal("tampered ciphertext must not open")
}
other, _ := NewCipher(strings.Repeat("ff", 32))
if _, err := other.Open(sealed[:len(sealed)]); err == nil {
t.Fatal("wrong key must not open")
}
if _, err := NewCipher("abc"); err == nil {
t.Fatal("short key must be refused")
}
}
func TestConfigValidate(t *testing.T) {
c := Config{}
if err := c.Validate(); err != nil {
t.Fatalf("disabled config must validate: %v", err)
}
if c.StatusPollInterval == 0 || c.BatchStrategy != StrategySplit || len(c.BatchFormats) != 3 {
t.Fatal("defaults not applied")
}
c = Config{Enabled: true}
if err := c.Validate(); err == nil {
t.Fatal("enabled without mints must fail")
}
c.Mints = []MintConfig{{Name: "21mint", URL: "https://lnurl.21mint.me", Default: true}}
if err := c.Validate(); err == nil || !strings.Contains(err.Error(), "secret_encryption_key") {
t.Fatalf("missing key must fail: %v", err)
}
c.SecretEncryptionKey = testKey
if err := c.Validate(); err != nil {
t.Fatal(err)
}
c.Mints = append(c.Mints, MintConfig{Name: "other", URL: "http://insecure.example", Default: true})
if err := c.Validate(); err == nil {
t.Fatal("http clearnet url and two defaults must fail")
}
c.Mints[1] = MintConfig{Name: "other", URL: "mint@other.example"}
if err := c.Validate(); err != nil {
t.Fatal(err)
}
if c.DefaultMint().Name != "21mint" {
t.Fatal("wrong default mint")
}
c.BatchFormats = []string{"docx"}
if err := c.Validate(); err == nil {
t.Fatal("unknown format must fail")
}
}
func TestResolveMintURL(t *testing.T) {
cases := map[string]string{
"https://lnurl.21mint.me": "https://lnurl.21mint.me/.well-known/lnurlp/mint",
"https://lnurl.21mint.me/": "https://lnurl.21mint.me/.well-known/lnurlp/mint",
"https://lnurl.21mint.me/.well-known/lnurlp/mint": "https://lnurl.21mint.me/.well-known/lnurlp/mint",
"lnurl.21mint.me": "https://lnurl.21mint.me/.well-known/lnurlp/mint",
"mint@lnurl.21mint.me": "https://lnurl.21mint.me/.well-known/lnurlp/mint",
"http://lnurl.21mint.me": "",
"http://localhost:3338": "http://localhost:3338/.well-known/lnurlp/mint",
"": "",
}
for in, want := range cases {
if got := ResolveMintURL(in); got != want {
t.Errorf("%q: got %q want %q", in, got, want)
}
}
}
-24
View File
@@ -1,24 +0,0 @@
package lnurlcash
import (
"errors"
"strings"
)
// Describe renders an error with the transport cause an AmbiguousError hides
// behind its detail, so a log line says why a mint could not be reached.
func Describe(err error) string {
if err == nil {
return ""
}
parts := []string{err.Error()}
for e := err; e != nil; e = errors.Unwrap(e) {
var ambiguous interface{ Unwrap() error }
if errors.As(e, &ambiguous) {
if cause := ambiguous.Unwrap(); cause != nil && !strings.Contains(parts[0], cause.Error()) {
parts = append(parts, cause.Error())
}
}
}
return strings.Join(parts, ": ")
}
-147
View File
@@ -1,147 +0,0 @@
// Package export renders a batch of notes as PDF, CSV or JSON. It never
// touches the database: the caller decrypts and passes the note strings.
package export
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"strconv"
"time"
"github.com/go-pdf/fpdf"
"github.com/skip2/go-qrcode"
)
// Note is one note ready to print. LNURL is the bech32 form, LNURLW the
// lnurlw:// form; both carry the secret.
type Note struct {
Index int
ID string
ShortID string
AmountMsat int64
LNURL string
LNURLW string
Mint string
Memo string
Cert string
CreatedAt time.Time
}
// Batch is what gets exported.
type Batch struct {
ID string
MintURL string
MintPubkey string
MintName string
Memo string
CreatedAt time.Time
Notes []Note
}
// CSV writes index,id,amount_sat,lnurl,lnurlw_url,mint,memo,created_at.
func CSV(w io.Writer, b Batch) error {
cw := csv.NewWriter(w)
if err := cw.Write([]string{"index", "id", "amount_sat", "lnurl", "lnurlw_url", "mint", "memo", "created_at"}); err != nil {
return err
}
for _, n := range b.Notes {
row := []string{strconv.Itoa(n.Index), n.ID, strconv.FormatInt(n.AmountMsat/1000, 10), n.LNURL, n.LNURLW, n.Mint, n.Memo, n.CreatedAt.UTC().Format(time.RFC3339)}
if err := cw.Write(row); err != nil {
return err
}
}
cw.Flush()
return cw.Error()
}
type jsonNote struct {
Index int `json:"index"`
ID string `json:"id"`
AmountMsat int64 `json:"amount_msat"`
LNURL string `json:"lnurl"`
LNURLW string `json:"lnurlw"`
Cert string `json:"certificate,omitempty"`
CreatedAt string `json:"created_at"`
}
type jsonBatch struct {
BatchID string `json:"batch_id"`
MintURL string `json:"mint_url"`
MintPubkey string `json:"mint_pubkey"`
Memo string `json:"memo"`
CreatedAt string `json:"created_at"`
Notes []jsonNote `json:"notes"`
}
// JSON writes the batch with its notes array.
func JSON(w io.Writer, b Batch) error {
out := jsonBatch{BatchID: b.ID, MintURL: b.MintURL, MintPubkey: b.MintPubkey, Memo: b.Memo, CreatedAt: b.CreatedAt.UTC().Format(time.RFC3339), Notes: []jsonNote{}}
for _, n := range b.Notes {
out.Notes = append(out.Notes, jsonNote{Index: n.Index, ID: n.ID, AmountMsat: n.AmountMsat, LNURL: n.LNURL, LNURLW: n.LNURLW, Cert: n.Cert, CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339)})
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(out)
}
// PDF lays out eight notes per A4 page: a QR code, value, memo, mint and
// short id each. The QR holds the bech32 LNURL.
func PDF(w io.Writer, b Batch) error {
const perPage = 8
pdf := fpdf.New("P", "mm", "A4", "")
pdf.SetAutoPageBreak(false, 0)
pdf.SetTitle("LNURLcash notes "+b.ID, true)
cellW, cellH := 95.0, 66.0
left, top := 10.0, 12.0
for i, n := range b.Notes {
if i%perPage == 0 {
pdf.AddPage()
pdf.SetFont("Helvetica", "", 8)
pdf.SetXY(left, 5)
pdf.CellFormat(190, 5, fmt.Sprintf("LNURLcash notes batch %s mint %s page %d", b.ID, b.MintName, i/perPage+1), "", 0, "L", false, 0, "")
}
slot := i % perPage
x := left + float64(slot%2)*cellW
y := top + float64(slot/2)*cellH
pdf.Rect(x, y, cellW-2, cellH-2, "D")
png, err := qrcode.Encode(n.LNURL, qrcode.Medium, 256)
if err != nil {
return err
}
name := "qr" + strconv.Itoa(i)
pdf.RegisterImageOptionsReader(name, fpdf.ImageOptions{ImageType: "PNG"}, bytes.NewReader(png))
pdf.ImageOptions(name, x+3, y+3, 48, 48, false, fpdf.ImageOptions{ImageType: "PNG"}, 0, "")
pdf.SetFont("Helvetica", "B", 14)
pdf.SetXY(x+54, y+6)
pdf.CellFormat(38, 8, fmt.Sprintf("%d sat", n.AmountMsat/1000), "", 0, "L", false, 0, "")
pdf.SetFont("Helvetica", "", 8)
pdf.SetXY(x+54, y+16)
pdf.MultiCell(37, 4, truncate(n.Memo, 90), "", "L", false)
pdf.SetXY(x+54, y+40)
pdf.CellFormat(38, 4, "mint: "+truncate(n.Mint, 30), "", 0, "L", false, 0, "")
pdf.SetXY(x+54, y+45)
pdf.CellFormat(38, 4, "id: "+n.ShortID, "", 0, "L", false, 0, "")
pdf.SetXY(x+54, y+50)
pdf.CellFormat(38, 4, fmt.Sprintf("#%d", n.Index), "", 0, "L", false, 0, "")
pdf.SetFont("Helvetica", "", 5)
pdf.SetXY(x+3, y+53)
pdf.MultiCell(cellW-8, 2.2, n.LNURL, "", "L", false)
}
if len(b.Notes) == 0 {
pdf.AddPage()
pdf.SetFont("Helvetica", "", 10)
pdf.SetXY(left, top)
pdf.CellFormat(190, 8, "No unclaimed notes in batch "+b.ID, "", 0, "L", false, 0, "")
}
return pdf.Output(w)
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n-1] + "…"
}
-61
View File
@@ -1,61 +0,0 @@
package export
import (
"bytes"
"encoding/json"
"strings"
"testing"
"time"
)
func sample(n int) Batch {
b := Batch{ID: "batch-abc", MintURL: "https://mint.example/w", MintPubkey: "02ab", MintName: "fake", Memo: "party", CreatedAt: time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC)}
for i := 1; i <= n; i++ {
id := "note-" + strings.Repeat("x", i)
lnurl := "LNURL1DP68GURN8GHJ7MRWW4EXCTNXD9SHG6NPVCHXXMMD9AKXUATJDSKHQCTE8AEK2UMND9HKU0TL" + strings.Repeat("A", i)
lnurlw := "lnurlw://mint.example/w?k1=" + strings.Repeat("a", 64)
b.Notes = append(b.Notes, Note{Index: i, ID: id, ShortID: "xxxxxx", AmountMsat: 21_000, LNURL: lnurl, LNURLW: lnurlw, Mint: "fake", Memo: "party", CreatedAt: b.CreatedAt})
}
return b
}
func TestCSVAndJSON(t *testing.T) {
var buf bytes.Buffer
if err := CSV(&buf, sample(2)); err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 3 || lines[0] != "index,id,amount_sat,lnurl,lnurlw_url,mint,memo,created_at" || !strings.HasPrefix(lines[1], "1,note-x,21,LNURL1") {
t.Fatalf("csv:\n%s", buf.String())
}
buf.Reset()
if err := JSON(&buf, sample(2)); err != nil {
t.Fatal(err)
}
var got map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got["batch_id"] != "batch-abc" || got["mint_pubkey"] != "02ab" || len(got["notes"].([]interface{})) != 2 {
t.Fatalf("json: %v", got)
}
buf.Reset()
if err := JSON(&buf, sample(0)); err != nil || !strings.Contains(buf.String(), `"notes": []`) {
t.Fatalf("empty batch must have an empty array: %s %v", buf.String(), err)
}
}
func TestPDFPages(t *testing.T) {
for notes, pages := range map[int]int{0: 1, 1: 1, 8: 1, 9: 2, 20: 3} {
var buf bytes.Buffer
if err := PDF(&buf, sample(notes)); err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) {
t.Fatal("not a pdf")
}
if got := bytes.Count(buf.Bytes(), []byte("/Type /Page\n")); got != pages {
t.Fatalf("%d notes: %d pages, want %d", notes, got, pages)
}
}
}
-324
View File
@@ -1,324 +0,0 @@
package lnurlcash
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
)
// fakeMint is an in-memory LUD-25 service for tests: payRequest with a fee,
// comment-bound mint invoices, ?p= lookups, split and melt, plus switches to
// drop a response after applying a mutation.
type fakeMint struct {
t *testing.T
srv *httptest.Server
mu sync.Mutex
base int64
ppm int64
pubkey string
notes map[string]int64 // h -> value msat (outstanding)
burned map[string]bool
pending map[string]bool
inv map[string]*fakeInvoice // pr -> invoice
melts []fakeMelt
// failure switches
dropAfterSplit bool
refuseSplit string // reason to answer every split with
meltReason string // reason to answer every melt with
pubkeyChange string
calls map[string]int
// satRound credits mint invoices in whole sats with the fee rounded up,
// as the live mints do; minSendable overrides the advertised minimum
satRound bool
minSendable int64
// connection bookkeeping: requests served per connection, and the
// connection of every mutation (mint invoice, melt, split)
nextConn int64
connReqs map[int64]int
mutConns []int64
}
type fakeConnKey struct{}
type fakeInvoice struct {
h string
amount int64
settled bool
}
type fakeMelt struct {
h string
pr string
}
func newFakeMint(t *testing.T) *fakeMint {
m := &fakeMint{
t: t, base: 1000, ppm: 100,
pubkey: "021ab89df9cbd28cdab8c71d228ca40deba1eaebd827f24849ec4f3e919c023555",
notes: map[string]int64{}, burned: map[string]bool{}, pending: map[string]bool{},
inv: map[string]*fakeInvoice{}, calls: map[string]int{}, connReqs: map[int64]int{},
}
m.srv = httptest.NewUnstartedServer(http.HandlerFunc(m.handle))
m.srv.Config.ConnContext = func(ctx context.Context, _ net.Conn) context.Context {
return context.WithValue(ctx, fakeConnKey{}, atomic.AddInt64(&m.nextConn, 1))
}
m.srv.Start()
t.Cleanup(m.srv.Close)
return m
}
func (m *fakeMint) url() string { return m.srv.URL }
// connStats reports how many mutations arrived on a connection that also
// carried another request, and whether any connection was reused at all.
func (m *fakeMint) connStats() (mutations, sharedMutations int, anyReuse bool) {
m.mu.Lock()
defer m.mu.Unlock()
for _, c := range m.mutConns {
if m.connReqs[c] > 1 {
sharedMutations++
}
}
for _, n := range m.connReqs {
if n > 1 {
anyReuse = true
}
}
return len(m.mutConns), sharedMutations, anyReuse
}
func (m *fakeMint) hashOf(k1 string) string {
raw, _ := hex.DecodeString(k1)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
func errJSON(w http.ResponseWriter, reason string) {
writeJSON(w, map[string]string{"status": "ERROR", "reason": reason})
}
func (m *fakeMint) handle(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
defer m.mu.Unlock()
m.calls[r.URL.Path]++
q := r.URL.Query()
conn, _ := r.Context().Value(fakeConnKey{}).(int64)
m.connReqs[conn]++
if r.URL.Path == "/p/cb" || (r.URL.Path == "/w/cb" && len(q["k1"]) > 0) {
m.mutConns = append(m.mutConns, conn)
}
pub := m.pubkey
if m.pubkeyChange != "" {
pub = m.pubkeyChange
}
switch {
case r.URL.Path == "/.well-known/lnurlp/mint":
meta := fmt.Sprintf(`[["text/plain","fake mint"],["text/plain","Mint fees: %d,%d"]]`, m.base, m.ppm)
writeJSON(w, map[string]interface{}{
"tag": "payRequest", "callback": m.srv.URL + "/p/cb", "minSendable": m.minSendableMsat(), "maxSendable": 100_000_000_000,
"metadata": meta, "withdrawLink": m.srv.URL + "/w", "commentAllowed": 64, "mintPubkey": pub,
})
case r.URL.Path == "/p/cb":
amount, _ := strconv.ParseInt(q.Get("amount"), 10, 64)
h := q.Get("comment")
if len(h) != 64 {
errJSON(w, "comment must be a 64 hex output")
return
}
pr := "fakepr" + strconv.Itoa(len(m.inv)+1) + h[:8]
m.inv[pr] = &fakeInvoice{h: h, amount: amount}
writeJSON(w, map[string]interface{}{"pr": pr, "routes": []string{}, "verify": m.srv.URL + "/v/" + pr})
case strings.HasPrefix(r.URL.Path, "/v/"):
pr := strings.TrimPrefix(r.URL.Path, "/v/")
inv, ok := m.inv[pr]
if !ok {
errJSON(w, "unknown invoice")
return
}
writeJSON(w, map[string]interface{}{"status": "OK", "settled": inv.settled, "preimage": "", "pr": pr})
case r.URL.Path == "/w":
// like mint.600.wtf: /w only serves info; a mutation sent here gets a
// 200 that confirms nothing, which the client reads as an unknown outcome
for k := range q {
if k == "p1" || k == "p2" || k == "pr" {
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest"})
return
}
}
m.withdraw(w, q, pub)
case r.URL.Path == "/w/cb":
m.withdraw(w, q, pub)
default:
http.NotFound(w, r)
}
}
func (m *fakeMint) withdraw(w http.ResponseWriter, q map[string][]string, pub string) {
get := func(k string) string {
if v := q[k]; len(v) > 0 {
return v[0]
}
return ""
}
k1s := q["k1"]
// informational GET by hash
if p := get("p"); p != "" && len(k1s) == 0 {
v, ok := m.notes[p]
if !ok {
if m.burned[p] {
errJSON(w, "already in use")
} else {
errJSON(w, "unknown note")
}
return
}
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w/cb", "minWithdrawable": v, "maxWithdrawable": v, "defaultDescription": "fake", "mintPubkey": pub})
return
}
if len(k1s) == 0 {
errJSON(w, "no k1")
return
}
hs := make([]string, 0, len(k1s))
var total int64
for _, k1 := range k1s {
h := m.hashOf(strings.ToLower(k1))
if m.pending[h] {
errJSON(w, "pending")
return
}
v, ok := m.notes[h]
if !ok {
if m.burned[h] {
errJSON(w, "already in use")
} else {
errJSON(w, "unknown note")
}
return
}
hs = append(hs, h)
total += v
}
pr, amount, p1, p2 := get("pr"), get("amount"), get("p1"), get("p2")
switch {
case pr != "":
if m.meltReason != "" {
errJSON(w, m.meltReason)
return
}
inv, ok := m.inv[pr]
if ok && inv.amount != total {
errJSON(w, "invoice amount must equal the note value")
return
}
m.pending[hs[0]] = true
m.melts = append(m.melts, fakeMelt{h: hs[0], pr: pr})
writeJSON(w, map[string]string{"status": "OK"})
case p1 != "" && amount != "":
if m.refuseSplit != "" {
errJSON(w, m.refuseSplit)
return
}
a, _ := strconv.ParseInt(amount, 10, 64)
if p2 == "" {
errJSON(w, "p1 and p2 required")
return
}
if _, used := m.notes[p1]; used || m.burned[p1] {
errJSON(w, "already in use")
return
}
change := total - a - m.base
if change <= 0 {
errJSON(w, "insufficient value")
return
}
for _, h := range hs {
delete(m.notes, h)
m.burned[h] = true
}
m.notes[p1] = a
m.notes[p2] = change
if m.dropAfterSplit {
m.dropAfterSplit = false
panic(http.ErrAbortHandler) // connection dropped after the mutation applied
}
writeJSON(w, map[string]string{"status": "OK"})
case p1 != "":
for _, h := range hs {
delete(m.notes, h)
m.burned[h] = true
}
m.notes[p1] = total
writeJSON(w, map[string]string{"status": "OK"})
case len(k1s) == 1:
// informational GET by k1; amount is display-only and ignored (LUD-25)
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w/cb", "k1": k1s[0], "minWithdrawable": total, "maxWithdrawable": total, "defaultDescription": "fake", "mintPubkey": pub})
default:
errJSON(w, "bad request")
}
}
// settle marks a mint invoice paid and credits its note.
func (m *fakeMint) settle(pr string) {
m.mu.Lock()
defer m.mu.Unlock()
inv, ok := m.inv[pr]
if !ok {
m.t.Fatalf("settle: unknown pr %s", pr)
}
inv.settled = true
net := inv.amount - m.base - (inv.amount/1_000_000)*m.ppm - ((inv.amount%1_000_000)*m.ppm)/1_000_000
if m.satRound {
net -= net % 1000
}
m.notes[inv.h] = net
}
func (m *fakeMint) minSendableMsat() int64 {
if m.minSendable > 0 {
return m.minSendable
}
return 1000
}
// finishMelt completes a pending melt: paid burns the note, failed restores it.
func (m *fakeMint) finishMelt(h string, paid bool) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.pending, h)
if paid {
delete(m.notes, h)
m.burned[h] = true
}
}
// claim burns a note as if somebody else redeemed it.
func (m *fakeMint) claim(h string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.notes, h)
m.burned[h] = true
}
func (m *fakeMint) value(h string) (int64, bool) {
m.mu.Lock()
defer m.mu.Unlock()
v, ok := m.notes[h]
return v, ok
}
-416
View File
@@ -1,416 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"sync"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// Notifier is how the jobs reach Telegram. Every method must be safe to call
// from a background goroutine and must never block on user input.
type Notifier interface {
// NoteClaimed tells a single note's creator that it was redeemed.
NoteClaimed(n *Note)
// BatchDigest tells a batch creator which notes were claimed since the last digest.
BatchDigest(b *Batch, claimed []*Note)
// NoteReclaimed tells the creator a reclaim settled.
NoteReclaimed(n *Note)
// RedeemSettled tells the redeemer the sats arrived.
RedeemSettled(r *Redeem)
// GroupNoteState edits a note's group post ("claimed", "withdrawn").
GroupNoteState(n *Note)
// Alert reaches the admin.
Alert(msg string)
}
// Jobs runs the background work: claim watching, pending recovery, mint
// health and auto reclaim.
type Jobs struct {
svc *Service
notifier Notifier
// perRun caps how many notes one watcher run probes.
perRun int
watchMu sync.Mutex
recoverMu sync.Mutex
refundMu sync.Mutex
refundRetry map[string]time.Time
}
// NewJobs wires the jobs. notifier may be nil (then nothing is sent).
func NewJobs(svc *Service, notifier Notifier) *Jobs {
if notifier == nil {
notifier = noopNotifier{}
}
return &Jobs{svc: svc, notifier: notifier, perRun: 200}
}
type noopNotifier struct{}
func (noopNotifier) NoteClaimed(*Note) {}
func (noopNotifier) BatchDigest(*Batch, []*Note) {}
func (noopNotifier) NoteReclaimed(*Note) {}
func (noopNotifier) RedeemSettled(*Redeem) {}
func (noopNotifier) GroupNoteState(*Note) {}
func (noopNotifier) Alert(string) {}
// Start launches every job until ctx ends.
func (j *Jobs) Start(ctx context.Context) {
cfg := j.svc.cfg
go j.svc.mints.RunHealth(ctx, 5*time.Minute)
go j.loop(ctx, time.Minute, j.RecoverOnce)
go j.loop(ctx, 10*time.Minute, j.RefundStrandedOnce)
go j.loop(ctx, cfg.StatusPollInterval, j.WatchOnce)
if cfg.AutoReclaimDays > 0 {
go j.loop(ctx, 24*time.Hour, j.AutoReclaimOnce)
}
log.Infof("[lnurlcash] jobs started (poll %s, auto reclaim %d days)", cfg.StatusPollInterval, cfg.AutoReclaimDays)
}
func (j *Jobs) loop(ctx context.Context, every time.Duration, run func(context.Context)) {
// first run shortly after start, once the mint health check had a chance
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
}
run(ctx)
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
run(ctx)
}
}
}
// WatchOnce probes live user notes and reports the ones that were claimed.
func (j *Jobs) WatchOnce(ctx context.Context) {
if !j.watchMu.TryLock() {
return
}
defer j.watchMu.Unlock()
notes, err := j.svc.store.NotesByState([]string{NoteLive}, []string{KindUser}, j.perRun)
if err != nil {
log.Errorf("[lnurlcash] watcher: %v", err)
return
}
claimedInBatch := map[string][]*Note{}
for _, n := range notes {
if ctx.Err() != nil {
return
}
state, _, err := j.svc.Status(ctx, n)
if err != nil && !errors.Is(err, lnurlcash.ErrNotePending) {
continue
}
if state != NoteClaimed {
continue
}
j.notifier.GroupNoteState(n)
if n.BatchID != nil {
if b, err := j.svc.store.Batch(*n.BatchID); err == nil && b.Count > 1 {
claimedInBatch[b.ID] = append(claimedInBatch[b.ID], n)
continue
}
}
j.notifier.NoteClaimed(n)
}
for id, claimed := range claimedInBatch {
b, err := j.svc.store.Batch(id)
if err != nil {
continue
}
if time.Since(b.LastDigestAt) < time.Hour {
continue // the next run will fold these into the next digest via the DB state
}
j.notifier.BatchDigest(b, claimed)
_ = j.svc.store.UpdateBatch(b.ID, map[string]interface{}{"last_digest_at": time.Now()})
}
}
// RecoverOnce finishes or rolls back every row in a non-final state.
func (j *Jobs) RecoverOnce(ctx context.Context) {
if !j.recoverMu.TryLock() {
return
}
defer j.recoverMu.Unlock()
j.recoverBatches(ctx)
j.recoverReclaims(ctx)
j.recoverRedeems(ctx)
}
// recoverBatches resumes batches whose funding or carving stopped midway.
func (j *Jobs) recoverBatches(ctx context.Context) {
batches, err := j.svc.store.BatchesByState([]string{BatchPendingInvoice, BatchPendingSettle, BatchCarving, BatchUnknown})
if err != nil {
log.Errorf("[lnurlcash] recovery: %v", err)
return
}
for _, b := range batches {
if ctx.Err() != nil {
return
}
if time.Since(b.UpdatedAt) < 30*time.Second {
continue // a handler may still be working on it
}
j.recoverBatch(ctx, b)
}
}
func (j *Jobs) recoverBatch(ctx context.Context, b *Batch) {
s := j.svc
unlock := lockNote(b.ID)
defer unlock()
notes, err := s.store.NotesInBatch(b.ID)
if err != nil {
return
}
if _, ok := s.mints.Get(b.MintID); !ok {
return
}
// rebuild the units: one funding note and the user/dust pairs that follow
// it. A directly minted user note (gross set) is a unit of its own.
var units, direct []*unit
byIndex := map[int][2]*Note{}
for _, n := range notes {
switch n.Kind {
case KindFunding:
units = append(units, &unit{funding: n})
case KindUser:
if n.GrossMsat > 0 {
direct = append(direct, &unit{funding: n})
continue
}
p := byIndex[n.Index]
p[0] = n
byIndex[n.Index] = p
case KindDust:
p := byIndex[n.Index]
p[1] = n
byIndex[n.Index] = p
}
}
if len(units) > 0 {
perUnit := b.Count / len(units)
idx := 1
for _, un := range units {
for i := 0; i < perUnit; i++ {
p := byIndex[idx]
idx++
if p[0] == nil || p[1] == nil {
continue
}
un.notes = append(un.notes, p[0])
un.dust = append(un.dust, p[1])
}
}
}
units = append(units, direct...)
if len(units) == 0 {
return
}
for _, un := range units {
f := un.funding
switch f.State {
case NotePendingInvoice:
// no invoice was ever requested: nothing was paid
s.failUnit(b, un, "recovery: no invoice requested")
continue
case NotePendingSettle:
// was the mint invoice paid? LNbits knows; the mint knows
if f.InvoiceHash != "" {
paid, pending, err := s.ledger.PaymentSucceeded(ctx, b.UserName, f.InvoiceHash)
if err == nil && !paid && !pending {
s.failUnit(b, un, "recovery: mint invoice payment failed")
continue
}
}
found, err := s.waitFunding(ctx, f, 0)
if err != nil || !found {
continue
}
case NoteFailed:
continue
}
if len(un.notes) == 0 {
continue // a directly minted note: nothing to carve
}
// any note carved in state unknown: ask the mint whether its hash exists
for i, n := range un.notes {
if n.State == NoteUnknown {
if _, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); err == nil {
_ = s.store.TransitionNote(n.ID, NoteUnknown, NoteLive, map[string]interface{}{"reported_msat": n.ValueMsat, "last_error": ""})
n.State, n.ReportedMsat = NoteLive, n.ValueMsat
prev := un.funding
if i > 0 {
prev = un.dust[i-1]
}
_ = s.store.TransitionNote(prev.ID, "", NoteSpent, nil)
prev.State = NoteSpent
fee := s.mintFee(n.MintID)
change := prev.ReportedMsat - n.ValueMsat - fee.BaseFeeMsat
_ = s.store.TransitionNote(un.dust[i].ID, "", NoteLive, map[string]interface{}{"reported_msat": change, "value_msat": change})
un.dust[i].State, un.dust[i].ReportedMsat = NoteLive, change
} else if lnurlcash.IsUnknownNote(err) || lnurlcash.IsSpent(err) {
_ = s.store.TransitionNote(n.ID, NoteUnknown, NotePendingCarve, map[string]interface{}{"last_error": ""})
n.State = NotePendingCarve
}
}
}
if err := s.carve(ctx, b, un, func() {}); err != nil {
log.Warnf("[lnurlcash] recovery: batch %s: %v", b.ID, err)
}
}
s.settleBatchState(b.ID)
}
// recoverReclaims resolves notes whose melt was sent but not settled.
func (j *Jobs) recoverReclaims(ctx context.Context) {
s := j.svc
notes, err := s.store.NotesByState([]string{NoteReclaiming, NoteUnknown}, []string{KindUser, KindRedeemSplit}, 0)
if err != nil {
return
}
for _, n := range notes {
if ctx.Err() != nil {
return
}
if time.Since(n.UpdatedAt) < 30*time.Second {
continue
}
unlock := lockNote(n.ID)
n, err := s.store.Note(n.ID)
if err != nil {
unlock()
continue
}
if n.InvoiceHash != "" {
paid, err := s.ledger.InvoicePaid(ctx, n.UserName, n.InvoiceHash)
if err == nil && paid {
if st, err := s.settleNoteLocked(n.ID); err == nil && st != nil {
unlock()
if st.Note != nil {
j.notifier.NoteReclaimed(st.Note)
j.notifier.GroupNoteState(st.Note)
}
continue
}
}
}
// not settled: what does the mint say?
_, err = s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
switch {
case err == nil:
// the note is outstanding again: the melt failed or never landed
_ = s.store.TransitionNote(n.ID, n.State, NoteLive, map[string]interface{}{"last_error": "melt did not settle; note restored"})
log.Infof("[lnurlcash] note %s: melt did not settle, note live again", n.ID)
case errors.Is(err, lnurlcash.ErrNotePending):
// still paying; wait
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
// burned, and our invoice is not paid: either the payment is still
// settling on LNbits' side (wait) or somebody else claimed it before
// the melt. The invoice poll above decides on the next run; after a
// day, give up and mark it claimed.
if time.Since(n.UpdatedAt) > 24*time.Hour {
t := time.Now()
_ = s.store.TransitionNote(n.ID, n.State, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_error": "burned without our invoice settling"})
j.notifier.Alert("LNURLcash note " + n.ID + " was burned but its reclaim invoice never settled; check LNbits payment " + n.InvoiceHash)
}
}
unlock()
}
}
// recoverRedeems resolves redeems whose melt was sent but not settled.
func (j *Jobs) recoverRedeems(ctx context.Context) {
s := j.svc
redeems, err := s.store.RedeemsByState([]string{RedeemConfirmed, RedeemMelting, RedeemUnknown})
if err != nil {
return
}
for _, r := range redeems {
if ctx.Err() != nil {
return
}
if time.Since(r.UpdatedAt) < 30*time.Second {
continue
}
unlock := lockNote(r.ID)
r, err := s.store.Redeem(r.ID)
if err != nil {
unlock()
continue
}
if r.State == RedeemConfirmed {
// invoice creation or split died: let the user press again
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemInfo, nil)
unlock()
continue
}
if r.InvoiceHash != "" {
if paid, err := s.ledger.InvoicePaid(ctx, r.UserName, r.InvoiceHash); err == nil && paid {
if st, err := s.settleRedeemLocked(r.ID); err == nil && st != nil && st.Redeem != nil {
unlock()
j.notifier.RedeemSettled(st.Redeem)
continue
}
}
}
noteURL, err := s.cipher.Open(r.NoteURLEnc)
if err != nil {
unlock()
continue
}
_, err = s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
// outstanding again: the melt failed. The user may try again.
_ = s.store.TransitionRedeem(r.ID, r.State, RedeemInfo, map[string]interface{}{"last_error": "melt did not settle"})
case errors.Is(err, lnurlcash.ErrNotePending):
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
if r.SplitNoteID != nil {
// the external note was split; the melt is on the split note
if sn, err := s.store.Note(*r.SplitNoteID); err == nil {
if _, err := s.reader.FetchNoteInfoByHash(ctx, sn.MintURL, sn.Hash); err == nil {
_ = s.store.TransitionRedeem(r.ID, r.State, RedeemInfo, map[string]interface{}{"last_error": "melt did not settle"})
unlock()
continue
}
}
}
if time.Since(r.UpdatedAt) > 24*time.Hour {
_ = s.store.TransitionRedeem(r.ID, r.State, RedeemFailed, map[string]interface{}{"last_error": "note burned but our invoice never settled"})
j.notifier.Alert("LNURLcash redeem " + r.ID + " burned its note but the invoice never settled; check LNbits invoice " + r.InvoiceHash)
}
}
unlock()
}
}
// AutoReclaimOnce reclaims live notes older than auto_reclaim_days.
func (j *Jobs) AutoReclaimOnce(ctx context.Context) {
days := j.svc.cfg.AutoReclaimDays
if days <= 0 {
return
}
notes, err := j.svc.store.LiveNotesOlderThan(time.Now().Add(-time.Duration(days) * 24 * time.Hour))
if err != nil {
return
}
for _, n := range notes {
if ctx.Err() != nil {
return
}
if _, err := j.svc.Reclaim(ctx, n.ID); err != nil && !errors.Is(err, ErrNoteClaimed) {
log.Warnf("[lnurlcash] auto reclaim %s: %v", n.ID, err)
}
}
}
-168
View File
@@ -1,168 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"testing"
"time"
)
type recNotifier struct {
claimed, reclaimed, group []string
digests int
redeems []string
}
func (r *recNotifier) NoteClaimed(n *Note) { r.claimed = append(r.claimed, n.ID) }
func (r *recNotifier) BatchDigest(b *Batch, c []*Note) { r.digests++ }
func (r *recNotifier) NoteReclaimed(n *Note) { r.reclaimed = append(r.reclaimed, n.ID) }
func (r *recNotifier) RedeemSettled(x *Redeem) { r.redeems = append(r.redeems, x.ID) }
func (r *recNotifier) GroupNoteState(n *Note) { r.group = append(r.group, n.ID) }
func (r *recNotifier) Alert(string) {}
func TestWatcherNotifiesClaims(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 1)
_, single, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q, ChatID: -100})
q3, _ := h.svc.Quote(ctx, mint, 100_000, 3)
_, batch, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q3})
rec := &recNotifier{}
jobs := NewJobs(h.svc, rec)
jobs.WatchOnce(ctx)
if len(rec.claimed) != 0 {
t.Fatal("nothing claimed yet")
}
h.mint.claim(single[0].Hash)
h.mint.claim(batch[1].Hash)
jobs.WatchOnce(ctx)
if len(rec.claimed) != 1 || rec.claimed[0] != single[0].ID || rec.digests != 1 || len(rec.group) != 2 {
t.Fatalf("claimed=%v digests=%d group=%v", rec.claimed, rec.digests, rec.group)
}
jobs.WatchOnce(ctx)
if len(rec.claimed) != 1 || rec.digests != 1 {
t.Fatal("a claim must be reported once")
}
}
func TestRecoveryFinishesReclaimAndRestoresFailedMelt(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 2)
_, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
a, b := live[0], live[1]
ra, _ := h.svc.Reclaim(ctx, a.ID)
rb, _ := h.svc.Reclaim(ctx, b.ID)
// a: melt paid but the webhook was lost; b: the mint's payment failed
h.mint.finishMelt(a.Hash, true)
h.ledger.settleIncoming(ra.InvoiceHash)
h.mint.finishMelt(b.Hash, false)
backdate(t, h.store, a.ID)
backdate(t, h.store, b.ID)
rec := &recNotifier{}
jobs := NewJobs(h.svc, rec)
jobs.RecoverOnce(ctx)
na, _ := h.store.Note(a.ID)
nb, _ := h.store.Note(b.ID)
if na.State != NoteReclaimed || nb.State != NoteLive {
t.Fatalf("a=%s b=%s", na.State, nb.State)
}
if len(rec.reclaimed) != 1 || rec.reclaimed[0] != a.ID {
t.Fatalf("reclaimed notifications: %v", rec.reclaimed)
}
_ = rb
}
func TestRecoveryResumesCarving(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
// simulate a crash after paying the invoice: run Create with a mint that refuses splits,
// then lift the refusal and let recovery carve
h.mint.refuseSplit = "temporarily unavailable"
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err == nil || len(live) != 0 {
t.Fatalf("expected the carve to fail: %v", err)
}
// the notes were marked failed by the handler; a crash would instead leave
// them pending_carve. Put them back to that state to model the crash.
notes, _ := h.store.NotesInBatch(batch.ID)
for _, n := range notes {
if n.Kind != KindFunding {
_ = h.store.TransitionNote(n.ID, "", NotePendingCarve, nil)
}
}
_ = h.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
backdateBatch(t, h.store, batch.ID)
h.mint.refuseSplit = ""
NewJobs(h.svc, nil).RecoverOnce(ctx)
b, _ := h.store.Batch(batch.ID)
if b.State != BatchLive {
t.Fatalf("batch state after recovery: %s", b.State)
}
userNotes, _ := h.store.UserNotes("42", []string{NoteLive})
if len(userNotes) != 3 {
t.Fatalf("expected 3 live notes, got %d", len(userNotes))
}
}
// A directly minted note whose funding outcome was lost is finished by the
// recovery job once the mint has it, and failed when nothing was requested.
func TestRecoveryResolvesDirectNote(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 1)
if !q.Direct {
t.Fatalf("expected a direct quote: %+v", q)
}
// the payment outcome is lost: the note stays pending_settle
h.ledger.payAmbig = true
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if !errors.Is(err, ErrInFlight) || len(live) != 0 {
t.Fatalf("expected in flight: %v live=%d", err, len(live))
}
h.ledger.payAmbig = false
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 1 || notes[0].State != NotePendingSettle {
t.Fatalf("expected one pending note, got %d", len(notes))
}
// the payment did go through after all
h.mint.settle(notes[0].InvoicePR)
backdateAll(h)
NewJobs(h.svc, nil).RecoverOnce(ctx)
n, _ := h.store.Note(notes[0].ID)
b, _ := h.store.Batch(batch.ID)
if n.State != NoteLive || n.ReportedMsat != 100_000 || b.State != BatchLive {
t.Fatalf("after recovery: note %s (%d msat), batch %s", n.State, n.ReportedMsat, b.State)
}
// a direct note whose invoice was never requested is failed
batch2, _, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
notes2, _ := h.store.NotesInBatch(batch2.ID)
_ = h.store.TransitionNote(notes2[0].ID, "", NotePendingInvoice, nil)
_ = h.store.TransitionBatch(batch2.ID, "", BatchPendingInvoice, nil)
backdateAll(h)
NewJobs(h.svc, nil).RecoverOnce(ctx)
if n2, _ := h.store.Note(notes2[0].ID); n2.State != NoteFailed {
t.Fatalf("never-requested note: %s", n2.State)
}
}
func backdate(t *testing.T, s *Store, id string) {
t.Helper()
if err := s.DB().Model(&Note{}).Where("id = ?", id).Update("updated_at", time.Now().Add(-time.Minute)).Error; err != nil {
t.Fatal(err)
}
}
func backdateBatch(t *testing.T, s *Store, id string) {
t.Helper()
if err := s.DB().Model(&Batch{}).Where("id = ?", id).Update("updated_at", time.Now().Add(-time.Minute)).Error; err != nil {
t.Fatal(err)
}
}
-478
View File
@@ -1,478 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// Reference prefixes carried on LNbits invoice events so a settlement can be
// matched back to its row.
const (
RefNote = "lnurlcash-note:"
RefRedeem = "lnurlcash-redeem:"
)
// ErrOwnNote is returned by RedeemInfo when the pasted note is one this user
// created; it should be reclaimed through its own buttons instead.
type ErrOwnNote struct{ NoteID string }
func (e *ErrOwnNote) Error() string { return "lnurlcash: this is your own note " + e.NoteID }
// Reclaim melts one of the user's own notes back into their balance. A nil
// error means the melt is in flight; the invoice settlement finishes it.
func (s *Service) Reclaim(ctx context.Context, noteID string) (*Note, error) {
unlock := lockNote(noteID)
defer unlock()
n, err := s.store.Note(noteID)
if err != nil {
return nil, err
}
switch n.State {
case NoteReclaiming:
return n, ErrInFlight
case NoteClaimed:
return n, ErrNoteClaimed
case NoteReclaimed, NoteFailed, NoteSpent:
return n, ErrNothingToReclaim
case NoteLive:
default:
return n, ErrNoteNotLive
}
// the lookup that checks the note also names the callback the melt goes to
state, value, info, err := s.probe(ctx, n)
if errors.Is(err, ErrNotePending) || errors.Is(err, lnurlcash.ErrNotePending) {
return n, ErrNotePending
}
if err != nil {
return n, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
if state == NoteClaimed {
return n, ErrNoteClaimed
}
if value%1000 != 0 {
// a bot-minted note is whole-sat by construction; anything else cannot be
// melted exactly into an LNbits invoice (LUD-25 melt is exact-amount)
return n, ErrFractionalValue
}
k1, err := s.secret(n)
if err != nil {
return n, err
}
pr, hash, err := s.ledger.CreateInvoice(ctx, n.UserName, value/1000, "LNURLcash reclaim "+ShortID(n.ID), RefNote+n.ID)
if err != nil {
return n, err
}
if err := s.store.TransitionNote(n.ID, NoteLive, NoteReclaiming, map[string]interface{}{"invoice_pr": pr, "invoice_hash": hash, "last_error": ""}); err != nil {
return n, err
}
n.State, n.InvoicePR, n.InvoiceHash = NoteReclaiming, pr, hash
return n, s.melt(ctx, n, k1, pr, info.Callback)
}
// melt sends one melt to callback, the one the mint named in the note's own
// withdraw info, and maps its outcome onto the note. Never retried.
func (s *Service) melt(ctx context.Context, n *Note, k1, pr, callback string) error {
if callback == "" {
err := fmt.Errorf("the mint named no callback for note %s", ShortID(n.ID))
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": err.Error()})
n.State = NoteLive
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
_, err := s.client.MeltNote(ctx, callback, k1, pr)
switch {
case err == nil:
log.Infof("[lnurlcash] note %s (%s): melt in flight", n.ID, n.Hash[:8])
return nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": "pending at the mint"})
n.State = NoteLive
return ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
t := s.now()
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_error": err.Error()})
n.State = NoteClaimed
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
return ErrNoteClaimed
case lnurlcash.IsAmbiguous(err):
if secrets := lnurlcash.NewSecrets(err); len(secrets) > 0 {
log.Errorf("[lnurlcash] note %s: a melt error carried %d new secrets, which a melt never mints", n.ID, len(secrets))
}
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteUnknown, map[string]interface{}{"last_error": err.Error()})
n.State = NoteUnknown
log.Warnf("[lnurlcash] note %s: melt outcome unknown, left for recovery", n.ID)
return ErrInFlight
default:
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": err.Error()})
n.State = NoteLive
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
// Settlement is what SettleInvoice resolved.
type Settlement struct {
Note *Note
Redeem *Redeem
}
// SettleInvoice records that an LNbits invoice with this payment hash was
// paid: a reclaim or a redeem is done. It returns nil, nil when the hash is
// not one of ours.
func (s *Service) SettleInvoice(ctx context.Context, hash string) (*Settlement, error) {
if n, err := s.store.NoteByInvoiceHash(hash); err == nil {
unlock := lockNote(n.ID)
defer unlock()
return s.settleNoteLocked(n.ID)
}
if r, err := s.store.RedeemByInvoiceHash(hash); err == nil {
unlock := lockNote(r.ID)
defer unlock()
return s.settleRedeemLocked(r.ID)
}
return nil, nil
}
// AwaitSettlement watches the LNbits invoice a melt pays, for at most
// timeout, and settles the reclaim or redeem it belongs to once it is paid.
// The webhook normally gets there first; this keeps the user from waiting for
// the recovery job when the webhook is late or lost. It returns nil, nil when
// the invoice did not settle in time or the webhook already settled it, so a
// caller notifies only on a non-nil Settlement and the user hears once.
func (s *Service) AwaitSettlement(ctx context.Context, user, invoiceHash string, timeout time.Duration) (*Settlement, error) {
if invoiceHash == "" {
return nil, nil
}
deadline := s.now().Add(timeout)
for attempt := 0; ; attempt++ {
paid, err := s.ledger.InvoicePaid(ctx, user, invoiceHash)
if err == nil && paid {
return s.SettleInvoice(ctx, invoiceHash)
}
// 500 ms, 1 s, then every 2 s
wait := pollDelay(settlePollMax, attempt+1)
if !s.now().Add(wait).Before(deadline) {
return nil, nil
}
select {
case <-ctx.Done():
return nil, nil
case <-time.After(wait):
}
}
}
// settlePollMax is the longest gap between two AwaitSettlement polls.
var settlePollMax = 2 * time.Second
// settleNoteLocked finishes a reclaim. The caller holds the note's lock.
func (s *Service) settleNoteLocked(noteID string) (*Settlement, error) {
n, err := s.store.Note(noteID)
if err != nil {
return nil, err
}
if n.State == NoteReclaimed {
return nil, nil
}
t := s.now()
if err := s.store.TransitionNote(n.ID, "", NoteReclaimed, map[string]interface{}{"reclaimed_at": t, "last_error": ""}); err != nil {
return nil, err
}
n.State, n.ReclaimedAt = NoteReclaimed, &t
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
log.Infof("[lnurlcash] note %s reclaimed (%d msat)", n.ID, n.ReportedMsat)
return &Settlement{Note: n}, nil
}
// settleRedeemLocked finishes a redeem. The caller holds the redeem's lock.
func (s *Service) settleRedeemLocked(redeemID string) (*Settlement, error) {
r, err := s.store.Redeem(redeemID)
if err != nil {
return nil, err
}
if r.State == RedeemSettled {
return nil, nil
}
if err := s.store.TransitionRedeem(r.ID, "", RedeemSettled, map[string]interface{}{"last_error": ""}); err != nil {
return nil, err
}
r.State = RedeemSettled
if r.SplitNoteID != nil {
_ = s.store.TransitionNote(*r.SplitNoteID, "", NoteReclaimed, nil)
}
log.Infof("[lnurlcash] redeem %s settled (%d msat)", r.ID, r.ReportedMsat)
return &Settlement{Redeem: r}, nil
}
// ---- redeem ----
// RedeemPreview is what the user sees before adding a note to their balance.
type RedeemPreview struct {
Redeem *Redeem
ValueMsat int64
MintHost string
KnownMint bool
}
// RedeemInfo resolves pasted input to a note, asks the mint what it is worth
// and records a redeem in state info. ErrNotANote means the input is not an
// LNURLcash note (no mintPubkey, or not a withdraw link at all).
func (s *Service) RedeemInfo(ctx context.Context, user, lang, input string) (*RedeemPreview, error) {
input = strings.TrimSpace(input)
if i := strings.Index(strings.ToLower(input), "lightning:"); i == 0 {
input = input[len("lightning:"):]
}
noteURL := lnurlcash.ResolveNoteInput(input)
if noteURL == "" {
return nil, ErrNotANote
}
k1 := lnurlcash.NoteK1(noteURL)
if lnurlcash.IsPreimage(k1) {
if h, err := lnurlcash.HashK1(k1); err == nil {
if own, err := s.store.NoteByHash(h); err == nil {
if own.UserName == user {
return nil, &ErrOwnNote{NoteID: own.ID}
}
}
}
}
info, err := s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
return nil, ErrNotePending
case lnurlcash.IsSpent(err):
return nil, ErrNoteClaimed
case lnurlcash.IsUnknownNote(err):
return nil, ErrNoteClaimed
default:
var p *lnurlcash.ProtocolError
if errors.As(err, &p) {
return nil, fmt.Errorf("%w: %v", ErrNotANote, err)
}
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
enc, err := s.cipher.Seal(noteURL)
if err != nil {
return nil, err
}
noteID, _ := lnurlcash.NoteIDOf(k1)
host, _ := lnurlcash.SpendDomainOf(noteURL)
_, known := s.mints.ByHost(noteURL)
r := &Redeem{ID: newID("redeem"), UserName: user, MintHost: host, KnownMint: known, NoteID: noteID,
NoteURLEnc: enc, ReportedMsat: info.MaxWithdrawableMsat, State: RedeemInfo, LanguageCode: lang}
if err := s.store.CreateRedeem(r); err != nil {
return nil, err
}
return &RedeemPreview{Redeem: r, ValueMsat: info.MaxWithdrawableMsat, MintHost: host, KnownMint: known}, nil
}
// Redeem melts a previewed note into the user's balance. A nil error means
// the melt is in flight.
func (s *Service) Redeem(ctx context.Context, redeemID, user string) (*Redeem, error) {
unlock := lockNote(redeemID)
defer unlock()
r, err := s.store.Redeem(redeemID)
if err != nil {
return nil, err
}
if r.UserName != user {
return r, ErrNotOwner
}
// A fractional note is burned by splitting it before the melt. If the
// invoice or the melt failed after that, the bot holds the value in the
// split note, so a retry melts that note instead of looking for the
// original, which no longer exists.
if r.SplitNoteID != nil && (r.State == RedeemInfo || r.State == RedeemFailed) {
if split, err := s.store.Note(*r.SplitNoteID); err == nil && split.State == NoteLive && split.ReportedMsat%1000 == 0 && split.ReportedMsat > 0 {
return s.meltRedeemSplit(ctx, r, split)
}
}
if r.State != RedeemInfo {
return r, ErrInFlight
}
noteURL, err := s.cipher.Open(r.NoteURLEnc)
if err != nil {
return r, err
}
info, err := s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
return r, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
_ = s.store.TransitionRedeem(r.ID, RedeemInfo, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
return r, ErrNoteClaimed
default:
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
if err := s.store.TransitionRedeem(r.ID, RedeemInfo, RedeemConfirmed, map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat}); err != nil {
return r, err
}
r.State, r.ReportedMsat = RedeemConfirmed, info.MaxWithdrawableMsat
meltK1, meltCallback, valueMsat := lnurlcash.NoteK1(noteURL), info.Callback, info.MaxWithdrawableMsat
if valueMsat%1000 != 0 {
split, err := s.splitWholeSat(ctx, r, noteURL, info)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
return r, err
}
meltK1, _ = s.secret(split)
sid := split.ID
r.SplitNoteID = &sid
cb, err := s.callbackOf(ctx, split)
if err != nil {
// the split landed and is recorded: a retry melts the split note
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemInfo, map[string]interface{}{"last_error": err.Error()})
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
meltCallback, valueMsat = cb, split.ReportedMsat
}
return s.meltRedeem(ctx, r, RedeemInfo, meltK1, meltCallback, valueMsat)
}
// meltRedeemSplit retries the melt of a redeem whose split note is still live.
func (s *Service) meltRedeemSplit(ctx context.Context, r *Redeem, split *Note) (*Redeem, error) {
from := r.State
if err := s.store.TransitionRedeem(r.ID, from, RedeemConfirmed, map[string]interface{}{"last_error": ""}); err != nil {
return r, err
}
r.State = RedeemConfirmed
k1, err := s.secret(split)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, from, map[string]interface{}{"last_error": err.Error()})
r.State = from
return r, err
}
cb, err := s.callbackOf(ctx, split)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, from, map[string]interface{}{"last_error": err.Error()})
r.State = from
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
return s.meltRedeem(ctx, r, RedeemInfo, k1, cb, split.ReportedMsat)
}
// meltRedeem creates the LNbits invoice for a confirmed redeem and melts the
// note into it. A failed invoice creation returns the redeem to resetTo.
func (s *Service) meltRedeem(ctx context.Context, r *Redeem, resetTo, meltK1, meltCallback string, valueMsat int64) (*Redeem, error) {
user := r.UserName
pr, hash, err := s.ledger.CreateInvoice(ctx, user, valueMsat/1000, "LNURLcash redeem "+ShortID(r.ID), RefRedeem+r.ID)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemInfo, map[string]interface{}{"last_error": err.Error()})
return r, err
}
if err := s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemMelting, map[string]interface{}{"invoice_pr": pr, "invoice_hash": hash}); err != nil {
return r, err
}
r.State, r.InvoicePR, r.InvoiceHash = RedeemMelting, pr, hash
_, err = s.client.MeltNote(ctx, meltCallback, meltK1, pr)
switch {
case err == nil:
log.Infof("[lnurlcash] redeem %s: melt in flight at %s (%d msat)", r.ID, r.MintHost, valueMsat)
return r, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemInfo, map[string]interface{}{"last_error": "pending"})
r.State = RedeemInfo
return r, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemFailed
return r, ErrNoteClaimed
case lnurlcash.IsAmbiguous(err):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemUnknown, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemUnknown
return r, ErrInFlight
default:
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemFailed
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
// splitWholeSat carves the largest whole-sat note off a fractional external
// note so it can be melted exactly. The remainder stays at the mint as dust
// owned by the bot. Both secrets are persisted before the split is sent.
func (s *Service) splitWholeSat(ctx context.Context, r *Redeem, noteURL string, info lnurlcash.WithdrawInfo) (*Note, error) {
k1 := lnurlcash.NoteK1(noteURL)
link := lnurlcash.FromLud17(strings.SplitN(noteURL, "?", 2)[0])
mk := func(kind string) (*Note, error) {
secret, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(secret)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(secret)
if err != nil {
return nil, err
}
owner := r.UserName
if kind == KindDust {
owner = "bot"
}
return &Note{ID: newID("note"), UserName: owner, MintID: "external:" + r.MintHost, MintURL: link,
MintPubkey: info.MintPubkey, Hash: h, SecretEnc: enc, Kind: kind, State: NotePendingCarve,
LanguageCode: r.LanguageCode, Memo: "redeem " + r.ID}, nil
}
target, err := mk(KindRedeemSplit)
if err != nil {
return nil, err
}
dust, err := mk(KindDust)
if err != nil {
return nil, err
}
if err := s.store.CreateNotes(nil, []*Note{target, dust}); err != nil {
return nil, err
}
sats := info.MaxWithdrawableMsat / 1000
for attempt := 0; attempt < 3 && sats > 0; attempt++ {
amount := sats * 1000
_, err := s.client.SplitNoteWithHash(ctx, info.Callback, []string{k1}, amount, target.Hash, dust.Hash)
if err == nil {
change := info.MaxWithdrawableMsat - amount
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
_ = s.store.TransitionNote(dust.ID, "", NoteLive, map[string]interface{}{"value_msat": change, "reported_msat": change})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
_ = s.store.TransitionRedeem(r.ID, "", RedeemConfirmed, map[string]interface{}{"split_note_id": target.ID})
return target, nil
}
if lnurlcash.IsAmbiguous(err) || lnurlcash.IsAlreadyInUse(err) || lnurlcash.IsSpent(err) || lnurlcash.IsUnknownNote(err) {
// the split may have landed: the output decides
if _, perr := s.reader.FetchNoteInfoByHash(ctx, link, target.Hash); perr == nil {
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
_ = s.store.TransitionRedeem(r.ID, "", RedeemConfirmed, map[string]interface{}{"split_note_id": target.ID})
return target, nil
}
if lnurlcash.IsAmbiguous(err) {
_ = s.store.TransitionNote(target.ID, "", NoteUnknown, map[string]interface{}{"last_error": err.Error()})
return nil, ErrInFlight
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, ErrNoteClaimed
}
if strings.Contains(strings.ToLower(err.Error()), "insufficient") {
sats--
continue
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": "could not split a whole-sat amount"})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, ErrFractionalValue
}
-283
View File
@@ -1,283 +0,0 @@
package lnurlcash
import (
"context"
"fmt"
"net/http"
"sort"
"strings"
"sync"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// Registry holds the admin-listed mints and their health.
type Registry struct {
cfg *Config
store *Store
client *lnurlcash.Client
// reader does the read-only lookups on pooled connections. It never
// carries a mutation: see NewRegistry.
reader *lnurlcash.Client
alert func(string)
mu sync.RWMutex
mints map[string]*Mint
}
// NewRegistry builds the registry. alert receives admin-worthy messages and
// may be nil.
//
// httpClient carries every mutation (mint invoice, split, melt). It may be nil
// (then lnurlcash.NewClient's transport is used); a supplied client MUST
// disable keep-alives and MUST NOT retry.
//
// readHTTP carries only read-only lookups (note info, payRequest, mint
// address), which are safe to resend, so it keeps connections alive and saves
// a TCP and TLS handshake per lookup. nil gives a pooled default.
func NewRegistry(cfg *Config, store *Store, httpClient, readHTTP *http.Client, alert func(string)) *Registry {
client := lnurlcash.NewClient()
if httpClient != nil {
client.HTTP = httpClient
}
reader := lnurlcash.NewClient()
if readHTTP == nil {
readHTTP = &http.Client{
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment, MaxIdleConnsPerHost: 4, IdleConnTimeout: 90 * time.Second},
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
reader.HTTP = readHTTP
// a lookup is never a mutation; make sure the library cannot treat it as one
reader.MutationRetries = -1
if alert == nil {
alert = func(msg string) { log.Warnf("[lnurlcash] alert: %s", msg) }
}
r := &Registry{cfg: cfg, store: store, client: client, reader: reader, alert: alert, mints: map[string]*Mint{}}
for _, mc := range cfg.Mints {
m, err := store.Mint(mc.Name)
if err != nil {
log.Errorf("[lnurlcash] load mint %s: %v", mc.Name, err)
}
if m == nil {
m = &Mint{ID: mc.Name}
}
m.URL = mc.URL
m.PayURL = ResolveMintURL(mc.URL)
r.mints[mc.Name] = m
}
return r
}
// Client is the LNURLcash client every mutation goes through: mint invoice,
// split, melt. It never reuses a connection.
func (r *Registry) Client() *lnurlcash.Client { return r.client }
// Reader is the LNURLcash client for read-only lookups (FetchNoteInfo,
// FetchNoteInfoByHash, FetchPayRequest, FetchMintAddress). It reuses
// connections, so it MUST NOT be used for a mutation.
func (r *Registry) Reader() *lnurlcash.Client { return r.reader }
// Check validates one mint: reachable, commentAllowed >= 64, a withdrawLink,
// a fee under the cap, and a pinned mintPubkey that has not changed.
func (r *Registry) Check(ctx context.Context, id string) error {
r.mu.RLock()
m, ok := r.mints[id]
r.mu.RUnlock()
if !ok {
return fmt.Errorf("lnurlcash: unknown mint %q", id)
}
err := r.check(ctx, m)
r.mu.Lock()
m.LastCheck = time.Now()
if err != nil {
m.Healthy = false
m.LastError = err.Error()
} else {
m.Healthy = true
m.LastError = ""
}
snapshot := *m
r.mu.Unlock()
if serr := r.store.SaveMint(&snapshot); serr != nil {
log.Errorf("[lnurlcash] save mint %s: %v", id, serr)
}
if err != nil {
log.Warnf("[lnurlcash] mint %s unhealthy: %s", id, Describe(err))
}
return err
}
func (r *Registry) check(ctx context.Context, m *Mint) error {
if m.PayURL == "" {
return fmt.Errorf("mint url does not resolve")
}
pay, err := r.reader.FetchPayRequest(ctx, m.PayURL)
if err != nil {
return fmt.Errorf("payRequest: %w", err)
}
if pay.WithdrawLink == "" {
return fmt.Errorf("payRequest advertises no withdrawLink: not an LNURLcash mint")
}
if !pay.NamesMintOutput() {
return fmt.Errorf("commentAllowed below %d: the mint cannot mint to a hash", lnurlcash.MintCommentLength)
}
if !lnurlcash.IsAllowedServiceURL(lnurlcash.FromLud17(pay.WithdrawLink)) || !lnurlcash.IsAllowedServiceURL(pay.Callback) {
return fmt.Errorf("mint publishes a callback or withdrawLink that is not https")
}
if pay.HasMintFee && pay.MintFee.FeePpm > r.cfg.MaxMintFeePpm {
return fmt.Errorf("mint fee %d ppm is above max_mint_fee_ppm %d", pay.MintFee.FeePpm, r.cfg.MaxMintFeePpm)
}
pubkey := strings.ToLower(strings.TrimSpace(pay.MintPubkey))
if pubkey == "" {
// LUD-25 publishes the key on the withdraw side; try the mint address.
if addrURL := lnurlcash.MintAddressURL(m.PayURL); addrURL != "" {
if addr, aerr := r.reader.FetchMintAddress(ctx, addrURL); aerr == nil {
pubkey = strings.ToLower(strings.TrimSpace(addr.NodePubkey))
}
}
}
if pubkey == "" {
return fmt.Errorf("mint publishes no mintPubkey")
}
if !lnurlcash.IsCompressedPubkey(pubkey) {
return fmt.Errorf("mint publishes a mintPubkey that is not a compressed secp256k1 key")
}
r.mu.Lock()
defer r.mu.Unlock()
m.PayCallback = pay.Callback
m.WithdrawLink = lnurlcash.FromLud17(pay.WithdrawLink)
m.FeeBaseMsat, m.FeePpm = 0, 0
if pay.HasMintFee {
m.FeeBaseMsat, m.FeePpm = pay.MintFee.BaseFeeMsat, pay.MintFee.FeePpm
}
m.CommentAllowed = pay.CommentAllowed
m.MinSendableMsat, m.MaxSendableMsat = pay.MinSendableMsat, pay.MaxSendableMsat
m.LastSeenPubkey = pubkey
if m.PinnedPubkey == "" {
m.PinnedPubkey = pubkey
log.Infof("[lnurlcash] pinned mintPubkey of %s", m.ID)
} else if m.PinnedPubkey != pubkey {
if !m.Disabled {
m.Disabled = true
r.alert(fmt.Sprintf("LNURLcash mint %s changed its mintPubkey (pinned %s…, now %s…). New notes at this mint are disabled until an admin clears the pin.", m.ID, m.PinnedPubkey[:8], pubkey[:8]))
}
return fmt.Errorf("mintPubkey changed; mint disabled")
}
return nil
}
// CheckAll checks every configured mint.
func (r *Registry) CheckAll(ctx context.Context) {
for _, mc := range r.cfg.Mints {
cctx, cancel := context.WithTimeout(ctx, 15*time.Second)
_ = r.Check(cctx, mc.Name)
cancel()
}
}
// RunHealth checks all mints now and then every interval until ctx ends.
func (r *Registry) RunHealth(ctx context.Context, interval time.Duration) {
r.CheckAll(ctx)
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
r.CheckAll(ctx)
}
}
}
// Get returns a copy of a mint's record.
func (r *Registry) Get(id string) (*Mint, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
m, ok := r.mints[id]
if !ok {
return nil, false
}
c := *m
return &c, true
}
// All returns copies of every mint, sorted by id.
func (r *Registry) All() []*Mint {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]*Mint, 0, len(r.mints))
for _, m := range r.mints {
c := *m
out = append(out, &c)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Usable reports whether new notes may be minted at a mint.
func (m *Mint) Usable() bool {
return m != nil && m.Healthy && !m.Disabled && m.WithdrawLink != "" && m.PayCallback != ""
}
// ForUser returns the mint to mint at for a user: their preference if usable,
// else the configured default. ok is false when none is usable.
func (r *Registry) ForUser(user string) (*Mint, bool) {
if p, err := r.store.Pref(user); err == nil && p != nil {
if m, ok := r.Get(p.DefaultMintID); ok && m.Usable() {
return m, true
}
}
if d := r.cfg.DefaultMint(); d != nil {
if m, ok := r.Get(d.Name); ok && m.Usable() {
return m, true
}
}
for _, m := range r.All() {
if m.Usable() {
return m, true
}
}
return nil, false
}
// ByHost finds a configured mint by the host of a withdraw link or note URL.
func (r *Registry) ByHost(rawURL string) (*Mint, bool) {
host, err := lnurlcash.SpendDomainOf(rawURL)
if err != nil {
return nil, false
}
for _, m := range r.All() {
if h, err := lnurlcash.SpendDomainOf(m.WithdrawLink); err == nil && h == host {
return m, true
}
if h, err := lnurlcash.SpendDomainOf(m.PayURL); err == nil && h == host {
return m, true
}
}
return nil, false
}
// Fee returns a mint's advertised fee.
func (m *Mint) Fee() lnurlcash.MintFee {
return lnurlcash.MintFee{BaseFeeMsat: m.FeeBaseMsat, FeePpm: m.FeePpm}
}
// ClearPin forgets a mint's pinned key and re-enables it (admin action).
func (r *Registry) ClearPin(id string) error {
r.mu.Lock()
m, ok := r.mints[id]
if !ok {
r.mu.Unlock()
return fmt.Errorf("lnurlcash: unknown mint %q", id)
}
m.PinnedPubkey, m.Disabled = "", false
snapshot := *m
r.mu.Unlock()
return r.store.SaveMint(&snapshot)
}
-67
View File
@@ -1,67 +0,0 @@
package lnurlcash
import (
"context"
"strings"
"testing"
)
func testConfig(mintURL string) *Config {
c := &Config{Enabled: true, Mints: []MintConfig{{Name: "fake", URL: mintURL, Default: true}}, SecretEncryptionKey: testKey}
c.Normalize()
return c
}
func TestRegistryCheckAndPin(t *testing.T) {
fm := newFakeMint(t)
s := testStore(t)
cfg := testConfig(fm.url())
alerts := []string{}
r := NewRegistry(cfg, s, nil, nil, func(msg string) { alerts = append(alerts, msg) })
if err := r.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
m, _ := r.Get("fake")
if !m.Usable() || m.PinnedPubkey != fm.pubkey || m.FeeBaseMsat != 1000 || m.FeePpm != 100 || m.WithdrawLink != fm.url()+"/w" {
t.Fatalf("mint not learned: %+v", m)
}
if got, _ := r.ForUser("42"); got.ID != "fake" {
t.Fatal("ForUser must return the default")
}
if got, ok := r.ByHost(fm.url() + "/w?k1=abc"); !ok || got.ID != "fake" {
t.Fatal("ByHost must find the mint")
}
// fee cap
cfg.MaxMintFeePpm = 50
if err := r.Check(context.Background(), "fake"); err == nil || !strings.Contains(err.Error(), "max_mint_fee_ppm") {
t.Fatalf("fee above cap must fail: %v", err)
}
cfg.MaxMintFeePpm = 20000
// pubkey change disables the mint and alerts once
fm.pubkeyChange = "03" + strings.Repeat("ab", 32)
for i := 0; i < 2; i++ {
if err := r.Check(context.Background(), "fake"); err == nil {
t.Fatal("changed pubkey must fail")
}
}
m, _ = r.Get("fake")
if !m.Disabled || m.Usable() || len(alerts) != 1 {
t.Fatalf("mint must be disabled with one alert: %+v alerts=%d", m, len(alerts))
}
if _, ok := r.ForUser("42"); ok {
t.Fatal("no usable mint expected")
}
// the pin survives a restart through the store
r2 := NewRegistry(cfg, s, nil, nil, nil)
m2, _ := r2.Get("fake")
if m2.PinnedPubkey != fm.pubkey || !m2.Disabled {
t.Fatalf("pin not persisted: %+v", m2)
}
fm.pubkeyChange = ""
if err := r2.ClearPin("fake"); err != nil {
t.Fatal(err)
}
if err := r2.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
}
-171
View File
@@ -1,171 +0,0 @@
package lnurlcash
import "time"
// Note states. A note moves forward only; "unknown" is any step whose answer
// was lost and is resolved by the recovery job.
const (
NotePendingInvoice = "pending_invoice" // row written, no invoice yet
NotePendingSettle = "pending_settle" // invoice requested and paid (or paying), not seen at the mint yet
NotePendingCarve = "pending_carve" // secret exists, split not done yet
NoteLive = "live"
NoteClaimed = "claimed"
NoteReclaiming = "reclaiming" // melt sent, LNbits invoice not settled yet
NoteReclaimed = "reclaimed"
NoteFailed = "failed"
NoteUnknown = "unknown"
NoteSpent = "spent" // a funding or dust note burned by the bot's own split
)
// Note kinds.
const (
KindUser = "user" // a note the user holds and shares
KindFunding = "funding" // the note a paid mint invoice created; carved into user notes
KindDust = "dust" // the change left after carving; bot-owned
KindRedeemSplit = "redeem_split" // the whole-sat part split off a fractional external note
)
// Batch states.
const (
BatchPendingInvoice = "pending_invoice"
BatchPendingSettle = "pending_settle"
BatchCarving = "carving"
BatchLive = "live"
BatchPartial = "partial"
BatchClaimed = "claimed"
BatchReclaimed = "reclaimed"
BatchFailed = "failed"
BatchUnknown = "unknown"
)
// Redeem states.
const (
RedeemInfo = "info" // previewed, waiting for the user
RedeemConfirmed = "confirmed" // user pressed add, invoice being created
RedeemMelting = "melting" // melt accepted, waiting for the invoice to settle
RedeemSettled = "settled"
RedeemFailed = "failed"
RedeemUnknown = "unknown"
)
// Note is one LNURLcash note the bot knows the secret of.
type Note struct {
ID string `gorm:"primaryKey"`
BatchID *string `gorm:"index"`
UserName string `gorm:"index"` // lnbits.User.Name: the Telegram user id as text
MintID string `gorm:"index"`
MintURL string // the withdraw link notes are built on
MintPubkey string
Hash string `gorm:"uniqueIndex"` // h = sha256(k1): the note's public name
SecretEnc []byte
ValueMsat int64 // what the user asked for
ReportedMsat int64 // what the mint last reported (authoritative)
GrossMsat int64 // what was paid for it: funding notes, and user notes minted directly from their own invoice
FeeMsat int64
Memo string
State string `gorm:"index"`
Kind string `gorm:"index"`
Index int // position in its batch, 1-based
InvoicePR string
InvoiceHash string `gorm:"index"`
VerifyURL string
Certificate string
ChatID int64 // group chat the note was posted in, 0 for private
MessageID string // the group message, for edits
ReceiptMessageID string
LanguageCode string
LastProbe time.Time
LastError string
ClaimedAt *time.Time
ReclaimedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
func (Note) TableName() string { return "lnurlcash_notes" }
// Batch groups the notes created by one command.
type Batch struct {
ID string `gorm:"primaryKey"`
UserName string `gorm:"index"`
MintID string
Memo string
Count int
ValueMsat int64 // per note
TotalGrossMsat int64
FeeMsat int64
Strategy string
State string `gorm:"index"`
FundingNoteID string
InvoiceHash string
LastDigestAt time.Time
ChatID int64
LanguageCode string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Batch) TableName() string { return "lnurlcash_batches" }
// Redeem is a received note being melted into the user's balance.
type Redeem struct {
ID string `gorm:"primaryKey"`
UserName string `gorm:"index"`
MintHost string
KnownMint bool
NoteID string `gorm:"index"` // hex(Q), the id the mint files the note under
NoteURLEnc []byte // the full note URL, k1 included, sealed
ReportedMsat int64
State string `gorm:"index"`
InvoicePR string
InvoiceHash string `gorm:"index"`
SplitNoteID *string
LastError string
LanguageCode string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Redeem) TableName() string { return "lnurlcash_redeems" }
// UserPref holds a user's default mint.
type UserPref struct {
UserName string `gorm:"primaryKey"`
DefaultMintID string
UpdatedAt time.Time
}
func (UserPref) TableName() string { return "lnurlcash_user_prefs" }
// Mint is what the registry learned about a configured mint.
type Mint struct {
ID string `gorm:"primaryKey"` // the configured name
URL string
PayURL string
PayCallback string
WithdrawLink string
PinnedPubkey string
LastSeenPubkey string
FeeBaseMsat int64
FeePpm int64
CommentAllowed int64
MinSendableMsat int64
MaxSendableMsat int64
Healthy bool
Disabled bool
LastCheck time.Time
LastError string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Mint) TableName() string { return "lnurlcash_mints" }
// IsFinal reports whether a note state cannot change any more.
func IsFinalNoteState(state string) bool {
switch state {
case NoteClaimed, NoteReclaimed, NoteFailed, NoteSpent:
return true
}
return false
}
-77
View File
@@ -1,77 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"testing"
lnurlcashlib "github.com/lnurlcash/lnurlcash-go"
)
// failingInvoices makes invoice creation fail while failCreate is set.
type failingInvoices struct {
*fakeLedger
failCreate bool
}
func (l *failingInvoices) CreateInvoice(ctx context.Context, user string, sat int64, memo, ref string) (string, string, error) {
if l.failCreate {
return "", "", errors.New("lnbits unavailable")
}
return l.fakeLedger.CreateInvoice(ctx, user, sat, memo, ref)
}
func externalNote(h *harness, value int64) string {
k1, _ := lnurlcashlib.GenerateNoteSecret()
hash, _ := lnurlcashlib.HashK1(k1)
h.mint.mu.Lock()
h.mint.notes[hash] = value
h.mint.mu.Unlock()
return lnurlcashlib.BuildNoteURL(h.mint.url()+"/w", k1, value)
}
// A fractional note is burned by the split before the melt. After a failed
// invoice or melt the redeem must melt the split note the bot now holds.
func TestRedeemRetryUsesSplitNoteAfterFailure(t *testing.T) {
for _, mode := range []string{"invoice", "melt"} {
t.Run(mode, func(t *testing.T) {
h := newHarness(t)
ledger := &failingInvoices{fakeLedger: h.ledger}
cipher, _ := NewCipher(testKey)
svc := NewService(h.cfg, h.store, h.reg, ledger, cipher)
ctx := context.Background()
prev, err := svc.RedeemInfo(ctx, "7", "en", externalNote(h, 1000_900))
if err != nil {
t.Fatal(err)
}
switch mode {
case "invoice":
ledger.failCreate = true
case "melt":
h.mint.mu.Lock()
h.mint.meltReason = "payment failed: no route"
h.mint.mu.Unlock()
}
if _, err := svc.Redeem(ctx, prev.Redeem.ID, "7"); err == nil {
t.Fatal("the first attempt should fail")
}
ledger.failCreate = false
h.mint.mu.Lock()
h.mint.meltReason = ""
h.mint.mu.Unlock()
r, err := svc.Redeem(ctx, prev.Redeem.ID, "7")
if err != nil || r.State != RedeemMelting {
t.Fatalf("retry: state=%s err=%v", r.State, err)
}
if got := ledger.invoices[r.InvoiceHash].sat; got != 999 {
t.Errorf("invoice for %d sat, want 999 (the split note)", got)
}
ledger.settleIncoming(r.InvoiceHash)
st, err := svc.SettleInvoice(ctx, r.InvoiceHash)
if err != nil || st == nil || st.Redeem == nil || st.Redeem.State != RedeemSettled {
t.Fatalf("settle: %+v %v", st, err)
}
})
}
}
-213
View File
@@ -1,213 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// StrandedCandidates returns live funding and change notes that hold at least
// one whole sat and belong to a batch.
func (s *Store) StrandedCandidates(limit int) ([]*Note, error) {
var notes []*Note
q := s.db.Where("state = ? AND kind IN ? AND batch_id IS NOT NULL AND reported_msat >= ?", NoteLive, []string{KindFunding, KindDust}, 1000).
Order("created_at asc")
if limit > 0 {
q = q.Limit(limit)
}
return notes, q.Find(&notes).Error
}
// batchSettled reports whether a batch is done minting: delivered, partly
// delivered or failed. From then on the value left in its funding and change
// notes is the owner's. A batch still funding or carving is not settled, since
// its change notes are the input of the next split.
func (s *Service) batchSettled(b *Batch) bool {
switch b.State {
case BatchLive, BatchPartial, BatchClaimed, BatchReclaimed, BatchFailed:
return true
}
return false
}
// RefundStranded melts the value that a settled batch left in a bot-held
// funding or change note back into its owner's balance: the change of a
// carved batch, or what a failed one stranded. The whole-sat part is split off
// if needed and reclaimed like any note. It returns nil when there is nothing
// to do and ErrInFlight/nil once a melt is under way.
func (s *Service) RefundStranded(ctx context.Context, noteID string) error {
var reclaimID string
err := func() error {
unlock := lockNote(noteID)
defer unlock()
n, err := s.store.Note(noteID)
if err != nil {
return err
}
if n.State != NoteLive || n.BatchID == nil || (n.Kind != KindFunding && n.Kind != KindDust) {
return nil
}
b, err := s.store.Batch(*n.BatchID)
if err != nil || !s.batchSettled(b) {
return err
}
state, value, err := s.Status(ctx, n)
if err != nil {
return err
}
if state != NoteLive || value < 1000 {
return nil
}
reclaimID = n.ID
if value%1000 != 0 {
target, err := s.splitOffWholeSats(ctx, n, value)
if err != nil {
reclaimID = ""
return err
}
reclaimID = target.ID
}
return nil
}()
if err != nil || reclaimID == "" {
return err
}
if _, err := s.Reclaim(ctx, reclaimID); err != nil && !errors.Is(err, ErrInFlight) {
return err
}
return nil
}
// splitOffWholeSats splits the largest whole-sat note off n. Both new secrets
// are stored before the split is sent, and a half-finished split is resumed.
func (s *Service) splitOffWholeSats(ctx context.Context, n *Note, value int64) (*Note, error) {
memo := "refund " + n.ID
var target, rest *Note
pending, err := s.store.NotesByState([]string{NotePendingCarve}, []string{KindRedeemSplit, KindDust}, 0)
if err != nil {
return nil, err
}
for _, p := range pending {
if p.Memo == memo && p.Kind == KindRedeemSplit {
target = p
} else if p.Memo == memo {
rest = p
}
}
if target == nil || rest == nil {
mk := func(kind string) (*Note, error) {
secret, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(secret)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(secret)
if err != nil {
return nil, err
}
return &Note{ID: newID("note"), UserName: n.UserName, MintID: n.MintID, MintURL: n.MintURL,
MintPubkey: n.MintPubkey, Hash: h, SecretEnc: enc, Kind: kind, State: NotePendingCarve,
LanguageCode: n.LanguageCode, Memo: memo}, nil
}
if target, err = mk(KindRedeemSplit); err != nil {
return nil, err
}
if rest, err = mk(KindDust); err != nil {
return nil, err
}
if err := s.store.CreateNotes(nil, []*Note{target, rest}); err != nil {
return nil, err
}
}
k1, err := s.secret(n)
if err != nil {
return nil, err
}
landed := func(amount int64) *Note {
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
change := value - amount
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, rest.Hash); perr == nil {
change = info.MaxWithdrawableMsat
}
_ = s.store.TransitionNote(rest.ID, "", NoteLive, map[string]interface{}{"value_msat": change, "reported_msat": change})
_ = s.store.TransitionNote(n.ID, "", NoteSpent, nil)
return target
}
callback, err := s.callbackOf(ctx, n)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
for sats := value / 1000; sats > 0; {
amount := sats * 1000
_, err := s.client.SplitNoteWithHash(ctx, callback, []string{k1}, amount, target.Hash, rest.Hash)
if err == nil {
return landed(amount), nil
}
if lnurlcash.IsAmbiguous(err) || lnurlcash.IsAlreadyInUse(err) || lnurlcash.IsSpent(err) || lnurlcash.IsUnknownNote(err) {
// the split may have landed: the output decides
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, target.Hash); perr == nil {
return landed(info.MaxWithdrawableMsat), nil
}
return nil, fmt.Errorf("refund split of %s unresolved: %w", n.ID, err)
}
if strings.Contains(strings.ToLower(err.Error()), "insufficient") {
sats-- // the mint's fee does not leave room for the full amount
continue
}
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
return nil, ErrFractionalValue
}
// RefundStrandedOnce returns the change and stranded value of settled batches
// to their owners. A note that cannot be refunded is retried hourly and reported to the
// operator once.
func (j *Jobs) RefundStrandedOnce(ctx context.Context) {
if !j.refundMu.TryLock() {
return
}
defer j.refundMu.Unlock()
notes, err := j.svc.store.StrandedCandidates(j.perRun)
if err != nil {
log.Errorf("[lnurlcash] refund: %v", err)
return
}
for _, n := range notes {
if ctx.Err() != nil {
return
}
if next, ok := j.refundRetry[n.ID]; ok && time.Now().Before(next) {
continue
}
err := j.svc.RefundStranded(ctx, n.ID)
if err == nil {
delete(j.refundRetry, n.ID)
continue
}
if j.refundRetry == nil {
j.refundRetry = map[string]time.Time{}
}
_, seen := j.refundRetry[n.ID]
j.refundRetry[n.ID] = time.Now().Add(time.Hour)
log.Warnf("[lnurlcash] refund of %s failed: %v", n.ID, err)
if !seen {
j.notifier.Alert(fmt.Sprintf("LNURLcash could not return %d msat held in note %s of batch %s to user %s: %v", n.ReportedMsat, n.ID, batchIDOf(n), n.UserName, err))
}
}
}
func batchIDOf(n *Note) string {
if n.BatchID == nil {
return "-"
}
return *n.BatchID
}
-159
View File
@@ -1,159 +0,0 @@
package lnurlcash
import (
"context"
"net/http"
"testing"
"time"
)
func backdateAll(h *harness) {
old := time.Now().Add(-time.Hour)
h.store.DB().Exec("UPDATE lnurlcash_batches SET updated_at = ?", old)
h.store.DB().Exec("UPDATE lnurlcash_notes SET updated_at = ?", old)
}
// settleRefunds pays every pending reclaim invoice, as the melt would.
func settleRefunds(t *testing.T, h *harness) int {
n := 0
for hash, inv := range h.ledger.invoices {
if !inv.paid && len(inv.ref) > len(RefNote) && inv.ref[:len(RefNote)] == RefNote {
h.ledger.settleIncoming(hash)
if _, err := h.svc.SettleInvoice(context.Background(), hash); err != nil {
t.Fatal(err)
}
n++
}
}
return n
}
// A split refused after the funding invoice was paid must not keep the value:
// the refund job returns it to the owner.
func TestRefundStrandedAfterCarveFailure(t *testing.T) {
for _, mode := range []string{"total", "partial"} {
t.Run(mode, func(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 100_000, 3)
if err != nil {
t.Fatal(err)
}
start := h.ledger.balances["42"]
wantLive, wantState := 0, BatchFailed
if mode == "total" {
h.mint.mu.Lock()
h.mint.refuseSplit = "service busy"
h.mint.mu.Unlock()
} else {
// the mint accepts the first split and refuses the second
wantLive, wantState = 1, BatchPartial
orig := h.mint.srv.Config.Handler
splits := 0
h.mint.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query()
if r.URL.Path == "/w/cb" && qs.Get("p1") != "" && qs.Get("amount") != "" {
splits++
if splits == 2 {
h.mint.mu.Lock()
h.mint.refuseSplit = "service busy"
h.mint.mu.Unlock()
}
}
orig.ServeHTTP(w, r)
})
}
batch, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if len(live) != wantLive || batch.State != wantState {
t.Fatalf("setup: live=%d state=%s", len(live), batch.State)
}
h.mint.mu.Lock()
h.mint.refuseSplit = ""
h.mint.mu.Unlock()
debited := start - h.ledger.balances["42"]
if debited != q.GrossMsat {
t.Fatalf("debited %d, gross %d", debited, q.GrossMsat)
}
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) == 0 {
t.Fatal("no refund invoice was created")
}
// everything but the delivered notes and the mint fees paid in the gross is back
delivered := int64(wantLive) * 100_000
if lost := start - h.ledger.balances["42"] - delivered; lost > q.GrossMsat-3*100_000 {
t.Errorf("user lost %d msat of %d", lost, q.GrossMsat)
}
// a second run must not pay out again
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("refund was repeated")
}
})
}
}
// The change left after a full carve is the owner's: it is melted back.
func TestRefundReturnsChangeOfHealthyBatch(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 3 || batch.State != BatchLive {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
var change *Note
notes, _ := h.store.NotesInBatch(batch.ID)
for _, n := range notes {
if n.Kind == KindDust && n.State == NoteLive {
change = n
}
}
if change == nil || change.ReportedMsat < 1000 {
t.Fatalf("expected a whole-sat change note, got %+v", change)
}
before := h.ledger.balances["42"]
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
h.mint.finishMelt(change.Hash, true)
if settleRefunds(t, h) != 1 {
t.Fatal("the change was not refunded")
}
if got := h.ledger.balances["42"] - before; got != change.ReportedMsat {
t.Errorf("refunded %d msat, change was %d", got, change.ReportedMsat)
}
if n, _ := h.store.Note(change.ID); n.State != NoteReclaimed {
t.Errorf("change note state %s", n.State)
}
// the user's notes are untouched
if userNotes, _ := h.store.UserNotes("42", []string{NoteLive}); len(userNotes) != 3 {
t.Errorf("live user notes: %d", len(userNotes))
}
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("refund was repeated")
}
}
// A batch still carving keeps its change: it is the input of the next split.
func TestRefundIgnoresBatchStillCarving(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 3 {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
_ = h.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("a batch that is still carving was refunded")
}
}
-15
View File
@@ -1,15 +0,0 @@
package lnurlcash
import "testing"
func TestPayReserve(t *testing.T) {
if r := payReserveMsat(Quote{GrossMsat: 25000, Count: 1}); r != 1000 {
t.Fatalf("small: %d", r)
}
if r := payReserveMsat(Quote{GrossMsat: 1_000_000, Count: 1}); r != 10000 {
t.Fatalf("1%%: %d", r)
}
if r := payReserveMsat(Quote{GrossMsat: 50000, Count: 5, Strategy: StrategyInvoices}); r != 5000 {
t.Fatalf("invoices: %d", r)
}
}
-813
View File
@@ -1,813 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
// Ledger is what the service needs from LNbits. user is lnbits.User.Name.
type Ledger interface {
// CreateInvoice makes an incoming invoice on the user's wallet. ref is an
// opaque reference the implementation may attach to the invoice event so
// that a settlement webhook can find the note or redeem it belongs to.
CreateInvoice(ctx context.Context, user string, amountSat int64, memo, ref string) (pr, hash string, err error)
// PayInvoice pays a bolt11 from the user's wallet and returns its payment hash.
// A failure whose outcome is unknown must be returned as *AmbiguousLedgerError.
PayInvoice(ctx context.Context, user, pr string) (hash string, err error)
// InvoicePaid reports whether an invoice on the user's wallet settled.
InvoicePaid(ctx context.Context, user, hash string) (bool, error)
// PaymentSucceeded reports whether an outgoing payment settled: paid, failed
// (definitively), or still pending.
PaymentSucceeded(ctx context.Context, user, hash string) (paid, pending bool, err error)
BalanceMsat(ctx context.Context, user string) (int64, error)
}
// AmbiguousLedgerError wraps a ledger failure whose outcome is unknown (a
// timeout, a dropped connection): the payment may still have been made.
type AmbiguousLedgerError struct{ Err error }
func (e *AmbiguousLedgerError) Error() string { return "ledger outcome unknown: " + e.Err.Error() }
func (e *AmbiguousLedgerError) Unwrap() error { return e.Err }
// IsAmbiguousLedger reports whether a ledger error carries an unknown outcome.
func IsAmbiguousLedger(err error) bool {
var a *AmbiguousLedgerError
return errors.As(err, &a)
}
// Sentinel errors handlers turn into messages.
var (
ErrInFlight = errors.New("lnurlcash: the operation is still in flight; the recovery job will finish it")
ErrCapNoteValue = errors.New("lnurlcash: note value outside the allowed range")
ErrCapBatch = errors.New("lnurlcash: batch too large")
ErrCapOutstanding = errors.New("lnurlcash: outstanding notes cap reached")
ErrInsufficientFunds = errors.New("lnurlcash: insufficient balance")
ErrNoMint = errors.New("lnurlcash: no usable mint")
ErrMintRange = errors.New("lnurlcash: amount outside what the mint accepts")
ErrNoteNotLive = errors.New("lnurlcash: note is not live")
ErrNoteClaimed = errors.New("lnurlcash: note was already claimed")
ErrNotePending = errors.New("lnurlcash: the mint is still settling an operation on this note")
ErrNotANote = errors.New("lnurlcash: not an LNURLcash note")
ErrFractionalValue = errors.New("lnurlcash: note value is not a whole number of sats and cannot be split")
ErrNotOwner = errors.New("lnurlcash: not the owner")
ErrMintUnavailable = errors.New("lnurlcash: mint unavailable")
ErrNothingToReclaim = errors.New("lnurlcash: nothing to reclaim")
ErrDisabledPrecondition = errors.New("lnurlcash: feature not configured")
)
// Service creates, watches, reclaims and redeems notes.
type Service struct {
cfg *Config
store *Store
mints *Registry
ledger Ledger
cipher *Cipher
// client carries every mutation (mint invoice, split, melt) on a fresh
// connection; reader carries the read-only lookups on pooled connections.
// A mutation MUST NOT go through reader.
client *lnurlcash.Client
reader *lnurlcash.Client
// now is replaceable in tests.
now func() time.Time
// the longest sleep between funding polls, replaceable in tests. The first
// polls come sooner: see pollDelay.
pollEvery time.Duration
}
// NewService wires the service. The registry supplies the LNURLcash client.
func NewService(cfg *Config, store *Store, mints *Registry, ledger Ledger, cipher *Cipher) *Service {
return &Service{cfg: cfg, store: store, mints: mints, ledger: ledger, cipher: cipher,
client: mints.Client(), reader: mints.Reader(), now: time.Now, pollEvery: 2 * time.Second}
}
// Store exposes the store to the Telegram layer for read-only listing.
func (s *Service) Store() *Store { return s.store }
// Mints exposes the registry.
func (s *Service) Mints() *Registry { return s.mints }
// Config exposes the configuration.
func (s *Service) Config() *Config { return s.cfg }
const idRunes = "abcdefghijklmnopqrstuvwxyz0123456789"
func newID(prefix string) string {
b := make([]byte, 10)
for i := range b {
b[i] = idRunes[rand.Intn(len(idRunes))]
}
return prefix + "-" + string(b)
}
// ShortID is the part of a note id shown to people.
func ShortID(id string) string {
if i := strings.IndexByte(id, '-'); i >= 0 && len(id) > i+6 {
return id[i+1 : i+7]
}
return id
}
func (s *Service) secret(n *Note) (string, error) {
return s.cipher.Open(n.SecretEnc)
}
// ---- quoting ----
// Quote is what a creation will cost.
type Quote struct {
MintID string
MintName string
ValueMsat int64 // per note
Count int
GrossMsat int64 // the invoice the user pays
FeeMsat int64 // GrossMsat - Count*ValueMsat: mint fee plus carving margin
Fee lnurlcash.MintFee
Strategy string
// Direct means each note is minted straight from its own invoice, with
// no funding note, split or change.
Direct bool `json:"direct,omitempty"`
}
// NetMsat is what the user's notes are worth together.
func (q Quote) NetMsat() int64 { return q.ValueMsat * int64(q.Count) }
// carveMargin keeps the last change above zero whatever the mint's rounding.
const carveMargin int64 = 1000
// grossFor returns the smallest whole-sat invoice whose net after the mint
// fee carves count notes of valueMsat, each split costing the base fee.
func grossFor(valueMsat int64, count int64, fee lnurlcash.MintFee) int64 {
needed := count*valueMsat + count*fee.BaseFeeMsat + carveMargin
gross := lnurlcash.GrossUpForMintFee(needed, fee)
if rem := gross % 1000; rem != 0 {
gross += 1000 - rem
}
return gross
}
// satCredit is what a mint that keeps notes in whole sats credits for an
// invoice: the gross less the fee, floored to the sat (the fee rounded up to
// the sat, for whole-sat amounts). The live mints do this: mint.600.wtf turned
// an 18000 msat invoice into a 14000 msat note, where ApplyMintFee says 14910.
func satCredit(grossMsat int64, fee lnurlcash.MintFee) int64 {
// the proportional fee in sats, rounded up: ceil(gross*ppm / 1e9), split
// so it cannot overflow
q, r := grossMsat/1_000_000_000, grossMsat%1_000_000_000
propSat := q*fee.FeePpm + (r*fee.FeePpm+999_999_999)/1_000_000_000
rest := grossMsat - fee.BaseFeeMsat
c := rest - rest%1000 - propSat*1000
if c < 0 {
return 0
}
return c
}
// directGross returns the smallest whole-sat invoice whose note is worth at
// least valueMsat after the mint fee, both as ApplyMintFee reads the fee and at
// a mint that rounds it to whole sats. At such a mint the note is worth
// exactly valueMsat.
func directGross(valueMsat int64, fee lnurlcash.MintFee) int64 {
g := lnurlcash.GrossUpForMintFee(valueMsat, fee)
if rem := g % 1000; rem != 0 {
g += 1000 - rem
}
for satCredit(g, fee) < valueMsat || lnurlcash.ApplyMintFee(g, fee) < valueMsat {
g += 1000
}
return g
}
// directGrossInRange prices one directly minted note within the mint's
// sendable range. A gross below the minimum is raised to it only while the
// note still comes out at the asked whole sat; ok is false otherwise.
func directGrossInRange(mint *Mint, valueMsat int64, fee lnurlcash.MintFee) (int64, bool) {
g := directGross(valueMsat, fee)
if g < mint.MinSendableMsat {
g = mint.MinSendableMsat
if g%1000 != 0 || satCredit(g, fee) >= valueMsat+1000 {
return 0, false
}
}
if mint.MaxSendableMsat > 0 && g > mint.MaxSendableMsat {
return 0, false
}
return g, true
}
// Quote prices count notes of valueMsat at a mint. A single note, and each
// note of the "invoices" strategy, is minted straight from its own invoice,
// so only the mint fee is paid on it. A single note the mint's minimum would
// overpay falls back to funding and carving. The "split" strategy carves
// every note of a batch out of one funding note.
func (s *Service) Quote(ctx context.Context, mint *Mint, valueMsat int64, count int) (Quote, error) {
if mint == nil || !mint.Usable() {
return Quote{}, ErrNoMint
}
if count < 1 {
count = 1
}
fee := mint.Fee()
q := Quote{MintID: mint.ID, MintName: mint.ID, ValueMsat: valueMsat, Count: count, Fee: fee, Strategy: s.cfg.BatchStrategy}
var gross int64
switch {
case count == 1 || s.cfg.BatchStrategy == StrategyInvoices:
per, ok := directGrossInRange(mint, valueMsat, fee)
q.Strategy, q.Direct = StrategyInvoices, true
if !ok {
if count > 1 {
return Quote{}, ErrMintRange
}
per = grossFor(valueMsat, 1, fee)
if per < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && per > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
q.Strategy, q.Direct = StrategySplit, false
}
gross = per * int64(count)
default:
gross = grossFor(valueMsat, int64(count), fee)
if gross < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && gross > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
}
q.GrossMsat = gross
q.FeeMsat = gross - q.NetMsat()
return q, nil
}
// CheckCaps enforces the configured limits for a creation.
func (s *Service) CheckCaps(ctx context.Context, user string, q Quote, inGroup bool) error {
valueSat := q.ValueMsat / 1000
if q.ValueMsat%1000 != 0 || valueSat < s.cfg.MinNoteSat || valueSat > s.cfg.MaxNoteSat {
return ErrCapNoteValue
}
if inGroup && valueSat > s.cfg.GroupNoteMaxSat {
return ErrCapNoteValue
}
if int64(q.Count) > s.cfg.MaxBatchSize || (q.Count > 1 && q.NetMsat()/1000 > s.cfg.MaxBatchTotalSat) {
return ErrCapBatch
}
count, sum, err := s.store.Outstanding(user)
if err != nil {
return err
}
if count+int64(q.Count) > s.cfg.MaxOutstandingNotesPerUser || (sum+q.NetMsat())/1000 > s.cfg.MaxOutstandingSatPerUser {
return ErrCapOutstanding
}
balance, err := s.ledger.BalanceMsat(ctx, user)
if err != nil {
return err
}
if balance < q.GrossMsat+payReserveMsat(q) {
return ErrInsufficientFunds
}
return nil
}
// payReserveMsat is what LNbits wants left in the wallet on top of an
// outgoing payment to cover routing fees: max(1 sat, 1%) of each invoice.
// A batch on the invoices strategy pays one invoice per note.
func payReserveMsat(q Quote) int64 {
units := int64(1)
if q.Strategy == StrategyInvoices && q.Count > 1 {
units = int64(q.Count)
}
per := q.GrossMsat / units / 100
if per < 1000 {
per = 1000
}
return per * units
}
// ---- creation ----
// CreateParams describes one creation request.
type CreateParams struct {
User string
LanguageCode string
Quote Quote
Memo string
ChatID int64 // group chat, 0 for private
// Progress is called after every carved note (batches).
Progress func(done, total int)
}
// unit is one mint invoice and the notes carved out of it.
type unit struct {
funding *Note
notes []*Note // user notes, in order
dust []*Note // dust_i is the change of split i
}
// Create mints the notes of a quote. It returns the batch and the user notes
// that are live. ErrInFlight means the recovery job will finish the rest.
func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note, error) {
q := p.Quote
mint, ok := s.mints.Get(q.MintID)
if !ok || !mint.Usable() {
return nil, nil, ErrNoMint
}
if err := s.CheckCaps(ctx, p.User, q, p.ChatID != 0); err != nil {
return nil, nil, err
}
units := 1
perUnit := q.Count
if q.Direct || (q.Strategy == StrategyInvoices && q.Count > 1) {
units, perUnit = q.Count, 1
}
unitGross := q.GrossMsat / int64(units)
batch := &Batch{ID: newID("batch"), UserName: p.User, MintID: mint.ID, Memo: p.Memo, Count: q.Count,
ValueMsat: q.ValueMsat, TotalGrossMsat: q.GrossMsat, FeeMsat: q.FeeMsat, Strategy: q.Strategy,
State: BatchPendingInvoice, ChatID: p.ChatID, LanguageCode: p.LanguageCode}
var all []*unit
index := 0
for u := 0; u < units; u++ {
un := &unit{}
if q.Direct {
// the note is minted straight from its invoice: it is its own funding
index++
n, err := s.newNote(batch, mint, p, KindUser, index, unitGross)
if err != nil {
return nil, nil, err
}
n.State = NotePendingInvoice
un.funding = n
all = append(all, un)
continue
}
f, err := s.newNote(batch, mint, p, KindFunding, 0, unitGross)
if err != nil {
return nil, nil, err
}
f.State = NotePendingInvoice
un.funding = f
for i := 0; i < perUnit; i++ {
index++
n, err := s.newNote(batch, mint, p, KindUser, index, 0)
if err != nil {
return nil, nil, err
}
d, err := s.newNote(batch, mint, p, KindDust, index, 0)
if err != nil {
return nil, nil, err
}
un.notes = append(un.notes, n)
un.dust = append(un.dust, d)
}
all = append(all, un)
}
if units == 1 {
batch.FundingNoteID = all[0].funding.ID
}
// Every secret is on disk before the first request leaves.
err := s.store.Transaction(func(tx *gorm.DB) error {
if err := s.store.CreateBatch(tx, batch); err != nil {
return err
}
for _, un := range all {
rows := append([]*Note{un.funding}, un.notes...)
rows = append(rows, un.dust...)
if err := s.store.CreateNotes(tx, rows); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, nil, err
}
log.Infof("[lnurlcash] batch %s: %d note(s) of %d msat at %s for user %s (gross %d msat, direct %t)", batch.ID, q.Count, q.ValueMsat, mint.ID, p.User, q.GrossMsat, q.Direct)
// the recovery job takes the same lock, so it never works this batch
// while the creation is still running
unlock := lockNote(batch.ID)
defer unlock()
var live []*Note
done := 0
var firstErr error
for _, un := range all {
err := s.fundAndCarve(ctx, batch, mint, un, func() {
done++
if p.Progress != nil {
p.Progress(done, q.Count)
}
})
if un.funding.Kind == KindUser && un.funding.State == NoteLive {
live = append(live, un.funding)
}
for _, n := range un.notes {
if n.State == NoteLive {
live = append(live, n)
}
}
if err != nil {
firstErr = err
break
}
}
s.settleBatchState(batch.ID)
b, _ := s.store.Batch(batch.ID)
if b == nil {
b = batch
}
return b, live, firstErr
}
func (s *Service) newNote(batch *Batch, mint *Mint, p CreateParams, kind string, index int, gross int64) (*Note, error) {
k1, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(k1)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(k1)
if err != nil {
return nil, err
}
bid := batch.ID
n := &Note{ID: newID("note"), BatchID: &bid, UserName: p.User, MintID: mint.ID, MintURL: mint.WithdrawLink,
MintPubkey: mint.PinnedPubkey, Hash: h, SecretEnc: enc, Memo: p.Memo, Kind: kind, Index: index,
State: NotePendingCarve, LanguageCode: p.LanguageCode, ChatID: p.ChatID}
if kind == KindUser {
n.ValueMsat = p.Quote.ValueMsat
n.GrossMsat = gross // > 0 only for a directly minted note
}
if kind == KindFunding {
n.GrossMsat = gross
n.ValueMsat = gross
}
return n, nil
}
// fundAndCarve requests and pays the mint invoice of a unit, waits for the
// note to appear, then carves the user notes out of it.
func (s *Service) fundAndCarve(ctx context.Context, batch *Batch, mint *Mint, un *unit, progress func()) error {
f := un.funding
if f.State == NotePendingInvoice {
inv, err := s.client.RequestMintInvoiceWithHash(ctx, mint.PayCallback, f.GrossMsat, f.Hash)
if err != nil {
s.failUnit(batch, un, "mint invoice: "+err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
patch := map[string]interface{}{"invoice_pr": inv.PR, "verify_url": inv.VerifyURL}
if err := s.store.TransitionNote(f.ID, NotePendingInvoice, NotePendingSettle, patch); err != nil {
return err
}
f.State, f.InvoicePR, f.VerifyURL = NotePendingSettle, inv.PR, inv.VerifyURL
_ = s.store.TransitionBatch(batch.ID, "", BatchPendingSettle, nil)
hash, err := s.ledger.PayInvoice(ctx, batch.UserName, inv.PR)
if err != nil {
if IsAmbiguousLedger(err) {
_ = s.store.UpdateNote(f.ID, map[string]interface{}{"last_error": err.Error()})
log.Warnf("[lnurlcash] batch %s funding %s: pay outcome unknown, left for recovery", batch.ID, f.Hash)
return ErrInFlight
}
s.failUnit(batch, un, "pay: "+err.Error())
return err
}
_ = s.store.UpdateNote(f.ID, map[string]interface{}{"invoice_hash": hash})
f.InvoiceHash = hash
}
if f.State == NotePendingSettle {
found, err := s.waitFunding(ctx, f, s.cfg.InvoiceWaitTimeout)
if err != nil {
return err
}
if !found {
return ErrInFlight
}
}
if len(un.notes) == 0 {
// a directly minted note: nothing to carve
if f.State == NoteLive {
progress()
}
return nil
}
return s.carve(ctx, batch, un, progress)
}
// waitFunding polls until the funding note exists at the mint or the timeout
// passes. It returns found=false on timeout.
func (s *Service) waitFunding(ctx context.Context, f *Note, timeout time.Duration) (bool, error) {
deadline := s.now().Add(timeout)
for attempt := 0; ; attempt++ {
info, err := s.reader.FetchNoteInfoByHash(ctx, f.MintURL, f.Hash)
if err == nil {
patch := map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature, "last_probe": s.now()}
if err := s.store.TransitionNote(f.ID, NotePendingSettle, NoteLive, patch); err != nil && !errors.Is(err, ErrStale) {
return false, err
}
f.State, f.ReportedMsat = NoteLive, info.MaxWithdrawableMsat
if f.Kind == KindUser && info.MaxWithdrawableMsat%1000 != 0 {
// the user cannot reclaim a fractional note: the mint does not round
// its fee to whole sats as directGross assumes
log.Errorf("[lnurlcash] note %s: mint %s credited %d msat for a %d msat note; direct minting at this mint gives fractional notes",
f.ID, f.MintID, info.MaxWithdrawableMsat, f.ValueMsat)
}
return true, nil
}
if lnurlcash.IsSpent(err) {
if f.Kind == KindUser {
// a directly minted note that was claimed before we saw it
f.State = NoteClaimed
_ = s.store.TransitionNote(f.ID, "", NoteClaimed, map[string]interface{}{"reported_msat": f.ValueMsat, "claimed_at": s.now()})
return true, nil
}
// burned already: the funding note was carved by a previous run
f.State = NoteSpent
_ = s.store.TransitionNote(f.ID, "", NoteSpent, nil)
return true, nil
}
if !s.now().Before(deadline) || ctx.Err() != nil {
return false, nil
}
select {
case <-ctx.Done():
return false, nil
case <-time.After(pollDelay(s.pollEvery, attempt)):
}
}
}
// pollDelay is the sleep after poll number attempt (from 0): an eighth of max,
// then a quarter, a half, and max from then on. A mint usually credits a note
// within a second of the payment settling, so the first polls come quickly.
func pollDelay(max time.Duration, attempt int) time.Duration {
if attempt >= 3 {
return max
}
return max >> (3 - attempt)
}
// carve splits the user notes off the funding note, one after the other.
// Idempotent: a note that already exists at the mint is taken as carved.
func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress func()) error {
_ = s.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
current := un.funding
// every note of a unit lives at the same withdraw link, so the callback the
// mint names for the first input serves the whole chain
callback := ""
for i, n := range un.notes {
if IsFinalNoteState(n.State) || n.State == NoteLive {
if n.State == NoteLive {
progress()
}
current = un.dust[i]
continue
}
if current.State != NoteLive {
// the previous change note is gone: nothing left to carve from
s.failRemaining(batch, un, i, "no change note to carve from")
return fmt.Errorf("%w: carve input not live", ErrMintUnavailable)
}
dust := un.dust[i]
k1, err := s.secret(current)
if err != nil {
return err
}
if callback == "" {
cb, cerr := s.callbackOf(ctx, current)
if cerr != nil {
// nothing was sent: the recovery job tries again
log.Warnf("[lnurlcash] batch %s: callback of %s: %v", batch.ID, current.Hash, cerr)
return ErrInFlight
}
callback = cb
}
_, err = s.client.SplitNoteWithHash(ctx, callback, []string{k1}, n.ValueMsat, n.Hash, dust.Hash)
if err != nil {
switch {
case lnurlcash.IsAmbiguous(err):
// the library already retried; the answer is lost. Probe the output.
if _, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break // it landed
}
_ = s.store.TransitionNote(n.ID, "", NoteUnknown, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionBatch(batch.ID, "", BatchUnknown, nil)
n.State = NoteUnknown
log.Warnf("[lnurlcash] batch %s note %s: split outcome unknown, left for recovery", batch.ID, n.Hash)
return ErrInFlight
case lnurlcash.IsAlreadyInUse(err), lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
// either the input was burned by an earlier attempt that did land,
// or the output is taken. The output's existence decides.
if _, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break
}
s.failRemaining(batch, un, i, err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
default:
s.failRemaining(batch, un, i, err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
fee := s.mintFee(n.MintID)
changeMsat := current.ReportedMsat - n.ValueMsat - fee.BaseFeeMsat
if err := s.store.TransitionNote(n.ID, "", NoteLive, map[string]interface{}{"reported_msat": n.ValueMsat, "last_probe": s.now()}); err != nil {
return err
}
n.State, n.ReportedMsat = NoteLive, n.ValueMsat
_ = s.store.TransitionNote(dust.ID, "", NoteLive, map[string]interface{}{"reported_msat": changeMsat, "value_msat": changeMsat})
dust.State, dust.ReportedMsat, dust.ValueMsat = NoteLive, changeMsat, changeMsat
_ = s.store.TransitionNote(current.ID, "", NoteSpent, nil)
current.State = NoteSpent
progress()
current = dust
// the mint's own word on the two outputs, best effort
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil && info.MaxWithdrawableMsat != n.ReportedMsat {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature})
n.ReportedMsat = info.MaxWithdrawableMsat
}
}
return nil
}
// callbackOf is where mutations of a note go: the callback the mint names in
// the note's own withdraw info. It is not the withdraw link (mint.600.wtf
// serves info at /w and takes mutations at /w/cb), and a mutation sent to the
// link comes back without a status, which reads as an unknown outcome.
func (s *Service) callbackOf(ctx context.Context, n *Note) (string, error) {
info, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
if err != nil {
return "", err
}
if info.Callback == "" {
return "", fmt.Errorf("the mint named no callback for note %s", ShortID(n.ID))
}
return info.Callback, nil
}
func (s *Service) mintFee(mintID string) lnurlcash.MintFee {
if m, ok := s.mints.Get(mintID); ok {
return m.Fee()
}
return lnurlcash.MintFee{}
}
func (s *Service) failUnit(batch *Batch, un *unit, reason string) {
_ = s.store.TransitionNote(un.funding.ID, "", NoteFailed, map[string]interface{}{"last_error": reason})
un.funding.State = NoteFailed
s.failRemaining(batch, un, 0, reason)
}
func (s *Service) failRemaining(batch *Batch, un *unit, from int, reason string) {
for i := from; i < len(un.notes); i++ {
if un.notes[i].State == NoteLive || IsFinalNoteState(un.notes[i].State) {
continue
}
_ = s.store.TransitionNote(un.notes[i].ID, "", NoteFailed, map[string]interface{}{"last_error": reason})
un.notes[i].State = NoteFailed
_ = s.store.TransitionNote(un.dust[i].ID, "", NoteFailed, nil)
un.dust[i].State = NoteFailed
}
}
// settleBatchState derives the batch state from its notes.
func (s *Service) settleBatchState(batchID string) {
notes, err := s.store.NotesInBatch(batchID)
if err != nil {
return
}
var live, claimed, reclaimed, failed, pending, total int
for _, n := range notes {
if n.Kind != KindUser {
continue
}
total++
switch n.State {
case NoteLive, NoteReclaiming:
live++
case NoteClaimed:
claimed++
case NoteReclaimed:
reclaimed++
case NoteFailed:
failed++
default:
pending++
}
}
state := BatchLive
switch {
case total == 0:
return
case pending > 0:
state = BatchCarving
case failed == total:
state = BatchFailed
case failed > 0:
state = BatchPartial
case claimed == total:
state = BatchClaimed
case claimed+reclaimed == total:
state = BatchReclaimed
}
_ = s.store.TransitionBatch(batchID, "", state, nil)
}
// ---- status ----
// Status asks the mint about a note and updates the row. It returns the
// note's new state.
func (s *Service) Status(ctx context.Context, n *Note) (string, int64, error) {
state, value, _, err := s.probe(ctx, n)
return state, value, err
}
// probe is Status that also returns the mint's withdraw info when the note
// exists, so a caller about to mutate the note can use its callback without
// asking the mint a second time.
func (s *Service) probe(ctx context.Context, n *Note) (string, int64, lnurlcash.WithdrawInfo, error) {
if IsFinalNoteState(n.State) {
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, nil
}
info, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
now := s.now()
switch {
case err == nil:
patch := map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "last_probe": now, "last_error": ""}
if info.Signature != "" {
patch["certificate"] = info.Signature
}
if n.State == NoteUnknown || n.State == NotePendingSettle || n.State == NotePendingCarve {
// it exists: it is live, whatever we feared
_ = s.store.TransitionNote(n.ID, n.State, NoteLive, patch)
n.State = NoteLive
} else {
_ = s.store.UpdateNote(n.ID, patch)
}
n.ReportedMsat = info.MaxWithdrawableMsat
return n.State, n.ReportedMsat, info, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now})
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
if n.State == NoteLive {
t := now
if terr := s.store.TransitionNote(n.ID, NoteLive, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_probe": now}); terr == nil {
n.State, n.ClaimedAt = NoteClaimed, &t
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
}
} else {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
}
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, nil
default:
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, err
}
}
// NoteURL builds the lnurlw:// form of a note. The URL is never stored.
func (s *Service) NoteURL(n *Note) (string, error) {
k1, err := s.secret(n)
if err != nil {
return "", err
}
value := n.ReportedMsat
if value <= 0 {
value = n.ValueMsat
}
u := lnurlcash.BuildNoteURL(n.MintURL, k1, value)
if u == "" {
return "", errors.New("lnurlcash: note URL does not build")
}
if n.Certificate != "" {
u = lnurlcash.WithNewK1(u, k1, value, n.Certificate)
}
return u, nil
}
// NoteStrings returns the lnurlw:// form and the bech32 LNURL of a note.
func (s *Service) NoteStrings(n *Note) (lnurlw, bech32 string, err error) {
u, err := s.NoteURL(n)
if err != nil {
return "", "", err
}
b, err := lnurlcash.ToBech32Lnurl(u)
if err != nil {
return "", "", err
}
return lnurlcash.ToLud17w(u), b, nil
}
// lockNote serialises work on one note across handlers and jobs.
func lockNote(id string) func() {
mutex.Lock("lnurlcash:" + id)
return func() { mutex.Unlock("lnurlcash:" + id) }
}
-108
View File
@@ -1,108 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"sort"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export"
)
// ExportBatch builds the export of a batch for its owner: live notes only,
// so a re-export after some were claimed leaves those out. The note strings
// are built in memory and never stored.
func (s *Service) ExportBatch(batchID, user string) (export.Batch, error) {
b, err := s.store.Batch(batchID)
if err != nil {
return export.Batch{}, err
}
if b.UserName != user {
return export.Batch{}, ErrNotOwner
}
notes, err := s.store.NotesInBatch(b.ID)
if err != nil {
return export.Batch{}, err
}
mint, _ := s.mints.Get(b.MintID)
out := export.Batch{ID: b.ID, Memo: b.Memo, CreatedAt: b.CreatedAt, MintName: b.MintID}
if mint != nil {
out.MintURL, out.MintPubkey = mint.WithdrawLink, mint.PinnedPubkey
}
for _, n := range notes {
if n.Kind != KindUser || n.State != NoteLive {
continue
}
lnurlw, bech, err := s.NoteStrings(n)
if err != nil {
return export.Batch{}, err
}
out.Notes = append(out.Notes, export.Note{Index: n.Index, ID: n.ID, ShortID: ShortID(n.ID), AmountMsat: n.ReportedMsat,
LNURL: bech, LNURLW: lnurlw, Mint: b.MintID, Memo: n.Memo, Cert: n.Certificate, CreatedAt: n.CreatedAt})
}
sort.Slice(out.Notes, func(i, j int) bool { return out.Notes[i].Index < out.Notes[j].Index })
return out, nil
}
// BatchSummary counts a batch's user notes by state.
type BatchSummary struct {
Total, Live, Claimed, Reclaimed, Failed, Pending int
}
// Summarize counts the notes of a batch.
func (s *Service) Summarize(batchID string) (BatchSummary, error) {
notes, err := s.store.NotesInBatch(batchID)
if err != nil {
return BatchSummary{}, err
}
var sum BatchSummary
for _, n := range notes {
if n.Kind != KindUser {
continue
}
sum.Total++
switch n.State {
case NoteLive:
sum.Live++
case NoteClaimed:
sum.Claimed++
case NoteReclaimed:
sum.Reclaimed++
case NoteFailed:
sum.Failed++
default:
sum.Pending++
}
}
return sum, nil
}
// ReclaimBatch reclaims every live note of a batch. It returns how many
// melts were sent and the first error.
func (s *Service) ReclaimBatch(ctx context.Context, batchID, user string) (int, error) {
b, err := s.store.Batch(batchID)
if err != nil {
return 0, err
}
if b.UserName != user {
return 0, ErrNotOwner
}
notes, err := s.store.NotesInBatch(b.ID)
if err != nil {
return 0, err
}
sent := 0
var first error
for _, n := range notes {
if n.Kind != KindUser || n.State != NoteLive {
continue
}
if _, err := s.Reclaim(ctx, n.ID); err != nil {
if !errors.Is(err, ErrNoteClaimed) && first == nil {
first = err
}
continue
}
sent++
}
return sent, first
}
-439
View File
@@ -1,439 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
)
// fakeLedger is an in-memory LNbits: invoices on user wallets, payments of
// fake-mint invoices, balances in msat.
type fakeLedger struct {
mu sync.Mutex
mint *fakeMint
balances map[string]int64
invoices map[string]*fakeLedgerInvoice // hash -> invoice
payFails bool
payAmbig bool
seq int
}
type fakeLedgerInvoice struct {
user string
sat int64
ref string
paid bool
}
func newFakeLedger(m *fakeMint) *fakeLedger {
return &fakeLedger{mint: m, balances: map[string]int64{}, invoices: map[string]*fakeLedgerInvoice{}}
}
func (l *fakeLedger) CreateInvoice(ctx context.Context, user string, sat int64, memo, ref string) (string, string, error) {
l.mu.Lock()
defer l.mu.Unlock()
l.seq++
hash := fmt.Sprintf("%064d", l.seq)
l.invoices[hash] = &fakeLedgerInvoice{user: user, sat: sat, ref: ref}
return "lnbcfake" + hash[:8], hash, nil
}
func (l *fakeLedger) PayInvoice(ctx context.Context, user, pr string) (string, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.payAmbig {
return "", &AmbiguousLedgerError{Err: errors.New("timeout")}
}
if l.payFails {
return "", errors.New("payment failed: no route")
}
l.seq++
hash := fmt.Sprintf("%064d", l.seq)
inv := l.mint.inv[pr]
if inv == nil {
return "", errors.New("unknown invoice")
}
l.balances[user] -= inv.amount
l.mu.Unlock()
l.mint.settle(pr)
l.mu.Lock()
return hash, nil
}
func (l *fakeLedger) InvoicePaid(ctx context.Context, user, hash string) (bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
inv, ok := l.invoices[hash]
return ok && inv.paid, nil
}
func (l *fakeLedger) PaymentSucceeded(ctx context.Context, user, hash string) (bool, bool, error) {
return true, false, nil
}
func (l *fakeLedger) BalanceMsat(ctx context.Context, user string) (int64, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.balances[user], nil
}
// settleIncoming marks an invoice on a user wallet paid (the melt arrived).
func (l *fakeLedger) settleIncoming(hash string) {
l.mu.Lock()
defer l.mu.Unlock()
inv := l.invoices[hash]
inv.paid = true
l.balances[inv.user] += inv.sat * 1000
}
type harness struct {
mint *fakeMint
ledger *fakeLedger
store *Store
reg *Registry
svc *Service
cfg *Config
}
func newHarness(t *testing.T) *harness {
t.Helper()
fm := newFakeMint(t)
s := testStore(t)
cfg := testConfig(fm.url())
cfg.InvoiceWaitTimeout = 2 * time.Second
reg := NewRegistry(cfg, s, nil, nil, nil)
if err := reg.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
ledger := newFakeLedger(fm)
ledger.balances["42"] = 10_000_000 // 10k sat
cipher, _ := NewCipher(testKey)
svc := NewService(cfg, s, reg, ledger, cipher)
svc.pollEvery = 10 * time.Millisecond
return &harness{mint: fm, ledger: ledger, store: s, reg: reg, svc: svc, cfg: cfg}
}
func TestGrossUpAgainstLiveFee(t *testing.T) {
fee := lnurlcash.MintFee{BaseFeeMsat: 1000, FeePpm: 100}
for _, count := range []int64{1, 3, 100} {
gross := grossFor(1000_000, count, fee)
if gross%1000 != 0 {
t.Fatalf("gross must be whole sats: %d", gross)
}
net := lnurlcash.ApplyMintFee(gross, fee)
if net < count*1000_000+count*fee.BaseFeeMsat+carveMargin {
t.Fatalf("count %d: net %d does not cover the notes and the splits", count, net)
}
if net-(count*1000_000+count*fee.BaseFeeMsat+carveMargin) > 1000 {
t.Fatalf("count %d: overpaying by more than a sat: %d", count, net)
}
}
}
// The live mints' fees: a direct note costs the mint fee and nothing else, and
// a mint that rounds its fee to whole sats credits exactly the asked value.
func TestDirectGrossLiveFees(t *testing.T) {
fees := map[string]lnurlcash.MintFee{
"21mint": {BaseFeeMsat: 1000, FeePpm: 100},
"mint.600.wtf": {BaseFeeMsat: 3000, FeePpm: 5000},
"mint.lnurlcash.com": {BaseFeeMsat: 3000, FeePpm: 2000},
}
want10 := map[string]int64{"21mint": 12000, "mint.600.wtf": 14000, "mint.lnurlcash.com": 14000}
for name, fee := range fees {
if g := directGross(10_000, fee); g != want10[name] {
t.Errorf("%s: 10 sat note costs %d msat, want %d", name, g, want10[name])
}
for sat := int64(1); sat <= 100_000; sat += 7 {
v := sat * 1000
g := directGross(v, fee)
if g%1000 != 0 {
t.Fatalf("%s %d sat: gross %d is not whole sats", name, sat, g)
}
if c := satCredit(g, fee); c != v {
t.Fatalf("%s %d sat: a whole-sat mint credits %d for gross %d", name, sat, c, g)
}
if lnurlcash.ApplyMintFee(g, fee) < v || (g > 1000 && satCredit(g-1000, fee) >= v) {
t.Fatalf("%s %d sat: gross %d is not minimal", name, sat, g)
}
}
}
}
// Below the mint's minimum invoice a note is minted directly only when the
// minimum still yields the asked value; otherwise it is carved as before, or
// refused when that is out of range too.
func TestQuoteAtMintMinimum(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
h.mint.minSendable = 12000 // 21mint
if err := h.reg.Check(ctx, "fake"); err != nil {
t.Fatal(err)
}
mint, _ := h.reg.Get("fake")
if q, err := h.svc.Quote(ctx, mint, 10_000, 1); err != nil || !q.Direct || q.GrossMsat != 12000 {
t.Fatalf("10 sat: %+v %v", q, err)
}
if q, err := h.svc.Quote(ctx, mint, 9_000, 1); err != nil || q.Direct || q.GrossMsat != grossFor(9_000, 1, mint.Fee()) {
t.Fatalf("9 sat must fall back to carving: %+v %v", q, err)
}
if _, err := h.svc.Quote(ctx, mint, 5_000, 1); !errors.Is(err, ErrMintRange) {
t.Fatalf("5 sat must be out of range: %v", err)
}
// a direct note created at the minimum is worth exactly what was asked
h.mint.satRound = true
q, _ := h.svc.Quote(ctx, mint, 10_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 1 || live[0].ReportedMsat != 10_000 {
t.Fatalf("create: %v live=%d", err, len(live))
}
}
func TestCreateSingleNoteAndReclaim(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
// minted straight into the note: only the mint fee, no split fee or margin
if want := directGross(1000_000, mint.Fee()); !q.Direct || q.GrossMsat != want || q.FeeMsat != want-1000_000 || q.GrossMsat%1000 != 0 {
t.Fatalf("unexpected quote %+v (want direct gross %d)", q, want)
}
if q.GrossMsat >= grossFor(1000_000, 1, mint.Fee()) {
t.Fatalf("direct gross %d is not below the carved gross", q.GrossMsat)
}
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", LanguageCode: "en", Quote: q, Memo: "hi"})
if err != nil {
t.Fatal(err)
}
if len(live) != 1 || batch.State != BatchLive {
t.Fatalf("expected one live note, got %d, batch %s", len(live), batch.State)
}
n := live[0]
if v, ok := h.mint.value(n.Hash); !ok || v != 1000_000 {
t.Fatalf("mint holds %d for the note (ok=%v)", v, ok)
}
if n.ReportedMsat != 1000_000 {
t.Fatalf("reported %d", n.ReportedMsat)
}
if h.ledger.balances["42"] != 10_000_000-q.GrossMsat {
t.Fatalf("balance %d", h.ledger.balances["42"])
}
// the user's note URL is a valid note at the fake mint
lnurlw, bech, err := h.svc.NoteStrings(n)
if err != nil || !strings.HasPrefix(lnurlw, "lnurlw://") || !strings.HasPrefix(bech, "LNURL1") {
t.Fatalf("note strings: %q %q %v", lnurlw, bech, err)
}
if lnurlcash.ResolveNoteInput(bech) == "" {
t.Fatal("bech32 note does not resolve")
}
// one row: the note is its own funding, nothing is left over
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 1 || notes[0].Kind != KindUser || notes[0].GrossMsat != q.GrossMsat || batch.FundingNoteID != n.ID {
t.Fatalf("expected one directly minted user note, got %d rows", len(notes))
}
// status: still live
state, _, err := h.svc.Status(ctx, n)
if err != nil || state != NoteLive {
t.Fatalf("status %s %v", state, err)
}
// reclaim: invoice of exactly 1000 sat, melt in flight, settle
rn, err := h.svc.Reclaim(ctx, n.ID)
if err != nil {
t.Fatal(err)
}
if rn.State != NoteReclaiming || h.ledger.invoices[rn.InvoiceHash].sat != 1000 {
t.Fatalf("reclaim state %s", rn.State)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrInFlight) {
t.Fatalf("second reclaim must report in flight: %v", err)
}
h.mint.finishMelt(n.Hash, true)
h.ledger.settleIncoming(rn.InvoiceHash)
st, err := h.svc.SettleInvoice(ctx, rn.InvoiceHash)
if err != nil || st == nil || st.Note == nil || st.Note.State != NoteReclaimed {
t.Fatalf("settle: %+v %v", st, err)
}
b, _ := h.store.Batch(batch.ID)
if b.State != BatchReclaimed {
t.Fatalf("batch state %s", b.State)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrNothingToReclaim) {
t.Fatalf("reclaimed note: %v", err)
}
}
func TestClaimDetection(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 500_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
n := live[0]
h.mint.claim(n.Hash)
state, _, err := h.svc.Status(ctx, n)
if err != nil || state != NoteClaimed {
t.Fatalf("expected claimed, got %s %v", state, err)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrNoteClaimed) {
t.Fatalf("reclaiming a claimed note: %v", err)
}
}
func TestCreateBatchSplitAndPartialFailure(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 100_000, 5)
if err != nil {
t.Fatal(err)
}
progress := 0
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q, Progress: func(done, total int) { progress = done }})
if err != nil || len(live) != 5 || batch.State != BatchLive || progress != 5 {
t.Fatalf("batch: live=%d state=%s progress=%d err=%v", len(live), batch.State, progress, err)
}
for _, n := range live {
if v, ok := h.mint.value(n.Hash); !ok || v != 100_000 {
t.Fatalf("note %d worth %d at the mint", n.Index, v)
}
}
// a split refused midway leaves the carved notes and fails the rest
h.mint.refuseSplit = "insufficient value"
q2, _ := h.svc.Quote(ctx, mint, 100_000, 3)
batch2, live2, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q2})
if err == nil || len(live2) != 0 || batch2.State != BatchFailed {
t.Fatalf("expected a failed batch, got live=%d state=%s err=%v", len(live2), batch2.State, err)
}
// the funding note is still live at the mint and owned by the bot's row
notes, _ := h.store.NotesInBatch(batch2.ID)
var funding *Note
for _, n := range notes {
if n.Kind == KindFunding {
funding = n
}
}
if funding == nil || funding.State != NoteLive {
t.Fatalf("funding note should stay live for recovery: %+v", funding)
}
}
func TestCreateAmbiguousSplitIsResolvedByProbe(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 2)
h.mint.dropAfterSplit = true
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 2 || batch.State != BatchLive {
t.Fatalf("dropped connection after an applied split must still carve: live=%d state=%s err=%v", len(live), batch.State, err)
}
}
func TestCreateCaps(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
h.cfg.GroupNoteMaxSat = 500
if err := h.svc.CheckCaps(ctx, "42", q, true); !errors.Is(err, ErrCapNoteValue) {
t.Fatalf("group cap: %v", err)
}
h.ledger.balances["42"] = 1000
if err := h.svc.CheckCaps(ctx, "42", q, false); !errors.Is(err, ErrInsufficientFunds) {
t.Fatalf("balance: %v", err)
}
h.ledger.balances["42"] = 10_000_000
h.cfg.MaxOutstandingNotesPerUser = 1
q2, _ := h.svc.Quote(ctx, mint, 100_000, 2)
if err := h.svc.CheckCaps(ctx, "42", q2, false); !errors.Is(err, ErrCapOutstanding) {
t.Fatalf("outstanding: %v", err)
}
h.ledger.payFails = true
h.cfg.MaxOutstandingNotesPerUser = 200
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err == nil || len(live) != 0 || batch.State != BatchFailed {
t.Fatalf("failed payment must fail the batch: %v %s", err, batch.State)
}
}
func TestRedeemWholeAndFractional(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
// a note somebody else minted: a whole-sat one and a fractional one
mk := func(value int64) (string, string) {
k1, _ := lnurlcash.GenerateNoteSecret()
hh, _ := lnurlcash.HashK1(k1)
h.mint.mu.Lock()
h.mint.notes[hh] = value
h.mint.mu.Unlock()
return k1, lnurlcash.BuildNoteURL(h.mint.url()+"/w", k1, value)
}
_, whole := mk(2000_000)
prev, err := h.svc.RedeemInfo(ctx, "7", "nl", "lightning:"+whole)
if err != nil {
t.Fatal(err)
}
if prev.ValueMsat != 2000_000 || !prev.KnownMint || prev.Redeem.State != RedeemInfo {
t.Fatalf("preview %+v", prev)
}
if _, err := h.svc.Redeem(ctx, prev.Redeem.ID, "8"); !errors.Is(err, ErrNotOwner) {
t.Fatalf("owner check: %v", err)
}
r, err := h.svc.Redeem(ctx, prev.Redeem.ID, "7")
if err != nil || r.State != RedeemMelting {
t.Fatalf("redeem: %s %v", r.State, err)
}
if h.ledger.invoices[r.InvoiceHash].sat != 2000 {
t.Fatal("invoice must be exactly the note value")
}
h.ledger.settleIncoming(r.InvoiceHash)
st, err := h.svc.SettleInvoice(ctx, r.InvoiceHash)
if err != nil || st == nil || st.Redeem == nil || st.Redeem.State != RedeemSettled {
t.Fatalf("settle %+v %v", st, err)
}
// fractional: 1000.9 sat -> split off 999 sat (1000 would leave change below the base fee)
_, frac := mk(1000_900)
prev2, err := h.svc.RedeemInfo(ctx, "7", "nl", frac)
if err != nil {
t.Fatal(err)
}
r2, err := h.svc.Redeem(ctx, prev2.Redeem.ID, "7")
if err != nil || r2.State != RedeemMelting || r2.SplitNoteID == nil {
t.Fatalf("fractional redeem: %s %v", r2.State, err)
}
if got := h.ledger.invoices[r2.InvoiceHash].sat; got != 999 {
t.Fatalf("expected a 999 sat invoice, got %d", got)
}
// not a note: a plain withdraw without mintPubkey, or garbage
if _, err := h.svc.RedeemInfo(ctx, "7", "nl", "hello"); !errors.Is(err, ErrNotANote) {
t.Fatalf("garbage: %v", err)
}
// a spent note
k3, spent := mk(1000_000)
h3, _ := lnurlcash.HashK1(k3)
h.mint.claim(h3)
if _, err := h.svc.RedeemInfo(ctx, "7", "nl", spent); !errors.Is(err, ErrNoteClaimed) {
t.Fatalf("spent: %v", err)
}
// the user's own note is refused with a pointer to reclaim
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 1)
_, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
own, _ := h.svc.NoteURL(live[0])
var ownErr *ErrOwnNote
if _, err := h.svc.RedeemInfo(ctx, "42", "en", own); !errors.As(err, &ownErr) || ownErr.NoteID != live[0].ID {
t.Fatalf("own note: %v", err)
}
}
-289
View File
@@ -1,289 +0,0 @@
package lnurlcash
import (
"errors"
"fmt"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Store is the feature's own sqlite file.
type Store struct {
db *gorm.DB
}
// ErrStale is returned by a conditional transition whose row was not in the
// expected state: another worker got there first.
var ErrStale = errors.New("lnurlcash: row is not in the expected state")
// Open opens (and migrates) the database at path. Use "file::memory:?cache=shared"
// in tests.
func Open(path string) (*Store, error) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
return nil, fmt.Errorf("lnurlcash: open %s: %w", path, err)
}
if err := db.AutoMigrate(&Note{}, &Batch{}, &Redeem{}, &UserPref{}, &Mint{}); err != nil {
return nil, fmt.Errorf("lnurlcash: migrate: %w", err)
}
return &Store{db: db}, nil
}
// DB exposes the handle for tests and one-off queries.
func (s *Store) DB() *gorm.DB { return s.db }
// Transaction runs fn atomically.
func (s *Store) Transaction(fn func(tx *gorm.DB) error) error {
return s.db.Transaction(fn)
}
// ---- notes ----
func (s *Store) CreateNotes(tx *gorm.DB, notes []*Note) error {
if tx == nil {
tx = s.db
}
for _, n := range notes {
if err := tx.Create(n).Error; err != nil {
return err
}
}
return nil
}
func (s *Store) Note(id string) (*Note, error) {
var n Note
if err := s.db.First(&n, "id = ?", id).Error; err != nil {
return nil, err
}
return &n, nil
}
func (s *Store) NoteByHash(h string) (*Note, error) {
var n Note
if err := s.db.First(&n, "hash = ?", h).Error; err != nil {
return nil, err
}
return &n, nil
}
func (s *Store) NoteByInvoiceHash(h string) (*Note, error) {
var n Note
if err := s.db.First(&n, "invoice_hash = ?", h).Error; err != nil {
return nil, err
}
return &n, nil
}
// TransitionNote moves a note from one state to another, applying patch, and
// returns ErrStale when the note was not in the from state. from may be empty
// to skip the check.
func (s *Store) TransitionNote(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Note{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
// UpdateNote applies a patch without a state check.
func (s *Store) UpdateNote(id string, patch map[string]interface{}) error {
patch["updated_at"] = time.Now()
return s.db.Model(&Note{}).Where("id = ?", id).Updates(patch).Error
}
func (s *Store) NotesByState(states []string, kinds []string, limit int) ([]*Note, error) {
var notes []*Note
q := s.db.Where("state IN ?", states).Order("last_probe asc, created_at asc")
if len(kinds) > 0 {
q = q.Where("kind IN ?", kinds)
}
if limit > 0 {
q = q.Limit(limit)
}
return notes, q.Find(&notes).Error
}
func (s *Store) NotesInBatch(batchID string) ([]*Note, error) {
var notes []*Note
return notes, s.db.Where("batch_id = ?", batchID).Order("`index` asc").Find(&notes).Error
}
// UserNotes lists a user's own notes, newest first.
func (s *Store) UserNotes(user string, states []string) ([]*Note, error) {
var notes []*Note
q := s.db.Where("user_name = ? AND kind = ?", user, KindUser).Order("created_at desc")
if len(states) > 0 {
q = q.Where("state IN ?", states)
}
return notes, q.Find(&notes).Error
}
// Outstanding returns how many live or in-flight user notes a user has and
// their total requested value.
func (s *Store) Outstanding(user string) (count int64, sumMsat int64, err error) {
type row struct {
N int64
S int64
}
var r row
err = s.db.Model(&Note{}).
Select("count(*) as n, coalesce(sum(value_msat), 0) as s").
Where("user_name = ? AND kind = ? AND state NOT IN ?", user, KindUser,
[]string{NoteClaimed, NoteReclaimed, NoteFailed, NoteSpent}).
Scan(&r).Error
return r.N, r.S, err
}
// LiveNotesOlderThan lists live user notes created before t.
func (s *Store) LiveNotesOlderThan(t time.Time) ([]*Note, error) {
var notes []*Note
return notes, s.db.Where("state = ? AND kind = ? AND created_at < ?", NoteLive, KindUser, t).Find(&notes).Error
}
// ---- batches ----
func (s *Store) CreateBatch(tx *gorm.DB, b *Batch) error {
if tx == nil {
tx = s.db
}
return tx.Create(b).Error
}
func (s *Store) Batch(id string) (*Batch, error) {
var b Batch
if err := s.db.First(&b, "id = ?", id).Error; err != nil {
return nil, err
}
return &b, nil
}
func (s *Store) TransitionBatch(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Batch{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
func (s *Store) UpdateBatch(id string, patch map[string]interface{}) error {
patch["updated_at"] = time.Now()
return s.db.Model(&Batch{}).Where("id = ?", id).Updates(patch).Error
}
func (s *Store) BatchesByState(states []string) ([]*Batch, error) {
var bs []*Batch
return bs, s.db.Where("state IN ?", states).Order("created_at asc").Find(&bs).Error
}
// UserBatches lists a user's batches with more than one note, newest first.
func (s *Store) UserBatches(user string) ([]*Batch, error) {
var bs []*Batch
return bs, s.db.Where("user_name = ? AND count > 1", user).Order("created_at desc").Find(&bs).Error
}
// ---- redeems ----
func (s *Store) CreateRedeem(r *Redeem) error { return s.db.Create(r).Error }
func (s *Store) Redeem(id string) (*Redeem, error) {
var r Redeem
if err := s.db.First(&r, "id = ?", id).Error; err != nil {
return nil, err
}
return &r, nil
}
func (s *Store) RedeemByInvoiceHash(h string) (*Redeem, error) {
var r Redeem
if err := s.db.First(&r, "invoice_hash = ?", h).Error; err != nil {
return nil, err
}
return &r, nil
}
func (s *Store) TransitionRedeem(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Redeem{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
func (s *Store) RedeemsByState(states []string) ([]*Redeem, error) {
var rs []*Redeem
return rs, s.db.Where("state IN ?", states).Order("created_at asc").Find(&rs).Error
}
// ---- prefs and mints ----
func (s *Store) Pref(user string) (*UserPref, error) {
var p UserPref
err := s.db.First(&p, "user_name = ?", user).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return &p, err
}
func (s *Store) SetPref(user, mintID string) error {
return s.db.Save(&UserPref{UserName: user, DefaultMintID: mintID, UpdatedAt: time.Now()}).Error
}
func (s *Store) Mint(id string) (*Mint, error) {
var m Mint
err := s.db.First(&m, "id = ?", id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return &m, err
}
func (s *Store) SaveMint(m *Mint) error { return s.db.Save(m).Error }
func (s *Store) Mints() ([]*Mint, error) {
var ms []*Mint
return ms, s.db.Order("id asc").Find(&ms).Error
}
-59
View File
@@ -1,59 +0,0 @@
package lnurlcash
import (
"testing"
"time"
)
func testStore(t *testing.T) *Store {
t.Helper()
s, err := Open("file:" + t.Name() + "?mode=memory&cache=shared")
if err != nil {
t.Fatal(err)
}
return s
}
func TestStoreTransitions(t *testing.T) {
s := testStore(t)
n := &Note{ID: "note-1", UserName: "42", Hash: "aa", ValueMsat: 1000_000, State: NotePendingCarve, Kind: KindUser}
if err := s.CreateNotes(nil, []*Note{n}); err != nil {
t.Fatal(err)
}
if err := s.TransitionNote("note-1", NoteLive, NoteClaimed, nil); err != ErrStale {
t.Fatalf("wrong-state transition must be stale, got %v", err)
}
if err := s.TransitionNote("note-1", NotePendingCarve, NoteLive, map[string]interface{}{"reported_msat": 1000_000}); err != nil {
t.Fatal(err)
}
got, _ := s.Note("note-1")
if got.State != NoteLive || got.ReportedMsat != 1000_000 {
t.Fatalf("unexpected note %+v", got)
}
count, sum, err := s.Outstanding("42")
if err != nil || count != 1 || sum != 1000_000 {
t.Fatalf("outstanding: %d %d %v", count, sum, err)
}
if err := s.TransitionNote("note-1", NoteLive, NoteClaimed, nil); err != nil {
t.Fatal(err)
}
count, _, _ = s.Outstanding("42")
if count != 0 {
t.Fatal("claimed notes must not count as outstanding")
}
if p, err := s.Pref("42"); err != nil || p != nil {
t.Fatal("no pref expected")
}
if err := s.SetPref("42", "21mint"); err != nil {
t.Fatal(err)
}
if p, _ := s.Pref("42"); p == nil || p.DefaultMintID != "21mint" {
t.Fatal("pref not stored")
}
old := &Note{ID: "note-2", UserName: "42", Hash: "bb", State: NoteLive, Kind: KindUser, CreatedAt: time.Now().Add(-48 * time.Hour)}
_ = s.CreateNotes(nil, []*Note{old})
older, _ := s.LiveNotesOlderThan(time.Now().Add(-24 * time.Hour))
if len(older) != 1 || older[0].ID != "note-2" {
t.Fatalf("expected note-2, got %v", older)
}
}
-146
View File
@@ -1,146 +0,0 @@
package lnurlcash
import (
"context"
"testing"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
)
// Lookups ride pooled connections, but a mutation (mint invoice, split, melt)
// must always arrive on a connection of its own: net/http resends a GET on a
// reused connection, and a resent melt or split is a second burn.
func TestMutationsNeverShareAConnection(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
// a directly minted note, then reclaim it
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 1 {
t.Fatalf("create: %d %v", len(live), err)
}
if _, err := h.svc.Reclaim(ctx, live[0].ID); err != nil {
t.Fatal(err)
}
// a carved batch
qb, err := h.svc.Quote(ctx, mint, 100_000, 3)
if err != nil {
t.Fatal(err)
}
if _, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: qb}); err != nil || len(live) != 3 {
t.Fatalf("batch: %d %v", len(live), err)
}
// redeem an external whole-sat note and a fractional one (split + melt)
for _, value := range []int64{2000_000, 1000_900} {
k1, _ := lnurlcash.GenerateNoteSecret()
hh, _ := lnurlcash.HashK1(k1)
h.mint.mu.Lock()
h.mint.notes[hh] = value
h.mint.mu.Unlock()
prev, err := h.svc.RedeemInfo(ctx, "7", "en", lnurlcash.BuildNoteURL(h.mint.url()+"/w", k1, value))
if err != nil {
t.Fatal(err)
}
if _, err := h.svc.Redeem(ctx, prev.Redeem.ID, "7"); err != nil {
t.Fatal(err)
}
}
mutations, shared, anyReuse := h.mint.connStats()
// 2 mint invoices, 3 splits, 1 reclaim melt, 2 redeem melts, 1 redeem split
if mutations < 9 {
t.Fatalf("expected at least 9 mutations, saw %d", mutations)
}
if shared != 0 {
t.Fatalf("%d of %d mutations arrived on a connection that carried another request", shared, mutations)
}
if !anyReuse {
t.Fatal("lookups never reused a connection: the reader is not pooled")
}
}
// A reclaim asks the mint about the note once and melts it at the callback
// that answer names, instead of looking the note up a second time.
func TestReclaimLooksUpOnce(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
h.mint.mu.Lock()
h.mint.calls = map[string]int{}
h.mint.mu.Unlock()
if _, err := h.svc.Reclaim(ctx, live[0].ID); err != nil {
t.Fatal(err)
}
h.mint.mu.Lock()
defer h.mint.mu.Unlock()
if h.mint.calls["/w"] != 1 || h.mint.calls["/w/cb"] != 1 || len(h.mint.melts) != 1 {
t.Fatalf("reclaim made %d lookups and %d callback requests (%d melts); want 1 and 1", h.mint.calls["/w"], h.mint.calls["/w/cb"], len(h.mint.melts))
}
}
func TestAwaitSettlement(t *testing.T) {
old := settlePollMax
settlePollMax = 20 * time.Millisecond
t.Cleanup(func() { settlePollMax = old })
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
n, err := h.svc.Reclaim(ctx, live[0].ID)
if err != nil {
t.Fatal(err)
}
// not paid in time: nothing settles, the note stays reclaiming
if st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, 50*time.Millisecond); st != nil || err != nil {
t.Fatalf("unpaid invoice settled: %+v %v", st, err)
}
// paid while the watcher waits: it settles the reclaim
go func() {
time.Sleep(30 * time.Millisecond)
h.mint.finishMelt(n.Hash, true)
h.ledger.settleIncoming(n.InvoiceHash)
}()
st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, 2*time.Second)
if err != nil || st == nil || st.Note == nil || st.Note.State != NoteReclaimed {
t.Fatalf("watcher did not settle: %+v %v", st, err)
}
// the webhook arriving after the watcher (or the other way round) finds
// nothing left to do, so the user is told once
if st, err := h.svc.SettleInvoice(ctx, n.InvoiceHash); st != nil || err != nil {
t.Fatalf("second settlement reported again: %+v %v", st, err)
}
if st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, time.Second); st != nil || err != nil {
t.Fatalf("watcher after settlement reported again: %+v %v", st, err)
}
}
func TestPollDelay(t *testing.T) {
want := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 2 * time.Second}
for i, w := range want {
if got := pollDelay(2*time.Second, i); got != w {
t.Fatalf("poll %d: %s, want %s", i, got, w)
}
}
}
-120
View File
@@ -1,120 +0,0 @@
// Package netguard keeps outgoing connections for user-supplied URLs away from
// the bot's own host and network.
package netguard
import (
"context"
"fmt"
"net"
"net/netip"
"strconv"
"strings"
"syscall"
"time"
)
// Ranges that are not public but pass netip's own checks.
var reserved = []netip.Prefix{
netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT, overlay networks
netip.MustParsePrefix("198.18.0.0/15"), // benchmarking
netip.MustParsePrefix("240.0.0.0/4"), // reserved
netip.MustParsePrefix("64:ff9b::/96"), // NAT64, embeds an IPv4 address
netip.MustParsePrefix("2002::/16"), // 6to4, embeds an IPv4 address
}
// IsPublic reports whether ip is an address on the public internet.
func IsPublic(ip netip.Addr) bool {
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() {
return false
}
for _, prefix := range reserved {
if prefix.Contains(ip) {
return false
}
}
return true
}
// The check runs at connect time on the resolved address, so it also covers
// redirects and hostnames that resolve to an internal address.
var dialer = &net.Dialer{
Timeout: 10 * time.Second,
Control: func(_, address string, _ syscall.RawConn) error {
ap, err := netip.ParseAddrPort(address)
if err != nil {
return err
}
if !IsPublic(ap.Addr()) {
return fmt.Errorf("connection to non-public address %s refused", ap.Addr())
}
return nil
},
}
// trusted holds hostnames that may resolve to a non-public address: the
// bot's own LNURL and LNbits hosts often point at loopback through the hosts
// file or split DNS. Filled once at startup by Trust.
var trusted = map[string]bool{}
// Trust exempts hosts from the public address check.
func Trust(hosts ...string) {
for _, host := range hosts {
if host != "" {
trusted[normalizeHost(host)] = true
}
}
}
func normalizeHost(host string) string {
return strings.TrimSuffix(strings.ToLower(host), ".")
}
// isTrusted reports whether addr ("host:port") names a trusted host.
func isTrusted(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
return trusted[normalizeHost(host)]
}
var plainDialer = &net.Dialer{Timeout: 10 * time.Second}
// DialContext dials like net.Dialer, but only connects to public addresses,
// unless addr names a trusted host.
func DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
if isTrusted(addr) {
return plainDialer.DialContext(ctx, network, addr)
}
return dialer.DialContext(ctx, network, addr)
}
// CheckHost rejects addr ("host:port") when the host is a literal non-public
// IP or a localhost name. It does not resolve other hostnames, so use it only
// where the connection is made by a proxy and DialContext cannot be used.
func CheckHost(addr string) error {
if isTrusted(addr) {
return nil
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
host = normalizeHost(host)
if host == "localhost" || strings.HasSuffix(host, ".localhost") {
return fmt.Errorf("connection to %s refused", host)
}
if ip, err := netip.ParseAddr(host); err == nil {
if !IsPublic(ip) {
return fmt.Errorf("connection to non-public address %s refused", ip)
}
return nil
}
// Resolvers also accept IPv4 addresses written as 2130706433, 127.1 or
// 0x7f.1. No real hostname ends in a number.
if _, err := strconv.ParseUint(host[strings.LastIndex(host, ".")+1:], 0, 64); err == nil {
return fmt.Errorf("connection to numeric host %s refused", host)
}
return nil
}
-105
View File
@@ -1,105 +0,0 @@
package netguard
import (
"context"
"net"
"net/netip"
"testing"
)
func TestIsPublic(t *testing.T) {
for addr, want := range map[string]bool{
"1.1.1.1": true,
"2606:4700:4700::1111": true,
"127.0.0.1": false,
"::1": false,
"0.0.0.0": false,
"10.1.2.3": false,
"172.16.0.1": false,
"192.168.1.1": false,
"169.254.169.254": false,
"100.64.0.1": false,
"fe80::1": false,
"fd00::1": false,
"::ffff:127.0.0.1": false,
"::ffff:192.168.1.1": false,
"224.0.0.1": false,
"255.255.255.255": false,
"198.18.0.1": false,
"240.0.0.1": false,
"64:ff9b::7f00:1": false,
"2002:7f00:1::1": false,
} {
if got := IsPublic(netip.MustParseAddr(addr)); got != want {
t.Errorf("IsPublic(%s) = %v, want %v", addr, got, want)
}
}
}
func TestDialContextRefusesLoopback(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
conn, err := DialContext(context.Background(), "tcp", l.Addr().String())
if err == nil {
conn.Close()
t.Fatal("dial to loopback succeeded")
}
// a hostname that resolves to loopback is refused as well
_, port, _ := net.SplitHostPort(l.Addr().String())
if conn, err := DialContext(context.Background(), "tcp", "localhost:"+port); err == nil {
conn.Close()
t.Fatal("dial to localhost succeeded")
}
}
func TestCheckHost(t *testing.T) {
for addr, ok := range map[string]bool{
"example.com:443": true,
"abc.onion:80": true,
"1.1.1.1:443": true,
"localhost:6060": false,
"LOCALHOST.:6060": false,
"foo.localhost:80": false,
"127.0.0.1:6060": false,
"[::1]:6060": false,
"192.168.0.10:5000": false,
"0.0.0.0:80": false,
"2130706433:80": false,
"127.1:80": false,
"0x7f.1:80": false,
"0x7f000001:80": false,
"017700000001:80": false,
"example.com1:80": true,
"1.example.com:80": true,
} {
if err := CheckHost(addr); (err == nil) != ok {
t.Errorf("CheckHost(%s) = %v, want ok=%v", addr, err, ok)
}
}
}
func TestTrustedHostBypassesCheck(t *testing.T) {
defer func() { trusted = map[string]bool{} }()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
_, port, _ := net.SplitHostPort(l.Addr().String())
Trust("LocalHost.")
conn, err := DialContext(context.Background(), "tcp", "localhost:"+port)
if err != nil {
t.Fatalf("dial to trusted localhost refused: %v", err)
}
conn.Close()
if err := CheckHost("localhost:" + port); err != nil {
t.Errorf("CheckHost refused trusted host: %v", err)
}
if conn, err := DialContext(context.Background(), "tcp", l.Addr().String()); err == nil {
conn.Close()
t.Error("literal loopback address was accepted")
}
}
+1 -69
View File
@@ -10,7 +10,6 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
@@ -39,31 +38,9 @@ func GetClientForScheme(url *url.URL) (*http.Client, error) {
}
}
// directTransport returns the transport used when no proxy is configured. The
// URLs fetched with these clients come from users and remote servers, so it
// only connects to public addresses. Every client gets its own transport,
// because callers change its TLS settings (satdress.SetupHttpClient).
func directTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.DialContext = netguard.DialContext
return t
}
// The bot's own hosts may resolve to loopback (hosts file, split DNS). Paying
// a lightning address on them must keep working.
func init() {
if u := internal.Configuration.Bot.LNURLHostUrl; u != nil {
netguard.Trust(u.Hostname())
}
if u, err := url.Parse(internal.Configuration.Lnbits.Url); err == nil {
netguard.Trust(u.Hostname())
}
}
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
Transport: directTransport(),
Timeout: 10 * time.Second,
}
var cfg *internal.SocksConfiguration
switch clientType {
@@ -97,53 +74,8 @@ func GetClient(clientType ClientType) (*http.Client, error) {
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// The proxy resolves hostnames, so only literal addresses and
// localhost names can be refused here.
if err := netguard.CheckHost(addr); err != nil {
return nil, err
}
return d.Dial(network, addr)
}
client.Transport = specialTransport
return &client, nil
}
// NewNoKeepAliveClient returns a client for LNURLcash mints: the same proxy
// and netguard rules as GetClient, but keep-alives off and redirects refused,
// because every LNURLcash mutation is a non-idempotent GET that net/http
// would otherwise retry on a reused connection. Every mutation goes through a
// client like this one; only read-only lookups may use NewPooledClient.
func NewNoKeepAliveClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
client = &http.Client{Transport: directTransport()}
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = true
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
// NewPooledClient returns a client for read-only LNURLcash lookups (note info,
// payRequest): the same proxy, netguard and redirect rules as
// NewNoKeepAliveClient, but connections are kept and reused, which saves a TCP
// and TLS handshake per request. net/http may resend a request on a reused
// connection, which is harmless for a lookup and never acceptable for a
// mutation: NEVER send a split, melt, rotate, merge or mint invoice request
// through this client.
func NewPooledClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
client = &http.Client{Transport: directTransport()}
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = false
t.MaxIdleConnsPerHost = 4
t.IdleConnTimeout = 90 * time.Second
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
-56
View File
@@ -1,56 +0,0 @@
package nostr
import (
"fmt"
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/api"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/prometheus/common/log"
"gorm.io/gorm"
)
type Nostr struct {
database *gorm.DB
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Nostr {
return Nostr{
database: bot.DB.Users,
bot: bot,
}
}
func (n Nostr) Handle(writer http.ResponseWriter, request *http.Request) {
username := request.FormValue("name")
if username == "" {
api.NotFoundHandler(writer, fmt.Errorf("[NostrNip05] Form value 'name' is not set"))
return
}
user, tx := db.FindUser(n.database, username)
if tx.Error == nil && user.Telegram != nil {
user, err := db.FindUserSettings(user, n.bot.DB.Users.Preload("Settings"))
if err != nil {
log.Errorf("[NostrNip05] user settings not found")
api.NotFoundHandler(writer, fmt.Errorf("user settings error"))
return
}
if user.Settings.Nostr.PubKey != "" {
data := []byte(fmt.Sprintf(`{
"names":{
"%s":"%s"
}
}
`, username, user.Settings.Nostr.PubKey))
_, err = writer.Write(data)
if err != nil {
log.Errorf("[NostrNip05] Failed responding to user %s", username)
}
}
} else {
log.Errorf("[NostrNip05] user not found")
api.NotFoundHandler(writer, fmt.Errorf("user not found"))
}
}
+5 -24
View File
@@ -7,7 +7,6 @@ import (
"net/url"
"strconv"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
@@ -22,26 +21,10 @@ type PriceWatcher struct {
}
var (
// price is written by the watcher and read by every fiat amount, so it is
// only accessed through Get and set.
price = make(map[string]float64)
priceMu sync.RWMutex
P *PriceWatcher
Price map[string]float64
P *PriceWatcher
)
// Get returns the last known price of currency, or 0 if there is none.
func Get(currency string) float64 {
priceMu.RLock()
defer priceMu.RUnlock()
return price[currency]
}
func set(currency string, value float64) {
priceMu.Lock()
price[currency] = value
priceMu.Unlock()
}
func NewPriceWatcher() *PriceWatcher {
pricewatcher := &PriceWatcher{
client: &http.Client{
@@ -64,6 +47,7 @@ func NewPriceWatcher() *PriceWatcher {
}
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
Price = make(map[string]float64, 0)
log.Infof("[PriceWatcher] Watcher started")
P = pricewatcher
return pricewatcher
@@ -90,11 +74,8 @@ func (p *PriceWatcher) Watch() error {
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
time.Sleep(time.Second * time.Duration(2))
}
if n_responses == 0 {
// every exchange failed: keep the last known price
continue
}
set(currency, avg_price/float64(n_responses))
Price[currency] = avg_price / float64(n_responses)
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
}
time.Sleep(p.UpdateInterval)
}
-28
View File
@@ -1,28 +0,0 @@
package price
import (
"sync"
"testing"
)
// Run with -race: a reader and a writer must not race on the price map.
func TestPriceAccessIsRaceFree(t *testing.T) {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 2000; i++ {
set("USD", float64(i+1))
}
}()
go func() {
defer wg.Done()
for i := 0; i < 2000; i++ {
_ = Get("USD")
}
}()
wg.Wait()
if Get("USD") != 2000 || Get("none") != 0 {
t.Errorf("unexpected prices: %v %v", Get("USD"), Get("none"))
}
}
+25 -80
View File
@@ -5,127 +5,72 @@ import (
"time"
)
var functionMap cmap.ConcurrentMap
var tickerMap cmap.ConcurrentMap
func init() {
functionMap = cmap.New()
tickerMap = cmap.New()
}
var DefaultTickerDuration = time.Second * 10
var defaultTickerCoolDown = time.Second * 10
// ResettableFunction will reset the user state as soon as tick is delivered.
type ResettableFunction struct {
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type ResettableFunctionTicker struct {
Ticker *time.Ticker
Timer *time.Timer
ResetChan chan struct{} // channel used to reset the ticker
StopChan chan struct{} // channel used to reset the ticker
duration time.Duration
Started bool
name string
}
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
type ResettableFunctionTickerOption func(*ResettableFunction)
func WithTicker(t *time.Ticker) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Ticker = t
}
}
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
return func(a *ResettableFunctionTicker) {
a.duration = d
}
}
func WithTimer(t *time.Timer) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Timer = t
}
}
func RemoveTicker(name string) {
functionMap.Remove(name)
tickerMap.Remove(name)
}
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
func Get(name string) (*ResettableFunction, bool) {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction), ok
}
return nil, false
}
func GetFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction)
if t, ok := tickerMap.Get(name); ok {
return t.(*ResettableFunctionTicker)
} else {
t := NewResettableFunction(name, option...)
functionMap.Set(name, t)
t := NewResettableFunctionTicker(name, option...)
tickerMap.Set(name, t)
return t
}
}
func NewResettableFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
t := &ResettableFunction{
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
StopChan: make(chan struct{}, 1),
name: name,
}
if t.duration == 0 {
t.duration = DefaultTickerDuration
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
// Do will listen for timers and invoke functionCallback on tick.
func (t *ResettableFunction) Do(functionCallback func()) {
func (t *ResettableFunctionTicker) Do(f func()) {
t.Started = true
// persist function
functionMap.Set(t.name, t)
tickerMap.Set(t.name, t)
go func() {
for {
if t.Timer != nil {
// timer is set. checking event
select {
case <-t.Timer.C:
functionCallback()
return
default:
}
}
if t.Ticker != nil {
// ticker is set. checking event
select {
case <-t.Ticker.C:
// ticker delivered signal. do function functionCallback
functionCallback()
return
default:
}
}
// check stop and reset channels
select {
case <-t.StopChan:
if t.Timer != nil {
t.Timer.Stop()
}
if t.Ticker != nil {
t.Ticker.Stop()
}
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
return
case <-t.ResetChan:
// reset signal received. creating new ticker.
if t.Ticker != nil {
t.Ticker.Reset(t.duration)
}
if t.Timer != nil {
t.Timer.Reset(t.duration)
}
default:
break
t.Ticker = time.NewTicker(t.duration)
}
time.Sleep(time.Millisecond * 500)
}
}()
}
+37 -1
View File
@@ -30,7 +30,7 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request) {
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
m.(*entry).mu.Unlock()
m.(*sync.Mutex).Unlock()
w.Write([]byte(fmt.Sprintf("Unlocked mutex %s.\nCurrent number of locks: %d\nLocks: %+v",
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
return
@@ -103,3 +103,39 @@ func UnlockWithContext(ctx context.Context, s string) {
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(s, m)
mutexMapSync.Unlock()
} else {
m := &sync.Mutex{}
m.Lock()
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(s, m)
mutexMapSync.Unlock()
}
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks a mutex in the mutexMap.
func Unlock(s string) {
mutexMapSync.Lock()
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
} else {
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
}
mutexMapSync.Unlock()
}
-55
View File
@@ -1,55 +0,0 @@
package mutex
import (
"sync"
log "github.com/sirupsen/logrus"
)
// entry is one named lock. waiters counts the callers that hold or wait for
// it, so the entry is only removed from the map when the last of them unlocks.
type entry struct {
mu sync.Mutex
waiters int
}
// Lock locks the named mutex. Every step that looks at the map runs under
// mutexMapSync, so two callers that both arrive for a name that is not in the
// map yet end up with the same mutex instead of one each.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
mutexMapSync.Lock()
var e *entry
if v, ok := mutexMap.Get(s); ok {
e = v.(*entry)
} else {
e = &entry{}
mutexMap.Set(s, e)
}
e.waiters++
mutexMapSync.Unlock()
e.mu.Lock()
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks the named mutex. The entry stays in the map while another
// caller is still waiting for it, so a waiter never ends up holding a mutex
// that a later caller cannot see.
func Unlock(s string) {
mutexMapSync.Lock()
v, ok := mutexMap.Get(s)
if !ok {
mutexMapSync.Unlock()
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
return
}
e := v.(*entry)
e.waiters--
if e.waiters <= 0 {
mutexMap.Remove(s)
}
mutexMapSync.Unlock()
e.mu.Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
}
-82
View File
@@ -1,82 +0,0 @@
package mutex
import (
"context"
"sync"
"testing"
)
// TestLockIsExclusive runs many goroutines through Lock/Unlock on one name
// and checks that no two of them are inside the critical section at once.
// Run with -race.
func TestLockIsExclusive(t *testing.T) {
const n = 200
var wg sync.WaitGroup
var inside, maxInside, counter int
var check sync.Mutex
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
Lock("x")
check.Lock()
inside++
if inside > maxInside {
maxInside = inside
}
check.Unlock()
counter++ // unsynchronised on purpose: -race catches a broken lock
check.Lock()
inside--
check.Unlock()
Unlock("x")
}()
}
wg.Wait()
if maxInside != 1 {
t.Fatalf("%d goroutines held the lock at once", maxInside)
}
if counter != n {
t.Fatalf("counter = %d, want %d", counter, n)
}
if !IsEmpty() {
t.Fatalf("mutex map not empty after all unlocks: %v", mutexMap.Keys())
}
}
// TestLockWithContextIsExclusive does the same through the context variant
// every handler uses, each goroutine with its own request uid.
func TestLockWithContextIsExclusive(t *testing.T) {
const n = 200
var wg sync.WaitGroup
var counter int
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
ctx := context.WithValue(context.Background(), "uid", "uid-"+string(rune('a'+i%26))+string(rune('a'+i/26)))
LockWithContext(ctx, "obj")
counter++
UnlockWithContext(ctx, "obj")
}(i)
}
wg.Wait()
if counter != n {
t.Fatalf("counter = %d, want %d", counter, n)
}
if !IsEmpty() {
t.Fatalf("mutex map not empty after all unlocks: %v", mutexMap.Keys())
}
}
// TestUnlockUnknownDoesNotPanic covers the admin "unlock anything" path and a
// double unlock.
func TestUnlockUnknownDoesNotPanic(t *testing.T) {
Unlock("never-locked")
Lock("y")
Unlock("y")
Unlock("y")
if !IsEmpty() {
t.Fatalf("mutex map not empty: %v", mutexMap.Keys())
}
}
+3 -4
View File
@@ -5,14 +5,13 @@ import (
"time"
)
// todo -- use function.go instead!
// var retryMap cmap.ConcurrentMap
// func init() {
// retryMap = cmap.New()
// }
// ResettableFunction will reset the user state as soon as tick is delivered.
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type FunctionRetry struct {
Ticker *time.Ticker
duration time.Duration
@@ -36,14 +35,14 @@ func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOpt
opt(t)
}
if t.duration == 0 {
t.duration = DefaultTickerDuration
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
functionMap.Set(t.name, t)
tickerMap.Set(t.name, t)
go func() {
for {
select {
+21 -15
View File
@@ -16,6 +16,7 @@ import (
"net/http"
"net/url"
"strings"
"time"
)
// Much of this is from github.com/fiatjaf/makeinvoice
@@ -29,6 +30,7 @@ type LNDParams struct {
}
func (l LNDParams) getCert() []byte { return l.Cert }
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type LNBitsParams struct {
@@ -39,10 +41,12 @@ type LNBitsParams struct {
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
type BackendParams interface {
getCert() []byte
isTor() bool
isLocal() bool
}
type Params struct {
@@ -61,17 +65,19 @@ type CheckInvoiceParams struct {
Status string
}
// SetupHttpClient returns the client for a user-supplied node. The host comes
// from a Telegram user, so it always goes through network.GetClient: that
// refuses non-public addresses (netguard) and uses the Tor proxy when one is
// configured. There is deliberately no exemption for local hosts.
func SetupHttpClient(cert []byte) (*http.Client, error) {
client, err := network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
if client.Transport == nil {
client.Transport = http.DefaultTransport.(*http.Transport).Clone()
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
var client *http.Client
if !useProxy {
client = &http.Client{
Timeout: 10 * time.Second,
}
} else {
var err error
client, err = network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
}
// use a cert or skip TLS verification?
if len(cert) > 0 {
@@ -97,9 +103,9 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(params.Backend.getCert())
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
log.Errorf(err.Error())
return CheckInvoiceParams{}, err
}
@@ -233,9 +239,9 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(params.Backend.getCert())
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
log.Errorf(err.Error())
return CheckInvoiceParams{}, err
}
-32
View File
@@ -1,32 +0,0 @@
package satdress
import (
"net/http"
"net/http/httptest"
"testing"
)
// A node host chosen by a Telegram user must never reach loopback or private
// addresses, whatever the host string starts with.
func TestSetupHttpClientRefusesNonPublicHosts(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("request reached the loopback server: %s", r.URL)
}))
defer srv.Close()
client, err := SetupHttpClient(nil)
if err != nil {
t.Fatal(err)
}
for _, host := range []string{
srv.URL, // https://127.0.0.1:port, the old "local" prefix
"https://127.0.0.1:1@" + srv.Listener.Addr().String(),
"https://127.0.0.1@10.0.0.5",
"https://localhost:" + srv.URL[len("https://127.0.0.1:"):],
} {
if resp, err := client.Get(host); err == nil {
resp.Body.Close()
t.Errorf("%s was reachable", host)
}
}
}
-2
View File
@@ -2,7 +2,6 @@ package storage
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
@@ -57,7 +56,6 @@ func (db *DB) Get(object Storable) error {
}
err = json.Unmarshal([]byte(val), object)
if err != nil {
fmt.Println(err)
return err
}
return nil
+10 -53
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
@@ -22,12 +21,6 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// amountsMap maps string to int64 amounts
var amountsMap = map[string]int64{
"🍌": 777,
"🥜": 69,
}
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", fmt.Errorf("message doesn't contain enough arguments")
@@ -40,58 +33,27 @@ func decodeAmountFromCommand(input string) (amount int64, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, fmt.Errorf("%s", errmsg)
return 0, fmt.Errorf(errmsg)
}
amount, err = GetAmount(strings.Split(input, " ")[1])
return amount, err
}
// maxAmountSat is the largest amount a single command may name. The bot is a
// tip bot; anything above this is a typo or an attack on a conversion path.
const maxAmountSat int64 = 10_000_000
// checkAmount rejects amounts that must never reach a money path: results of
// a float conversion that are not a number, non-positive amounts and amounts
// above maxAmountSat.
func checkAmount(fmount float64, amount int64) (int64, error) {
if math.IsNaN(fmount) || math.IsInf(fmount, 0) {
return 0, fmt.Errorf("amount is not a number")
}
if amount <= 0 {
return 0, fmt.Errorf("amount must be greater than 0")
}
if amount > maxAmountSat {
return 0, fmt.Errorf("amount must not be greater than %d sat", maxAmountSat)
}
return amount, nil
}
// GetAmount parses an amount from a string like 1.2k or 3.50€
// and returns the value in satoshis
func GetAmount(input string) (amount int64, err error) {
// replace occurances of comma with dot
input = strings.Replace(input, ",", ".", -1)
// replace strings in amountsMap with their integer values
for k, v := range amountsMap {
input = strings.Replace(input, k, strconv.FormatInt(v, 10), -1)
}
// convert something like 1.2k into 1200
if strings.HasSuffix(strings.ToLower(input), "k") {
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
if err != nil {
return 0, err
}
return checkAmount(fmount, int64(fmount*1000))
amount = int64(fmount * 1000)
return amount, err
}
// convert fiat currencies to satoshis
var currencies map[string]string
if price.P != nil {
currencies = price.P.Currencies
}
for currency, symbol := range currencies {
for currency, symbol := range price.P.Currencies {
if strings.HasPrefix(input, symbol) || strings.HasSuffix(input, symbol) || // for 1$ and $1
strings.HasPrefix(strings.ToLower(input), strings.ToLower(currency)) || // for USD1
strings.HasSuffix(strings.ToLower(input), strings.ToLower(currency)) { // for 1USD
@@ -103,11 +65,11 @@ func GetAmount(input string) (amount int64, err error) {
log.Errorln(err)
return 0, err
}
if !(price.Get(currency) > 0) {
if !(price.Price[currency] > 0) {
return 0, fmt.Errorf("price is zero")
}
sats := fmount / price.Get(currency) * float64(100_000_000)
return checkAmount(sats, int64(sats))
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
return amount, nil
}
}
@@ -116,15 +78,10 @@ func GetAmount(input string) (amount int64, err error) {
if err != nil {
return 0, err
}
return checkAmount(float64(amount), amount)
}
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
if !(price.Get(currency) > 0) {
return 0, fmt.Errorf("price is zero")
if amount <= 0 {
return 0, fmt.Errorf("amount must be greater than 0")
}
fiat = float64(amount) / 100_000_000 * price.Get(currency)
return fiat, nil
return amount, err
}
type EnterAmountStateData struct {
-55
View File
@@ -1,55 +0,0 @@
package telegram
import (
"math"
"testing"
)
func TestCheckAmount(t *testing.T) {
good := []int64{1, 21, 1000, maxAmountSat}
for _, a := range good {
if got, err := checkAmount(float64(a), a); err != nil || got != a {
t.Errorf("checkAmount(%d) = %d, %v", a, got, err)
}
}
bad := []struct {
name string
f float64
a int64
}{
{"zero", 0, 0},
{"negative", -5, -5},
{"above max", float64(maxAmountSat + 1), maxAmountSat + 1},
{"nan", math.NaN(), 0},
{"+inf", math.Inf(1), math.MaxInt64},
{"-inf", math.Inf(-1), math.MinInt64},
}
for _, c := range bad {
if got, err := checkAmount(c.f, c.a); err == nil || got != 0 {
t.Errorf("%s: accepted: got %d, err %v", c.name, got, err)
}
}
}
// TestGetAmount covers the integer and "k" branches; the fiat branch needs a
// live price feed.
func TestGetAmount(t *testing.T) {
cases := map[string]int64{
"21": 21,
"1k": 1000,
"1.5k": 1500,
"1,5k": 1500,
"10000k": maxAmountSat,
}
for in, want := range cases {
if got, err := GetAmount(in); err != nil || got != want {
t.Errorf("GetAmount(%q) = %d, %v; want %d", in, got, err, want)
}
}
rejected := []string{"0", "-1", "-1k", "0k", "NaNk", "Infk", "10001k", "99999999999", "abc", ""}
for _, in := range rejected {
if got, err := GetAmount(in); err == nil {
t.Errorf("GetAmount(%q) accepted with %d", in, got)
}
}
}
-9
View File
@@ -16,7 +16,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
@@ -31,9 +30,6 @@ type TipBot struct {
Client *lnbits.Client
limiter map[string]limiter.Limiter
Cache
// LNURLCash is nil unless the lnurlcash feature is enabled.
LNURLCash *lnurlcash.Service
lnurlcashJobs *lnurlcash.Jobs
}
type Cache struct {
*store.GoCacheStore
@@ -120,9 +116,6 @@ func (bot *TipBot) Start() {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
// LNURLcash notes (optional feature)
bot.initLNURLCash()
// register telegram handlers
bot.registerTelegramHandlers()
@@ -142,8 +135,6 @@ func (bot *TipBot) Start() {
// start the telegram bot
go bot.Telegram.Start()
go bot.restartPersistedTickets()
bot.startLNURLCashJobs()
// gracefully shutdown
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
// we need to catch SIGTERM and SIGSTOP
+3 -5
View File
@@ -19,7 +19,7 @@ const (
// MainMenuCommandHelp = "📖 Help"
// MainMenuCommandSend = "⤴️ Send"
// SendMenuCommandEnter = "👤 Enter"
MainMenuCommandWebApp = "🗳️ App"
MainMenuCommandWebApp = "⤵️"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
@@ -44,8 +44,7 @@ func init() {
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
@@ -107,8 +106,7 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
}
-104
View File
@@ -1,104 +0,0 @@
package telegram
import (
"context"
"regexp"
"sort"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
)
// commandWordRx is what telebot (and Telegram) accept as a command: ASCII
// letters, digits and underscores. A translated word with other characters
// could never be typed as a command, so it gets no alias.
var commandWordRx = regexp.MustCompile(`^[a-z0-9_]+$`)
// faucetAliases and tipjarAliases map each translated command word, taken
// from the translation files, to the language it belongs to. The English
// word is not in the map: English is the default language.
var (
faucetAliases = loadCommandAliases("faucet", "faucetCommandStr")
tipjarAliases = loadCommandAliases("tipjar", "tipjarCommandStr")
)
func loadCommandAliases(english, messageID string) map[string]string {
aliases := map[string]string{}
for _, lang := range i18n.Languages {
word, err := i18n2.NewLocalizer(i18n.Bundle, lang).Localize(&i18n2.LocalizeConfig{MessageID: messageID})
if err != nil {
continue
}
word = strings.ToLower(strings.TrimSpace(word))
if word == english {
continue
}
if !commandWordRx.MatchString(word) {
log.Debugf("[commandAliases] %s %s %q is not a valid command, skipping", lang, messageID, word)
continue
}
if _, taken := aliases[word]; taken {
// languages share the word; the first one in i18n.Languages wins
continue
}
aliases[word] = lang
}
return aliases
}
// commandEndpoints returns the English command followed by every alias,
// each with a leading slash, in a stable order.
func commandEndpoints(english string, aliases map[string]string) []interface{} {
words := make([]string, 0, len(aliases))
for word := range aliases {
words = append(words, word)
}
sort.Strings(words)
endpoints := []interface{}{"/" + english}
for _, word := range words {
endpoints = append(endpoints, "/"+word)
}
return endpoints
}
// commandWord normalizes the first word of a command or inline query:
// no leading slash, no @botname, lower case.
func commandWord(text string) string {
fields := strings.Fields(text)
if len(fields) == 0 {
return ""
}
word := strings.TrimPrefix(fields[0], "/")
if i := strings.Index(word, "@"); i >= 0 {
word = word[:i]
}
return strings.ToLower(word)
}
// isCommand reports whether word is the English command or one of its aliases.
func isCommand(word, english string, aliases map[string]string) bool {
if word == english {
return true
}
_, ok := aliases[word]
return ok
}
// commandTranslationMap sets the public language to the language of a
// translated command, so that a faucet or tipjar created with /zapfhahn is
// posted in German no matter which language the creator uses.
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
word := commandWord(command)
lang, ok := faucetAliases[word]
if !ok {
lang, ok = tipjarAliases[word]
}
if !ok {
return ctx
}
ctx = context.WithValue(ctx, "publicLanguageCode", lang)
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, lang))
return ctx
}
-78
View File
@@ -1,78 +0,0 @@
package telegram
import (
"context"
"testing"
)
func TestCommandAliasesFromTranslations(t *testing.T) {
wantFaucet := map[string]string{
"zapfhahn": "de", "kraan": "nl", "grifo": "es", "kran": "pl",
"hana": "fi", "keran": "id", "torneira": "pt-br", "distribuzione": "it",
}
wantTipjar := map[string]string{
"spendendose": "de", "donatiebox": "nl", "tippikulho": "fi",
"salvadanaio": "it", "cofrinho": "pt-br",
}
for name, c := range map[string]struct{ got, want map[string]string }{
"faucet": {faucetAliases, wantFaucet},
"tipjar": {tipjarAliases, wantTipjar},
} {
if len(c.got) != len(c.want) {
t.Errorf("%s aliases = %v, want %v", name, c.got, c.want)
}
for word, lang := range c.want {
if c.got[word] != lang {
t.Errorf("%s alias %q = %q, want %q", name, word, c.got[word], lang)
}
}
}
// words Telegram cannot send as a command get no alias
for _, word := range []string{"fıçı", "alcancía", "bağışkutusu"} {
if _, ok := faucetAliases[word]; ok {
t.Errorf("faucet alias %q should be skipped", word)
}
if _, ok := tipjarAliases[word]; ok {
t.Errorf("tipjar alias %q should be skipped", word)
}
}
}
func TestCommandTranslationMap(t *testing.T) {
for text, want := range map[string]string{
"/kran 100 10": "pl",
"/Kran@LightningTipBot 100 10": "pl",
"zapfhahn 100 10": "de",
"/spendendose 100 10": "de",
"/faucet 100 10": "",
"/send 100": "",
} {
ctx := TipBot{}.commandTranslationMap(context.Background(), text)
got, _ := ctx.Value("publicLanguageCode").(string)
if got != want {
t.Errorf("%q: language %q, want %q", text, got, want)
}
}
}
// an alias must not take over a command that another handler already owns
func TestCommandAliasesDoNotCollide(t *testing.T) {
seen := map[string]int{}
for i, h := range (TipBot{}).getHandler() {
for _, e := range h.Endpoints {
s, ok := e.(string)
if !ok {
continue
}
if j, dup := seen[s]; dup && j != i {
t.Errorf("endpoint %q is registered by handlers %d and %d", s, j, i)
}
seen[s] = i
}
}
for _, word := range []string{"/kran", "/hana", "/cofrinho"} {
if _, ok := seen[word]; !ok {
t.Errorf("%s is not registered", word)
}
}
}
+2 -61
View File
@@ -11,14 +11,12 @@ import (
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
@@ -34,34 +32,21 @@ type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
Groups *gorm.DB
// LNURLCash is nil when the feature is disabled.
LNURLCash *lnurlcash.Store
}
const (
JoinTicketIndex = "join-ticket:*"
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
)
func createBunt(file string) *storage.DB {
t1 := time.Now()
// create bunt database
bunt := storage.NewBunt(file)
log.Infof("[blunt] loaded file in %s", time.Since(t1))
// create bunt database index for ascending (searching) TipTooltips
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
log.Infof("[blunt] index 1 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
err = bunt.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString)
log.Infof("[blunt] index 2 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
log.Infof("[blunt] total time: %s", time.Since(t1))
return bunt
}
@@ -139,19 +124,10 @@ func AutoMigration() *Databases {
panic(err)
}
var cashStore *lnurlcash.Store
if internal.Configuration.LNURLCash.Enabled {
cashStore, err = lnurlcash.Open(internal.Configuration.Database.LNURLCashPath)
if err != nil {
panic(err)
}
}
return &Databases{
Users: orm,
Transactions: txLogger,
Groups: groupsDb,
LNURLCash: cashStore,
}
}
@@ -275,21 +251,6 @@ func debugStack() {
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.UpdatedAt = time.Now()
// The ban state (banned flag and the "banned_" admin key) always comes from
// the database row. Callers may hold an old copy of the user, for example
// an invoice event or inline object stored before a ban, and saving it must
// not lift the ban. Only UpdateUserBan changes these two columns.
keepBanState := false
if user.Name != "" && user.Wallet != nil && user.Wallet.ID != "" {
freshUser := &lnbits.User{Name: user.Name}
if tx := bot.DB.Users.First(freshUser); tx.Error == nil && freshUser.Wallet != nil &&
freshUser.Wallet.ID == user.Wallet.ID && freshUser.Wallet.Adminkey != "" {
user.Wallet.Adminkey = freshUser.Wallet.Adminkey
user.Banned = freshUser.Banned
keepBanState = true
}
}
// There is a weird bug that makes the AnonID vanish. This is a workaround.
// TODO -- Remove this after empty anon id bug is identified
if user.AnonIDSha256 == "" {
@@ -310,12 +271,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
db := bot.DB.Users
if keepBanState {
// leave the columns out, so a ban written since the read above stays
db = db.Omit("banned", "wallet_adminkey")
}
tx := db.Save(user)
tx := bot.DB.Users.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
@@ -327,18 +283,3 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
}
return nil
}
// UpdateUserBan writes the ban state of the user (banned flag and admin key)
// to the database. UpdateUserRecord never changes these two columns for a
// user that already has a wallet.
func UpdateUserBan(user *lnbits.User, bot TipBot) error {
tx := bot.DB.Users.Model(&lnbits.User{}).Where("name = ?", user.Name).
Updates(map[string]interface{}{"banned": user.Banned, "wallet_adminkey": user.Wallet.Adminkey})
if tx.Error != nil {
return tx.Error
}
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
return nil
}
+4 -33
View File
@@ -2,14 +2,10 @@ package telegram
import (
"context"
"encoding/json"
"fmt"
"github.com/fiatjaf/go-lnurl"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
@@ -55,24 +51,11 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return ctx, err
}
amount = amount * 1000
// command is valid
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
// get invoice
r, err := http.NewRequest(http.MethodGet, donationEndpoint, nil)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// Create query parameters
params := url.Values{}
params.Set("amount", strconv.FormatInt(amount, 10))
params.Set("comment", fmt.Sprintf("from %s bot %s", GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
// Set the query parameters in the URL
r.URL.RawQuery = params.Encode()
resp, err := http.DefaultClient.Do(r)
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
@@ -84,23 +67,11 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
pv := lnurl.LNURLPayValues{}
err = json.Unmarshal(body, &pv)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
if pv.Status == "ERROR" || len(pv.PR) < 1 {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// send donation invoice
// user := LoadUser(ctx)
// bot.trySendMessage(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(pv.PR)}, bot.Client)
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
if err != nil {
userStr := GetUserStr(user.Telegram)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
@@ -118,7 +89,7 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/.jryy-xabja/yaheyc/YvtugavatGvcObg")})
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
+4 -11
View File
@@ -53,10 +53,6 @@ func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context
return ctx
}
// maxFaucetSlots bounds how many users one faucet can pay out to. Every slot
// is a message edit and an LNbits transfer.
const maxFaucetSlots = 1000
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
amount, err := decodeAmountFromCommand(text)
if err != nil {
@@ -70,13 +66,10 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 1 || amount%perUserAmount != 0 {
if perUserAmount < 5 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := int(amount / perUserAmount)
if nTotal > maxFaucetSlots {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("faucet has too many slots (%d > %d)", nTotal, maxFaucetSlots))
}
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(sender)
balance, err := bot.GetUserBalanceCached(fromUser)
@@ -165,7 +158,7 @@ func (bot TipBot) makeQueryFaucet(ctx intercept.Context) (*InlineFaucet, error)
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf("%s", err.Error())
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
@@ -264,7 +257,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
from := inlineFaucet.From
// failsafe for queued users
if !inlineFaucet.Active {
log.Tracef("%s", fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
log.Tracef(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
bot.finishFaucet(ctx, c, inlineFaucet)
return ctx, errors.Create(errors.NotActiveError)
}
@@ -358,7 +351,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
log.Debugf("%s", fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
// faucet is depleted
bot.finishFaucet(ctx, c, inlineFaucet)
}
+1 -2
View File
@@ -5,7 +5,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
"time"
)
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
@@ -17,7 +16,7 @@ func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error)
if c := stateCallbackMessage[user.StateKey]; c != nil {
// found ctx for this state
// now looking for user state reset ticker
ticker := runtime.GetFunction(user.ID, runtime.WithTicker(time.NewTicker(runtime.DefaultTickerDuration)))
ticker := runtime.GetTicker(user.ID)
if !ticker.Started {
ticker.Do(func() {
ResetUserState(user, bot)
+1 -1
View File
@@ -65,7 +65,7 @@ func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Conte
if err != nil {
return ctx, err
}
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), "", InvoiceCallbackGenerateDalle, prompt)
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", GetUserStr(user.Telegram)), InvoiceCallbackGenerateDalle, prompt)
invoice.Payer = user
if err != nil {
return ctx, err
+26 -175
View File
@@ -5,9 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
@@ -24,33 +22,6 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type JoinTicket struct {
Sender *tb.User `json:"sender"`
Message *tb.Message `json:"message"`
CreatedTimestamp time.Time `json:"created_timestamp"`
Ticket *Ticket `json:"ticket"`
// PaymentHash of the ticket invoice. Empty for tickets stored by older
// versions of the bot.
PaymentHash string `json:"payment_hash,omitempty"`
}
func (jt JoinTicket) Key() string {
return fmt.Sprintf("join-ticket:%d_%d", jt.Message.Chat.ID, jt.Sender.ID)
}
func (jt JoinTicket) Type() EventType {
return EventTypeTicketInvoice
}
func (bot *TipBot) loadGroup(groupName string) (*Group, error) {
group := &Group{}
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
if tx.Error != nil {
return nil, tx.Error
}
return group, nil
}
type Ticket struct {
Price int64 `json:"price"`
Memo string `json:"memo"`
@@ -112,9 +83,8 @@ var (
btnPayTicket = paymentConfirmationMenu.Data("✅ Pay", "pay_ticket")
)
const (
groupInvoiceMemo = "🎟 Ticket for group %s"
groupInvoiceCommissionMemo = "🎟 Commission for group %s"
var (
groupInvoiceMemo = "🎟 Ticket for group %s"
)
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
@@ -122,18 +92,15 @@ const (
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
// user := LoadUser(ctx)
user := LoadUser(ctx)
if len(splits) == 1 {
// command: /group
if ctx.Message().Private() {
// /group help message
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "groupHelpMessage"), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me)))
} else {
if bot.isOwner(ctx.Message().Chat, user.Telegram) {
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
}
}
// else {
// if bot.isOwner(ctx.Message().Chat, user.Telegram) {
// bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
// }
// }
return ctx, nil
} else if len(splits) > 1 {
if splits[1] == "join" {
@@ -142,9 +109,6 @@ func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error)
if splits[1] == "add" {
return bot.addGroupHandler(ctx)
}
if splits[1] == "ticket" {
return bot.handleJoinTicketPayWall(ctx)
}
if splits[1] == "remove" {
// todo -- implement this
// return bot.addGroupHandler(ctx, m)
@@ -181,10 +145,8 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
return ctx, fmt.Errorf("group not found")
}
// create tickets. The id is per group and payer: with a per-group id a
// later /join overwrote the stored payer and the invite link went to
// whoever joined last, not to whoever paid.
id := fmt.Sprintf("ticket:%d:%d", group.ID, user.Telegram.ID)
// create tickets
id := fmt.Sprintf("ticket:%d", group.ID)
invoiceEvent := &InvoiceEvent{
Base: storage.New(storage.ID(id)),
User: group.Ticket.Creator,
@@ -251,11 +213,6 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
// pay button is sent to the user.
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
confirmText, confirmationMenu := bot.getSendPayButton(ctx, ticket)
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, confirmationMenu)
return ctx, nil
}
func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (string, *tb.ReplyMarkup) {
// object that holds all information about the send payment
// // // create inline buttons
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
@@ -264,10 +221,11 @@ func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (
btnPayTicket),
)
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), ticket.Group.Ticket.Price)
// if len(ticket.Group.Ticket.Memo) > 0 {
// confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
// }
return confirmText, ticketPayConfirmationMenu
if len(ticket.Group.Ticket.Memo) > 0 {
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
}
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, ticketPayConfirmationMenu)
return ctx, nil
}
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
@@ -307,19 +265,14 @@ func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercep
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: ticketEvent.Invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
err = fmt.Errorf("%s", i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
if ticketEvent.Callback != InvoiceCallbackPayJoinTicket {
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
}
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
log.Errorln(errmsg)
return ctx, err
}
// the invoice is paid, a second press must not pay it again
ticketEvent.Active = false
// update the message and remove the button
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
return ctx, nil
}
@@ -329,7 +282,7 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
// take a cut
// amount_bot := int64(ticketEvent.Group.Ticket.Price * int64(ticketEvent.Group.Ticket.Cut) / 100)
log.Infof("%s", invoiceEvent.CallbackData)
log.Infof(invoiceEvent.CallbackData)
ticketEvent := &TicketEvent{Base: storage.New(storage.ID(invoiceEvent.CallbackData))}
err := bot.Bunt.Get(ticketEvent)
if err != nil {
@@ -375,12 +328,19 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
// take a commission
ticketSat := ticketEvent.Group.Ticket.Price
if commissionSat := getTicketCommission(ticketEvent.Group.Ticket); commissionSat > 0 {
if ticketEvent.Group.Ticket.Price > 20 {
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
log.Errorf("[groupGetInviteLinkHandler] Could not get bot user from DB: %s", err.Error())
return
}
// 2% cut + 100 sat base fee
commissionSat := ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.Cut/100 + ticketEvent.Group.Ticket.BaseFee
if ticketEvent.Group.Ticket.Price <= 1000 {
// if < 1000, then 10% cut + 10 sat base fee
commissionSat = ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.CutCheap/100 + ticketEvent.Group.Ticket.BaseFeeCheap
}
ticketSat = ticketEvent.Group.Ticket.Price - commissionSat
invoice, err := me.Wallet.Invoice(
lnbits.InvoiceParams{
@@ -412,115 +372,6 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
}
}
func (bot TipBot) handleJoinTicketPayWall(ctx intercept.Context) (intercept.Context, error) {
var err error
var cmd string
if cmd, err = getArgumentFromCommand(ctx.Message().Text, 2); err == nil {
switch strings.TrimSpace(strings.ToLower(cmd)) {
case "del":
fallthrough
case "delete":
fallthrough
case "remove":
return bot.removeJoinTicketPayWallHandler(ctx)
default:
return bot.addJoinTicketPayWallHandler(ctx)
}
}
return ctx, err
}
func (bot TipBot) removeJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type == tb.ChatPrivate {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, fmt.Errorf("not in group")
}
// only the creator of the chat may remove its registration
user := LoadUser(ctx)
if !bot.isOwner(m.Chat, user.Telegram) {
return ctx, fmt.Errorf("not owner")
}
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).Delete(&Group{})
if tx.Error != nil {
return ctx, tx.Error
}
bot.trySendMessage(ctx.Message().Chat, "🎟 Ticket removed.")
return ctx, nil
}
// addJoinTicketPayWallHandler is invoked if the user calls the "/group ticket" command
func (bot TipBot) addJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type == tb.ChatPrivate {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, fmt.Errorf("not in group")
}
// parse command "/group ticket <grou_name> [<amount>]"
splits := strings.Split(m.Text, " ")
if len(splits) < 3 || len(m.Text) > 100 {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, nil
}
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
user := LoadUser(ctx)
// check if the user is the owner of the group
if !bot.isOwner(m.Chat, user.Telegram) {
return ctx, fmt.Errorf("not owner")
}
if !bot.isAdminAndCanInviteUsers(m.Chat, bot.Telegram.Me) {
bot.trySendMessage(m.Chat, Translate(ctx, "groupBotIsNotAdminMessage"))
return ctx, fmt.Errorf("bot is not admin")
}
// check if the group with this name is already in db
// only if a group with this name is owned by this user, it can be overwritten
group := &Group{}
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
if tx.Error == nil {
// if it is already added, check if this user is the admin
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
return ctx, fmt.Errorf("not owner")
}
}
amount := int64(0) // default amount is zero
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = GetAmount(amount_str)
if err != nil {
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
return ctx, err
}
}
ticket := &Ticket{
Price: amount,
Memo: "Ticket for group " + groupName,
Creator: user,
Cut: 2,
BaseFee: 100,
CutCheap: 10,
BaseFeeCheap: 10,
}
group = &Group{
Name: groupName,
Title: m.Chat.Title,
ID: m.Chat.ID,
Owner: user.Telegram,
Ticket: ticket,
}
bot.DB.Groups.Save(group)
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddedMessagePublic"))
return ctx, nil
}
// addGroupHandler is invoked if the user calls the "/group add" command
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
@@ -588,7 +439,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
bot.DB.Groups.Save(group)
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessagePrivate"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
return ctx, nil
}
+35 -410
View File
@@ -28,7 +28,7 @@ func (bot TipBot) registerTelegramHandlers() {
}
func getDefaultBeforeInterceptor(bot TipBot) []intercept.Func {
return []intercept.Func{bot.idInterceptor, bot.rejectPlaceholderSenderInterceptor}
return []intercept.Func{bot.idInterceptor}
}
func getDefaultDeferInterceptor(bot TipBot) []intercept.Func {
return []intercept.Func{bot.unlockInterceptor}
@@ -84,333 +84,6 @@ func (bot TipBot) register(h InterceptionWrapper) {
// getHandler returns a list of all handlers, that need to be registered with Telegram
func (bot TipBot) getHandler() []InterceptionWrapper {
return []InterceptionWrapper{
// LNURLcash notes (docs/lnurlcash)
{
Endpoints: []interface{}{"/lnurlhelp", "/notehelp"},
Handler: bot.lnurlHelpHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
},
},
},
{
Endpoints: []interface{}{"/note"},
Handler: bot.noteHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/notes"},
Handler: bot.notesHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/redeem"},
Handler: bot.redeemHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/lnurlmints"},
Handler: bot.lnurlmintsHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteCreate},
Handler: bot.noteCreateHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteMint},
Handler: bot.noteMintHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteCancel},
Handler: bot.noteCancelHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteStatus},
Handler: bot.noteStatusHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteReclaim},
Handler: bot.noteReclaimHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNoteQR},
Handler: bot.noteQRHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNotesPage},
Handler: bot.notesPageHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNotesOpen},
Handler: bot.notesOpenHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnNotesOpenB},
Handler: bot.notesOpenBatchHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnBatchExportPDF},
Handler: bot.batchExportHandler("pdf"),
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnBatchExportJSON},
Handler: bot.batchExportHandler("json"),
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnBatchExportCSV},
Handler: bot.batchExportHandler("csv"),
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnBatchRefresh},
Handler: bot.batchRefreshHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnBatchReclaim},
Handler: bot.batchReclaimHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnSetMint},
Handler: bot.setMintHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnRedeemOK},
Handler: bot.redeemConfirmHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnRedeemCancel},
Handler: bot.redeemCancelHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/start"},
Handler: bot.startHandler,
@@ -426,24 +99,24 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// {
// Endpoints: []interface{}{"/generate"},
// Handler: bot.generateImages,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.requirePrivateChatInterceptor,
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.loadUserInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/tip", "/t", "/honk", "/zap"},
Endpoints: []interface{}{"/generate"},
Handler: bot.generateImages,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/tip", "/t", "/honk"},
Handler: bot.tipHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -491,38 +164,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
{
Endpoints: []interface{}{"/set"},
Handler: bot.settingHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/nostr"},
Handler: bot.nostrHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/node"},
Handler: bot.nodeHandler,
@@ -586,22 +227,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
bot.unlockInterceptor,
}},
},
// {
// Endpoints: []interface{}{"/gpt", "/chat"},
// Handler: bot.gptHandler,
// Interceptor: &Interceptor{
{
Endpoints: []interface{}{"/gpt", "/chat"},
Handler: bot.gptHandler,
Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.requireUserInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/balance", &btnBalanceMainMenu},
Handler: bot.balanceHandler,
@@ -716,7 +357,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
{
Endpoints: commandEndpoints("faucet", faucetAliases),
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
Handler: bot.faucetHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -731,7 +372,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
{
Endpoints: commandEndpoints("tipjar", tipjarAliases),
Endpoints: []interface{}{"/tipjar", "/spendendose"},
Handler: bot.tipjarHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -856,22 +497,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// group join
{
Endpoints: []interface{}{tb.OnUserJoined, tb.OnAddedToGroup},
Handler: bot.handleTelegramNewMember,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.tryLoadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
// group tickets
{
Endpoints: []interface{}{"/group"},
+24 -3
View File
@@ -1,6 +1,7 @@
package telegram
import (
"context"
"fmt"
"reflect"
"strconv"
@@ -11,6 +12,8 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
@@ -116,6 +119,25 @@ func (bot TipBot) anyChosenInlineHandler(ctx intercept.Context) (intercept.Conte
return ctx, nil
}
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
switch command {
// is default, we don't have to check it
// case "faucet":
// ctx = context.WithValue(ctx, "publicLanguageCode", "en")
// ctx = context.WithValue(ctx, "publicLocalizer", i18n.NewLocalizer(i18n.Bundle, "en"))
case "zapfhahn", "spendendose":
ctx = context.WithValue(ctx, "publicLanguageCode", "de")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "de"))
case "kraan":
ctx = context.WithValue(ctx, "publicLanguageCode", "nl")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "nl"))
case "grifo":
ctx = context.WithValue(ctx, "publicLanguageCode", "es")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "es"))
}
return ctx
}
func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, error) {
if ctx.Query().Text == "" {
return bot.inlineQueryInstructions(ctx)
@@ -130,15 +152,14 @@ func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, err
return bot.handleInlineSendQuery(ctx)
}
word := commandWord(text)
if isCommand(word, "faucet", faucetAliases) {
if strings.HasPrefix(text, "faucet") || strings.HasPrefix(text, "zapfhahn") || strings.HasPrefix(text, "kraan") || strings.HasPrefix(text, "grifo") {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
}
return bot.handleInlineFaucetQuery(ctx)
}
if isCommand(word, "tipjar", tipjarAliases) {
if strings.HasPrefix(text, "tipjar") || strings.HasPrefix(text, "spendendose") {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
+1 -1
View File
@@ -274,7 +274,7 @@ func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *In
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), "", InvoiceCallbackInlineReceive, inlineReceive.ID)
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
+2 -31
View File
@@ -58,31 +58,6 @@ func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error
return ctx, nil
}
// isPlaceholderSender reports whether u is one of the fake users Telegram puts
// into `from` for messages sent on behalf of a chat: channel posts forwarded
// to a discussion group (777000), messages sent as a channel (@Channel_Bot,
// 136817688) and anonymous group admins (@GroupAnonymousBot, 1087968824).
// Everyone who posts that way shares the same user, so it must never own or
// receive money.
func isPlaceholderSender(u *tb.User) bool {
if u == nil {
return false
}
switch u.ID {
case 777000, 136817688, 1087968824:
return true
}
return false
}
// rejectPlaceholderSenderInterceptor stops updates sent on behalf of a chat.
func (bot TipBot) rejectPlaceholderSenderInterceptor(ctx intercept.Context) (intercept.Context, error) {
if isPlaceholderSender(ctx.Sender()) {
return ctx, fmt.Errorf("[rejectPlaceholderSenderInterceptor] placeholder sender %d", ctx.Sender().ID)
}
return ctx, nil
}
// answerCallbackInterceptor will answer the callback with the given text in the context
func (bot TipBot) answerCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
@@ -156,10 +131,6 @@ func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context,
}
return ctx, nil
}
func (bot TipBot) tryLoadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx)
return ctx, nil
}
// loadReplyToInterceptor Loading the Telegram user with message intercept
func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Context, error) {
@@ -228,11 +199,11 @@ func (bot TipBot) logMessageInterceptor(ctx intercept.Context) (intercept.Contex
if ctx.Message() != nil {
if ctx.Message().Text != "" {
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", ctx.Message().Chat.Title, ctx.Message().Chat.ID, GetUserStr(ctx.Message().Sender), ctx.Message().Sender.ID, redactForLog(ctx.Message().Text))
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", ctx.Message().Chat.Title, ctx.Message().Chat.ID, GetUserStr(ctx.Message().Sender), ctx.Message().Sender.ID, ctx.Message().Text)
if ctx.Message().IsReply() {
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(ctx.Message().ReplyTo.Sender))
}
log.Info(log_string)
log.Infof(log_string)
} else if ctx.Message().Photo != nil {
log.Infof("[%s:%d %s:%d] %s", ctx.Message().Chat.Title, ctx.Message().Chat.ID, GetUserStr(ctx.Message().Sender), ctx.Message().Sender.ID, photoTag)
}
+13 -61
View File
@@ -8,7 +8,6 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/nbd-wtf/go-nostr"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -42,8 +41,6 @@ func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
InvoiceCallbackPayJoinTicket: EventHandler{Function: bot.stopJoinTicketTimer, Type: EventTypeInvoice},
InvoiceCallbackLNURLCashSettle: EventHandler{Function: bot.lnurlcashSettleEvent, Type: EventTypeInvoice},
}
}
@@ -56,8 +53,6 @@ const (
InvoiceCallbackGroupTicket
InvoiceCallbackSatdressProxy
InvoiceCallbackGenerateDalle
InvoiceCallbackPayJoinTicket
// InvoiceCallbackLNURLCashSettle (8) is declared in lnurlcash.go
)
const (
@@ -91,7 +86,6 @@ type InvoiceEvent struct {
CallbackData string `json:"callbackdata"` // add some data for the callback
Chat *tb.Chat `json:"chat,omitempty"` // if invoice is supposed to be sent to a particular chat
Payer *lnbits.User `json:"payer,omitempty"` // if a particular user is supposed to pay this
UserCurrency string `json:"usercurrency,omitempty"` // the currency a user selected
}
func (invoiceEvent InvoiceEvent) Type() EventType {
@@ -119,8 +113,6 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
// check and print all commands
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
// load user settings
user, err := GetLnbitsUserWithSettings(user.Telegram, *bot)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -152,13 +144,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
currency := user.Settings.Display.DisplayCurrency
if currency == "" {
currency = "BTC"
}
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, currency, InvoiceCallbackGeneric, "")
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
@@ -184,7 +170,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
return ctx, nil
}
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, currency string, callback int, callbackData string) (InvoiceEvent, error) {
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
@@ -206,7 +192,6 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
UserCurrency: currency,
}
// save invoice struct for later use
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
@@ -222,30 +207,17 @@ func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
log.Errorln(errmsg)
}
if invoiceEvent.UserCurrency == "" || strings.ToLower(invoiceEvent.UserCurrency) == "btc" {
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
} else {
fiatAmount, err := SatoshisToFiat(invoiceEvent.Amount, strings.ToUpper(invoiceEvent.UserCurrency))
if err != nil {
log.Errorln(err)
// fallback to satoshis
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
return
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedCurrencyMessage"), invoiceEvent.Amount, fiatAmount, strings.ToUpper(invoiceEvent.UserCurrency)))
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
}
type LNURLInvoice struct {
*Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Nip57Receipt nostr.Event `json:"nip57_receipt"`
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
}
func (lnurlInvoice LNURLInvoice) Key() string {
@@ -254,40 +226,20 @@ func (lnurlInvoice LNURLInvoice) Key() string {
func (bot *TipBot) lnurlReceiveEvent(event Event) {
invoiceEvent := event.(*InvoiceEvent)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
err := bot.Bunt.Get(tx)
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
if err == nil {
// filter: if tx.Comment includes a URL, return if tx.Amount is less than 100 sat
if len(tx.Comment) > 0 && tx.Amount < 100 {
if strings.Contains(tx.Comment, "http") {
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
return
}
}
if tx.Amount < 21 {
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
return
}
// notify user with LNURL comment and sender Information
if len(tx.Comment) > 0 {
if len(tx.From) == 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)), tb.NoPreview)
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)))
} else {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)), tb.NoPreview)
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)))
}
} else if len(tx.From) > 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)), tb.NoPreview)
}
// send out NIP57 zap receipt
if len(tx.Nip57Receipt.Sig) > 0 {
// zapEventSerialized, _ := json.Marshal(tx.Nip57Receipt)
bot.trySendMessage(tx.User.Telegram, "💜 This was a zap on nostr.")
go bot.publishNostrEvent(tx.Nip57Receipt, tx.Nip57ReceiptRelays)
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)))
}
}
}
-5
View File
@@ -85,11 +85,6 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
}
lnurlAuthState := sn.(*LnurlAuthState)
// only the correct user can press
if lnurlAuthState.From.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
if !lnurlAuthState.Active {
return ctx, fmt.Errorf("LnurlAuthData not active.")
}
+17 -5
View File
@@ -36,7 +36,7 @@ type LnurlPayState struct {
}
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hasn't necessarily entered an amount yet
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
@@ -201,15 +201,27 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
}
// todo: doesn't work with lnurls from lnbits??
// check whether description hash matches with expected hash
// decode invoice
// bolt11, err := decodepay.Decodepay(response2.PR)
// if err != nil {
// bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
// errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
// log.Errorln(errmsg)
// return ctx, errors.New(errors.InvalidSyntaxError, err)
// }
// if bolt11.DescriptionHash != lnurlPayState.DescriptionHash {
// log.Errorf("[lnurlPayHandlerSend] Error: description hash doesn't match")
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "description hash doesn't match.\nExpected: `"+lnurlPayState.DescriptionHash+"` Received: `"+bolt11.DescriptionHash+"`"))
// return ctx, fmt.Errorf("description hash doesn't match")
// }
// all good
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
// store success action in context for printing after the payHandler
ctx.Context = context.WithValue(ctx, "SuccessAction", lnurlPayState.LNURLPayValues.SuccessAction)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
return bot.payHandler(ctx)
}
-2
View File
@@ -306,8 +306,6 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
var response2 lnurl.LNURLResponse
json.Unmarshal(body, &response2)
if response2.Status == "OK" {
// the service accepted the invoice, a second press must not send another one
lnurlWithdrawState.Active = false
// update button text
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess")})
+10 -36
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
goerrors "errors"
"fmt"
"io/ioutil"
"net/url"
@@ -19,9 +18,7 @@ import (
"github.com/tidwall/gjson"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
lnurlcashpkg "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
lnurl "github.com/fiatjaf/go-lnurl"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -40,7 +37,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
if m.Chat.Type != tb.ChatPrivate {
return ctx, errors.Create(errors.NoPrivateChatError)
}
log.Infof("[lnurlHandler] %s", redactForLog(m.Text))
log.Infof("[lnurlHandler] %s", m.Text)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -70,29 +67,19 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
// an LNURLcash note is a withdraw link whose k1 is the money: redeem it
// directly. A withdraw link without mintPubkey falls through below.
if bot.LNURLCash != nil && lnurlcash.ResolveNoteInput(lnurlSplit) != "" {
ctx, err := bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, lnurlSplit, false)
if !goerrors.Is(err, lnurlcashpkg.ErrNotANote) {
bot.tryDeleteMessage(statusMsg)
return ctx, err
}
}
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", errorForLog(err))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
return ctx, err
}
switch params.(type) {
case lnurl.LNURLAuthParams:
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
log.Infof("[LNURL-auth] %s", lnurlcash.ServerOf(authParams.LNURLAuthParams.Callback))
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
bot.tryDeleteMessage(statusMsg)
ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams)
return ctx, err
@@ -115,17 +102,9 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
// ask whether to make payment
bot.lnurlPayHandler(ctx, payParams)
case LNURLCashNoteParams:
bot.tryDeleteMessage(statusMsg)
if bot.LNURLCash == nil {
return ctx, errors.Create(errors.UnknownError)
}
log.Infof("[LNURL-cash] note from %s", lnurlcash.ServerOf(params.(LNURLCashNoteParams).URL))
return bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, lnurlSplit, false)
case lnurl.LNURLWithdrawResponse:
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
log.Infof("[LNURL-w] %s", lnurlcash.ServerOf(withdrawParams.LNURLWithdrawResponse.Callback))
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlWithdrawHandler(ctx, withdrawParams)
default:
@@ -204,7 +183,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
var rawurl string
if name, domain, ok := lnurl.ParseInternetIdentifier(rawlnurl); ok {
isOnion := strings.HasSuffix(domain, ".onion")
isOnion := strings.Index(domain, ".onion") == len(domain)-6
rawurl = domain + "/.well-known/lnurlp/" + name
if isOnion {
rawurl = "http://" + rawurl
@@ -218,29 +197,28 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
strings.HasPrefix(rawlnurl, "lnurla://") ||
strings.HasPrefix(rawlnurl, "keyauth://") {
location := strings.SplitN(rawlnurl, ":", 2)[1]
scheme := "https:"
if strings.Contains(location, ".onion/") || strings.HasSuffix(location, ".onion") {
if strings.Contains(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
scheme = "http:"
}
location := strings.SplitN(rawlnurl, ":", 2)[1]
rawurl = scheme + location
} else {
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
if !ok {
return "", nil,
fmt.Errorf("%s", "invalid bech32-encoded lnurl: "+rawlnurl)
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
}
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
if err != nil {
return "", nil, err
}
}
log.Debug("[HandleLNURL] rawurl: ", rawurl)
parsed, err := url.Parse(rawurl)
if err != nil {
return rawurl, nil, err
}
// host only: the query string of a withdraw or login link carries k1
log.Debug("[HandleLNURL] host: ", parsed.Host)
query := parsed.Query()
@@ -269,7 +247,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
return rawurl, nil, err
}
if resp.StatusCode >= 300 {
return rawurl, nil, fmt.Errorf("%s", "HTTP error: "+resp.Status)
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
@@ -288,10 +266,6 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
switch j.Get("tag").String() {
case "withdrawRequest":
if bot.LNURLCash != nil && j.Get("mintPubkey").String() != "" {
// an LNURLcash note (LUD-25): the withdraw link publishes a mintPubkey
return rawurl, LNURLCashNoteParams{URL: rawurl}, nil
}
value, err := lnurl.HandleWithdraw(b)
return rawurl, value, err
case "payRequest":
-464
View File
@@ -1,464 +0,0 @@
package telegram
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// InvoiceCallbackLNURLCashSettle is the invoice event callback for reclaim and
// redeem invoices; CallbackData carries the lnurlcash reference.
const InvoiceCallbackLNURLCashSettle = 8
// initLNURLCash wires the note service when the feature is enabled.
func (bot *TipBot) initLNURLCash() {
cfg := &internal.Configuration.LNURLCash
if !cfg.Enabled || bot.DB.LNURLCash == nil {
return
}
cipher, err := lnurlcash.NewCipher(cfg.SecretEncryptionKey)
if err != nil {
panic(err)
}
notifier := &lnurlcashNotifier{bot: bot}
// mutations on fresh connections, read-only lookups on pooled ones
registry := lnurlcash.NewRegistry(cfg, bot.DB.LNURLCash, network.NewNoKeepAliveClient(30*time.Second),
network.NewPooledClient(30*time.Second), notifier.Alert)
bot.LNURLCash = lnurlcash.NewService(cfg, bot.DB.LNURLCash, registry, &lnbitsLedger{bot: bot}, cipher)
bot.lnurlcashJobs = lnurlcash.NewJobs(bot.LNURLCash, notifier)
log.Infof("[lnurlcash] enabled with %d mint(s)", len(cfg.Mints))
}
// startLNURLCashJobs runs the background jobs. The bot has no shutdown
// context; the jobs are restart-safe by design.
func (bot *TipBot) startLNURLCashJobs() {
if bot.lnurlcashJobs != nil {
bot.lnurlcashJobs.Start(context.Background())
}
}
// userByName loads a user by the lnbits.User.Name key (Telegram id as text).
func (bot *TipBot) userByName(name string) (*lnbits.User, error) {
id, err := strconv.ParseInt(name, 10, 64)
if err != nil {
return nil, fmt.Errorf("bad user name %q", name)
}
user, err := GetLnbitsUser(&tb.User{ID: id}, *bot)
if err != nil {
return nil, err
}
if user.Wallet == nil {
return nil, fmt.Errorf("user %s has no wallet", name)
}
return user, nil
}
// ---- Ledger: what the note service needs from LNbits ----
type lnbitsLedger struct{ bot *TipBot }
func (l *lnbitsLedger) CreateInvoice(ctx context.Context, userName string, amountSat int64, memo, ref string) (string, string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", "", err
}
invoice, err := user.Wallet.Invoice(lnbits.InvoiceParams{Out: false, Amount: amountSat, Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer}, l.bot.Client)
if err != nil {
return "", "", err
}
event := InvoiceEvent{
Invoice: &Invoice{PaymentHash: invoice.PaymentHash, PaymentRequest: invoice.PaymentRequest, Amount: amountSat, Memo: memo},
User: user,
Callback: InvoiceCallbackLNURLCashSettle,
CallbackData: ref,
LanguageCode: user.Telegram.LanguageCode,
}
runtime.IgnoreError(l.bot.Bunt.Set(event))
return invoice.PaymentRequest, invoice.PaymentHash, nil
}
func (l *lnbitsLedger) PayInvoice(ctx context.Context, userName, pr string) (string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", err
}
paid, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: pr}, l.bot.Client)
if err != nil {
var lnErr lnbits.Error
if errors.As(err, &lnErr) {
// LNbits answered with an error, but the payment can still be in
// flight or have settled, so ask LNbits what became of it.
var paid, pending bool
var lookupErr error
if b, derr := decodepay.Decodepay(pr); derr == nil {
paid, pending, lookupErr = l.PaymentSucceeded(ctx, userName, b.PaymentHash)
} else {
lookupErr = derr
}
return "", classifyPayError(err, paid, pending, lookupErr)
}
return "", &lnurlcash.AmbiguousLedgerError{Err: err}
}
runtime.IgnoreErrorMultiReturn(l.bot.GetUserBalance(user))
return paid.PaymentHash, nil
}
func (l *lnbitsLedger) InvoicePaid(ctx context.Context, userName, hash string) (bool, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return false, err
}
p, err := l.bot.Client.Payment(*user.Wallet, hash)
if err != nil {
return false, err
}
return p.Paid, nil
}
func (l *lnbitsLedger) PaymentSucceeded(ctx context.Context, userName, hash string) (bool, bool, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return false, false, err
}
p, err := l.bot.Client.Payment(*user.Wallet, hash)
if err != nil {
return false, false, err
}
if p.Paid {
return true, false, nil
}
return false, p.Details.Pending, nil
}
func (l *lnbitsLedger) BalanceMsat(ctx context.Context, userName string) (int64, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return 0, err
}
w, err := l.bot.Client.Info(*user.Wallet)
if err != nil {
return 0, err
}
return w.Balance, nil
}
// lnurlcashSettleEvent runs when a reclaim or redeem invoice was paid.
func (bot *TipBot) lnurlcashSettleEvent(event Event) {
ev := event.(*InvoiceEvent)
if bot.LNURLCash == nil {
return
}
st, err := bot.LNURLCash.SettleInvoice(context.Background(), ev.PaymentHash)
if err != nil {
log.Errorf("[lnurlcash] settle %s: %v", ev.PaymentHash, err)
return
}
bot.notifyLNURLCashSettlement(st)
}
// notifyLNURLCashSettlement tells the user a reclaim or redeem settled. st
// may be nil (nothing settled, or another path already told them).
func (bot *TipBot) notifyLNURLCashSettlement(st *lnurlcash.Settlement) {
if st == nil {
return
}
n := &lnurlcashNotifier{bot: bot}
if st.Note != nil {
n.NoteReclaimed(st.Note)
n.GroupNoteState(st.Note)
}
if st.Redeem != nil {
n.RedeemSettled(st.Redeem)
}
}
// lnurlcashSettleWait is how long a handler watches a melt's invoice after
// sending the melt. Later settlements reach the user through the webhook or
// the recovery job.
const lnurlcashSettleWait = 45 * time.Second
// awaitLNURLCashSettlement watches the invoice a melt pays in the background
// and tells the user as soon as it settles, whether or not the LNbits webhook
// arrives. The webhook and this watcher settle under the same lock, so the
// user hears only once.
func (bot *TipBot) awaitLNURLCashSettlement(userName, invoiceHash string) {
if bot.LNURLCash == nil || invoiceHash == "" {
return
}
go func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("[lnurlcash] settlement watcher for %s panicked: %v", invoiceHash, r)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), lnurlcashSettleWait+10*time.Second)
defer cancel()
st, err := bot.LNURLCash.AwaitSettlement(ctx, userName, invoiceHash, lnurlcashSettleWait)
if err != nil {
log.Warnf("[lnurlcash] settle %s: %v", invoiceHash, err)
return
}
bot.notifyLNURLCashSettlement(st)
}()
}
// ---- Notifier: how the jobs reach Telegram ----
type lnurlcashNotifier struct{ bot *TipBot }
func recipientOf(userName string) *tb.User {
id, _ := strconv.ParseInt(userName, 10, 64)
return &tb.User{ID: id}
}
func (n *lnurlcashNotifier) send(userName, lang, text string, opts ...interface{}) {
if userName == "bot" || userName == "" {
return
}
n.bot.trySendMessage(recipientOf(userName), text, opts...)
}
func (n *lnurlcashNotifier) NoteClaimed(note *lnurlcash.Note) {
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteClaimedNotifyMessage"),
formatSat(note.ReportedMsat), lnurlcash.ShortID(note.ID), str.MarkdownEscape(note.Memo)))
}
func (n *lnurlcashNotifier) BatchDigest(b *lnurlcash.Batch, claimed []*lnurlcash.Note) {
notes, _ := n.bot.DB.LNURLCash.NotesInBatch(b.ID)
total, done := 0, 0
for _, x := range notes {
if x.Kind != lnurlcash.KindUser {
continue
}
total++
if x.State == lnurlcash.NoteClaimed {
done++
}
}
n.send(b.UserName, b.LanguageCode, fmt.Sprintf(i18n.Translate(b.LanguageCode, "noteBatchDigestMessage"),
len(claimed), lnurlcash.ShortID(b.ID), done, total))
}
func (n *lnurlcashNotifier) NoteReclaimed(note *lnurlcash.Note) {
if user, err := n.bot.userByName(note.UserName); err == nil {
runtime.IgnoreErrorMultiReturn(n.bot.GetUserBalance(user))
}
if (note.Kind == lnurlcash.KindFunding || note.Kind == lnurlcash.KindDust) && note.BatchID != nil {
// the change of a batch, a note the user never saw
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteChangeReturnedMessage"),
formatSat(note.ReportedMsat), lnurlcash.ShortID(*note.BatchID)))
return
}
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteReclaimedMessage"),
formatSat(note.ReportedMsat), lnurlcash.ShortID(note.ID)))
}
func (n *lnurlcashNotifier) RedeemSettled(r *lnurlcash.Redeem) {
if user, err := n.bot.userByName(r.UserName); err == nil {
runtime.IgnoreErrorMultiReturn(n.bot.GetUserBalance(user))
}
n.send(r.UserName, r.LanguageCode, fmt.Sprintf(i18n.Translate(r.LanguageCode, "redeemDoneMessage"), formatSat(r.ReportedMsat)))
}
// GroupNoteState edits the caption of a note's group post.
func (n *lnurlcashNotifier) GroupNoteState(note *lnurlcash.Note) {
if note.ChatID == 0 || note.MessageID == "" {
return
}
var key string
switch note.State {
case lnurlcash.NoteClaimed:
key = "noteGroupClaimedMessage"
case lnurlcash.NoteReclaimed, lnurlcash.NoteReclaiming:
key = "noteGroupWithdrawnMessage"
default:
return
}
caption := fmt.Sprintf(i18n.Translate("en", key), formatSat(note.ReportedMsat))
msg := &tb.StoredMessage{MessageID: note.MessageID, ChatID: note.ChatID}
if _, err := n.bot.Telegram.EditCaption(msg, caption); err != nil {
log.Warnf("[lnurlcash] edit group post of %s: %v", note.ID, err)
}
}
func (n *lnurlcashNotifier) Alert(msg string) {
log.Errorf("[lnurlcash] ALERT: %s", msg)
if id := internal.Configuration.LNURLCash.AdminTelegramID; id != 0 {
n.bot.trySendMessage(&tb.User{ID: id}, "⚠️ "+msg)
}
}
// ---- shared handler helpers ----
// lnurlcashReady tells the user the feature is off and reports false.
func (bot *TipBot) lnurlcashReady(ctx intercept.Context) bool {
if bot.LNURLCash != nil {
return true
}
bot.trySendMessage(ctx.Sender(), Translate(ctx, "lnurlcashDisabledMessage"))
return false
}
// sendPrivate sends to the user's private chat and reports whether Telegram
// accepted it, which it does not when the user never started the bot.
func (bot *TipBot) sendPrivate(user *tb.User, what interface{}, opts ...interface{}) (*tb.Message, bool) {
msg := bot.trySendMessageEditable(user, what, opts...)
return msg, msg != nil
}
// lnurlcashErrorText maps a service error to a user message.
func lnurlcashErrorText(ctx context.Context, err error) string {
cfg := &internal.Configuration.LNURLCash
var own *lnurlcash.ErrOwnNote
switch {
case errors.Is(err, lnurlcash.ErrCapNoteValue):
return fmt.Sprintf(TranslateUser(ctx, "noteCapValueMessage"), cfg.MinNoteSat, cfg.MaxNoteSat, cfg.GroupNoteMaxSat)
case errors.Is(err, lnurlcash.ErrCapBatch):
return fmt.Sprintf(TranslateUser(ctx, "noteCapBatchMessage"), cfg.MaxBatchSize, cfg.MaxBatchTotalSat)
case errors.Is(err, lnurlcash.ErrCapOutstanding):
return fmt.Sprintf(TranslateUser(ctx, "noteCapOutstandingMessage"), cfg.MaxOutstandingNotesPerUser, cfg.MaxOutstandingSatPerUser)
case errors.Is(err, lnurlcash.ErrInsufficientFunds):
return TranslateUser(ctx, "noteInsufficientFundsMessage")
case errors.Is(err, lnurlcash.ErrNoMint), errors.Is(err, lnurlcash.ErrMintUnavailable):
return TranslateUser(ctx, "noteMintUnavailableMessage")
case errors.Is(err, lnurlcash.ErrMintRange):
return TranslateUser(ctx, "noteMintRangeMessage")
case errors.Is(err, lnurlcash.ErrNoteClaimed):
return TranslateUser(ctx, "noteStatusClaimedMessage")
case errors.Is(err, lnurlcash.ErrNotePending):
return TranslateUser(ctx, "redeemPendingMessage")
case errors.Is(err, lnurlcash.ErrNotANote):
return TranslateUser(ctx, "redeemNotANoteMessage")
case errors.Is(err, lnurlcash.ErrFractionalValue):
return TranslateUser(ctx, "redeemFractionalMessage")
case errors.Is(err, lnurlcash.ErrInFlight):
return TranslateUser(ctx, "noteInFlightMessage")
case errors.Is(err, lnurlcash.ErrNothingToReclaim), errors.Is(err, lnurlcash.ErrNoteNotLive):
return TranslateUser(ctx, "noteNothingToReclaimMessage")
case errors.Is(err, lnurlcash.ErrNotOwner):
return TranslateUser(ctx, "noteNotOwnerMessage")
case errors.As(err, &own):
return TranslateUser(ctx, "redeemOwnNoteMessage")
}
log.Warnf("[lnurlcash] %v", err)
return TranslateUser(ctx, "noteErrorMessage")
}
// noteStateText is the translated state label.
func noteStateText(ctx context.Context, state string) string {
switch state {
case lnurlcash.NoteLive:
return TranslateUser(ctx, "noteStateLive")
case lnurlcash.NoteClaimed:
return TranslateUser(ctx, "noteStateClaimed")
case lnurlcash.NoteReclaiming:
return TranslateUser(ctx, "noteStateReclaiming")
case lnurlcash.NoteReclaimed:
return TranslateUser(ctx, "noteStateReclaimed")
case lnurlcash.NoteFailed:
return TranslateUser(ctx, "noteStateFailed")
}
return TranslateUser(ctx, "noteStatePending")
}
// noteViewText renders one note.
func noteViewText(ctx context.Context, n *lnurlcash.Note) string {
value := n.ReportedMsat
if value == 0 {
value = n.ValueMsat
}
memo := ""
if n.Memo != "" {
memo = fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(n.Memo))
}
return fmt.Sprintf(TranslateUser(ctx, "noteViewMessage"), lnurlcash.ShortID(n.ID), formatSat(value),
noteStateText(ctx, n.State), n.MintID, n.CreatedAt.UTC().Format("2 Jan 06 15:04")) + memo
}
// noteKeyboard builds the buttons under a note: QR, status, reclaim.
func noteKeyboard(ctx context.Context, n *lnurlcash.Note, withQR bool) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
var row []tb.Btn
if withQR && n.State == lnurlcash.NoteLive {
row = append(row, menu.Data(TranslateUser(ctx, "noteShowQrButton"), "lnc_qr", n.ID))
}
if !lnurlcash.IsFinalNoteState(n.State) {
row = append(row, menu.Data(TranslateUser(ctx, "noteStatusButton"), "lnc_status", n.ID))
}
if n.State == lnurlcash.NoteLive {
row = append(row, menu.Data(TranslateUser(ctx, "noteReclaimButton"), "lnc_reclaim", n.ID))
}
if len(row) > 0 {
menu.Inline(menu.Row(row...))
}
return menu
}
// loadOwnNote loads the note behind a callback and checks the presser owns it.
func (bot *TipBot) loadOwnNote(ctx intercept.Context) (*lnurlcash.Note, error) {
n, err := bot.LNURLCash.Store().Note(ctx.Data())
if err != nil {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
if n.UserName != LoadUser(ctx).Name {
return nil, lnurlcash.ErrNotOwner
}
return n, nil
}
// sendNoteQR sends the QR photo of a note with the bech32 LNURL as caption.
func (bot *TipBot) sendNoteQR(to tb.Recipient, n *lnurlcash.Note) *tb.Message {
_, bech, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
log.Errorf("[lnurlcash] note strings %s: %v", n.ID, err)
return nil
}
qr, err := qrcodeEncode(bech)
if err != nil {
return nil
}
return bot.trySendMessageEditable(to, &tb.Photo{File: tb.File{FileReader: qr}, Caption: fmt.Sprintf("`%s`", bech)})
}
// formatSat renders msat as sats for messages.
func formatSat(msat int64) string {
if msat%1000 == 0 {
return strconv.FormatInt(msat/1000, 10)
}
return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.3f", float64(msat)/1000), "0"), ".")
}
// classifyPayError turns an LNbits error from a payment into the ledger error.
// The payment is only a definitive failure when LNbits itself says it neither
// settled nor is pending. If that cannot be established the outcome is
// ambiguous and the batch is left for recovery instead of being failed.
func classifyPayError(payErr error, paid, pending bool, lookupErr error) error {
if paid || pending {
return &lnurlcash.AmbiguousLedgerError{Err: payErr}
}
if lookupErr != nil {
var lnErr lnbits.Error
if errors.As(lookupErr, &lnErr) {
return payErr // LNbits does not know the payment: it never started
}
return &lnurlcash.AmbiguousLedgerError{Err: payErr}
}
return payErr
}
-17
View File
@@ -1,17 +0,0 @@
package telegram
import (
"bytes"
"io"
"github.com/skip2/go-qrcode"
)
// qrcodeEncode renders a PNG QR code for Telegram.
func qrcodeEncode(data string) (io.Reader, error) {
png, err := qrcode.Encode(data, qrcode.Medium, 256)
if err != nil {
return nil, err
}
return bytes.NewReader(png), nil
}
-88
View File
@@ -1,88 +0,0 @@
package telegram
import (
"errors"
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
)
func TestParseBatchCommand(t *testing.T) {
amount, count, memo, ok := parseBatchCommand("/notes 100 x 10 party time")
if !ok || amount != 100 || count != 10 || memo != "party time" {
t.Fatalf("got %d %d %q %v", amount, count, memo, ok)
}
if _, _, _, ok := parseBatchCommand("/notes"); ok {
t.Fatal("bare /notes is a list")
}
if _, _, _, ok := parseBatchCommand("/notes 100 y 10"); ok {
t.Fatal("wrong separator")
}
if _, _, _, ok := parseBatchCommand("/notes 100 x 0"); ok {
t.Fatal("zero count")
}
if _, c, _, ok := parseBatchCommand("/notes 1k × 3"); !ok || c != 3 {
t.Fatal("unicode times and 1k amounts must parse")
}
}
func TestRedactNoteURLs(t *testing.T) {
in := "/redeem lnurlw://mint.example/w?k1=" + "ab" + "cd"
if got := redactForLog(in); got == in || !contains(got, "/redeem <") {
t.Fatalf("note not redacted: %q", got)
}
in = "/lnurl https://mint.example/w?k1=abcd&amount=1000"
if got := redactForLog(in); got == in {
t.Fatalf("withdraw link with k1 not redacted: %q", got)
}
if got := redactForLog("/note 100 hello"); got != "/note 100 hello" {
t.Fatalf("plain command changed: %q", got)
}
if got := formatSat(1000_900); got != "1000.9" {
t.Fatalf("formatSat: %q", got)
}
if got := formatSat(21_000); got != "21" {
t.Fatalf("formatSat: %q", got)
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
func TestPreserveNoteCase(t *testing.T) {
if got := preserveNoteCase("LNURLW://Mint.Example/W/Abc?k1=AB"); got != "lnurlw://Mint.Example/W/Abc?k1=AB" {
t.Fatalf("got %q", got)
}
if got := preserveNoteCase("LIGHTNING:LNURL1ABC"); got != "lightning:lnurl1abc" {
t.Fatalf("got %q", got)
}
}
func TestClassifyPayError(t *testing.T) {
payErr := lnbits.Error{Detail: "boom"}
ambiguous := func(err error) bool { return lnurlcash.IsAmbiguousLedger(err) }
if !ambiguous(classifyPayError(payErr, true, false, nil)) {
t.Error("a settled payment must be ambiguous, not failed")
}
if !ambiguous(classifyPayError(payErr, false, true, nil)) {
t.Error("a pending payment must be ambiguous")
}
if !ambiguous(classifyPayError(payErr, false, false, errors.New("timeout"))) {
t.Error("an unreachable lookup must be ambiguous")
}
if ambiguous(classifyPayError(payErr, false, false, lnbits.Error{Detail: "not found"})) {
t.Error("a payment LNbits does not know is a definitive failure")
}
if ambiguous(classifyPayError(payErr, false, false, nil)) {
t.Error("a payment LNbits reports as failed is definitive")
}
}
-97
View File
@@ -1,97 +0,0 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
lnurlcashgo "github.com/lnurlcash/lnurlcash-go"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var btnSetMint = (&tb.ReplyMarkup{}).Data("", "lnc_setmint")
func bot_lnurlcash_cfg() *lnurlcash.Config { return &internal.Configuration.LNURLCash }
// lnurlmintsHandler lists the admin mints and lets the user pick a default.
func (bot *TipBot) lnurlmintsHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
text, kb := bot.mintsText(ctx, user.Name)
if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, nil
}
func (bot *TipBot) mintsText(ctx intercept.Context, user string) (string, *tb.ReplyMarkup) {
reg := bot.LNURLCash.Mints()
current, _ := reg.ForUser(user)
menu := &tb.ReplyMarkup{}
var rows []tb.Row
text := TranslateUser(ctx, "lnurlmintsHeader")
for _, mnt := range reg.All() {
state := "🟢"
switch {
case mnt.Disabled:
state = "⛔️"
case !mnt.Healthy:
state = "🔴"
}
mark := ""
if current != nil && current.ID == mnt.ID {
mark = " ⭐️"
}
fee := TranslateUser(ctx, "lnurlmintsNoFee")
if mnt.FeeBaseMsat > 0 || mnt.FeePpm > 0 {
fee = fmt.Sprintf(TranslateUser(ctx, "lnurlmintsFee"), formatSat(mnt.FeeBaseMsat), lnurlcashgo.FormatFeePercent(mnt.FeePpm))
}
text += fmt.Sprintf(TranslateUser(ctx, "lnurlmintsItem"), state, mnt.ID, mark, lnurlcashgo.ServerOf(mnt.PayURL), fee)
if mnt.Usable() {
rows = append(rows, menu.Row(menu.Data(fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetButton"), mnt.ID), "lnc_setmint", mnt.ID)))
}
}
menu.Inline(rows...)
return text, menu
}
// setMintHandler stores the user's default mint.
func (bot *TipBot) setMintHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
user := LoadUser(ctx)
mnt, ok := bot.LNURLCash.Mints().Get(ctx.Data())
if !ok || !mnt.Usable() {
bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, nil
}
if err := bot.LNURLCash.Store().SetPref(user.Name, mnt.ID); err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetMessage"), mnt.ID))
text, kb := bot.mintsText(ctx, user.Name)
bot.tryEditMessage(ctx.Callback().Message, text, kb)
return ctx, nil
}
// lnurlHelpHandler sends the LNURLcash notes help, privately.
func (bot *TipBot) lnurlHelpHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if !m.Private() {
bot.tryDeleteMessage(m)
}
bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteHelpMessage"), tb.NoPreview)
return ctx, nil
}
-217
View File
@@ -1,217 +0,0 @@
package telegram
import (
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/gorilla/websocket"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
log "github.com/sirupsen/logrus"
)
// maxRequestedRelays caps the relays taken from a zap request, so they can't
// push the default relays out of the list.
const maxRequestedRelays = 10
// go-nostr connects with the default websocket dialer. Relay URLs come from
// zap requests, so it must only reach public addresses.
func init() {
websocket.DefaultDialer.NetDialContext = netguard.DialContext
}
// requestedRelays keeps the wss:// relays of a zap request, up to maxRequestedRelays.
func requestedRelays(relays []string) []string {
list := []string{}
for _, relay := range relays {
if strings.HasPrefix(relay, "wss://") && len(list) < maxRequestedRelays {
list = append(list, relay)
}
}
return list
}
var (
nosterRegisterMessage = "📖 Add your nostr pubkey for zap receipts"
nostrInfoMessage = "💜 *Your nostr information*\n\nYour pubkey: `%s`"
nostrInfoLNAddrMessage = "Your Lightning address: `%s`"
nostrHelpMessage = "⚙️ *Nostr commands:*\n`/nostr add <pubkey>` ✅ Add your nostr pubkey.\n`/nostr help` 📖 Show help."
nostrAddedMessage = "✅ *Nostr pubkey added.*"
nostrPrivateKeyErrorMessage = "🚫 This is not your public key but your private key! Very dangerous! Try again with your npub..."
nostrPublicKeyErrorMessage = "🚫 There was an error decoding your public key."
)
func uniqueSlice(slice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range slice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func cleanUrls(slice []string) []string {
list := []string{}
for _, entry := range slice {
if strings.HasSuffix(entry, "/") {
entry = entry[:len(entry)-1]
}
list = append(list, entry)
}
return list
}
func (bot *TipBot) publishNostrEvent(ev nostr.Event, relays []string) {
pk := internal.Configuration.Nostr.PrivateKey
// // BEGIN: testing
// pub, _ := nostr.GetPublicKey(pk)
// ev = nostr.Event{
// PubKey: pub,
// CreatedAt: time.Now(),
// Kind: 1,
// Tags: nil,
// Content: "Hello World!",
// }
// // END: testing
// calling Sign sets the event ID field and the event Sig field
ev.Sign(pk)
log.Debugf("[NOSTR] 🟣 publishing nostr event %s", ev.ID)
// more relays (only public wss:// relays are taken from the zap request)
relays = append(requestedRelays(relays), "wss://relay.nostr.ch", "wss://eden.nostr.land", "wss://nostr.btcmp.com", "wss://nostr.relayer.se", "wss://relay.current.fyi", "wss://nos.lol", "wss://nostr.mom", "wss://relay.nostr.info", "wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net", "wss://relay.snort.social/", "wss://relay.damus.io/", "wss://nostr.oxtr.dev/", "wss://nostr.fmt.wiz.biz/", "wss://brb.io")
// remove trailing /
relays = cleanUrls(relays)
// unique relays
relays = uniqueSlice(relays)
// crop relays
var max_relays int = 50
if len(relays) > max_relays {
relays = relays[:max_relays]
}
// publish the event to relays
for _, url := range relays {
go func(url string) {
// remove trailing /
relay, e := nostr.RelayConnect(context.Background(), url)
if e != nil {
log.Errorf("%s", e.Error())
return
}
time.Sleep(3 * time.Second)
status := relay.Publish(context.Background(), ev)
log.Debugf("[NOSTR] published to %s: %s", url, status)
time.Sleep(3 * time.Second)
relay.Close()
}(url)
}
}
func (bot *TipBot) nostrHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
return bot.getNostrHandler(ctx)
} else if len(splits) > 1 {
switch strings.ToLower(splits[1]) {
case "add":
return bot.addNostrPubkeyHandler(ctx)
case "help":
return bot.nostrHelpHandler(ctx)
}
}
return ctx, nil
}
func (bot *TipBot) addNostrPubkeyHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 3 {
return ctx, fmt.Errorf("not enough arguments")
}
nostrKeyInput := splits[2]
// parse input
if strings.HasPrefix(nostrKeyInput, "nsec") {
bot.trySendMessage(ctx.Message().Sender, nostrPrivateKeyErrorMessage)
return ctx, fmt.Errorf("user entered nostr private key")
}
// conver to hex
if strings.HasPrefix(nostrKeyInput, "npub") {
prefix, pubkey, err := nip19.Decode(nostrKeyInput)
if err != nil {
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
return ctx, fmt.Errorf("shouldn't error: %s", err)
}
if prefix != "npub" {
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
return ctx, fmt.Errorf("returned invalid prefix")
}
nostrKeyInput = pubkey.(string)
}
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
// save node in db
user.Settings.Nostr.PubKey = nostrKeyInput
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
return ctx, err
}
bot.trySendMessage(ctx.Message().Sender, nostrAddedMessage)
return ctx, nil
}
func (bot *TipBot) nostrHelpHandler(ctx intercept.Context) (intercept.Context, error) {
bot.trySendMessage(ctx.Message().Sender, nosterRegisterMessage+"\n\n"+nostrHelpMessage)
return ctx, nil
}
func (bot *TipBot) getNostrHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
return ctx, err
}
var dynamicHelpMessage string
dynamicHelpMessage += nostrHelpMessage
if user.Settings.Nostr.PubKey == "" {
bot.trySendMessage(m.Sender, dynamicHelpMessage)
return ctx, fmt.Errorf("no nostr pubkey registered")
} else if len(user.Settings.Nostr.PubKey) > 0 {
pubkeyBech32, err := nip19.EncodePublicKey(user.Settings.Nostr.PubKey)
if err != nil {
log.Infof("Could not decode user nostr pubkey %s", GetUserStr(user.Telegram))
return ctx, err
}
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoMessage, pubkeyBech32)
if lnaddr, _ := bot.UserGetLightningAddress(user); len(lnaddr) > 0 {
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoLNAddrMessage, lnaddr)
}
bot.trySendMessage(m.Sender, dynamicHelpMessage)
}
return ctx, nil
}
-387
View File
@@ -1,387 +0,0 @@
package telegram
import (
"context"
"errors"
"fmt"
"strconv"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// NoteConfirm is the pending "create a note" dialog in private chat.
type NoteConfirm struct {
*storage.Base
UserName string `json:"user_name"`
Quote lnurlcash.Quote `json:"quote"`
Memo string `json:"memo"`
LanguageCode string `json:"languagecode"`
ValueMsat int64 `json:"value_msat"`
Count int `json:"count"`
}
var (
btnNoteCreate = (&tb.ReplyMarkup{}).Data("", "lnc_create")
btnNoteMint = (&tb.ReplyMarkup{}).Data("", "lnc_mint")
btnNoteCancel = (&tb.ReplyMarkup{}).Data("", "lnc_cancel")
btnNoteStatus = (&tb.ReplyMarkup{}).Data("", "lnc_status")
btnNoteReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_reclaim")
btnNoteQR = (&tb.ReplyMarkup{}).Data("", "lnc_qr")
)
// noteCommandUser resolves the sender for a note command. In a group a user
// without a wallet is told to start a private chat; in private chat the
// start flow runs.
func (bot *TipBot) noteCommandUser(ctx intercept.Context) (*lnbits.User, bool) {
user := LoadUser(ctx)
m := ctx.Message()
if user == nil || user.Wallet == nil || !user.Initialized {
if m.Private() {
_, _ = bot.startHandler(ctx)
return nil, false
}
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return nil, false
}
return user, true
}
// noteHandler handles /note <amount> [memo].
func (bot *TipBot) noteHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount <= 0 {
if m.Private() {
bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteHelpMessage"))
} else {
NewMessage(m, WithDuration(0, bot))
bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteHelpMessage"))
}
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
memo := GetMemoFromCommand(m.Text, 2)
svc := bot.LNURLCash
mint, ok := svc.Mints().ForUser(user.Name)
if !ok {
bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
q, err := svc.Quote(ctx, mint, amount*1000, 1)
if err == nil {
err = svc.CheckCaps(ctx, user.Name, q, !m.Private())
}
if err != nil {
text := lnurlcashErrorText(ctx, err)
if m.Private() {
bot.trySendMessage(m.Sender, text)
} else {
NewMessage(m, WithDuration(0, bot))
bot.sendPrivate(m.Sender, text)
}
return ctx, err
}
if !m.Private() {
return bot.createNoteInGroup(ctx, user, q, memo)
}
confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))),
UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: 1}
bot.trySendMessageEditable(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID))
return ctx, confirm.Set(confirm, bot.Bunt)
}
func noteConfirmText(ctx context.Context, c *NoteConfirm) string {
q := c.Quote
text := fmt.Sprintf(TranslateUser(ctx, "noteConfirmMessage"), q.Count, formatSat(q.ValueMsat), formatSat(q.FeeMsat), formatSat(q.GrossMsat), q.MintName)
if c.Memo != "" {
text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(c.Memo))
}
return text
}
func noteConfirmKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
menu.Inline(
menu.Row(menu.Data(TranslateUser(ctx, "noteCreateButton"), "lnc_create", id)),
menu.Row(menu.Data(TranslateUser(ctx, "noteChangeMintButton"), "lnc_mint", id),
menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_cancel", id)),
)
return menu
}
// loadNoteConfirm loads the dialog behind a callback and checks ownership.
func (bot *TipBot) loadNoteConfirm(ctx intercept.Context) (*NoteConfirm, error) {
tx := &NoteConfirm{Base: storage.New(storage.ID(ctx.Data()))}
got, err := tx.Get(tx, bot.Bunt)
if err != nil {
return nil, err
}
c := got.(*NoteConfirm)
if c.UserName != LoadUser(ctx).Name {
return nil, tiperrors.Create(tiperrors.UnknownError)
}
if !c.Active {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
return c, nil
}
// noteCreateHandler runs when the user pressed Create.
func (bot *TipBot) noteCreateHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
_ = c.Inactivate(c, bot.Bunt)
user := LoadUser(ctx)
msg := ctx.Callback().Message
bot.tryEditMessage(msg, TranslateUser(ctx, "noteCreatingMessage"), &tb.ReplyMarkup{})
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: c.Quote, Memo: c.Memo}
if c.Count > 1 {
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
return bot.createBatchFromConfirm(ctx, c, params, msg)
})
return ctx, nil
}
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return err
}
bot.tryDeleteMessage(msg)
bot.sendNoteCreated(ctx, user.Telegram, live[0])
return nil
})
return ctx, nil
}
// goNoteCreate runs a note creation in the background, so the handler can
// return and release the user's lock while the mint invoice is paid and the
// note is awaited. One user's creations still run one at a time, which keeps
// the caps that Create checks from being raced.
func (bot *TipBot) goNoteCreate(ctx intercept.Context, userName string, run func(intercept.Context) error) {
bg := ctx
// keep the request's values (localizer, user) but not its lifetime
bg.Context = context.WithoutCancel(ctx.Context)
go func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("[lnurlcash] note creation for %s panicked: %v", userName, r)
}
}()
key := "lnurlcash-create:" + userName
mutex.Lock(key)
defer mutex.Unlock(key)
if err := run(bg); err != nil {
log.Warnf("[lnurlcash] note creation for %s: %v", userName, err)
}
}()
}
// sendNoteCreated sends the QR and the note text with its buttons.
func (bot *TipBot) sendNoteCreated(ctx context.Context, to *tb.User, n *lnurlcash.Note) {
bot.sendNoteQR(to, n)
lnurlw, _, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
log.Errorf("[lnurlcash] note strings: %v", err)
return
}
text := fmt.Sprintf(TranslateUser(ctx, "noteCreatedMessage"), formatSat(n.ReportedMsat), lnurlcash.ShortID(n.ID), lnurlw)
bot.trySendMessageEditable(to, text, noteKeyboard(ctx, n, false))
}
// noteMintHandler cycles the dialog to the next usable mint and re-quotes.
func (bot *TipBot) noteMintHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
mints := bot.LNURLCash.Mints().All()
var usable []*lnurlcash.Mint
for _, m := range mints {
if m.Usable() {
usable = append(usable, m)
}
}
if len(usable) < 2 {
bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteOnlyOneMintMessage"))
return ctx, nil
}
next := usable[0]
for i, m := range usable {
if m.ID == c.Quote.MintID {
next = usable[(i+1)%len(usable)]
break
}
}
q, err := bot.LNURLCash.Quote(ctx, next, c.ValueMsat, c.Count)
if err != nil {
bot.trySendMessage(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
c.Quote = q
bot.tryEditMessage(ctx.Callback().Message, noteConfirmText(ctx, c), noteConfirmKeyboard(ctx, c.ID))
return ctx, c.Set(c, bot.Bunt)
}
// noteCancelHandler runs when the user pressed Cancel.
func (bot *TipBot) noteCancelHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "noteCancelledMessage"), &tb.ReplyMarkup{})
return ctx, c.Inactivate(c, bot.Bunt)
}
// createNoteInGroup creates a note without a confirm step, posts it in the
// group and sends the receipt privately.
func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q lnurlcash.Quote, memo string) (intercept.Context, error) {
m := ctx.Message()
receipt, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteCreatingMessage"))
if !ok {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: q, Memo: memo, ChatID: m.Chat.ID}
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
return bot.finishGroupNote(ctx, m, receipt, q, memo, params)
})
return ctx, nil
}
// finishGroupNote creates a group note, posts it in the group and fills in
// the private receipt. It runs in the background.
func (bot *TipBot) finishGroupNote(ctx intercept.Context, m, receipt *tb.Message, q lnurlcash.Quote, memo string, params lnurlcash.CreateParams) error {
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(receipt, lnurlcashErrorText(ctx, err))
return err
}
n := live[0]
_, bech, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
return err
}
qr, err := qrcodeEncode(bech)
if err != nil {
return err
}
caption := fmt.Sprintf(Translate(ctx, "noteGroupMessage"), formatSat(n.ReportedMsat), GetUserStrMd(m.Sender), bech)
if memo != "" {
caption += fmt.Sprintf(Translate(ctx, "noteViewMemo"), str.MarkdownEscape(memo))
}
post := bot.tryReplyMessage(m, &tb.Photo{File: tb.File{FileReader: qr}, Caption: caption})
if post != nil {
_ = bot.LNURLCash.Store().UpdateNote(n.ID, map[string]interface{}{"chat_id": post.Chat.ID, "message_id": strconv.Itoa(post.ID)})
}
lnurlw, _, _ := bot.LNURLCash.NoteStrings(n)
text := fmt.Sprintf(TranslateUser(ctx, "noteReceiptMessage"), formatSat(n.ReportedMsat), formatSat(q.FeeMsat), q.MintName, lnurlcash.ShortID(n.ID), lnurlw)
bot.tryEditMessage(receipt, text, noteKeyboard(ctx, n, false))
log.Infof("[lnurlcash] %s created group note %s (%d msat) in chat %d", GetUserStr(m.Sender), n.ID, n.ReportedMsat, m.Chat.ID)
return nil
}
// noteStatusHandler answers the Check status button.
func (bot *TipBot) noteStatusHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
state, value, err := bot.LNURLCash.Status(ctx, n)
var text string
switch {
case errors.Is(err, lnurlcashgoPending()):
text = TranslateUser(ctx, "noteStatusPendingMessage")
case err != nil:
text = TranslateUser(ctx, "noteMintUnavailableMessage")
case state == lnurlcash.NoteClaimed:
text = TranslateUser(ctx, "noteStatusClaimedMessage")
case state == lnurlcash.NoteLive:
text = fmt.Sprintf(TranslateUser(ctx, "noteStatusLiveMessage"), formatSat(value))
default:
text = fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, state))
}
bot.trySendMessageEditable(ctx.Sender(), text)
if ctx.Callback().Message != nil {
_, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false))
}
return ctx, nil
}
// noteReclaimHandler answers the Reclaim button.
func (bot *TipBot) noteReclaimHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
n, err = bot.LNURLCash.Reclaim(ctx, n.ID)
if err != nil {
bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteReclaimRequestedMessage"), formatSat(n.ReportedMsat)))
bot.awaitLNURLCashSettlement(n.UserName, n.InvoiceHash)
if ctx.Callback().Message != nil {
_, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false))
}
(&lnurlcashNotifier{bot: bot}).GroupNoteState(n)
return ctx, nil
}
// noteQRHandler answers the Show QR button.
func (bot *TipBot) noteQRHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
if n.State != lnurlcash.NoteLive {
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, n.State)))
return ctx, nil
}
bot.sendNoteCreated(ctx, ctx.Sender(), n)
return ctx, nil
}
// lnurlcashgoPending is the library's pending sentinel, kept behind a
// function so this file does not import the library for one value.
func lnurlcashgoPending() error { return lnurlcash.ErrNotePending }
-127
View File
@@ -1,127 +0,0 @@
package telegram
import (
"errors"
"fmt"
"strings"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// LNURLCashNoteParams is what HandleLNURL returns for a withdraw link that
// publishes a mintPubkey: an LNURLcash note rather than a plain withdraw.
type LNURLCashNoteParams struct {
URL string
}
var (
btnRedeemOK = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_ok")
btnRedeemCancel = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_no")
)
// redeemHandler handles /redeem <note>. In a group the command is deleted
// at once because it carries the secret, and the flow continues privately.
func (bot *TipBot) redeemHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
if !m.Private() {
bot.tryDeleteMessage(m)
}
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
parts := strings.Fields(m.Text)
if len(parts) < 2 {
if _, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "redeemHelpMessage")); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
return bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, parts[1], !m.Private())
}
// redeemInput previews a pasted note and offers to add it to the balance.
// Everything goes to the user's private chat.
func (bot *TipBot) redeemInput(ctx intercept.Context, userName, lang, input string, fromGroup bool) (intercept.Context, error) {
sender := ctx.Sender()
preview, err := bot.LNURLCash.RedeemInfo(ctx, userName, lang, input)
if err != nil {
if errors.Is(err, lnurlcash.ErrNotANote) && !fromGroup {
// the caller decides (the /lnurl flow falls back to a plain withdraw)
return ctx, err
}
text := lnurlcashErrorText(ctx, err)
var opts []interface{}
var own *lnurlcash.ErrOwnNote
if errors.As(err, &own) {
// show the note itself with its own Check status / Reclaim buttons
if n, nerr := bot.LNURLCash.Store().Note(own.NoteID); nerr == nil {
text += "\n\n" + noteViewText(ctx, n)
opts = append(opts, noteKeyboard(ctx, n, false))
}
}
if _, ok := bot.sendPrivate(sender, text, opts...); !ok && fromGroup {
bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, err
}
text := fmt.Sprintf(TranslateUser(ctx, "redeemPreviewMessage"), formatSat(preview.ValueMsat), preview.MintHost)
if !preview.KnownMint {
text += "\n\n" + TranslateUser(ctx, "redeemUnknownMintWarning")
}
menu := &tb.ReplyMarkup{}
menu.Inline(menu.Row(
menu.Data(TranslateUser(ctx, "redeemAddButton"), "lnc_redeem_ok", preview.Redeem.ID),
menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_redeem_no", preview.Redeem.ID)))
if _, ok := bot.sendPrivate(sender, text, menu); !ok && fromGroup {
bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, nil
}
// redeemConfirmHandler runs when Add to balance was pressed.
func (bot *TipBot) redeemConfirmHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
user := LoadUser(ctx)
msg := ctx.Callback().Message
bot.tryEditMessage(msg, TranslateUser(ctx, "redeemInFlightMessage"), &tb.ReplyMarkup{})
r, err := bot.LNURLCash.Redeem(ctx, ctx.Data(), user.Name)
if err != nil {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
}
log.Infof("[lnurlcash] %s redeems %s (%d msat)", GetUserStr(ctx.Sender()), r.ID, r.ReportedMsat)
bot.awaitLNURLCashSettlement(r.UserName, r.InvoiceHash)
bot.tryEditMessage(msg, fmt.Sprintf(TranslateUser(ctx, "redeemRequestedMessage"), formatSat(r.ReportedMsat)), &tb.ReplyMarkup{})
return ctx, nil
}
// redeemCancelHandler runs when Cancel was pressed on a preview.
func (bot *TipBot) redeemCancelHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
r, err := bot.LNURLCash.Store().Redeem(ctx.Data())
if err != nil || r.UserName != LoadUser(ctx).Name {
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
_ = bot.LNURLCash.Store().TransitionRedeem(r.ID, lnurlcash.RedeemInfo, lnurlcash.RedeemFailed, map[string]interface{}{"last_error": "cancelled"})
bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "redeemCancelledMessage"), &tb.ReplyMarkup{})
return ctx, nil
}
// LNURLKind satisfies go-lnurl's LNURLParams so HandleLNURL can return a note.
func (LNURLCashNoteParams) LNURLKind() string { return "lnurlcash-note" }
-234
View File
@@ -1,234 +0,0 @@
package telegram
import (
"bytes"
"context"
"fmt"
"strings"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
btnBatchExportPDF = (&tb.ReplyMarkup{}).Data("", "lnc_exp_pdf")
btnBatchExportJSON = (&tb.ReplyMarkup{}).Data("", "lnc_exp_json")
btnBatchExportCSV = (&tb.ReplyMarkup{}).Data("", "lnc_exp_csv")
btnBatchRefresh = (&tb.ReplyMarkup{}).Data("", "lnc_brefresh")
btnBatchReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_breclaim")
)
// parseBatchCommand reads "/notes <amount> x <count> [memo]". ok is false
// when the text is not a batch command.
func parseBatchCommand(text string) (amount int64, count int, memo string, ok bool) {
parts := strings.Fields(text)
if len(parts) < 4 {
return 0, 0, "", false
}
sep := strings.ToLower(parts[2])
if sep != "x" && sep != "×" && sep != "*" {
return 0, 0, "", false
}
amount, err := GetAmount(parts[1])
if err != nil {
return 0, 0, "", false
}
var n int
if _, err := fmt.Sscanf(parts[3], "%d", &n); err != nil || n < 1 {
return 0, 0, "", false
}
return amount, n, GetMemoFromCommand(text, 4), true
}
// noteBatchStart quotes a batch and shows the confirm dialog privately.
func (bot *TipBot) noteBatchStart(ctx intercept.Context, user *lnbits.User, amount int64, count int, memo string) (intercept.Context, error) {
m := ctx.Message()
svc := bot.LNURLCash
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
mint, ok := svc.Mints().ForUser(user.Name)
if !ok {
bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
q, err := svc.Quote(ctx, mint, amount*1000, count)
if err == nil {
err = svc.CheckCaps(ctx, user.Name, q, false)
}
if err != nil {
if _, ok := bot.sendPrivate(m.Sender, lnurlcashErrorText(ctx, err)); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, err
}
confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))),
UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: count}
if _, ok := bot.sendPrivate(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)); !ok {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, confirm.Set(confirm, bot.Bunt)
}
// createBatchFromConfirm runs after Create was pressed on a batch dialog.
// It runs in the background (see goNoteCreate).
func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) error {
total := c.Count
key := "lnc-progress-" + c.ID
params.Progress = func(done, total int) {
bot.tryEditStack(msg, key, fmt.Sprintf(TranslateUser(ctx, "notesBatchProgressMessage"), done, total, MakeProgressbar(int64(done), int64(total))))
}
batch, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return err
}
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchCreatedMessage"), len(live), total, lnurlcash.ShortID(batch.ID))
if err != nil {
text += "\n" + fmt.Sprintf(TranslateUser(ctx, "notesBatchPartialMessage"), lnurlcashErrorText(ctx, err))
}
text += "\n\n" + TranslateUser(ctx, "notesBatchFormatMessage")
bot.tryEditMessage(msg, text, batchKeyboard(ctx, batch.ID))
return nil
}
// batchKeyboard offers the export formats and the batch actions.
func batchKeyboard(ctx context.Context, batchID string) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
cfg := bot_lnurlcash_cfg()
var formats []tb.Btn
if cfg.HasFormat("pdf") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportPdfButton"), "lnc_exp_pdf", batchID))
}
if cfg.HasFormat("json") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportJsonButton"), "lnc_exp_json", batchID))
}
if cfg.HasFormat("csv") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportCsvButton"), "lnc_exp_csv", batchID))
}
rows := []tb.Row{}
if len(formats) > 0 {
rows = append(rows, menu.Row(formats...))
}
rows = append(rows, menu.Row(
menu.Data(TranslateUser(ctx, "notesRefreshButton"), "lnc_brefresh", batchID),
menu.Data(TranslateUser(ctx, "notesReclaimUnclaimedButton"), "lnc_breclaim", batchID)))
menu.Inline(rows...)
return menu
}
// batchViewText renders a batch with its counts.
func (bot *TipBot) batchViewText(ctx context.Context, b *lnurlcash.Batch) string {
sum, _ := bot.LNURLCash.Summarize(b.ID)
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchOpenMessage"), lnurlcash.ShortID(b.ID), b.Count, formatSat(b.ValueMsat), b.MintID,
b.CreatedAt.UTC().Format("2 Jan 06 15:04"), sum.Live, sum.Claimed, sum.Reclaimed, sum.Failed+sum.Pending)
if b.Memo != "" {
text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), b.Memo)
}
return text
}
// loadOwnBatch loads the batch behind a callback and checks ownership.
func (bot *TipBot) loadOwnBatch(ctx intercept.Context) (*lnurlcash.Batch, error) {
b, err := bot.LNURLCash.Store().Batch(ctx.Data())
if err != nil {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
if b.UserName != LoadUser(ctx).Name {
return nil, lnurlcash.ErrNotOwner
}
return b, nil
}
func (bot *TipBot) batchExportHandler(format string) intercept.Func {
return func(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
if !bot_lnurlcash_cfg().HasFormat(format) {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
// files only ever go to the private chat
if msg := ctx.Callback().Message; msg != nil && !msg.Private() {
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
data, err := bot.LNURLCash.ExportBatch(b.ID, LoadUser(ctx).Name)
if err != nil {
bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
var buf bytes.Buffer
var mime string
switch format {
case "pdf":
err, mime = export.PDF(&buf, data), "application/pdf"
case "json":
err, mime = export.JSON(&buf, data), "application/json"
case "csv":
err, mime = export.CSV(&buf, data), "text/csv"
}
if err != nil {
log.Errorf("[lnurlcash] export %s of %s: %v", format, b.ID, err)
bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteErrorMessage"))
return ctx, err
}
doc := &tb.Document{File: tb.File{FileReader: &buf}, FileName: fmt.Sprintf("notes-%s.%s", lnurlcash.ShortID(b.ID), format), MIME: mime,
Caption: fmt.Sprintf(TranslateUser(ctx, "notesExportCaption"), len(data.Notes), lnurlcash.ShortID(b.ID))}
bot.trySendMessageEditable(ctx.Sender(), doc)
return ctx, nil
}
}
// batchRefreshHandler probes every live note of the batch and re-renders it.
func (bot *TipBot) batchRefreshHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
notes, _ := bot.LNURLCash.Store().NotesInBatch(b.ID)
for _, n := range notes {
if n.Kind == lnurlcash.KindUser && n.State == lnurlcash.NoteLive {
_, _, _ = bot.LNURLCash.Status(ctx, n)
}
}
b, _ = bot.LNURLCash.Store().Batch(b.ID)
bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
// batchReclaimHandler reclaims every unclaimed note of the batch.
func (bot *TipBot) batchReclaimHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
sent, err := bot.LNURLCash.ReclaimBatch(ctx, b.ID, LoadUser(ctx).Name)
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchReclaimMessage"), sent)
if err != nil {
text += "\n" + lnurlcashErrorText(ctx, err)
}
bot.trySendMessageEditable(ctx.Sender(), text)
b, _ = bot.LNURLCash.Store().Batch(b.ID)
bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
-205
View File
@@ -1,205 +0,0 @@
package telegram
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
const notesPerPage = 8
var (
btnNotesPage = (&tb.ReplyMarkup{}).Data("", "lnc_page")
btnNotesOpen = (&tb.ReplyMarkup{}).Data("", "lnc_open")
btnNotesOpenB = (&tb.ReplyMarkup{}).Data("", "lnc_openb")
)
// NotesList is a user's open /notes list; pages are computed from the DB.
type NotesList struct {
*storage.Base
UserName string `json:"user_name"`
}
type notesEntry struct {
id string
batch bool
created time.Time
label string
}
// notesHandler handles /notes and /notes <amount> x <count> [memo].
func (bot *TipBot) notesHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
if amount, count, memo, isBatch := parseBatchCommand(m.Text); isBatch {
return bot.noteBatchStart(ctx, user, amount, count, memo)
}
if len(strings.Fields(m.Text)) > 1 {
bot.sendPrivate(m.Sender, TranslateUser(ctx, "notesHelpMessage"))
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
list := &NotesList{Base: storage.New(storage.ID(fmt.Sprintf("lncl-%d-%s", m.Sender.ID, RandStringRunes(6)))), UserName: user.Name}
text, kb := bot.notesPage(ctx, list, 0)
if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, list.Set(list, bot.Bunt)
}
// notesEntries lists single notes and batches, newest first.
func (bot *TipBot) notesEntries(ctx context.Context, user string) []notesEntry {
store := bot.LNURLCash.Store()
var entries []notesEntry
batches, _ := store.UserBatches(user)
inBatch := map[string]bool{}
for _, b := range batches {
inBatch[b.ID] = true
sum, _ := bot.LNURLCash.Summarize(b.ID)
entries = append(entries, notesEntry{id: b.ID, batch: true, created: b.CreatedAt,
label: fmt.Sprintf(TranslateUser(ctx, "notesBatchItem"), b.Count, formatSat(b.ValueMsat), sum.Live, sum.Claimed, lnurlcash.ShortID(b.ID))})
}
notes, _ := store.UserNotes(user, nil)
for _, n := range notes {
if n.BatchID != nil && inBatch[*n.BatchID] {
continue
}
value := n.ReportedMsat
if value == 0 {
value = n.ValueMsat
}
memo := n.Memo
if len(memo) > 20 {
memo = memo[:19] + "…"
}
entries = append(entries, notesEntry{id: n.ID, created: n.CreatedAt,
label: fmt.Sprintf(TranslateUser(ctx, "notesListItem"), noteStateEmoji(n.State), formatSat(value), lnurlcash.ShortID(n.ID), memo)})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].created.After(entries[j].created) })
return entries
}
func noteStateEmoji(state string) string {
switch state {
case lnurlcash.NoteLive:
return "🟢"
case lnurlcash.NoteClaimed:
return "✅"
case lnurlcash.NoteReclaimed:
return "↩️"
case lnurlcash.NoteReclaiming:
return "🔄"
case lnurlcash.NoteFailed:
return "🚫"
}
return "⏳"
}
// notesPage renders one page of the list with its buttons.
func (bot *TipBot) notesPage(ctx context.Context, list *NotesList, page int) (string, *tb.ReplyMarkup) {
entries := bot.notesEntries(ctx, list.UserName)
menu := &tb.ReplyMarkup{}
if len(entries) == 0 {
return TranslateUser(ctx, "notesListEmpty"), menu
}
pages := (len(entries) + notesPerPage - 1) / notesPerPage
if page < 0 {
page = 0
}
if page >= pages {
page = pages - 1
}
start := page * notesPerPage
end := start + notesPerPage
if end > len(entries) {
end = len(entries)
}
var rows []tb.Row
text := fmt.Sprintf(TranslateUser(ctx, "notesListHeader"), len(entries), page+1, pages) + "\n"
for i, e := range entries[start:end] {
text += fmt.Sprintf("\n%d. %s", start+i+1, str.MarkdownEscape(e.label))
unique := "lnc_open"
if e.batch {
unique = "lnc_openb"
}
rows = append(rows, menu.Row(menu.Data(fmt.Sprintf("%d · %s", start+i+1, lnurlcash.ShortID(e.id)), unique, e.id)))
}
var nav []tb.Btn
if page > 0 {
nav = append(nav, menu.Data("◀️", "lnc_page", list.ID+":"+strconv.Itoa(page-1)))
}
if page < pages-1 {
nav = append(nav, menu.Data("▶️", "lnc_page", list.ID+":"+strconv.Itoa(page+1)))
}
if len(nav) > 0 {
rows = append(rows, menu.Row(nav...))
}
menu.Inline(rows...)
return text, menu
}
// notesPageHandler scrolls the list.
func (bot *TipBot) notesPageHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
id, pageStr, _ := strings.Cut(ctx.Data(), ":")
page, _ := strconv.Atoi(pageStr)
tx := &NotesList{Base: storage.New(storage.ID(id))}
got, err := tx.Get(tx, bot.Bunt)
if err != nil {
return ctx, err
}
list := got.(*NotesList)
if list.UserName != LoadUser(ctx).Name {
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
text, kb := bot.notesPage(ctx, list, page)
bot.tryEditMessage(ctx.Callback().Message, text, kb)
return ctx, nil
}
// notesOpenHandler shows one note with its actions.
func (bot *TipBot) notesOpenHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), noteViewText(ctx, n), noteKeyboard(ctx, n, true))
return ctx, nil
}
// notesOpenBatchHandler shows one batch with its actions.
func (bot *TipBot) notesOpenBatchHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
+13 -34
View File
@@ -17,7 +17,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
lnurl "github.com/fiatjaf/go-lnurl"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -39,16 +38,15 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
type PayData struct {
*storage.Base
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
SuccessAction *lnurl.SuccessAction `json:"successAction"`
TelegramMessage *tb.Message `json:"telegrammessage"`
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
TelegramMessage *tb.Message `json:"telegrammessage"`
}
// payHandler invoked on "/pay lnbc..." command
@@ -134,12 +132,6 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
cancelButton),
)
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
// read successaction
sa, ok := ctx.Value("SuccessAction").(*lnurl.SuccessAction)
if !ok {
sa = &lnurl.SuccessAction{}
}
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
@@ -148,7 +140,6 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
Memo: bolt11.Description,
Message: confirmText,
LanguageCode: ctx.Value("publicLanguageCode").(string),
SuccessAction: sa,
TelegramMessage: payMessage,
}
// add result to persistent struct
@@ -192,6 +183,8 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
return ctx, errors.Create(errors.UserNoWalletError)
}
invoiceString := payData.Invoice
// reset state immediately
ResetUserState(user, bot)
@@ -210,10 +203,10 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payData.Invoice}, bot.Client)
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
err = fmt.Errorf("%s", i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
@@ -224,8 +217,6 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
return ctx, err
}
payData.Hash = invoice.PaymentHash
// the invoice is paid, a second press must not pay it again
payData.Active = false
// do balance check for keyboard update
_, err = bot.GetUserBalance(user)
@@ -245,18 +236,6 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
// display LNURL success action if present
sa := payData.SuccessAction
if sa.Tag == "message" && len(sa.Message) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: `%s`", sa.Message))
} else if sa.Tag == "url" && len(sa.URL) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("🔗: %s", str.MarkdownEscape(sa.URL)), tb.NoPreview)
if len(sa.Description) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: %s", sa.Description))
}
}
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return ctx, nil
}

Some files were not shown because too many files have changed in this diff Show More