Compare commits

..
Author SHA1 Message Date
gohumble 2cfbacf704 update GetUserStrMd 2022-06-13 08:34:27 +02:00
gohumble df8e198b2e update GetUserStr 2022-06-12 22:25:19 +02:00
139 changed files with 1105 additions and 15331 deletions
+1 -6
View File
@@ -1,9 +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
!data/.placeholder
+3 -12
View File
@@ -18,7 +18,7 @@ To build the bot from source, clone the repository and compile the source code.
git clone https://github.com/LightningTipBot/LightningTipBot.git
cd LightningTipBot
go build .
cp config.yaml.example config.yaml
cp config.yaml-example config.yaml
```
After the configuration (see below), start it using the command
@@ -56,10 +56,9 @@ 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).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
## Features
@@ -117,7 +116,7 @@ Users can send and receive via . For this to work, you need to set the `lnurl_pu
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
### Link to BlueWallet or Zeus
### Link to BlueWallet or Zap
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
@@ -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
+2 -42
View File
@@ -1,16 +1,8 @@
bot:
socks_proxy:
host: 127.0.0.1:9996
username: test
password: username
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,35 +18,3 @@ 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:
# url may list several mints, comma separated (e.g. "lnurl.21mint.me,mint.600.wtf"):
# the first keeps this name, the others are named after their host. Users pick
# their own default with /lnurlmints; `default: true` is the fallback.
- name: 21mint
url: https://lnurl.21mint.me
default: true
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
-1
View File
@@ -1 +0,0 @@
this is where dalle images are stored
-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?
+10 -97
View File
@@ -1,121 +1,34 @@
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/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7
github.com/fiatjaf/go-lnurl v1.8.4
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
github.com/sethvargo/go-limiter v0.7.2
github.com/sirupsen/logrus v1.6.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
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/time v0.0.0-20210220033141-f8bda1e9f3ba
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8
golang.org/x/text v0.3.6
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
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/btcutil/psbt v1.1.4 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // 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
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
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/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
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
github.com/lightninglabs/neutrino v0.14.2 // indirect
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
github.com/mattn/go-sqlite3 v1.14.5 // indirect
github.com/miekg/dns v1.1.43 // indirect
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
github.com/pegasus-kv/thrift v0.13.0 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/tidwall/btree v0.6.1 // indirect
github.com/tidwall/grect v0.1.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
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/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
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
)
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
+98 -759
View File
File diff suppressed because it is too large Load Diff
+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
-14
View File
@@ -1,14 +0,0 @@
package admin
import (
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
"net/http"
)
func (s Service) DisableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = false
}
func (s Service) EnableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = true
}
-27
View File
@@ -1,27 +0,0 @@
package api
type BalanceResponse struct {
Balance int64 `json:"balance"`
}
type InvoiceStatusResponse struct {
State string `json:"state,omitempty"`
PaymentHash string `json:"payment_hash"`
Preimage int64 `json:"preimage"`
}
type CreateInvoiceResponse struct {
PaymentHash string `json:"payment_hash"`
PayRequest string `json:"pay_request"`
Preimage string `json:"preimage,omitempty"`
}
type CreateInvoiceRequest struct {
Memo string `json:"memo"`
Amount int64 `json:"amount"`
DescriptionHash string `json:"description_hash"`
UnhashedDescription string `json:"unhashed_description"`
}
type PayInvoiceRequest struct {
PayRequest string `json:"pay_req"`
}
-231
View File
@@ -1,231 +0,0 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"github.com/r3labs/sse"
)
type Service struct {
Bot *telegram.TipBot
}
type ErrorResponse struct {
Message string `json:"error"`
}
func RespondError(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
}
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
balance, err := s.Bot.GetUserBalance(user)
if err != nil {
RespondError(w, "balance check failed")
return
}
balanceResponse := BalanceResponse{
Balance: balance,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(balanceResponse)
}
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var createInvoiceRequest CreateInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: createInvoiceRequest.Amount,
Out: false,
DescriptionHash: createInvoiceRequest.DescriptionHash,
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
Memo: createInvoiceRequest.Memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
s.Bot.Client)
if err != nil {
RespondError(w, "could not create invoice")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(invoice)
}
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var payInvoiceRequest PayInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
if err != nil {
RespondError(w, "could not pay invoice: "+err.Error())
return
}
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
if err != nil {
// we assume that it's paid since thre was no error earlier
payment.Paid = true
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get payment")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
// InvoiceStatus
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
user.Wallet = &lnbits.Wallet{}
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get invoice")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
type InvoiceStream struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
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)
return
}
client := sse.NewClient(fmt.Sprintf("%s/api/v1/payments/sse", internal.Configuration.Lnbits.Url))
client.Connection.Transport = &http.Transport{DisableCompression: true}
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
c := make(chan *sse.Event)
err := client.SubscribeChan("", c)
if err != nil {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
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 {
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()
}
}
// 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
}
}
}
-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")
}
}
-129
View File
@@ -1,18 +1,8 @@
package api
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"net/http"
"net/http/httputil"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
)
@@ -26,108 +16,6 @@ func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
}
}
type AuthType struct {
Type string
Decoder func(s string) ([]byte, error)
}
var AuthTypeBasic = AuthType{Type: "Basic"}
var AuthTypeBearerBase64 = AuthType{Type: "Bearer", Decoder: base64.StdEncoding.DecodeString}
var AuthTypeNone = AuthType{}
// invoice key or admin key requirement
type AccessKeyType struct {
Type string
}
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if accessType.Type == "none" {
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
// check if the user is banned
if auth == "" {
w.WriteHeader(401)
log.Warn("[api] no auth")
return
}
_, password, ok := parseAuth(authType, auth)
if !ok {
w.WriteHeader(401)
return
}
// 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")
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
var tx *gorm.DB
if accessType.Type == "admin" {
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
} else if accessType.Type == "invoice" {
tx = database.Where("wallet_inkey = ? OR wallet_adminkey = ? COLLATE NOCASE", password, password).First(user)
} else {
log.Errorf("[api] route without access type")
w.WriteHeader(401)
return
}
if tx.Error != nil {
log.Warnf("[api] could not load access key: %v", tx.Error)
w.WriteHeader(401)
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)
}
}
// parseAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
parse := func(prefix string) (username, password string, ok bool) {
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
if authType.Decoder != nil {
c, err := authType.Decoder(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
return auth[len(prefix):], auth[len(prefix):], true
}
return parse(fmt.Sprintf("%s ", authType.Type))
}
func dump(r *http.Request) string {
x, err := httputil.DumpRequest(r, true)
if err != nil {
@@ -135,20 +23,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)
}
}
}
+3 -30
View File
@@ -5,8 +5,6 @@ import (
"net/http"
"time"
"gorm.io/gorm"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
@@ -25,37 +23,25 @@ func NewServer(address string) *Server {
srv := &http.Server{
Addr: address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 90 * time.Second,
ReadTimeout: 90 * time.Second,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &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)
log.Infof("[API] Server started at %s", address)
return apiServer
}
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)
}
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, accessType, handler)))
if len(methods) > 0 {
r.Methods(methods...)
}
}
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
if len(methods) > 0 {
@@ -77,16 +63,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)
})
}
-387
View File
@@ -1,387 +0,0 @@
<!-- @format -->
{{define "webapp"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="MobileOptimized" content="176" />
<meta name="HandheldFriendly" content="True" />
<meta name="robots" content="noindex,nofollow" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>@LightningTipBot</title>
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
<script>
function setThemeClass() {
document.documentElement.className = Telegram.WebApp.colorScheme;
}
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
setThemeClass();
</script>
<style>
body {
font-family: sans-serif;
background-color: var(--tg-theme-bg-color, #ffffff);
color: var(--tg-theme-text-color, #222222);
font-size: 16px;
margin: 0;
padding: 0;
color-scheme: var(--tg-color-scheme);
}
a {
color: var(--tg-theme-link-color, #2678b6);
}
button {
display: block;
width: 100%;
font-size: 14px;
border: none;
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
cursor: pointer;
}
.btn-primary {
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
}
button[disabled] {
opacity: 0.6;
cursor: auto;
pointer-events: none;
}
input {
font-size: 14px;
text-align: center;
border: none;
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
.input-group-text {
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
section {
padding: 5px 5px 65px;
text-align: center;
}
p {
margin: 40px 0 15px;
}
ul {
text-align: left;
}
li {
color: var(--tg-theme-hint-color, #a8a8a8);
}
textarea {
width: 100%;
box-sizing: border-box;
padding: 7px;
}
pre {
background: rgba(0, 0, 0, .07);
border-radius: 4px;
padding: 4px;
margin: 7px 0;
word-break: break-all;
word-break: break-word;
white-space: pre-wrap;
text-align: left;
}
.dark pre {
background: rgba(255, 255, 255, .15);
}
.hint {
font-size: .8em;
color: var(--tg-theme-hint-color, #a8a8a8);
}
.ok {
color: green;
}
.err {
color: red;
}
#fixed_wrap {
position: fixed;
left: 0;
right: 0;
top: 0;
transform: translateY(100vh);
}
.viewport_border,
.viewport_stable_border {
position: fixed;
left: 0;
right: 0;
top: 0;
height: var(--tg-viewport-height, 100vh);
pointer-events: none;
}
.viewport_stable_border {
height: var(--tg-viewport-stable-height, 100vh);
}
.viewport_border:before,
.viewport_stable_border:before {
content: attr(text);
display: inline-block;
position: absolute;
background: gray;
right: 0;
top: 0;
font-size: 7px;
padding: 2px 4px;
vertical-align: top;
}
.viewport_stable_border:before {
background: green;
left: 0;
right: auto;
}
.viewport_border:after,
.viewport_stable_border:after {
content: '';
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
border: 2px dashed gray;
}
.viewport_stable_border:after {
border-color: green;
}
small {
font-size: 12px;
}
h1 {
font-size: 120%;
word-wrap: break-word;
margin: 0.5em;
}
.qr-container {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
.qr {
display: flex;
justify-content: center;
margin: 0px;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.qr > canvas {
max-height: 800px;
max-width: 800px;
width: 100% !important;
height: 100% !important;
}
.wrapper {
display: grid;
grid-template-columns: 3fr 2fr;
padding: 12px 20px;
column-gap: 10px;
row-gap: 1em;
align-items: center;
}
</style>
</head>
<body>
<section>
<h1 id="greeting"></h1>
<div class="qr-container">
<div class="qr" id="qr">
</div>
</div>
<div id="buttons">
<!-- <button onclick="webviewClose();">Close</button> -->
<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">
<div class="input-group-append">
<div class="input-group-text" id="inputCurrency"></div>
</div>
</div>
<div>
<button class="btn btn-primary" onclick="invoiceButtonClick();" style="display: inline;" id="requestInvoice">Invoice</button>
</div>
</div>
</div>
</section>
<script type="application/javascript">
Telegram.WebApp.ready();
// render the LNURL pay QR code
var s = "{{.LNURLPay}}";
const currencies = ["sat", "USD", "EUR"];
var currency_idx = 0;
document.getElementById("inputCurrency").innerHTML = currencies[0];
renderQr(s);
// data passed form telegram server
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').textContent = "{{.Username}}@ln.tips";
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
// react to theme changes
try {
document.querySelector('#themeData').html(JSON.stringify(Telegram.WebApp.themeParams, null, 2));
Telegram.WebApp.onEvent('themeChanged', function() {
document.querySelector('#themeData').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
});
} catch (error) {
console.error(error);
}
// listen for enter in input field
var el = document.getElementById("invoiceAmount");
el.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
document.getElementById("requestInvoice").click();
}
document.getElementById("requestInvoice").innerHTML = "Invoice"
// revert color of button
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
var el = document.getElementById("inputCurrency");
el.addEventListener("click", function(event) {
currency_idx += 1;
$(this).html(currencies[currency_idx%(currencies.length)]);
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
// ------------------ functions ------------------
function invoiceButtonClick() {
var c = "{{.Callback}}";
getInvoice(this, c);
// hide keyboard and scroll up
document.getElementById("invoiceAmount").blur();
window.scrollTo(0, 0);
}
function invoiceButtonDisplayError(message) {
btn = document.getElementById("requestInvoice")
btn.innerHTML = message
// update color of button
$('#requestInvoice').removeClass('btn-primary').addClass('btn-danger');
}
function webviewClose() {
Telegram.WebApp.close();
}
function renderQr(payload) {
const qr = document.getElementById('qr');
qr.innerHTML = '';
if ( qr ) {
const qrGfx = kjua({
text: payload,
rounded: 50,
size: 500,
render: 'canvas',
});
qr.appendChild( qrGfx );
// var href_link = "lightning:" + payload;
// qr.setAttribute('href', "javascript:window.open('"+ href_link+ "');" );
}
}
function getInvoice(el, callback) {
curr_idx = currency_idx%currencies.length
var invoiceAmount = Number(document.getElementById("invoiceAmount").value);
if ((currencies[curr_idx] == "sat" && !Number.isInteger(invoiceAmount)) || invoiceAmount < 1) {
invoiceButtonDisplayError("Invalid")
return false;
}
var amountQueryParam;
if (currencies[curr_idx] == "sat") {
amountQueryParam = invoiceAmount * 1000 // sat to msat
} else {
amountQueryParam = invoiceAmount + currencies[curr_idx]
}
fetch(callback)
.then(data => {
return data.json();
})
.then(r => {
console.log(r);
console.log("requesting invoice with amount " + amountQueryParam);
fetch(r.callback + '?amount='+ amountQueryParam).then(data => {
return data.json();
})
.then(r => {
console.log(r);
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').textContent = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
}
})
})
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
{{end}}
+3 -37
View File
@@ -6,7 +6,6 @@ import (
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"time"
@@ -28,17 +27,11 @@ 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
var templates embed.FS
var userpage_tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
var qr_tmpl = template.Must(template.ParseFS(templates, "static/webapp.html"))
var tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
var Client = &http.Client{
Timeout: 10 * time.Second,
@@ -74,12 +67,8 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
}
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/@<username>
// https://ln.tips/.well-known/lnurlp/<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)
@@ -93,7 +82,7 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
image = botImage
}
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
Username string
Image string
LNURLPay string
@@ -101,26 +90,3 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
log.Errorf("failed to render template")
}
}
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)
if err != nil {
log.Errorln("[UserPage]", err)
return
}
if err := qr_tmpl.ExecuteTemplate(w, "webapp", struct {
Username string
LNURLPay string
Callback string
}{username, lnurlEncode, callback}); err != nil {
log.Errorf("failed to render template")
}
}
-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")
}
}
+7 -56
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"
)
@@ -16,39 +14,16 @@ var Configuration = struct {
Telegram TelegramConfiguration `yaml:"telegram"`
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"`
DallePrice int64 `yaml:"dalle_price"`
Worker int `yaml:"worker"`
}
type SocksConfiguration struct {
Host string `yaml:"host"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type BotConfiguration struct {
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
AdminAPIToken string `yaml:"admin_api_token"`
HttpProxy string `yaml:"http_proxy"`
SocksProxy string `yaml:"socks_proxy"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
}
type TelegramConfiguration struct {
@@ -61,8 +36,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 +68,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() {
-23
View File
@@ -1,23 +0,0 @@
package dalle
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal"
"io"
)
var Enabled bool
func init() {
if internal.Configuration.Generate.DalleKey != "" {
Enabled = true
}
}
type Client interface {
Generate(ctx context.Context, prompt string) (*Task, error)
ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error)
GetTask(ctx context.Context, taskID string) (*Task, error)
Download(ctx context.Context, generationID string) (io.ReadCloser, error)
Share(ctx context.Context, generationID string) (string, error)
}
-11
View File
@@ -1,11 +0,0 @@
package dalle
const (
StatusPending = "pending"
StatusRejected = "rejected"
StatusSucceeded = "succeeded"
TaskTypeText2Im = "text2im"
defaultBatchSize = 4
)
-242
View File
@@ -1,242 +0,0 @@
package dalle
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
libraryVersion = "1.0.0"
defaultUserAgent = "dalle/" + libraryVersion
baseURL = "https://labs.openai.com/api/labs"
defaultHTTPClientTimeout = 15 * time.Second
)
type option func(*HTTPClient) error
func WithHTTPClient(httpClient *http.Client) option {
return func(c *HTTPClient) error {
c.httpClient = httpClient
return nil
}
}
func WithUserAgent(userAgent string) option {
return func(c *HTTPClient) error {
c.userAgent = userAgent
return nil
}
}
type HTTPClient struct {
httpClient *http.Client
userAgent string
apiKey string
}
var _ Client = (*HTTPClient)(nil)
func NewHTTPClient(apiKey string, opts ...option) (*HTTPClient, error) {
c := &HTTPClient{
httpClient: &http.Client{Timeout: defaultHTTPClientTimeout},
userAgent: defaultUserAgent,
apiKey: apiKey,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
}
type Task struct {
Object string `json:"object"`
ID string `json:"id"`
Created int64 `json:"created"`
TaskType string `json:"task_type"`
Status string `json:"status"`
PromptID string `json:"prompt_id"`
Prompt Prompt `json:"prompt"`
Generations Generations `json:"generations"`
}
type Generations struct {
Data []GenerationData `json:"data"`
Object string `json:"object"`
}
type GenerationData struct {
Created int64 `json:"created"`
Generation Generation `json:"generation"`
GenerationType string `json:"generation_type"`
ID string `json:"id"`
}
type Generation struct {
ImagePath string `json:"image_path"`
}
type Prompt struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
PromptType string `json:"prompt_type"`
Prompt struct {
Caption string `json:"caption"`
} `json:"prompt"`
ParentGenerationID string `json:"parent_generation_id"`
}
type GenerateRequest struct {
Prompt GenerateRequestPrompt `json:"prompt"`
TaskType string `json:"task_type"`
}
type GenerateRequestPrompt struct {
BatchSize int32 `json:"batch_size"`
Caption string `json:"caption"`
}
func (c *HTTPClient) Generate(ctx context.Context, caption string) (*Task, error) {
task := &Task{}
req := &GenerateRequest{
Prompt: GenerateRequestPrompt{
BatchSize: defaultBatchSize,
Caption: caption,
},
TaskType: TaskTypeText2Im,
}
return task, c.request(ctx, "POST", "/tasks", nil, req, task)
}
type ListTasksResponse struct {
Object string `json:"object"`
Data []Task `json:"data"`
}
type ListTasksRequest struct {
Limit int32 `json:"limit"`
}
func (c *HTTPClient) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
res := &ListTasksResponse{}
url := "/tasks"
if req != nil {
if req.Limit != 0 {
url += fmt.Sprintf("?limit=%d", req.Limit)
}
}
return res, c.request(ctx, "GET", url, nil, nil, res)
}
func (c *HTTPClient) GetTask(ctx context.Context, taskID string) (*Task, error) {
task := &Task{}
return task, c.request(ctx, "GET", "/tasks/"+taskID, nil, nil, task)
}
func (c *HTTPClient) Download(ctx context.Context, generationID string) (io.ReadCloser, error) {
req, err := c.createRequest(ctx, "/generations/"+generationID+"/download", "GET", nil, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("performing request: %w", err)
}
return resp.Body, nil
}
// Share makes the generation public and returns the public url
func (c *HTTPClient) Share(ctx context.Context, generationID string) (string, error) {
res := &GenerationData{}
err := c.request(ctx, "POST", "/generations/"+generationID+"/share", nil, nil, res)
if err != nil {
return "", err
}
return res.Generation.ImagePath, nil
}
func (c *HTTPClient) createRequest(ctx context.Context, path, method string, values *url.Values, data interface{}) (*http.Request, error) {
url := baseURL + path
if values != nil {
url += "?" + values.Encode()
}
var body io.Reader
if data != nil {
b, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("parsing request data: %w", err)
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("building request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+c.apiKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
return req, nil
}
func (c *HTTPClient) request(ctx context.Context, method, path string, values *url.Values, body interface{}, result interface{}) error {
req, err := c.createRequest(ctx, path, method, values, body)
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("performing request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
// TODO: improve error handling...
if resp.StatusCode != http.StatusOK {
return Error{
Message: "unexpected non 200 status code",
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
if err = json.Unmarshal(respBody, result); err != nil {
return Error{
Message: err.Error(),
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
return nil
}
type Error struct {
Message string
StatusCode int
Details string
}
func (e Error) Error() string {
return fmt.Sprintf("dalle: %s (status: %d, details: %s)", e.Message, e.StatusCode, e.Details)
}
+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
}
-102
View File
@@ -1,102 +0,0 @@
package gpt
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"net/http"
)
type Response struct {
Message struct {
ID string `json:"id"`
Role string `json:"role"`
User interface{} `json:"user"`
CreateTime interface{} `json:"create_time"`
UpdateTime interface{} `json:"update_time"`
Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
} `json:"content"`
EndTurn interface{} `json:"end_turn"`
Weight float64 `json:"weight"`
Metadata struct {
} `json:"metadata"`
Recipient string `json:"recipient"`
} `json:"message"`
ConversationID string `json:"conversation_id"`
Error interface{} `json:"error"`
}
type Request struct {
Action string `json:"action"`
ConversationId string `json:"conversation_id,omitempty"`
Messages []Messages `json:"messages"`
ParentMessageID string `json:"parent_message_id"`
Model string `json:"model"`
}
type Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
}
type Messages struct {
ID string `json:"id"`
Role string `json:"role"`
Content Content `json:"content"`
}
var dataPrefix = []byte("data: ")
var doneSequence = []byte("[DONE]")
func GetRawCompletion(ctx intercept.Context, rr Request, cb func(s string)) (*Response, error) {
rawClient := http.Client{}
r, err := json.Marshal(rr)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx.Context, "POST", "https://chat.openai.com/backend-api/conversation", bytes.NewBuffer(r))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", internal.Configuration.Generate.OpenAiBearerToken))
req.Header.Set("accept", "text/event-stream")
req.Header.Set("authority", "chat.openai.com")
req.Header.Set("accept-language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7")
req.Header.Set("Content-type", "application/json")
req.Header.Set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
resp, err := rawClient.Do(req)
if err != nil {
return nil, err
}
reader := bufio.NewReader(resp.Body)
defer resp.Body.Close()
output := new(Response)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
// make sure there isn't any extra whitespace before or after
line = bytes.TrimSpace(line)
// the completion API only returns data events
if !bytes.HasPrefix(line, dataPrefix) {
continue
}
line = bytes.TrimPrefix(line, dataPrefix)
// the stream is completed when terminated by [DONE]
if bytes.HasPrefix(line, doneSequence) {
break
}
if err := json.Unmarshal(line, output); err != nil {
return nil, fmt.Errorf("invalid json stream data: %v", err)
}
if len(output.Message.Content.Parts) > 0 {
cb(output.Message.Content.Parts[len(output.Message.Content.Parts)-1])
}
}
return output, 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)
}
}
}
}
+10 -30
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,36 +13,19 @@ 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"
}
func RegisterLanguages() *i18n.Bundle {
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
dir := translationsDir()
bundle.MustLoadMessageFile(filepath.Join(dir, "en.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "de.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "fi.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "it.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "es.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "nl.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "pl.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "fr.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "pt-br.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "tr.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "cs.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "id.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "ru.toml"))
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/fr.toml")
bundle.LoadMessageFile("translations/pt-br.toml")
bundle.LoadMessageFile("translations/tr.toml")
bundle.LoadMessageFile("translations/id.toml")
bundle.LoadMessageFile("translations/ru.toml")
return bundle
}
func Translate(languageCode string, MessgeID string) string {
+3 -28
View File
@@ -1,7 +1,6 @@
package lnbits
import (
"fmt"
"time"
"github.com/imroc/req"
@@ -85,7 +84,7 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
}
// Invoice creates an invoice associated with this wallet.
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
@@ -132,7 +131,7 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
return
}
// Payments returns wallet payments
// Info returns wallet payments
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
@@ -156,30 +155,6 @@ func (c Client) Payments(w Wallet) (wtx Payments, err error) {
return
}
// Payment state of a payment
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
if err != nil {
return
}
if resp.Response().StatusCode >= 300 {
var reqErr Error
resp.ToJSON(&reqErr)
err = reqErr
return
}
err = resp.ToJSON(&payment)
return
}
// Wallets returns all wallets belonging to an user
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
@@ -199,7 +174,7 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
}
// Pay pays a given invoice with funds from the wallet.
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
// custom header with admin key
adminHeader := req.Header{
"Content-Type": "application/json",
+18 -34
View File
@@ -7,8 +7,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcec"
"github.com/imroc/req"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -39,18 +38,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_"`
@@ -73,7 +64,6 @@ const (
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
UserEnterDallePrompt
)
type UserStateKey int
@@ -84,12 +74,11 @@ func (u *User) ResetState() {
}
type InvoiceParams struct {
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in Satoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in MilliSatoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
}
type PaymentParams struct {
@@ -111,11 +100,14 @@ type TransferParams struct {
}
type Error struct {
Detail string `json:"detail"`
Name string `json:"name"`
Message string `json:"message"`
Code int `json:"code"`
Status int `json:"status"`
}
func (err Error) Error() string {
return err.Detail
return err.Message
}
type Wallet struct {
@@ -127,7 +119,7 @@ type Wallet struct {
User string `json:"user"`
}
type Payment struct {
type Payments []struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
@@ -143,25 +135,17 @@ type Payment struct {
WebhookStatus interface{} `json:"webhook_status"`
}
type LNbitsPayment struct {
Paid bool `json:"paid"`
Preimage string `json:"preimage"`
Details Payment `json:"details,omitempty"`
}
type Payments []Payment
type Invoice struct {
type BitInvoice struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
}
// from fiatjaf/lnurl-go
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
seedHash := sha256.Sum256([]byte(
seedhash := sha256.Sum256([]byte(
fmt.Sprintf("lnurlkeyseed:%s:%s",
domain, u.ID)))
return btcec.PrivKeyFromBytes(seedHash[:])
return btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
}
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
@@ -173,7 +157,7 @@ func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string,
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
}
signature := ecdsa.Sign(sk, k1)
signature, err := sk.Sign(k1)
if err != nil {
return "", "", fmt.Errorf("error signing k1: %w", err)
}
-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)
}
}
}
+8 -96
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,37 +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)
}
// markHandled records paymentHash and reports whether this is the first time.
func (w *Server) markHandled(paymentHash string) (first bool, err error) {
err = w.buntdb.Update(func(tx *buntdb.Tx) error {
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", nil)
first = !replaced
return err
})
return first, err
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
@@ -121,54 +83,21 @@ 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
}
// Handle every payment once, so a webhook can't be replayed.
first, err := w.markHandled(webhookEvent.PaymentHash)
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)
@@ -177,11 +106,6 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
err = w.buntdb.Get(txInvoiceEvent)
if err != nil {
log.Errorln(err)
} 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
} else {
// do something with the event
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
@@ -189,26 +113,14 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Errorln(err)
return
}
go runCallback(c.Function, txInvoiceEvent)
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)
}
+47
View File
@@ -1,11 +1,15 @@
package lndhub
import (
"encoding/base64"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
@@ -17,5 +21,48 @@ func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
auth := request.Header.Get("Authorization")
// check if the user is banned
if auth != "" {
_, password, ok := parseBearerAuth(auth)
if !ok {
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
log.Warnf("[LNDHUB] 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)
user := &lnbits.User{}
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
return
}
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
}
// if not, proxy the request
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
}
// parseBearerAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBearerAuth(auth string) (username, password string, ok bool) {
const prefix = "Bearer "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
+68 -207
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 {
@@ -87,19 +81,11 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
return
}
var amount int64
if amount, err = strconv.ParseInt(stringAmount, 10, 64); err != nil {
// if the value wasn't a clean msat denomination, parse it
amount, err = telegram.GetAmount(stringAmount)
if err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int: %v", err))
return
}
// GetAmount returns sat, we need msat
amount *= 1000
amount, parseError := strconv.Atoi(stringAmount)
if parseError != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
return
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
@@ -109,39 +95,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))
fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
fmt.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 +137,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 +148,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 +160,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,20 +173,18 @@ 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
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d sat, max: %d sat).", MinSendable/1000, MaxSendable/1000)},
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
}, fmt.Errorf("amount out of bounds")
}
// check comment length
@@ -263,11 +195,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 +210,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 +255,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{
@@ -441,8 +281,8 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
}
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
// descriptionHash is the SHA256 hash of the metadata
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
var hashString string
var hash [32]byte
if len(payerData) == 0 {
@@ -462,7 +302,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 +343,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)
}
}
}
-273
View File
@@ -1,273 +0,0 @@
package lnurlcash
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"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
}
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{},
}
m.srv = httptest.NewServer(http.HandlerFunc(m.handle))
t.Cleanup(m.srv.Close)
return m
}
func (m *fakeMint) url() string { return m.srv.URL }
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()
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": 1000, "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
m.notes[inv.h] = net
}
// 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
}
-405
View File
@@ -1,405 +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
var units []*unit
byIndex := map[int][2]*Note{}
for _, n := range notes {
switch n.Kind {
case KindFunding:
units = append(units, &unit{funding: n})
case KindUser:
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 {
return
}
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])
}
}
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
}
// 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.client.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.client.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.client.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.client.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)
}
}
}
-123
View File
@@ -1,123 +0,0 @@
package lnurlcash
import (
"context"
"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))
}
}
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)
}
}
-443
View File
@@ -1,443 +0,0 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
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
}
state, value, err := s.Status(ctx, n)
if 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)
}
// melt sends one melt and maps its outcome onto the note. Never retried.
func (s *Service) melt(ctx context.Context, n *Note, k1, pr string) error {
callback, err := s.callbackOf(ctx, n)
if err != nil {
_ = 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
}
// 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.client.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.client.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.client.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
}
-255
View File
@@ -1,255 +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
alert func(string)
mu sync.RWMutex
mints map[string]*Mint
}
// NewRegistry builds the registry. alert receives admin-worthy messages and
// may be nil. httpClient may be nil (then lnurlcash.NewClient's transport is
// used); a supplied client MUST disable keep-alives and MUST NOT retry.
func NewRegistry(cfg *Config, store *Store, httpClient *http.Client, alert func(string)) *Registry {
client := lnurlcash.NewClient()
if httpClient != nil {
client.HTTP = httpClient
}
if alert == nil {
alert = func(msg string) { log.Warnf("[lnurlcash] alert: %s", msg) }
}
r := &Registry{cfg: cfg, store: store, client: client, 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 service call goes through.
func (r *Registry) Client() *lnurlcash.Client { return r.client }
// 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.client.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.client.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, 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)
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)
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)
}
})
}
}
-211
View File
@@ -1,211 +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
}
// batchStranded reports whether a batch ended without delivering every note.
// Only then is the value left in its funding and change notes the owner's.
func (s *Service) batchStranded(b *Batch) bool {
if b.State == BatchFailed {
return true
}
notes, err := s.store.NotesInBatch(b.ID)
if err != nil {
return false
}
for _, n := range notes {
if n.Kind == KindUser && n.State == NoteFailed {
return true
}
}
return false
}
// RefundStranded melts the value that a failed or partial batch left in a
// bot-held funding or change note back into its owner's balance: 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.batchStranded(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.client.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.client.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 stranded value of failed 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 a failed batch to user %s: %v", n.ReportedMsat, n.ID, n.UserName, err))
}
}
}
-112
View File
@@ -1,112 +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")
}
})
}
}
// Value of healthy batches (the dust left after a full carve) is not refunded.
func TestRefundIgnoresHealthyBatches(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
if _, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q}); err != nil || len(live) != 3 {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("a healthy batch 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)
}
}
-686
View File
@@ -1,686 +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 *lnurlcash.Client
// now is replaceable in tests.
now func() time.Time
// sleep between settlement polls, replaceable in tests.
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(), 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
}
// 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
}
// Quote prices count notes of valueMsat at a mint. With strategy "invoices"
// each note gets its own invoice, so the fee is paid count times.
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 := grossFor(valueMsat, 1, fee)
if per < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && per > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
gross = per * int64(count)
q.Strategy = StrategyInvoices
if count == 1 {
q.Strategy = StrategySplit
}
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.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{}
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)", batch.ID, q.Count, q.ValueMsat, mint.ID, p.User, q.GrossMsat)
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)
}
})
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
}
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
}
}
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 {
info, err := s.client.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
return true, nil
}
if lnurlcash.IsSpent(err) {
// 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(s.pollEvery):
}
}
}
// 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
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
}
callback, 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
}
_, 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.client.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.client.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.client.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.client.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) {
if IsFinalNoteState(n.State) {
return n.State, n.ReportedMsat, nil
}
info, err := s.client.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, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now})
return n.State, n.ReportedMsat, 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, nil
default:
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
return n.State, n.ReportedMsat, 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
}
-376
View File
@@ -1,376 +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)
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)
}
}
}
func TestCreateSingleNoteAndReclaim(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
if want := grossFor(1000_000, 1, mint.Fee()); q.GrossMsat != want || q.FeeMsat != want-1000_000 || q.GrossMsat%1000 != 0 {
t.Fatalf("unexpected quote %+v (want gross %d)", q, want)
}
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")
}
// every secret was persisted and is distinct
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 3 {
t.Fatalf("expected funding + note + dust rows, got %d", 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)
}
}
-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")
}
}
+28 -102
View File
@@ -2,125 +2,51 @@ package network
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
type ClientType string
const (
ClientTypeClearNet = "clearnet"
ClientTypeTor = "tor"
)
// checks if strings contains http(s)://*.onion
var isOnion = regexp.MustCompile("^https?\\:\\/\\/[\\w\\-\\.]+\\.onion")
// GetClientForScheme returns correct client for url scheme.
// if tld is .onion, function will also return an onion client.
func GetClientForScheme(url *url.URL) (*http.Client, error) {
if isOnion.FindString(url.String()) != "" {
return GetClient(ClientTypeTor)
}
switch url.Scheme {
case "onion":
return GetClient(ClientTypeTor)
default:
return GetClient(ClientTypeClearNet)
}
}
// 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) {
func GetHttpClient() (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
Transport: directTransport(),
Timeout: 10 * time.Second,
}
var cfg *internal.SocksConfiguration
switch clientType {
case ClientTypeClearNet:
cfg = internal.Configuration.Bot.SocksProxy
case ClientTypeTor:
cfg = internal.Configuration.Bot.TorProxy
default:
return nil, fmt.Errorf("[GetClient] invalid clientType")
}
if cfg == nil {
return &client, nil
}
if cfg.Host == "" {
return &client, nil
}
proxyURL, _ := url.Parse(cfg.Host)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
var auth *proxy.Auth
if cfg.Username != "" && cfg.Password != "" {
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
}
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
log.Errorln(err)
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 {
if internal.Configuration.Bot.HttpProxy != "" {
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
if err != nil {
log.Errorln(err)
return nil, err
}
return d.Dial(network, addr)
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
}
client.Transport = specialTransport
return &client, nil
}
// NewNoKeepAliveClient returns a client for LNURLcash mints: the same proxy
// and netguard rules as GetClient, but keep-alives off and redirects refused,
// because every LNURLcash mutation is a non-idempotent GET that net/http
// would otherwise retry on a reused connection.
func NewNoKeepAliveClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
client = &http.Client{Transport: directTransport()}
func GetSocksClient() (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = true
if internal.Configuration.Bot.SocksProxy != "" {
proxyURL, _ := url.Parse(internal.Configuration.Bot.SocksProxy)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
d, err := proxy.SOCKS5("tcp", internal.Configuration.Bot.SocksProxy, nil, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
log.Errorln(err)
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.Dial(network, addr)
}
client.Transport = specialTransport
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
return &client, nil
}
-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"))
}
}
+1 -2
View File
@@ -2,11 +2,10 @@ package rate
import (
"context"
log "github.com/sirupsen/logrus"
"strconv"
"sync"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
+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 {
+45 -24
View File
@@ -2,25 +2,33 @@ package satdress
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/network"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"io/ioutil"
"net/http"
"net/url"
"strings"
"golang.org/x/net/proxy"
)
// Much of this is from github.com/fiatjaf/makeinvoice
// but with added "checkInvoice" and http proxy support
var Client, _ = network.GetSocksClient()
type LNDParams struct {
Cert []byte `json:"cert" gorm:"-"`
CertString string `json:"certstring"`
@@ -29,6 +37,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 +48,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,30 +72,40 @@ 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) {
specialTransport := &http.Transport{}
// use a cert or skip TLS verification?
if len(cert) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(cert)
if !ok {
return client, fmt.Errorf("invalid root certificate")
return Client, fmt.Errorf("invalid root certificate")
}
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
return client, nil
// use a proxy?
var HttpProxyURL = internal.Configuration.Bot.SocksProxy
if useProxy && len(HttpProxyURL) > 0 {
proxyURL, _ := url.Parse(HttpProxyURL)
specialTransport.Proxy = http.ProxyURL(proxyURL)
d, err := proxy.SOCKS5("tcp", HttpProxyURL, nil, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
return Client, err
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.Dial(network, addr)
}
}
Client.Transport = specialTransport
return Client, nil
}
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
@@ -97,9 +118,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 +254,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
+14 -60
View File
@@ -4,12 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
"math"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -22,12 +20,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 +32,25 @@ 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])
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)
}
func getAmount(input string) (amount int64, err error) {
// 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 +62,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 +75,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 {
@@ -186,7 +140,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
return ctx, err
}
amount, err := GetAmount(ctx.Message().Text)
amount, err := getAmount(ctx.Message().Text)
if err != nil {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
-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)
}
}
}
-1
View File
@@ -2,7 +2,6 @@ package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
-10
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
@@ -67,7 +63,6 @@ func newTelegramBot() *tb.Bot {
Token: internal.Configuration.Telegram.ApiKey,
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
ParseMode: tb.ModeMarkdown,
Verbose: false,
})
if err != nil {
panic(err)
@@ -120,9 +115,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 +134,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
+7 -37
View File
@@ -3,9 +3,7 @@ package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -13,24 +11,16 @@ import (
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
// MainMenuCommandWebApp = "⤵️ Recv"
// MainMenuCommandBalance = "Balance"
// MainMenuCommandInvoice = "⚡️ Invoice"
// MainMenuCommandHelp = "📖 Help"
// MainMenuCommandSend = "⤴️ Send"
// SendMenuCommandEnter = "👤 Enter"
MainMenuCommandWebApp = "🗳️ App"
MainMenuCommandSend = "💸 Send"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
MainMenuCommandSend = "⤴️"
SendMenuCommandEnter = "👤 Enter"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
btnWebAppMainMenu = mainMenu.Text(MainMenuCommandWebApp)
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
@@ -41,11 +31,9 @@ var (
)
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, btnSendMainMenu, btnHelpMainMenu),
)
}
@@ -70,21 +58,6 @@ func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Ro
return rows
}
// appendWebAppLinkToButton adds a WebApp object to a Button with the user's webapp page
func (bot *TipBot) appendWebAppLinkToButton(btn *tb.Btn, user *lnbits.User) {
var url string
if len(user.Telegram.Username) > 0 {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.Telegram.Username)
} else {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
}
if strings.HasPrefix(url, "https://") {
// prevent adding a link if not https is used, otherwise
// Telegram returns an error and does not show the keyboard
btn.WebApp = &tb.WebAppInfo{Url: url}
}
}
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
var user *lnbits.User
@@ -102,14 +75,11 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
)
}
}
@@ -128,7 +98,7 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
// get all contacts and add them to the buttons
for i, r := range records {
log.Tracef("[makeContactsButtons] toNames[%d] = %s (id=%d)", i, r.ToUser, r.ID)
sendToButtons = append(sendToButtons, tb.Btn{Text: r.ToUser})
sendToButtons = append(sendToButtons, tb.Btn{Text: fmt.Sprintf("%s", r.ToUser)})
}
// add the "enter a username" button to the end
+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
}
+5 -35
View File
@@ -2,18 +2,13 @@ package telegram
import (
"context"
"encoding/json"
"fmt"
"github.com/fiatjaf/go-lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/str"
@@ -55,24 +50,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 +66,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 +88,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 {
@@ -66,7 +62,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.DecodePerUserAmountError, err)
}
perUserAmount, err := GetAmount(peruserStr)
perUserAmount, err := getAmount(peruserStr)
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
@@ -74,9 +70,6 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
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)
-263
View File
@@ -1,263 +0,0 @@
package telegram
import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// generateImages is called when the user enters /generate or /generate <prompt>
// asks the user for a prompt if not given
func (bot *TipBot) generateImages(ctx intercept.Context) (intercept.Context, error) {
if !dalle.Enabled {
bot.trySendMessage(ctx.Message().Sender, "🤖💤 Dalle image generation is currently not available. Please try again later.")
return ctx, nil
}
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
}
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
// We need to save the pay state in the user state so we can load the payment in the next handler
SetUserState(user, bot, lnbits.UserEnterDallePrompt, "")
bot.trySendMessage(ctx.Message().Sender, "⌨️ Enter image prompt.", tb.ForceReply)
return ctx, nil
}
// write the prompt into the command and call confirm
m := ctx.Message()
m.Text = GetMemoFromCommand(m.Text, 1)
return bot.confirmGenerateImages(ctx)
}
// confirmGenerateImages is called when the user has entered a prompt through /generate <prompt>
// or because he answered to the request to enter it in generateImages()
// confirmGenerateImages will create an invoice that the user can pay and if they pay
// generateDalleImages will fetch the images and send it to the user
func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
ResetUserState(user, bot)
m := ctx.Message()
prompt := m.Text
if len(prompt) == 0 {
return ctx, fmt.Errorf("prompt not given")
}
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
}
me, err := GetUser(bot.Telegram.Me, *bot)
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.Payer = user
if err != nil {
return ctx, err
}
runtime.IgnoreError(bot.Bunt.Set(invoice))
balance, err := bot.GetUserBalance(user)
if err != nil {
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
log.Warnln(errmsg)
}
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "generateDallePayInvoiceMessage"))
// invoke internal pay if enough balance
if balance >= internal.Configuration.Generate.DallePrice {
m.Text = fmt.Sprintf("/pay %s", invoice.PaymentRequest)
return bot.payHandler(ctx)
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
bot.tryEditMessage(invoice.Message, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
// send the invoice data to user
msg := bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
invoice.InvoiceMessage = msg
runtime.IgnoreError(bot.Bunt.Set(invoice))
return ctx, nil
}
var jobChan chan func(workerId int)
var workers = internal.Configuration.Generate.Worker
func init() {
if workers == 0 {
log.Printf("Dalle is disabled. No worker started.")
return
}
log.Printf("Starting Dalle image generation. Worker: %d, Price: %d sat", workers, internal.Configuration.Generate.DallePrice)
jobChan = make(chan func(workerId int), workers)
for i := 0; i < workers; i++ {
go worker(jobChan, i)
}
}
func worker(linkChan chan func(workerId int), workerId int) {
for generatePrompt := range linkChan {
generatePrompt(workerId)
}
}
// generateDalleImages is called by the invoice event when the user has paid
func (bot *TipBot) generateDalleImages(event Event) {
invoiceEvent := event.(*InvoiceEvent)
user := invoiceEvent.Payer
if user == nil || user.Wallet == nil {
log.Errorf("[generateDalleImages] invalid user")
return
}
bot.trySendMessage(user.Telegram, "🔄 Your images are being generated. Please wait a few moments.")
var job = func(workerId int) {
// create the client with the bearer token api key
dalleClient, err := dalle.NewHTTPClient(internal.Configuration.Generate.DalleKey)
// handle err
if err != nil {
log.Errorf("[NewHTTPClient-%d] %v", workerId, err.Error())
bot.dalleRefundUser(user, "")
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*15)
defer cancel()
// generate a task to create an image with a prompt
task, err := dalleClient.Generate(ctx, invoiceEvent.CallbackData)
if err != nil {
log.Errorf("[Generate-%d] %v", workerId, err.Error())
bot.dalleRefundUser(user, "")
return
}
// poll the task.ID until status is succeeded
var t *dalle.Task
timeout := time.After(10 * time.Minute)
ticker := time.Tick(5 * time.Second)
// Keep trying until we're timed out or get a result/error
for {
select {
case <-ctx.Done():
bot.dalleRefundUser(user, "")
log.Errorf("[DALLE-%d] ctx done. Task %s", workerId, task.ID)
return
// Got a timeout! fail with a timeout error
case <-timeout:
bot.dalleRefundUser(user, "Timeout. Please try again later.")
log.Errorf("[DALLE-%d] timeout. Task: %s", workerId, task.ID)
return
// Got a tick, we should check on checkSomething()
case <-ticker:
t, err = dalleClient.GetTask(ctx, task.ID)
// handle err
if err != nil {
log.Errorf("[GetTask-%d] Task: %s. Error: %v", workerId, task.ID, err.Error())
//bot.dalleRefundUser(user, "")
continue
}
if t.Status == dalle.StatusSucceeded {
log.Printf("[DALLE-%d] 🎆 task succeeded for user %s", workerId, GetUserStr(user.Telegram))
// download the first generated image
for _, data := range t.Generations.Data {
err = bot.downloadAndSendImages(ctx, dalleClient, data, invoiceEvent)
if err != nil {
log.Errorf("[downloadAndSendImages-%d] Id: %s. Error: %v", workerId, data.ID, err.Error())
}
}
return
} else if t.Status == dalle.StatusRejected {
log.Errorf("[DALLE-%d] rejected: %s", workerId, t.ID)
bot.dalleRefundUser(user, "Your prompt has been rejected by OpenAI. Do not use celebrity names, sexual expressions, or any other harmful content as prompt.")
return
}
log.Debugf("[DALLE-%d] pending for user %s", workerId, GetUserStr(user.Telegram))
}
}
}
jobChan <- job
}
// downloadAndSendImages will download dalle images and send them to the payer.
func (bot *TipBot) downloadAndSendImages(ctx context.Context, dalleClient dalle.Client, data dalle.GenerationData, event *InvoiceEvent) error {
reader, err := dalleClient.Download(ctx, data.ID)
if err != nil {
return err
}
defer reader.Close()
image := "data/dalle/" + data.ID + ".png"
file, err := os.Create(image)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, reader)
if err != nil {
return err
}
f, err := os.OpenFile(image, 0, os.ModePerm)
if err != nil {
return err
}
defer f.Close()
bot.trySendMessage(event.Payer.Telegram, &tb.Photo{File: tb.File{FileReader: f}})
return nil
}
func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
if user.Wallet == nil {
return fmt.Errorf("user has no wallet")
}
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
return err
}
// create invioce for user
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(internal.Configuration.Generate.DallePrice),
Memo: fmt.Sprintf("Refund DALLE2 %s", GetUserStr(user.Telegram)),
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
return err
}
// pay invoice
_, err = me.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
log.Errorln(err)
return err
}
log.Warnf("[DALLE] refunding user %s with %d sat", GetUserStr(user.Telegram), internal.Configuration.Generate.DallePrice)
var err_reason string
if len(message) > 0 {
err_reason = message
} else {
err_reason = "Something went wrong."
}
bot.trySendMessage(user.Telegram, fmt.Sprintf("🚫 %s You have been refunded.", err_reason))
return nil
}
-73
View File
@@ -1,73 +0,0 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/gpt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) gptHandler(ctx intercept.Context) (intercept.Context, error) {
question := GetMemoFromCommand(ctx.Text(), 1)
req := gpt.Request{
Action: "next",
Model: "text-davinci-002-render",
Messages: []gpt.Messages{{
ID: uuid.NewV4().String(),
Role: "user",
Content: gpt.Content{
ContentType: "text",
Parts: []string{question},
},
},
},
}
conversationIdCacheKey := fmt.Sprintf("conversation_%d", ctx.Chat().ID)
parentIdCacheKey := fmt.Sprintf("conversation_parent_%d", ctx.Chat().ID)
conversationId, _ := bot.Cache.Get(conversationIdCacheKey)
if parentId, _ := bot.Cache.Get(parentIdCacheKey); parentId != nil {
req.ParentMessageID = parentId.(string)
}
if conversationId != nil {
req.ConversationId = conversationId.(string)
}
cbc := 0
var msg *telebot.Message
completion, err := gpt.GetRawCompletion(ctx, req, func(s string) {
cbc++
if ctx.Chat().Type == telebot.ChatPrivate {
if cbc == 20 {
msg = bot.trySendMessageEditable(ctx.Sender(), s)
return
}
} else {
if cbc == 20 {
msg = bot.tryReplyMessage(ctx.Message(), s)
return
}
}
if cbc%20 == 0 {
bot.tryEditMessage(msg, s)
}
})
if err != nil {
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not create completion."))
return ctx, err
}
answer := completion.Message.Content.Parts[len(completion.Message.Content.Parts)-1]
bot.tryEditMessage(msg, answer)
err = bot.Cache.Set(conversationIdCacheKey, completion.ConversationID, nil)
if err != nil {
log.Errorf("[/gpt] error setting conversation id %s: %v", conversationIdCacheKey, err)
}
err = bot.Cache.Set(parentIdCacheKey, completion.Message.ID, nil)
if err != nil {
log.Errorf("[/gpt] error setting parent message id %s: %v", parentIdCacheKey, err)
}
log.Infof("[/gpt] \"%s\" => \"%s\"", question, answer)
return ctx, nil
}
+30 -176
View File
@@ -5,9 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
@@ -24,30 +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"`
}
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"`
@@ -109,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
@@ -119,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" {
@@ -139,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)
@@ -178,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,
@@ -248,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)
@@ -261,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.
@@ -304,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
}
@@ -326,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 {
@@ -368,16 +324,23 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
// send a notification to the group that sold the ticket
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStrMd(ticketEvent.Payer.Telegram)))
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStr(ticketEvent.Payer.Telegram)))
// 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{
@@ -403,121 +366,12 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
log.Errorln(errmsg)
}
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
} else {
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
}
}
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()
@@ -558,7 +412,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
amount := int64(0) // default amount is zero
if amount_str, err := getArgumentFromCommand(m.Text, 3); err == nil {
amount, err = GetAmount(amount_str)
amount, err = getAmount(amount_str)
if err != nil {
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
return ctx, err
@@ -585,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
}
+8 -494
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,8 @@ 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{}{"/tip", "/t", "/honk"},
Handler: bot.tipHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -491,38 +148,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,
@@ -547,7 +172,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -586,22 +210,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
bot.unlockInterceptor,
}},
},
// {
// 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,
// },
// },
// },
{
Endpoints: []interface{}{"/balance", &btnBalanceMainMenu},
Handler: bot.balanceHandler,
@@ -653,25 +261,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// previously, this was the send menu but it
// was replaced with the webapp
// {
// Endpoints: []interface{}{&btnWebAppMainMenu},
// Handler: bot.keyboardSendHandler,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.requireUserInterceptor,
// bot.loadReplyToInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/transactions"},
Handler: bot.transactionsHandler,
@@ -691,7 +280,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -707,7 +295,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -734,6 +321,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/tipjar", "/spendendose"},
Handler: bot.tipjarHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -749,6 +337,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/help", &btnHelpMainMenu},
Handler: bot.helpHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -796,8 +385,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/advanced"},
Handler: bot.advancedHelpHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -812,24 +401,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/link"},
Handler: bot.lndhubHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/api"},
Handler: bot.apiHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -844,8 +417,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/lnurl"},
Handler: bot.lnurlHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -856,27 +429,12 @@ 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"},
Handler: bot.groupHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -913,7 +471,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -991,7 +548,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1007,7 +563,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1023,7 +578,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1039,7 +593,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1055,7 +608,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1071,7 +623,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1087,7 +638,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1103,7 +653,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1120,12 +669,10 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
bot.singletonCallbackInterceptor,
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
bot.answerCallbackInterceptor,
},
},
},
@@ -1137,7 +684,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1153,7 +699,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1169,7 +714,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1185,7 +729,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1201,7 +744,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1217,7 +759,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1233,7 +774,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1249,7 +789,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1264,7 +803,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1279,7 +817,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1294,7 +831,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1309,7 +845,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1324,7 +859,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1340,7 +874,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1356,7 +889,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1372,7 +904,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1388,7 +919,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1404,7 +934,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1420,7 +949,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1436,7 +964,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1452,7 +979,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1468,7 +994,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1483,7 +1008,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1498,7 +1022,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1513,7 +1036,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1529,7 +1051,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1544,7 +1065,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1559,7 +1079,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1574,7 +1093,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1589,7 +1107,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1604,7 +1121,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1619,7 +1135,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1634,7 +1149,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
+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"))
+6 -34
View File
@@ -58,35 +58,11 @@ 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()
if c != nil {
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Callback:
c := i.(*tb.Callback)
ctxcr := ctx.Value("callback_response")
var res []*tb.CallbackResponse
if ctxcr != nil {
@@ -156,10 +132,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 +200,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 -63
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"
@@ -41,9 +40,6 @@ func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
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},
}
}
@@ -55,9 +51,6 @@ const (
InvoiceCallbackLNURLPayReceive
InvoiceCallbackGroupTicket
InvoiceCallbackSatdressProxy
InvoiceCallbackGenerateDalle
InvoiceCallbackPayJoinTicket
// InvoiceCallbackLNURLCashSettle (8) is declared in lnurlcash.go
)
const (
@@ -91,7 +84,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 +111,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 +142,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 +168,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 +190,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 +205,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 +224,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)))
}
}
}
+20 -18
View File
@@ -3,9 +3,8 @@ package telegram
import (
"bytes"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -20,9 +19,22 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
return ctx, fmt.Errorf("invalid configuration")
}
// check and print all commands
bot.anyTextHandler(ctx)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
}
// first check whether the user is initialized
fromUser := LoadUser(ctx)
linkmsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "walletConnectMessage"))
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
// do not respond to banned users
if bot.UserIsBanned(fromUser) {
log.Warnln("[lndhubHandler] user is banned. not responding.")
return ctx, fmt.Errorf("user is banned")
}
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
@@ -35,24 +47,14 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
}
// send the link to the user
qrmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
// auto delete
go func() {
time.Sleep(time.Second * 60)
bot.tryDeleteMessage(qrmsg)
bot.tryEditMessage(linkmsg, Translate(ctx, "linkHiddenMessage"), tb.Silent)
}()
return ctx, nil
}
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
func (bot *TipBot) apiHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
fromUser := LoadUser(ctx)
apimesg := bot.trySendMessageEditable(m.Sender, fmt.Sprintf(Translate(ctx, "apiConnectMessage"), fromUser.Wallet.Adminkey, fromUser.Wallet.Inkey))
// auto delete
go func() {
time.Sleep(time.Second * 60)
bot.tryEditMessage(apimesg, Translate(ctx, "apiHiddenMessage"))
bot.tryDeleteMessage(linkmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
}()
// auto delete the message
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
return ctx, nil
}
+3 -12
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.")
}
@@ -102,7 +97,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
// statusMsg := bot.trySendMessageEditable(c.Sender,
// Translate(ctx, "lnurlResolvingUrlMessage"),
// )
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlAuthState.Message.Text, ButtonText: Translate(ctx, "lnurlResolvingUrlMessage")})
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlResolvingUrlMessage"))
// from fiatjaf/go-lnurl
p := lnurlAuthState.LNURLAuthParams
@@ -112,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
}
var sentsigres lnurl.LNURLResponse
client, err := network.GetClientForScheme(p.CallbackURL)
client, err := network.GetHttpClient()
if err != nil {
return ctx, err
}
@@ -130,11 +125,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
bot.tryEditMessage(c, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
return ctx, err
}
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{
Message: lnurlAuthState.Message.Text,
ButtonText: Translate(ctx, "lnurlSuccessfulLogin"),
URL: fmt.Sprintf("https://%s", lnurlAuthState.LNURLAuthParams.Host),
})
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlSuccessfulLogin"))
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
}
+18 -32
View File
@@ -1,7 +1,6 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
@@ -26,22 +25,21 @@ import (
// LnurlPayState saves the state of the user for an LNURL payment
type LnurlPayState struct {
*storage.Base
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
DescriptionHash string `json:"descriptionHash,omitempty"`
LanguageCode string `json:"languagecode"`
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
}
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hasn't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
@@ -78,18 +76,11 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
ResetUserState(user, bot)
return ctx, err
return
}
// set also amount in the state of the user
payParams.Amount = amount * 1000 // save as mSat
// calculate description hash of the metadata and save it
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
if err != nil {
return nil, err
}
payParams.DescriptionHash = descriptionHash
// add result to persistent struct
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
@@ -100,7 +91,7 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
} else if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
return ctx, nil
return
}
// We need to save the pay state in the user state so we can load the payment in the next ctx
@@ -108,12 +99,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
return ctx, err
return
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlPayHandlerSend(ctx)
return ctx, nil
return
}
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
@@ -154,13 +145,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
// LnurlPayState loaded
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
client, err := network.GetHttpClient()
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
client, err := network.GetClientForScheme(callbackUrl)
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
@@ -196,20 +187,15 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
if len(response2.Reason) > 0 {
error_reason = response2.Reason
}
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
}
// 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)
}
+14 -30
View File
@@ -42,35 +42,21 @@ type LnurlWithdrawState struct {
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Success bool `json:"success"`
Invoice lnbits.Invoice `json:"invoice"`
Invoice lnbits.BitInvoice `json:"invoice"`
Message string `json:"message"`
}
type EditSingleButtonParams struct {
Message string
ButtonText string
Data string
URL string
}
// editSingleButton edits a message to display a single button (for something like a progress indicator)
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, params EditSingleButtonParams) (*tb.Message, error) {
if len(params.URL) > 0 && len(params.Data) > 0 {
return &tb.Message{}, fmt.Errorf("URL and Data cannot be set at the same time.")
}
if len(params.URL) == 0 && len(params.Data) == 0 {
params.Data = "placeholder"
}
return bot.tryEditMessage(
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
bot.tryEditMessage(
m,
params.Message,
message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: params.ButtonText, Data: params.Data, URL: params.URL}},
{tb.InlineButton{Text: button}},
},
},
)
}
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
@@ -246,13 +232,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
ResetUserState(user, bot)
// update button text
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return ctx, err
}
@@ -268,7 +254,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
if err != nil {
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return ctx, err
}
lnurlWithdrawState.Invoice = invoice
@@ -280,25 +266,25 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := network.GetClientForScheme(callbackUrl)
client, err := network.GetHttpClient()
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return ctx, err
}
res, err := client.Get(callbackUrl.String())
if err != nil || res.StatusCode >= 300 {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return ctx, errors.New(errors.UnknownError, err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return ctx, err
}
@@ -306,15 +292,13 @@ 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")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
} else {
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
// update button text
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed")})
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
}
+19 -61
View File
@@ -2,9 +2,6 @@ package telegram
import (
"bytes"
"crypto/sha256"
"encoding/hex"
goerrors "errors"
"fmt"
"io/ioutil"
"net/url"
@@ -19,15 +16,13 @@ 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"
)
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
}
// lnurlHandler is invoked on /lnurl command
@@ -40,7 +35,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 +65,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)
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
@@ -106,7 +91,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
bot.trySendMessage(m.Sender, &tb.Photo{
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
Caption: payParams.LNURLPayParams.Metadata.Description})
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
// display the metadata text from the first LNURL-p response
// if there was no photo in the last step
@@ -115,17 +100,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:
@@ -165,7 +142,7 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
}
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
return "", err
@@ -174,7 +151,7 @@ func UserGetAnonLNURL(user *lnbits.User) (string, error) {
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
fromUser := LoadUser(ctx)
lnurlEncode, err := UserGetLNURL(fromUser)
@@ -199,12 +176,12 @@ func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context
}
// fiatjaf/go-lnurl 1.8.4 with proxy
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
var err error
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 +195,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)
rawurl, err = lnurl.LNURLDecode(lnurl_str)
if err != nil {
return "", nil, err
}
}
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()
@@ -260,7 +236,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
// return rawurl, nil, err
// }
client, err := network.GetClientForScheme(parsed)
client, err := network.GetHttpClient()
if err != nil {
return "", nil, err
}
@@ -269,7 +245,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 +264,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":
@@ -301,20 +273,6 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
// value, err := lnurl.HandleChannel(b)
// return rawurl, value, err
default:
return rawurl, nil, fmt.Errorf("unkown LNURL response")
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
}
}
// DescriptionHash is the SHA256 hash of the metadata
func (bot *TipBot) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
var hashString string
var hash [32]byte
if len(payerData) == 0 {
hash = sha256.Sum256([]byte(metadata.Encode()))
hashString = hex.EncodeToString(hash[:])
} else {
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
hashString = hex.EncodeToString(hash[:])
}
return hashString, nil
}
-420
View File
@@ -1,420 +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}
registry := lnurlcash.NewRegistry(cfg, bot.DB.LNURLCash, network.NewNoKeepAliveClient(30*time.Second), notifier.Alert)
bot.LNURLCash = lnurlcash.NewService(cfg, bot.DB.LNURLCash, registry, &lnbitsLedger{bot: bot}, cipher)
bot.lnurlcashJobs = lnurlcash.NewJobs(bot.LNURLCash, notifier)
log.Infof("[lnurlcash] enabled with %d mint(s)", len(cfg.Mints))
}
// startLNURLCashJobs runs the background jobs. The bot has no shutdown
// context; the jobs are restart-safe by design.
func (bot *TipBot) startLNURLCashJobs() {
if bot.lnurlcashJobs != nil {
bot.lnurlcashJobs.Start(context.Background())
}
}
// userByName loads a user by the lnbits.User.Name key (Telegram id as text).
func (bot *TipBot) userByName(name string) (*lnbits.User, error) {
id, err := strconv.ParseInt(name, 10, 64)
if err != nil {
return nil, fmt.Errorf("bad user name %q", name)
}
user, err := GetLnbitsUser(&tb.User{ID: id}, *bot)
if err != nil {
return nil, err
}
if user.Wallet == nil {
return nil, fmt.Errorf("user %s has no wallet", name)
}
return user, nil
}
// ---- Ledger: what the note service needs from LNbits ----
type lnbitsLedger struct{ bot *TipBot }
func (l *lnbitsLedger) CreateInvoice(ctx context.Context, userName string, amountSat int64, memo, ref string) (string, string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", "", err
}
invoice, err := user.Wallet.Invoice(lnbits.InvoiceParams{Out: false, Amount: amountSat, Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer}, l.bot.Client)
if err != nil {
return "", "", err
}
event := InvoiceEvent{
Invoice: &Invoice{PaymentHash: invoice.PaymentHash, PaymentRequest: invoice.PaymentRequest, Amount: amountSat, Memo: memo},
User: user,
Callback: InvoiceCallbackLNURLCashSettle,
CallbackData: ref,
LanguageCode: user.Telegram.LanguageCode,
}
runtime.IgnoreError(l.bot.Bunt.Set(event))
return invoice.PaymentRequest, invoice.PaymentHash, nil
}
func (l *lnbitsLedger) PayInvoice(ctx context.Context, userName, pr string) (string, error) {
user, err := l.bot.userByName(userName)
if err != nil {
return "", err
}
paid, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: pr}, l.bot.Client)
if err != nil {
var lnErr lnbits.Error
if errors.As(err, &lnErr) {
// 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
}
if st == nil {
return
}
n := &lnurlcashNotifier{bot: bot}
if st.Note != nil {
n.NoteReclaimed(st.Note)
n.GroupNoteState(st.Note)
}
if st.Redeem != nil {
n.RedeemSettled(st.Redeem)
}
}
// ---- Notifier: how the jobs reach Telegram ----
type lnurlcashNotifier struct{ bot *TipBot }
func recipientOf(userName string) *tb.User {
id, _ := strconv.ParseInt(userName, 10, 64)
return &tb.User{ID: id}
}
func (n *lnurlcashNotifier) send(userName, lang, text string, opts ...interface{}) {
if userName == "bot" || userName == "" {
return
}
n.bot.trySendMessage(recipientOf(userName), text, opts...)
}
func (n *lnurlcashNotifier) NoteClaimed(note *lnurlcash.Note) {
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteClaimedNotifyMessage"),
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))
}
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")
}
}

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