Compare commits

..
39 Commits
Author SHA1 Message Date
MichilisandClaude Sonnet 5.5 48f8a6c7c9 Send note mutations to the mint's callback and polish LNURLcash UX
- Splits and melts went to the withdraw link, but mints such as
  mint.600.wtf take mutations at the callback named in the note's own
  withdraw info (/w/cb). The mint answered 200 without a status, which
  read as an unknown outcome and left minting stuck in recovery. The
  fake mint now behaves the same way.
- Count the LNbits routing reserve (max 1 sat, 1%) in the balance check.
- Allow several comma separated mints in one url entry.
- Format the LNURLcash help like the other help menus.
- Fix int64 passed to %s in the claimed, reclaimed, redeem and view
  messages.
- Reword the in-progress and insufficient-balance messages in every
  language.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 23:48:14 +00:00
MichilisandClaude Sonnet 5.5 cd511cd7cc Return value stranded by a failed note batch to its owner
A refused split after the funding invoice was paid left the funding or
change note in a bot-held row that nothing melted back. A job now splits off
the whole-sat part if needed and reclaims it to the owner's balance, retrying
hourly and alerting the operator once when it cannot.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:27:53 +00:00
MichilisandClaude Sonnet 5.5 b6178e335d Do not fail a funding payment that LNbits may still settle
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:25:01 +00:00
MichilisandClaude Sonnet 5.5 82b291a69b Retry a failed fractional redeem from its split note
The split burns the pasted note before the melt. A failed invoice or melt
used to leave the value in a bot-held split note while a second press
answered 'already claimed'. The retry now melts the split note.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:24:01 +00:00
MichilisandClaude Sonnet 5.5 7f49e422f4 Fix the low-severity audit findings
- price map: guard with a RWMutex (fatal concurrent map access)
- InvoiceStream: stop on client disconnect, unsubscribe once, cap streams per wallet
- join tickets: key the ticket event per joiner; enforce tickets that
  expired while the bot was down

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:22:52 +00:00
MichilisandClaude Sonnet 5.5 6824ef5928 Validate NIP-57 zap requests and refuse ones that do not parse
The bot signs the receipt for whatever p tag the request carries, so the
request must name the paid user, be kind 9734, carry one p tag and match the
amount. A zap request that fails to decode is rejected instead of continuing
with the fields read before the error. Users without a registered nostr
pubkey no longer get zap receipts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:20:45 +00:00
MichilisandClaude Sonnet 5.5 15b95d962b Refuse a banned user's invoice key and keep nsec and k1 out of logs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:19:43 +00:00
MichilisandClaude Sonnet 5.5 8b8b0fa369 Fix the three medium audit findings
- /group ticket del: only the chat creator may remove a group registration
- /node: always dial user-supplied node hosts through the netguard client;
  drop the https://127.0.0.1 prefix exemption
- /app/@{username}: accept only username characters, render the greeting as
  text, add basic security headers

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:18:41 +00:00
MichilisandClaude Fable 5.1 7f89896a6c Translate the LNURLcash messages into every bot language
All 78 note keys now exist in cs, de, es, fi, fr, id, it, pl, pt-br, ru
and tr as well as en and nl, with indexed verbs where a language orders
the arguments differently. The mint fee line goes through a key instead
of the library's English text. A test localizes every key in every
language and formats it with the English argument list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 22:50:58 +00:00
MichilisandClaude Fable 5.1 e36d522764 Add /lnurlhelp and list the note commands in the advanced help
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 22:39:49 +00:00
MichilisandClaude Fable 5.1 1ed809f56c Log the transport cause when a mint check fails
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 22:31:45 +00:00
MichilisandClaude Fable 5.1 3c2ccf8d83 Add the LNURLcash Telegram commands
/note, /notes (list and batch), /redeem and /lnurlmints with confirm
dialogs, group posting with private receipts, claim notifications,
batch export as PDF/JSON/CSV, and LNURLcash notes detected inside the
existing /lnurl, paste and QR-photo flows. Plain withdraw links behave
as before. Two /lnurl log lines no longer print k1.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 22:12:27 +00:00
MichilisandClaude Fable 5.1 721c923aac Add PDF, CSV and JSON export of note batches
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:59:26 +00:00
MichilisandClaude Fable 5.1 a92df0d4ef Add the LNURLcash background jobs
Claim watcher, pending recovery (funding, carving, reclaims, redeems),
mint health and auto reclaim, with tests for lost webhooks, failed melts
and carving resumed after a crash.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:59:01 +00:00
MichilisandClaude Fable 5.1 e695443f7f Add the LNURLcash note service: create, status, reclaim, redeem
Every secret is written encrypted before the first request leaves. Notes
are carved out of one funding note by split so each is a whole number of
sats, which LUD-25's exact-amount melt needs against LNbits' whole-sat
invoices. Tested against an in-memory LUD-25 mint and ledger, including
a dropped connection after an applied split and fractional external notes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:52:37 +00:00
MichilisandClaude Fable 5.1 1fc9a81cd2 Add the lnurlcash store, models and mint registry
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:47:52 +00:00
MichilisandClaude Fable 5.1 d04669b6d6 Add lnurlcash-go and the lnurlcash config block
Pin btcec/v2 at v2.3.3: v2.3.4 changed ecdsa.SignCompact's signature and
lnd/keychain (via ln-decodepay) no longer compiles against it. The
lnurlcash package gets its Config with validation and an AES-256-GCM
cipher for note secrets at rest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:43:16 +00:00
MichilisandClaude Fable 5.1 74f5ae53a7 Add LNURLcash audit and implementation plan
Phase 1 and 2 documents for LUD-25 bearer note support: an audit of the
bot (routing, locking, money paths, LNURL, storage, i18n, jobs, risks)
and of lnurlcash-go v0.3.0 including the btcec/lnd dependency conflict,
plus a step-by-step plan with open questions. No code changes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 21:38:00 +00:00
MichilisandClaude Fable 5.1 5a3b4dad7c Make go test ./... run and fix the stale tooltip test
internal/config.go panicked in init without a config.yaml and the i18n
loader only found translations/ from the repository root, so no test in
a package importing them could run. Config checks are skipped in a test
binary, the translation directory is located by walking up, GetAmount
no longer dereferences a nil price watcher, and the tooltip test expects
the text the code actually produces. Adds tests for amount validation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:58:30 +00:00
MichilisandClaude Fable 5.1 81af610980 Never pass dynamic strings as format strings
Sixteen log and error calls used a message, an LNURL string or callback
data as the format string. Go vet (printf check, Go 1.24+) fails the
test build on these.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:51:57 +00:00
MichilisandClaude Fable 5.1 7268fe6d31 Fix LNURL onion detection and go vet findings
A five-character domain was treated as an onion address (strings.Index
returned -1 == len-6) and the lnurlp:// scheme check tested an empty
string. Also: wrong format verb in the AnonID migration log, an error
that was built but never logged, an unreachable return, and the message
log line was passed as a format string.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:50:26 +00:00
MichilisandClaude Fable 5.1 8514341118 Update the Go toolchain and golang.org/x/net
go run with the host's Go 1.21.6 reached 13 known net/http, crypto/tls
and crypto/x509 vulnerabilities, and golang.org/x/net was from 2021. The
module now asks for go1.26.11 through the toolchain directive (Go 1.21+
downloads it on first run) and uses x/net v0.62.0 and gorilla/websocket
v1.5.3. govulncheck is down to two findings in dependencies with no fix
(imroc/req v0.3.0, lnd v0.15 zpay32) that the bot's code paths do not
exercise.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:50:26 +00:00
MichilisandClaude Fable 5.1 86b7a8f7bc Fix crashes and the dropped certificate in satdress
Transaction.Send dereferenced a nil error when logging a failed DB save
after a successful transfer. satdress.SetupHttpClient type-asserted a
nil Transport for local nodes. The /node command shadowed the cert
variable, so a supplied certificate was never used and TLS verification
was always disabled for LND nodes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:41:39 +00:00
MichilisandClaude Fable 5.1 afd1050e57 Keep invoices, LNURLs, ecash tokens and node credentials out of the log
The message interceptor logged every private text at Info, which put
bolt11 invoices, LNURLs, Cashu tokens and '/node add lnd <host>
<macaroon>' into journald. The API middleware logged the submitted key
of banned users. Both are redacted now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:41:39 +00:00
MichilisandClaude Fable 5.1 bb1037bcb7 Validate amounts in every GetAmount branch; cap faucet slots
The k and fiat branches returned the float conversion unchecked, so
non-positive, NaN or Inf inputs reached callers that have no guard of
their own (faucet total, ticket price, shop price, satdress amount).
Every branch now rejects non-positive and non-finite amounts and anything
above 10,000,000 sat. A faucet can have at most 1000 slots.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:41:39 +00:00
MichilisandClaude Fable 5.1 0bcb821b82 Per-payer group ticket ids; deactivate paid objects
The group ticket event was stored under ticket:<groupID>, so a later
/join by another user overwrote the payer and the invite link went to
whoever joined last. The id now includes the payer.

The pay, LNURL-withdraw and group-ticket confirm handlers left their
object Active after success, so a second press repeated the request.
They now deactivate it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:41:39 +00:00
MichilisandClaude Fable 5.1 b27b0b7bcb Make the named mutex atomic
Lock did a get-then-set on the map without holding mutexMapSync, and
Unlock removed the entry before unlocking it. Two handlers that arrived
for a name not yet in the map each got their own mutex, and a waiter
could end up holding a mutex that later callers could not see. Both let
two button presses run the same faucet or inline object at once.

Entries are now created and looked up under one lock and reference
counted, so they are only removed when the last holder unlocks. Tests
run 200 goroutines through Lock and LockWithContext under -race.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:41:39 +00:00
MichilisandClaude Fable 5.1 f040b67597 Verify webhook payments with LNbits before acting on them
The webhook listener accepted any POST as proof of payment and fired the
invoice callbacks (inline receive, group tickets, satdress payout, DALL-E
refund) for whatever payment hash the body named. It now:

- limits the body to 1 MB and only accepts a 64-hex payment hash,
- asks LNbits whether the named wallet really received a settled
  incoming payment for that hash, and uses the amount LNbits reports,
- handles every payment hash once (bunt key "webhook:<hash>"),
- refuses to dispatch an invoice event registered for another wallet,
- runs the callback with a recover, so a panic can't take the bot down.

The pure checks live in internal/lnbits/webhook/verify, which does not
depend on the bot configuration and is unit tested.

Port of kravens/BitTipBot b7e56da and 27eb079 onto our simpler handler.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:36:48 +00:00
MichilisandClaude Fable 5.1 e010b31fd5 Ignore build artefacts, toolchain tarballs and node_modules
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:34:56 +00:00
MichilisandClaude Fable 5.1 1a3815902a Keep the ban state when an old copy of a user is saved
UpdateUserRecord wrote every column of the user it was given, so saving
a copy taken before a ban (cached user, stored inline object, invoice
event) lifted the ban. The banned flag and the admin key now always come
from the database row and are left out of the save; only the new
UpdateUserBan changes them, and the admin API uses it.

Manual port of kravens/BitTipBot 05c0a4e and dfc8d13.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:34:56 +00:00
MichilisandClaude Fable 5.1 39bddc2cb5 Only publish zap receipts to public wss relays
Relay URLs come from the zap request. Keep at most 10 of them, only
wss://, and make the websocket dialer refuse non-public addresses.

Manual port of kravens/BitTipBot efe2fa2 (the only conflict was the
hard-coded default relay list, which is kept as is).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:34:56 +00:00
Kevin RavensbergandMichilis 2c3c9fb3ce Only let the requesting user confirm an LNURL-auth login
The confirm handler signed the stored challenge with the key of whoever pressed the button. Check the owner like the cancel handler does.

(cherry picked from commit 547568cadcfd28d5ae94a1eb30f25dd0cfa03f91)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:45 +00:00
Kevin RavensbergandMichilis d1d51bbb16 Refuse transfers to placeholder users
Check the recipient where the money moves, so reaction tips, /send and inline sends to an existing placeholder wallet are covered too. The reply check in loadReplyToInterceptor is no longer needed and blocked /send with an explicit recipient.

(cherry picked from commit c8ea81d58aed2f288d0aee9fe63c3da08a97867c)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:45 +00:00
Kevin RavensbergandMichilis 8989483891 Ignore updates sent as a channel or anonymous admin
Telegram uses one shared fake user for all anonymous group admins and for messages sent as a channel. Such a sender must not own a wallet: reject its updates, do not tip it and do not create a wallet for it.

(cherry picked from commit 1b7478fc505b9ed388474192541185bc40569184)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:45 +00:00
lightningtipbotandMichilis 064f36889a Trust the bot's own LNURL and LNbits hosts in netguard
On nodes where the bot's public hostname resolves to loopback (hosts file,
split DNS), the public address check refused every payment to a lightning
address on the bot's own domain. The LNURL host and the LNbits host from
the config are now exempt from the check; literal internal addresses stay
refused.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qy4RRoDyYEWTZWESFHp7dp
(cherry picked from commit ba6c6a36293adf000c495cc81fdd18ecc96a69f6)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:45 +00:00
Kevin RavensbergandMichilis 8d557f3043 Give every HTTP client its own transport
satdress.SetupHttpClient changes the TLS settings of the transport it gets from network.GetClient. With one shared transport that switched certificate checks off for all later LNURL requests.

(cherry picked from commit 864cc7b3e7d6b4cd9b57ae84b5d2646f8ba3177f)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:44 +00:00
Kevin RavensbergandMichilis 5360a9d4a1 Refuse more non-public address forms
Add the benchmarking, reserved, NAT64 and 6to4 ranges, and refuse numeric host names such as 2130706433 or 127.1 when a proxy resolves the name.

(cherry picked from commit a802a59627acdc6400ac2ecf19c8e5cbcc2868e8)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:44 +00:00
Kevin RavensbergandMichilis 5ff6e841e1 Refuse non-public addresses in the LNURL HTTP client
The clients from network.GetClient fetch URLs that come from users and from remote LNURL servers. Without a proxy they now only connect to public addresses. The check runs at connect time on the resolved address, so it also covers redirects and hostnames that resolve to an internal address. With a SOCKS proxy, literal internal addresses and localhost names are refused.

(cherry picked from commit c3bcae870ec6018e8809d96f86b0d091ab124a5a)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:44 +00:00
Kevin RavensbergandMichilis 34f2e562e2 Require a token for the admin API
The admin API (ban, unban, mutex, DALL-E toggles, pprof) had no authentication. Every request now needs 'Authorization: Bearer <bot.admin_api_token>'. Without a configured token all requests are rejected.

(cherry picked from commit 3fb544687d8cd8563f1e4e1720de1ef832653457)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 20:33:44 +00:00
105 changed files with 9991 additions and 552 deletions
+6 -1
View File
@@ -1,4 +1,9 @@
config.yaml
config.yaml*
data/*
!data/.placeholder
!data/.placeholder
# build artefacts and vendored toolchains must not be committed
/LightningTipBot
*.tar.gz
cashu/node_modules/
trace_*.txt
+5
View File
@@ -56,6 +56,7 @@ 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).
@@ -147,3 +148,7 @@ 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/`.
+6 -1
View File
@@ -14,4 +14,9 @@ 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
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
+26
View File
@@ -10,6 +10,7 @@ bot:
lnurl_server: "http://127.0.0.1:5454" # or http://0.0.0.0:5454 depending on your configuration
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"
@@ -25,6 +26,7 @@ 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"
@@ -32,3 +34,27 @@ generate:
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
+373
View File
@@ -0,0 +1,373 @@
# LNURLcash audit of LightningTipBot (branch update-bugfixes @ 5a3b4da)
> Audit of `update-bugfixes` @ `5a3b4da` (clean tree) for the LNURLcash feature. Paths are
> relative to the repo root; `t/` means `internal/telegram/`. Every claim names a file and
> function. Where something could not be verified from code, it says so.
## 1. Structure
**Entry point** `main.go`: package `init()`s run first (`internal/config.go:72` loads
`config.yaml` with `configor.Load`, panics on error, parses the webhook and LNURL URLs;
`internal/i18n/localize.go:15` loads `translations/*.toml`). Then `main()`:
`setLogger()` (Debug level, unconditionally, `main.go:28`), `price.NewPriceWatcher().Start()`,
`telegram.NewBot()` (`t/bot.go:44`: go-cache, `AutoMigration()`, rate limiter, LNbits
client, two buntdb files, `tb.NewBot` with 60 s long poller and Markdown parse mode),
`startApiServer()` (`main.go:45`: no-op `OnError`, webhook server, public API, admin API),
`bot.Start()` (`t/bot.go:111`: `initBotWallet`, `registerTelegramHandlers`, edit worker,
`initInvoiceEventCallbacks`, `initializeStateCallbackMessage`, `go Telegram.Start()`,
`go restartPersistedTickets()`, then wait for SIGINT and `GracefulShutdown`, which polls
`mutex.IsEmpty()` for at most 10 s).
**Config**: one global struct `internal.Configuration` (`internal/config.go:13`) with
`Bot`, `Telegram`, `Database`, `Lnbits`, `Generate`, `Nostr`. A new `lnurlcash:` block is a
new struct + field here. configor decodes YAML with yaml.v2, so `time.Duration` fields
accept `5m`/`60s`. `config.yaml.example` lists every key; `http_proxy` in the example has
no struct field.
**Packages**: `internal` (config), `internal/api` (+`admin`, `userpage`), `internal/database`
(column migrations + user lookups only; it opens no DB), `internal/errors`, `internal/i18n`,
`internal/lnbits` (REST client + `User`/`Wallet`/`Settings` GORM models), `internal/lnbits/webhook`
(+`verify`), `internal/lnurl` (LNURL-pay server, NIP-57), `internal/netguard` (refuses private
IPs), `internal/network` (`GetClientForScheme`: 10 s timeout, netguard dialer, SOCKS/Tor),
`internal/nostr`, `internal/price`, `internal/rate`, `internal/runtime` (+`mutex`, `once`),
`internal/satdress`, `internal/storage` (buntdb wrapper, `Base`), `internal/str`,
`internal/telegram` (+`intercept`), `internal/gpt`, `internal/dalle`, `internal/lndhub`,
`pkg/lightning` (`IsInvoice`, `IsLnurl`, `IsLightningAddress`; string checks only).
**Versions** (`go.mod`): `go 1.26.0`, `toolchain go1.26.11`; telebot fork
`gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd`; `gorm.io/gorm v1.21.12`;
`gorm.io/driver/sqlite v1.1.4` (mattn/go-sqlite3 v1.14.5, cgo); `tidwall/buntdb v1.2.7`;
`fiatjaf/go-lnurl v1.11.3-0.20220819192234`; `fiatjaf/ln-decodepay v1.1.0` (only use:
`t/pay.go:81`); `skip2/go-qrcode` (2020); `makiuchi-d/gozxing v0.0.2`; `go-i18n/v2 v2.1.2`;
`jinzhu/configor v1.2.1`; `btcsuite/btcd/btcec/v2 v2.2.0` (direct, `internal/lnbits/types.go:160`
for LNURL-auth); `lightningnetwork/lnd v0.15.0-beta` (indirect, via ln-decodepay → zpay32).
There is no LNbits client library dependency: the client is hand-written in `internal/lnbits/lnbits.go`.
## 2. Handler registration and routing
- `t/handler.go:19 registerTelegramHandlers` iterates `getHandler()` (`handler.go:85-1316`,
one `InterceptionWrapper{Endpoints, Handler, Interceptor}` per entry) and calls
`registerHandlerWithInterceptor` (`handler.go:41`), which prepends the defaults
`idInterceptor, rejectPlaceholderSenderInterceptor` and wraps with
`intercept.WithHandler`. `handle()` (`handler.go:55`) also registers `/CMD` and `/Cmd`
variants for slash commands.
- Endpoints are strings (`"/faucet"`), telebot events (`tb.OnText`, `tb.OnPhoto`,
`tb.OnQuery`) or `*tb.Btn`. Buttons route by `Unique`: telebot serialises callback data
as `"\f<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
@@ -0,0 +1,375 @@
# LNURLcash implementation plan
> Implementation plan for LNURLcash notes. Each step compiles and can be merged alone.
> Amounts are int64 msat inside `internal/lnurlcash`; sats appear only at the Telegram and
> LNbits edges. `k1` is never logged; `h` (sha256 of k1) and the note id are safe to log.
## Design decisions (deviations from the spec, with reasons)
- **D1. Every bot-minted note is carved by a split so its value is a whole number of sats.**
LUD-25 requires a melt invoice for exactly the note's value, and LNbits invoices are whole
sats (`InvoiceParams.Amount int64`). With the default mint's fee (`1000,100`) a directly
minted note is almost never whole-sat. So creation always does: pay one mint invoice for the
gross → the funding note (secret `k1_0`, hash `h_0`) → `SplitNoteWithHash(cb, [k1_0],
value_msat, h_1, h_2)` → the user's note `h_1` is exactly `value`; the change `h_2` is dust
owned by the bot. A single note is therefore a batch of one with `batch_strategy: split`.
Gross is computed as the smallest whole-sat invoice whose net after the mint fee is at least
`N·value + N·base_fee_msat + 1 msat` (each split costs `base_fee_msat` on the change and the
change must stay positive). The confirm message shows value, mint fee (both parts), total.
Alternative (open question Q1): if the running LNbits accepts fractional sats
(`amount` as float, `unit: "sat"`), melts could be exact without splits; the split path
stays necessary for externally minted fractional notes anyway.
- **D2. `batch_strategy: invoices` is kept but documented as "one invoice per note, then one
split per note"** (same carving, N invoices). Default remains `split`.
- **D3. Redeeming a note with a fractional-sat value** (possible from other mints): split off
`S = floor(value_msat/1000)` sats to a fresh bot secret (persisted first), retrying with
`S−1`, `S−2` on a definitive `insufficient value` refusal (nothing burned), then melt that
whole-sat note. The dust change stays as a bot-owned `dust` row. Whole-sat notes melt directly.
- **D4. Detection of a note inside the existing `/lnurl` flow happens in `HandleLNURL`'s
`withdrawRequest` branch** by reading `mintPubkey` from the body with gjson; when present
and the feature is enabled it returns a new `LNURLCashNoteParams` value and `lnurlHandler`
hands it to the redeem flow. Withdraw links without `mintPubkey` behave exactly as today.
- **D5. Two log lines in `t/lnurl.go` that print the raw text (:40) and the decoded URL
(:217) are changed to go through `redactForLog` / to drop the query string.** This is a
log change only; command behaviour is untouched. Required by "never log k1".
- **D6. Secrets are stored AES-256-GCM encrypted** (stdlib `crypto/aes`, random 12-byte
nonce, key = `secret_encryption_key` as 64 hex chars). When `lnurlcash.enabled` and the key
is empty or malformed the bot refuses to start with a clear message. The hash `h` is stored
in clear as the lookup key.
- **D7. New sqlite file `database.lnurlcash_path` (default `data/lnurlcash.db`)** holding
the five new tables, opened in `AutoMigration`. Keeps the users DB untouched and lets the
feature be dropped by deleting one file. Models live in `internal/lnurlcash` (imports
`internal/lnbits` for `Wallet`; `telegram` imports `lnurlcash`; no cycle).
- **D8. Idempotent "in-flight" rows instead of Bunt objects**: all state is in GORM rows with
a `state` column; Bunt is used only for the short-lived confirm dialogs (`storage.Base`
pattern, like `/send`). Background jobs read rows, never Bunt.
- **D9. Settle detection = webhook event + polling.** Redeem/reclaim invoices are created
with `createInvoiceWithEvent`-style events (new `InvoiceCallbackLNURLCashSettle`), and the
recovery job also polls `bot.Client.Payment(wallet, hash).Paid`, so a lost webhook cannot
strand a melt.
- **D10. The per-user Telegram lock is held for the whole creation handler** (including
the mint invoice and the LNbits pay), matching `/pay`. Background jobs lock per note id
with `mutex.Lock(noteID)` (plain, not `LockWithContext`, because of the nLocks caveat) and
skip rows whose lock is busy.
## Step 0: branch, docs, dependency (no behaviour change)
- `git checkout -b lnurlcash`; add `docs/lnurlcash/AUDIT.md`, `docs/lnurlcash/PLAN.md`.
- `go get github.com/lnurlcash/lnurlcash-go@v0.3.0`; add
`replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3`
with a comment explaining the lnd `SignCompact` incompatibility; `go mod tidy`.
- Test: `go build ./... && go vet ./... && go test ./... && go test github.com/lnurlcash/lnurlcash-go`
(all verified green in the scratch copy).
## Step 1: config and crypto (`internal/config.go`, `internal/lnurlcash/crypto.go`)
- Add to `internal/config.go`: `LNURLCash LnurlcashConfiguration \`yaml:"lnurlcash"\`` with
fields mirroring the spec block (`Enabled bool`, `Mints []MintConfiguration{Name, URL,
Default bool}`, `MinNoteSat, MaxNoteSat, MaxOutstandingSatPerUser, MaxOutstandingNotesPerUser,
MaxBatchSize, MaxBatchTotalSat, GroupNoteMaxSat, MaxMintFeePpm int64`, `AutoReclaimDays int`,
`StatusPollInterval, InvoiceWaitTimeout time.Duration`, `BatchStrategy string`,
`BatchFormats []string`, `SecretEncryptionKey string`) and
`DatabaseConfiguration.LNURLCashPath \`yaml:"lnurlcash_path"\``. Add the block to
`config.yaml.example` (disabled by default). Add `Validate() error` (defaults for zero
values: poll 5m, wait 60s, strategy split, formats pdf,json,csv; exactly one default mint;
URLs must pass `lnurlcash.IsAllowedServiceURL`; key hex of 32 bytes when enabled). Call it
from `checkLnbitsConfiguration` (skipped in tests by `isTestBinary`).
- `internal/lnurlcash/crypto.go`: `type Cipher struct{aead cipher.AEAD}`, `NewCipher(hexKey)`,
`Seal(plain string) ([]byte, error)`, `Open([]byte) (string, error)`.
- Tests: `crypto_test.go` round-trip, wrong key fails, tamper fails; `config_test.go` for
`Validate`.
## Step 2: models and store (`internal/lnurlcash/models.go`, `store.go`; `t/database.go`)
Tables (GORM, table names via `TableName()`):
- `lnurlcash_notes`: `ID string` (pk, `note-<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?
+27 -14
View File
@@ -1,17 +1,21 @@
module github.com/LightningTipBot/LightningTipBot
go 1.18
go 1.26.0
toolchain go1.26.11
require (
github.com/BurntSushi/toml v0.3.1
github.com/PuerkitoBio/goquery v1.8.0
github.com/btcsuite/btcd/btcec/v2 v2.2.0
github.com/btcsuite/btcd/btcec/v2 v2.5.0
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.11.3-0.20220819192234-5c5819dd0aa7
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/go-pdf/fpdf v0.9.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/lnurlcash/lnurlcash-go v0.3.0
github.com/makiuchi-d/gozxing v0.0.2
github.com/nbd-wtf/go-nostr v0.13.0
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
@@ -26,14 +30,22 @@ require (
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
golang.org/x/text v0.3.7
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
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
@@ -42,10 +54,10 @@ require (
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.23.1 // indirect
github.com/btcsuite/btcd/btcutil v1.1.1 // 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.0.1 // 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
@@ -58,13 +70,13 @@ require (
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.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.4.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
@@ -91,11 +103,10 @@ require (
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.0.0-20210921155107-089bfa567519 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
golang.org/x/sys v0.1.0 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // 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
@@ -106,3 +117,5 @@ require (
)
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3
+44 -25
View File
@@ -104,22 +104,22 @@ github.com/btcsuite/btcd v0.22.0-beta.0.20220204213055-eaf0459ff879/go.mod h1:os
github.com/btcsuite/btcd v0.22.0-beta.0.20220207191057-4dc4ff7963b4/go.mod h1:7alexyj/lHlOtr2PJK7L/+HDJZpcGDn/pAU98r7DY08=
github.com/btcsuite/btcd v0.22.0-beta.0.20220316175102-8d5c75c28923/go.mod h1:taIcYprAW2g6Z9S0gGUxyR+zDwimyDMK5ePOX+iJ2ds=
github.com/btcsuite/btcd v0.23.0/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY=
github.com/btcsuite/btcd v0.23.1 h1:IB8cVQcC2X5mHbnfirLG5IZnkWYNTPlLZVrxUYSotbE=
github.com/btcsuite/btcd v0.23.1/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY=
github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA=
github.com/btcsuite/btcd/btcec/v2 v2.1.1/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
github.com/btcsuite/btcd/btcec/v2 v2.2.0 h1:fzn1qaOt32TuLjFlkzYSsBC35Q3KUjT1SwPxiMSCF5k=
github.com/btcsuite/btcd/btcec/v2 v2.2.0/go.mod h1:U7MHm051Al6XmscBQ0BoNydpOTsFAn707034b5nY8zU=
github.com/btcsuite/btcd v0.24.2 h1:aLmxPguqxza+4ag8R1I2nnJjSu2iFn/kqtHTIImswcY=
github.com/btcsuite/btcd v0.24.2/go.mod h1:5C8ChTkl5ejr3WHj8tkQSCmydiMEPB0ZhQhehpq7Dgg=
github.com/btcsuite/btcd/btcec/v2 v2.3.3 h1:6+iXlDKE8RMtKsvK0gshlXIuPbyWM/h84Ensb7o3sC0=
github.com/btcsuite/btcd/btcec/v2 v2.3.3/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A=
github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE=
github.com/btcsuite/btcd/btcutil v1.1.1 h1:hDcDaXiP0uEzR8Biqo2weECKqEw0uHDZ9ixIWevVQqY=
github.com/btcsuite/btcd/btcutil v1.1.1/go.mod h1:nbKlBMNm9FGsdvKvu0essceubPiAcI57pYBNnsLAa34=
github.com/btcsuite/btcd/btcutil v1.2.0 h1:p3+S2g3Q+7G5NOh4Ji+2UrBOrg5Z0Q4ykzShWG1Dhgs=
github.com/btcsuite/btcd/btcutil v1.2.0/go.mod h1:/Taflm113pYjUpbWKKQEfa6XOtI/+WS8awxeMZpY75k=
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 h1:Edx4AfBn+YPam2KP5AobDitulGp4r1Oibm8oruzkMdI=
github.com/btcsuite/btcd/btcutil/psbt v1.1.4/go.mod h1:9AyU6EQVJ9Iw9zPyNT1lcdHd6cnEZdno5wLu5FY74os=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f h1:bAs4lUbRJpnnkd9VhRV3jjAVU7DJVjMaK+IsvSeZvFo=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
@@ -210,10 +210,12 @@ github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/decred/dcrd/lru v1.0.0 h1:Kbsb1SFDsIlaupWPwsPp+dkxiBY1frcS07PCPgotKz8=
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
github.com/dgraph-io/ristretto v0.0.3 h1:jh22xisGBjrEVnRZ1DVTpBVQm0Xndu8sMl0CWDzSIBI=
@@ -265,6 +267,7 @@ github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVB
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
@@ -290,6 +293,8 @@ github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk=
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw=
github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
@@ -366,6 +371,7 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
@@ -392,8 +398,9 @@ github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw=
@@ -550,6 +557,8 @@ github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23/go.mod h1:Ljlbryh9
github.com/julienschmidt/httprouter v1.1.1-0.20151013225520-77a895ad01eb/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee h1:FPP9HDkBbPyniu+u7FHZg+kKFX1WW0gxOGteJ0h3AJk=
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee/go.mod h1:N6sz6HwJAenJ6d+/xmSl0ikfV05ZrVGmjt1ryy/WOtE=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
@@ -573,6 +582,7 @@ github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFB
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
@@ -625,6 +635,8 @@ github.com/lightningnetwork/lnd/tor v1.0.1 h1:A11FrpU0Y//g+fA827W4VnjOeoIvExONdc
github.com/lightningnetwork/lnd/tor v1.0.1/go.mod h1:RDtaAdwfAm+ONuPYwUhNIH1RAvKPv+75lHPOegUcz64=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/lnurlcash/lnurlcash-go v0.3.0 h1:12LUZJXqvyDfvZ1uWbk1kFh9le7vOIMKiraQiUqvZ1A=
github.com/lnurlcash/lnurlcash-go v0.3.0/go.mod h1:tBFpb7fqLeX0zcLqjNqqa9R9ogH2q5QM8m/rUZMFz1s=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY=
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
@@ -802,6 +814,7 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
@@ -850,8 +863,10 @@ github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
@@ -859,8 +874,10 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
@@ -1012,8 +1029,9 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -1024,7 +1042,6 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20220426173459-3bcf042a4bf5/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 h1:Fq7F/w7MAa1KJ5bt2aJ62ihqp9HDcRuyILskkpIAurw=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
@@ -1051,7 +1068,6 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180406214816-61147c48b25b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -1102,8 +1118,9 @@ golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1121,8 +1138,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde h1:ejfdSekXMDxDLbRrJMwUk6KnSLZ2McaUCVcIKM+N6jc=
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180816055513-1c9583448a9c/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1196,11 +1213,12 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -1210,8 +1228,9 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1275,7 +1294,6 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1428,8 +1446,9 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
+2 -2
View File
@@ -26,7 +26,7 @@ func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
user.Banned = false
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
err = telegram.UpdateUserRecord(user, *s.bot)
err = telegram.UpdateUserBan(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.UpdateUserRecord(user, *s.bot)
err = telegram.UpdateUserBan(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
+64 -21
View File
@@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"time"
"sync"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -141,8 +141,43 @@ type InvoiceStream struct {
WebhookStatus interface{} `json:"webhook_status"`
}
// maxStreamsPerWallet bounds the SSE connections one wallet can hold open. Each
// one keeps a goroutine and a connection to LNbits alive.
const maxStreamsPerWallet = 3
var (
streamsMu sync.Mutex
streams = map[string]int{}
)
// acquireStream reserves a stream slot for the wallet.
func acquireStream(walletID string) bool {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] >= maxStreamsPerWallet {
return false
}
streams[walletID]++
return true
}
func releaseStream(walletID string) {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] <= 1 {
delete(streams, walletID)
return
}
streams[walletID]--
}
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
if !acquireStream(user.Wallet.ID) {
http.Error(w, "Too many streams", http.StatusTooManyRequests)
return
}
defer releaseStream(user.Wallet.ID)
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
@@ -160,29 +195,37 @@ func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
out:
for {
select {
case <-r.Context().Done():
// the client went away: do not wait for the next payment event
break out
case msg := <-c:
select {
case <-r.Context().Done():
client.Unsubscribe(c)
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
break out
default:
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
}
// Unsubscribe once. It blocks until the subscription goroutine takes the
// request, and that goroutine may be sending an event, so keep draining.
done := make(chan struct{})
go func() {
client.Unsubscribe(c)
close(done)
}()
for {
select {
case <-c:
case <-done:
return
}
}
close(c)
time.Sleep(time.Second * 5)
}
+21
View File
@@ -0,0 +1,21 @@
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")
}
}
+28 -1
View File
@@ -2,6 +2,7 @@ package api
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"net/http"
@@ -10,6 +11,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
@@ -63,7 +65,7 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
w.WriteHeader(401)
log.Warnf("[api] Banned user %s. Not forwarding request", password)
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)
@@ -85,6 +87,14 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType Ac
return
}
// The ban rewrites only the admin key, so a banned user's invoice key
// still matches above. Refuse every key of a banned user.
if user.Banned || user.Wallet == nil || strings.HasPrefix(user.Wallet.Adminkey, "banned") || strings.Contains(user.Wallet.Adminkey, "_") {
w.WriteHeader(401)
log.Warnf("[api] Request with a key of a banned user. Not forwarding request")
return
}
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
r = r.WithContext(context.WithValue(r.Context(), "user", user))
next.ServeHTTP(w, r)
@@ -125,3 +135,20 @@ 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
@@ -0,0 +1,56 @@
package api
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// The ban rewrites only the admin key. Every key of a banned user must be
// refused, the invoice key included, and a normal user must still pass.
func TestAuthorizationMiddlewareRefusesBannedUsersKeys(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared&_banmw=1"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&lnbits.User{}); err != nil {
t.Fatal(err)
}
users := []*lnbits.User{
{ID: "u1", Name: "111", Banned: true, Wallet: &lnbits.Wallet{ID: "w1", Adminkey: "banned_aaaaaaaaaaaaaaaa", Inkey: "bbbbbbbbbbbbbbbb"}},
{ID: "u2", Name: "222", Wallet: &lnbits.Wallet{ID: "w2", Adminkey: "cccccccccccccccc", Inkey: "dddddddddddddddd"}},
}
for _, u := range users {
if err := db.Create(u).Error; err != nil {
t.Fatal(err)
}
}
call := func(access AccessKeyType, key string) int {
h := AuthorizationMiddleware(db, AuthTypeBasic, access, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
req := httptest.NewRequest("GET", "/api/v1/balance", nil)
req.Header.Set("Authorization", "Basic "+key)
rr := httptest.NewRecorder()
h(rr, req)
return rr.Code
}
for _, c := range []struct {
access AccessKeyType
key string
want int
}{
{AccessKeyTypeInvoice, "bbbbbbbbbbbbbbbb", 401}, // banned user's invoice key
{AccessKeyTypeInvoice, "aaaaaaaaaaaaaaaa", 401}, // banned user's old admin key
{AccessKeyTypeAdmin, "aaaaaaaaaaaaaaaa", 401},
{AccessKeyTypeInvoice, "dddddddddddddddd", 200}, // normal user still works
{AccessKeyTypeAdmin, "cccccccccccccccc", 200},
} {
if got := call(c.access, c.key); got != c.want {
t.Errorf("%s key %s: got %d, want %d", c.access.Type, c.key, got, c.want)
}
}
}
+19
View File
@@ -32,6 +32,7 @@ func NewServer(address string) *Server {
httpServer: srv,
}
apiServer.router = mux.NewRouter()
apiServer.router.Use(securityHeaders)
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[api] Server started at %s", address)
@@ -41,6 +42,11 @@ func NewServer(address string) *Server {
func (w *Server) ListenAndServe() {
go w.httpServer.ListenAndServe()
}
// Use adds a middleware that runs for every route of the server.
func (w *Server) Use(middleware mux.MiddlewareFunc) {
w.router.Use(middleware)
}
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
@@ -71,3 +77,16 @@ 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)
})
}
+2 -2
View File
@@ -270,7 +270,7 @@
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
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);
@@ -368,7 +368,7 @@
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
document.querySelector('#greeting').textContent = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
+14
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"time"
@@ -27,6 +28,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
@@ -70,6 +76,10 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/@<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering page of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
@@ -95,6 +105,10 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/app/<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering webapp of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
+42
View File
@@ -0,0 +1,42 @@
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")
}
}
+29
View File
@@ -3,8 +3,10 @@ package internal
import (
"fmt"
"net/url"
"os"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/jinzhu/configor"
log "github.com/sirupsen/logrus"
)
@@ -16,6 +18,8 @@ var Configuration = struct {
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 {
@@ -44,6 +48,7 @@ type BotConfiguration struct {
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
AdminAPIToken string `yaml:"admin_api_token"`
}
type TelegramConfiguration struct {
@@ -56,6 +61,8 @@ 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 {
@@ -88,7 +95,29 @@ func init() {
panic(err)
}
Configuration.Bot.LNURLHostUrl = hostname
if isTestBinary() {
// go test has no config.yaml; a missing LNbits URL must not stop
// unit tests of packages that import this one.
return
}
checkLnbitsConfiguration()
checkLNURLCashConfiguration()
}
// checkLNURLCashConfiguration refuses to start with a broken lnurlcash block:
// a half-configured note feature would mint money it cannot keep track of.
func checkLNURLCashConfiguration() {
if err := Configuration.LNURLCash.Validate(); err != nil {
panic(err)
}
if Configuration.LNURLCash.Enabled && Configuration.Database.LNURLCashPath == "" {
Configuration.Database.LNURLCashPath = "data/lnurlcash.db"
}
}
// isTestBinary reports whether the process is a go test binary.
func isTestBinary() bool {
return strings.HasSuffix(os.Args[0], ".test") || strings.HasSuffix(os.Args[0], ".test.exe")
}
func checkLnbitsConfiguration() {
+1 -1
View File
@@ -13,7 +13,7 @@ func MigrateAnonIdInt32Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
log.Infof("[MigrateAnonIdInt32Hash] %s -> %d", u.ID, str.Int32Hash(u.ID))
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
tx := db.Save(u)
if tx.Error != nil {
+55
View File
@@ -0,0 +1,55 @@
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)
}
}
}
}
+30 -13
View File
@@ -1,6 +1,9 @@
package i18n
import (
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
@@ -13,22 +16,36 @@ 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)
bundle.MustLoadMessageFile("translations/en.toml")
bundle.LoadMessageFile("translations/de.toml")
bundle.LoadMessageFile("translations/fi.toml")
bundle.LoadMessageFile("translations/it.toml")
bundle.LoadMessageFile("translations/es.toml")
bundle.LoadMessageFile("translations/nl.toml")
bundle.LoadMessageFile("translations/pl.toml")
bundle.LoadMessageFile("translations/fr.toml")
bundle.LoadMessageFile("translations/pt-br.toml")
bundle.LoadMessageFile("translations/tr.toml")
bundle.LoadMessageFile("translations/cs.toml")
bundle.LoadMessageFile("translations/id.toml")
bundle.LoadMessageFile("translations/ru.toml")
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"))
return bundle
}
func Translate(languageCode string, MessgeID string) string {
+49
View File
@@ -0,0 +1,49 @@
// 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
}
@@ -0,0 +1,52 @@
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)
}
}
}
+97 -9
View File
@@ -3,10 +3,12 @@ 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"
@@ -17,11 +19,16 @@ 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
@@ -74,6 +81,37 @@ 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)
@@ -83,21 +121,54 @@ func (w *Server) newRouter() *mux.Router {
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
webhookEvent := Webhook{}
// need to delete the header otherwise the Decode will fail
request.Header.Del("content-length")
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, maxBodyBytes))
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
}
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil {
log.Errorf("[Webhook] Error getting user: %s", err.Error())
// 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
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
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)
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))
writer.WriteHeader(200)
@@ -106,6 +177,11 @@ 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 {
@@ -113,14 +189,26 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Errorln(err)
return
}
go c.Function(txInvoiceEvent)
go runCallback(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"), webhookEvent.Amount/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), amountMsat/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)
}
+28 -16
View File
@@ -127,21 +127,17 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
zapEventQuery := request.FormValue("nostr")
var zapEvent nostr.Event
if len(zapEventQuery) > 0 {
err = json.Unmarshal([]byte(zapEventQuery), &zapEvent)
if err != nil {
log.Errorf("[handleLnUrl] Couldn't parse nostr event: %v", err)
} else {
valid, err := zapEvent.CheckSignature()
if !valid || err != nil {
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event signature invalid: %v", err)
return
}
if len(zapEvent.Tags) == 0 || zapEvent.Tags.GetFirst([]string{"p"}) == nil {
// zapEvent.Tags.GetFirst([]string{"e"}) == nil {
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event validation error")
return
}
// 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
}
}
@@ -289,10 +285,26 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
// get user settings
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
if err != nil {
fmt.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
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
+38
View File
@@ -3,7 +3,11 @@ package lnurl
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
"github.com/nbd-wtf/go-nostr"
)
type Tag []string
@@ -26,3 +30,37 @@ func (w Lnurl) Nip57DescriptionHash(zapEventSerialized string) string {
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
@@ -0,0 +1,37 @@
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
@@ -0,0 +1,232 @@
// 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
@@ -0,0 +1,13 @@
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
@@ -0,0 +1,64 @@
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
@@ -0,0 +1,97 @@
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
@@ -0,0 +1,24 @@
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
@@ -0,0 +1,147 @@
// 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
@@ -0,0 +1,61 @@
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
@@ -0,0 +1,273 @@
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
@@ -0,0 +1,405 @@
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
@@ -0,0 +1,123 @@
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
@@ -0,0 +1,443 @@
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
@@ -0,0 +1,255 @@
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
@@ -0,0 +1,67 @@
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
@@ -0,0 +1,171 @@
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
@@ -0,0 +1,77 @@
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
@@ -0,0 +1,211 @@
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
@@ -0,0 +1,112 @@
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
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,686 @@
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
@@ -0,0 +1,108 @@
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
@@ -0,0 +1,376 @@
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
@@ -0,0 +1,289 @@
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
@@ -0,0 +1,59 @@
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
@@ -0,0 +1,120 @@
// 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
@@ -0,0 +1,105 @@
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")
}
}
+46 -1
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
@@ -38,9 +39,31 @@ func GetClientForScheme(url *url.URL) (*http.Client, error) {
}
}
// directTransport returns the transport used when no proxy is configured. The
// URLs fetched with these clients come from users and remote servers, so it
// only connects to public addresses. Every client gets its own transport,
// because callers change its TLS settings (satdress.SetupHttpClient).
func directTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.DialContext = netguard.DialContext
return t
}
// The bot's own hosts may resolve to loopback (hosts file, split DNS). Paying
// a lightning address on them must keep working.
func init() {
if u := internal.Configuration.Bot.LNURLHostUrl; u != nil {
netguard.Trust(u.Hostname())
}
if u, err := url.Parse(internal.Configuration.Lnbits.Url); err == nil {
netguard.Trust(u.Hostname())
}
}
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
Timeout: 10 * time.Second,
Transport: directTransport(),
}
var cfg *internal.SocksConfiguration
switch clientType {
@@ -74,8 +97,30 @@ func GetClient(clientType ClientType) (*http.Client, error) {
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// The proxy resolves hostnames, so only literal addresses and
// localhost names can be refused here.
if err := netguard.CheckHost(addr); err != nil {
return nil, err
}
return d.Dial(network, addr)
}
client.Transport = specialTransport
return &client, nil
}
// NewNoKeepAliveClient returns a client for LNURLcash mints: the same proxy
// and netguard rules as GetClient, but keep-alives off and redirects refused,
// because every LNURLcash mutation is a non-idempotent GET that net/http
// would otherwise retry on a reused connection.
func NewNoKeepAliveClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
client = &http.Client{Transport: directTransport()}
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = true
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
+24 -5
View File
@@ -7,6 +7,7 @@ import (
"net/url"
"strconv"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
@@ -21,10 +22,26 @@ type PriceWatcher struct {
}
var (
Price map[string]float64
P *PriceWatcher
// 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
)
// 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{
@@ -47,7 +64,6 @@ 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
@@ -74,8 +90,11 @@ func (p *PriceWatcher) Watch() error {
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
time.Sleep(time.Second * time.Duration(2))
}
Price[currency] = avg_price / float64(n_responses)
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
if n_responses == 0 {
// every exchange failed: keep the last known price
continue
}
set(currency, avg_price/float64(n_responses))
}
time.Sleep(p.UpdateInterval)
}
+28
View File
@@ -0,0 +1,28 @@
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 -37
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.(*sync.Mutex).Unlock()
m.(*entry).mu.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,39 +103,3 @@ 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
@@ -0,0 +1,55 @@
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
@@ -0,0 +1,82 @@
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())
}
}
+15 -21
View File
@@ -16,7 +16,6 @@ import (
"net/http"
"net/url"
"strings"
"time"
)
// Much of this is from github.com/fiatjaf/makeinvoice
@@ -30,7 +29,6 @@ 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 {
@@ -41,12 +39,10 @@ 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 {
@@ -65,19 +61,17 @@ type CheckInvoiceParams struct {
Status string
}
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
var client *http.Client
if !useProxy {
client = &http.Client{
Timeout: 10 * time.Second,
}
} else {
var err error
client, err = network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
// 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()
}
// use a cert or skip TLS verification?
if len(cert) > 0 {
@@ -103,9 +97,9 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf(err.Error())
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
}
@@ -239,9 +233,9 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf(err.Error())
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
}
+32
View File
@@ -0,0 +1,32 @@
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)
}
}
}
+34 -13
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
@@ -39,12 +40,32 @@ 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(errmsg)
return 0, fmt.Errorf("%s", errmsg)
}
amount, err = GetAmount(strings.Split(input, " ")[1])
return amount, err
}
// maxAmountSat is the largest amount a single command may name. The bot is a
// tip bot; anything above this is a typo or an attack on a conversion path.
const maxAmountSat int64 = 10_000_000
// checkAmount rejects amounts that must never reach a money path: results of
// a float conversion that are not a number, non-positive amounts and amounts
// above maxAmountSat.
func checkAmount(fmount float64, amount int64) (int64, error) {
if math.IsNaN(fmount) || math.IsInf(fmount, 0) {
return 0, fmt.Errorf("amount is not a number")
}
if amount <= 0 {
return 0, fmt.Errorf("amount must be greater than 0")
}
if amount > maxAmountSat {
return 0, fmt.Errorf("amount must not be greater than %d sat", maxAmountSat)
}
return amount, nil
}
// GetAmount parses an amount from a string like 1.2k or 3.50€
// and returns the value in satoshis
func GetAmount(input string) (amount int64, err error) {
@@ -62,12 +83,15 @@ func GetAmount(input string) (amount int64, err error) {
if err != nil {
return 0, err
}
amount = int64(fmount * 1000)
return amount, err
return checkAmount(fmount, int64(fmount*1000))
}
// convert fiat currencies to satoshis
for currency, symbol := range price.P.Currencies {
var currencies map[string]string
if price.P != nil {
currencies = price.P.Currencies
}
for currency, symbol := range 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
@@ -79,11 +103,11 @@ func GetAmount(input string) (amount int64, err error) {
log.Errorln(err)
return 0, err
}
if !(price.Price[currency] > 0) {
if !(price.Get(currency) > 0) {
return 0, fmt.Errorf("price is zero")
}
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
return amount, nil
sats := fmount / price.Get(currency) * float64(100_000_000)
return checkAmount(sats, int64(sats))
}
}
@@ -92,17 +116,14 @@ func GetAmount(input string) (amount int64, err error) {
if err != nil {
return 0, err
}
if amount <= 0 {
return 0, fmt.Errorf("amount must be greater than 0")
}
return amount, err
return checkAmount(float64(amount), amount)
}
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
if !(price.Price[currency] > 0) {
if !(price.Get(currency) > 0) {
return 0, fmt.Errorf("price is zero")
}
fiat = float64(amount) / 100_000_000 * price.Price[currency]
fiat = float64(amount) / 100_000_000 * price.Get(currency)
return fiat, nil
}
+55
View File
@@ -0,0 +1,55 @@
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)
}
}
}
+8
View File
@@ -16,6 +16,7 @@ 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"
@@ -30,6 +31,9 @@ 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
@@ -116,6 +120,9 @@ 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()
@@ -136,6 +143,7 @@ func (bot *TipBot) Start() {
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
+48 -1
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
@@ -33,6 +34,8 @@ type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
Groups *gorm.DB
// LNURLCash is nil when the feature is disabled.
LNURLCash *lnurlcash.Store
}
const (
@@ -136,10 +139,19 @@ 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,
}
}
@@ -263,6 +275,21 @@ 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 == "" {
@@ -283,7 +310,12 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
tx := bot.DB.Users.Save(user)
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)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
@@ -295,3 +327,18 @@ 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
}
+10 -3
View File
@@ -53,6 +53,10 @@ func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context
return ctx
}
// maxFaucetSlots bounds how many users one faucet can pay out to. Every slot
// is a message edit and an LNbits transfer.
const maxFaucetSlots = 1000
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
amount, err := decodeAmountFromCommand(text)
if err != nil {
@@ -70,6 +74,9 @@ 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)
@@ -158,7 +165,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(err.Error())
log.Errorf("%s", err.Error())
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
@@ -257,7 +264,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
from := inlineFaucet.From
// failsafe for queued users
if !inlineFaucet.Active {
log.Tracef(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
log.Tracef("%s", fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
bot.finishFaucet(ctx, c, inlineFaucet)
return ctx, errors.Create(errors.NotActiveError)
}
@@ -351,7 +358,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
log.Debugf("%s", fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
// faucet is depleted
bot.finishFaucet(ctx, c, inlineFaucet)
}
+18 -5
View File
@@ -178,8 +178,10 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
return ctx, fmt.Errorf("group not found")
}
// create tickets
id := fmt.Sprintf("ticket:%d", group.ID)
// 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)
invoiceEvent := &InvoiceEvent{
Base: storage.New(storage.ID(id)),
User: group.Ticket.Creator,
@@ -302,14 +304,15 @@ 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(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
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{})
}
log.Errorln(errmsg)
return ctx, err
}
// if this was a join-ticket, we want to delete the invoice message
// 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{})
@@ -323,7 +326,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(invoiceEvent.CallbackData)
log.Infof("%s", invoiceEvent.CallbackData)
ticketEvent := &TicketEvent{Base: storage.New(storage.ID(invoiceEvent.CallbackData))}
err := bot.Bunt.Get(ticketEvent)
if err != nil {
@@ -424,6 +427,16 @@ func (bot TipBot) handleJoinTicketPayWall(ctx intercept.Context) (intercept.Cont
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 {
+328 -1
View File
@@ -28,7 +28,7 @@ func (bot TipBot) registerTelegramHandlers() {
}
func getDefaultBeforeInterceptor(bot TipBot) []intercept.Func {
return []intercept.Func{bot.idInterceptor}
return []intercept.Func{bot.idInterceptor, bot.rejectPlaceholderSenderInterceptor}
}
func getDefaultDeferInterceptor(bot TipBot) []intercept.Func {
return []intercept.Func{bot.unlockInterceptor}
@@ -84,6 +84,333 @@ 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,
+27 -2
View File
@@ -58,6 +58,31 @@ 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()
@@ -203,11 +228,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, 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))
if ctx.Message().IsReply() {
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(ctx.Message().ReplyTo.Sender))
}
log.Infof(log_string)
log.Info(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)
}
+2
View File
@@ -43,6 +43,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
InvoiceCallbackPayJoinTicket: EventHandler{Function: bot.stopJoinTicketTimer, Type: EventTypeInvoice},
InvoiceCallbackLNURLCashSettle: EventHandler{Function: bot.lnurlcashSettleEvent, Type: EventTypeInvoice},
}
}
@@ -56,6 +57,7 @@ const (
InvoiceCallbackSatdressProxy
InvoiceCallbackGenerateDalle
InvoiceCallbackPayJoinTicket
// InvoiceCallbackLNURLCashSettle (8) is declared in lnurlcash.go
)
const (
+5
View File
@@ -85,6 +85,11 @@ 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.")
}
+2
View File
@@ -306,6 +306,8 @@ 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")})
+36 -10
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
goerrors "errors"
"fmt"
"io/ioutil"
"net/url"
@@ -18,7 +19,9 @@ 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"
@@ -37,7 +40,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", m.Text)
log.Infof("[lnurlHandler] %s", redactForLog(m.Text))
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -67,19 +70,29 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
// an LNURLcash note is a withdraw link whose k1 is the money: redeem it
// directly. A withdraw link without mintPubkey falls through below.
if bot.LNURLCash != nil && lnurlcash.ResolveNoteInput(lnurlSplit) != "" {
ctx, err := bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, lnurlSplit, false)
if !goerrors.Is(err, lnurlcashpkg.ErrNotANote) {
bot.tryDeleteMessage(statusMsg)
return ctx, err
}
}
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
log.Warnf("[HandleLNURL] Error: %s", errorForLog(err))
return ctx, err
}
switch params.(type) {
case lnurl.LNURLAuthParams:
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
log.Infof("[LNURL-auth] %s", lnurlcash.ServerOf(authParams.LNURLAuthParams.Callback))
bot.tryDeleteMessage(statusMsg)
ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams)
return ctx, err
@@ -102,9 +115,17 @@ 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", withdrawParams.LNURLWithdrawResponse.Callback)
log.Infof("[LNURL-w] %s", lnurlcash.ServerOf(withdrawParams.LNURLWithdrawResponse.Callback))
bot.tryDeleteMessage(statusMsg)
bot.lnurlWithdrawHandler(ctx, withdrawParams)
default:
@@ -183,7 +204,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
var rawurl string
if name, domain, ok := lnurl.ParseInternetIdentifier(rawlnurl); ok {
isOnion := strings.Index(domain, ".onion") == len(domain)-6
isOnion := strings.HasSuffix(domain, ".onion")
rawurl = domain + "/.well-known/lnurlp/" + name
if isOnion {
rawurl = "http://" + rawurl
@@ -197,28 +218,29 @@ 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(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
if strings.Contains(location, ".onion/") || strings.HasSuffix(location, ".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("invalid bech32-encoded lnurl: " + rawlnurl)
fmt.Errorf("%s", "invalid bech32-encoded lnurl: "+rawlnurl)
}
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
if err != nil {
return "", nil, err
}
}
log.Debug("[HandleLNURL] rawurl: ", rawurl)
parsed, err := url.Parse(rawurl)
if err != nil {
return rawurl, nil, err
}
// host only: the query string of a withdraw or login link carries k1
log.Debug("[HandleLNURL] host: ", parsed.Host)
query := parsed.Query()
@@ -247,7 +269,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
return rawurl, nil, err
}
if resp.StatusCode >= 300 {
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
return rawurl, nil, fmt.Errorf("%s", "HTTP error: "+resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
@@ -266,6 +288,10 @@ 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":
+420
View File
@@ -0,0 +1,420 @@
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
@@ -0,0 +1,17 @@
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
@@ -0,0 +1,88 @@
package telegram
import (
"errors"
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
)
func TestParseBatchCommand(t *testing.T) {
amount, count, memo, ok := parseBatchCommand("/notes 100 x 10 party time")
if !ok || amount != 100 || count != 10 || memo != "party time" {
t.Fatalf("got %d %d %q %v", amount, count, memo, ok)
}
if _, _, _, ok := parseBatchCommand("/notes"); ok {
t.Fatal("bare /notes is a list")
}
if _, _, _, ok := parseBatchCommand("/notes 100 y 10"); ok {
t.Fatal("wrong separator")
}
if _, _, _, ok := parseBatchCommand("/notes 100 x 0"); ok {
t.Fatal("zero count")
}
if _, c, _, ok := parseBatchCommand("/notes 1k × 3"); !ok || c != 3 {
t.Fatal("unicode times and 1k amounts must parse")
}
}
func TestRedactNoteURLs(t *testing.T) {
in := "/redeem lnurlw://mint.example/w?k1=" + "ab" + "cd"
if got := redactForLog(in); got == in || !contains(got, "/redeem <") {
t.Fatalf("note not redacted: %q", got)
}
in = "/lnurl https://mint.example/w?k1=abcd&amount=1000"
if got := redactForLog(in); got == in {
t.Fatalf("withdraw link with k1 not redacted: %q", got)
}
if got := redactForLog("/note 100 hello"); got != "/note 100 hello" {
t.Fatalf("plain command changed: %q", got)
}
if got := formatSat(1000_900); got != "1000.9" {
t.Fatalf("formatSat: %q", got)
}
if got := formatSat(21_000); got != "21" {
t.Fatalf("formatSat: %q", got)
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
func TestPreserveNoteCase(t *testing.T) {
if got := preserveNoteCase("LNURLW://Mint.Example/W/Abc?k1=AB"); got != "lnurlw://Mint.Example/W/Abc?k1=AB" {
t.Fatalf("got %q", got)
}
if got := preserveNoteCase("LIGHTNING:LNURL1ABC"); got != "lightning:lnurl1abc" {
t.Fatalf("got %q", got)
}
}
func TestClassifyPayError(t *testing.T) {
payErr := lnbits.Error{Detail: "boom"}
ambiguous := func(err error) bool { return lnurlcash.IsAmbiguousLedger(err) }
if !ambiguous(classifyPayError(payErr, true, false, nil)) {
t.Error("a settled payment must be ambiguous, not failed")
}
if !ambiguous(classifyPayError(payErr, false, true, nil)) {
t.Error("a pending payment must be ambiguous")
}
if !ambiguous(classifyPayError(payErr, false, false, errors.New("timeout"))) {
t.Error("an unreachable lookup must be ambiguous")
}
if ambiguous(classifyPayError(payErr, false, false, lnbits.Error{Detail: "not found"})) {
t.Error("a payment LNbits does not know is a definitive failure")
}
if ambiguous(classifyPayError(payErr, false, false, nil)) {
t.Error("a payment LNbits reports as failed is definitive")
}
}
+97
View File
@@ -0,0 +1,97 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
lnurlcashgo "github.com/lnurlcash/lnurlcash-go"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var btnSetMint = (&tb.ReplyMarkup{}).Data("", "lnc_setmint")
func bot_lnurlcash_cfg() *lnurlcash.Config { return &internal.Configuration.LNURLCash }
// lnurlmintsHandler lists the admin mints and lets the user pick a default.
func (bot *TipBot) lnurlmintsHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
text, kb := bot.mintsText(ctx, user.Name)
if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, nil
}
func (bot *TipBot) mintsText(ctx intercept.Context, user string) (string, *tb.ReplyMarkup) {
reg := bot.LNURLCash.Mints()
current, _ := reg.ForUser(user)
menu := &tb.ReplyMarkup{}
var rows []tb.Row
text := TranslateUser(ctx, "lnurlmintsHeader")
for _, mnt := range reg.All() {
state := "🟢"
switch {
case mnt.Disabled:
state = "⛔️"
case !mnt.Healthy:
state = "🔴"
}
mark := ""
if current != nil && current.ID == mnt.ID {
mark = " ⭐️"
}
fee := TranslateUser(ctx, "lnurlmintsNoFee")
if mnt.FeeBaseMsat > 0 || mnt.FeePpm > 0 {
fee = fmt.Sprintf(TranslateUser(ctx, "lnurlmintsFee"), formatSat(mnt.FeeBaseMsat), lnurlcashgo.FormatFeePercent(mnt.FeePpm))
}
text += fmt.Sprintf(TranslateUser(ctx, "lnurlmintsItem"), state, mnt.ID, mark, lnurlcashgo.ServerOf(mnt.PayURL), fee)
if mnt.Usable() {
rows = append(rows, menu.Row(menu.Data(fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetButton"), mnt.ID), "lnc_setmint", mnt.ID)))
}
}
menu.Inline(rows...)
return text, menu
}
// setMintHandler stores the user's default mint.
func (bot *TipBot) setMintHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
user := LoadUser(ctx)
mnt, ok := bot.LNURLCash.Mints().Get(ctx.Data())
if !ok || !mnt.Usable() {
bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, nil
}
if err := bot.LNURLCash.Store().SetPref(user.Name, mnt.ID); err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "lnurlmintsSetMessage"), mnt.ID))
text, kb := bot.mintsText(ctx, user.Name)
bot.tryEditMessage(ctx.Callback().Message, text, kb)
return ctx, nil
}
// lnurlHelpHandler sends the LNURLcash notes help, privately.
func (bot *TipBot) lnurlHelpHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if !m.Private() {
bot.tryDeleteMessage(m)
}
bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteHelpMessage"), tb.NoPreview)
return ctx, nil
}
+26 -3
View File
@@ -7,12 +7,35 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/gorilla/websocket"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
log "github.com/sirupsen/logrus"
)
// maxRequestedRelays caps the relays taken from a zap request, so they can't
// push the default relays out of the list.
const maxRequestedRelays = 10
// go-nostr connects with the default websocket dialer. Relay URLs come from
// zap requests, so it must only reach public addresses.
func init() {
websocket.DefaultDialer.NetDialContext = netguard.DialContext
}
// requestedRelays keeps the wss:// relays of a zap request, up to maxRequestedRelays.
func requestedRelays(relays []string) []string {
list := []string{}
for _, relay := range relays {
if strings.HasPrefix(relay, "wss://") && len(list) < maxRequestedRelays {
list = append(list, relay)
}
}
return list
}
var (
nosterRegisterMessage = "📖 Add your nostr pubkey for zap receipts"
nostrInfoMessage = "💜 *Your nostr information*\n\nYour pubkey: `%s`"
@@ -64,8 +87,8 @@ func (bot *TipBot) publishNostrEvent(ev nostr.Event, relays []string) {
ev.Sign(pk)
log.Debugf("[NOSTR] 🟣 publishing nostr event %s", ev.ID)
// more relays
relays = append(relays, "wss://relay.nostr.ch", "wss://eden.nostr.land", "wss://nostr.btcmp.com", "wss://nostr.relayer.se", "wss://relay.current.fyi", "wss://nos.lol", "wss://nostr.mom", "wss://relay.nostr.info", "wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net", "wss://relay.snort.social/", "wss://relay.damus.io/", "wss://nostr.oxtr.dev/", "wss://nostr.fmt.wiz.biz/", "wss://brb.io")
// more relays (only public wss:// relays are taken from the zap request)
relays = append(requestedRelays(relays), "wss://relay.nostr.ch", "wss://eden.nostr.land", "wss://nostr.btcmp.com", "wss://nostr.relayer.se", "wss://relay.current.fyi", "wss://nos.lol", "wss://nostr.mom", "wss://relay.nostr.info", "wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net", "wss://relay.snort.social/", "wss://relay.damus.io/", "wss://nostr.oxtr.dev/", "wss://nostr.fmt.wiz.biz/", "wss://brb.io")
// remove trailing /
relays = cleanUrls(relays)
@@ -85,7 +108,7 @@ func (bot *TipBot) publishNostrEvent(ev nostr.Event, relays []string) {
// remove trailing /
relay, e := nostr.RelayConnect(context.Background(), url)
if e != nil {
log.Errorf(e.Error())
log.Errorf("%s", e.Error())
return
}
time.Sleep(3 * time.Second)
+348
View File
@@ -0,0 +1,348 @@
package telegram
import (
"context"
"errors"
"fmt"
"strconv"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// NoteConfirm is the pending "create a note" dialog in private chat.
type NoteConfirm struct {
*storage.Base
UserName string `json:"user_name"`
Quote lnurlcash.Quote `json:"quote"`
Memo string `json:"memo"`
LanguageCode string `json:"languagecode"`
ValueMsat int64 `json:"value_msat"`
Count int `json:"count"`
}
var (
btnNoteCreate = (&tb.ReplyMarkup{}).Data("", "lnc_create")
btnNoteMint = (&tb.ReplyMarkup{}).Data("", "lnc_mint")
btnNoteCancel = (&tb.ReplyMarkup{}).Data("", "lnc_cancel")
btnNoteStatus = (&tb.ReplyMarkup{}).Data("", "lnc_status")
btnNoteReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_reclaim")
btnNoteQR = (&tb.ReplyMarkup{}).Data("", "lnc_qr")
)
// noteCommandUser resolves the sender for a note command. In a group a user
// without a wallet is told to start a private chat; in private chat the
// start flow runs.
func (bot *TipBot) noteCommandUser(ctx intercept.Context) (*lnbits.User, bool) {
user := LoadUser(ctx)
m := ctx.Message()
if user == nil || user.Wallet == nil || !user.Initialized {
if m.Private() {
_, _ = bot.startHandler(ctx)
return nil, false
}
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return nil, false
}
return user, true
}
// noteHandler handles /note <amount> [memo].
func (bot *TipBot) noteHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount <= 0 {
if m.Private() {
bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteHelpMessage"))
} else {
NewMessage(m, WithDuration(0, bot))
bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteHelpMessage"))
}
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
memo := GetMemoFromCommand(m.Text, 2)
svc := bot.LNURLCash
mint, ok := svc.Mints().ForUser(user.Name)
if !ok {
bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
q, err := svc.Quote(ctx, mint, amount*1000, 1)
if err == nil {
err = svc.CheckCaps(ctx, user.Name, q, !m.Private())
}
if err != nil {
text := lnurlcashErrorText(ctx, err)
if m.Private() {
bot.trySendMessage(m.Sender, text)
} else {
NewMessage(m, WithDuration(0, bot))
bot.sendPrivate(m.Sender, text)
}
return ctx, err
}
if !m.Private() {
return bot.createNoteInGroup(ctx, user, q, memo)
}
confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))),
UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: 1}
bot.trySendMessageEditable(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID))
return ctx, confirm.Set(confirm, bot.Bunt)
}
func noteConfirmText(ctx context.Context, c *NoteConfirm) string {
q := c.Quote
text := fmt.Sprintf(TranslateUser(ctx, "noteConfirmMessage"), q.Count, formatSat(q.ValueMsat), formatSat(q.FeeMsat), formatSat(q.GrossMsat), q.MintName)
if c.Memo != "" {
text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(c.Memo))
}
return text
}
func noteConfirmKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
menu.Inline(
menu.Row(menu.Data(TranslateUser(ctx, "noteCreateButton"), "lnc_create", id)),
menu.Row(menu.Data(TranslateUser(ctx, "noteChangeMintButton"), "lnc_mint", id),
menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_cancel", id)),
)
return menu
}
// loadNoteConfirm loads the dialog behind a callback and checks ownership.
func (bot *TipBot) loadNoteConfirm(ctx intercept.Context) (*NoteConfirm, error) {
tx := &NoteConfirm{Base: storage.New(storage.ID(ctx.Data()))}
got, err := tx.Get(tx, bot.Bunt)
if err != nil {
return nil, err
}
c := got.(*NoteConfirm)
if c.UserName != LoadUser(ctx).Name {
return nil, tiperrors.Create(tiperrors.UnknownError)
}
if !c.Active {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
return c, nil
}
// noteCreateHandler runs when the user pressed Create.
func (bot *TipBot) noteCreateHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
_ = c.Inactivate(c, bot.Bunt)
user := LoadUser(ctx)
msg := ctx.Callback().Message
bot.tryEditMessage(msg, TranslateUser(ctx, "noteCreatingMessage"), &tb.ReplyMarkup{})
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: c.Quote, Memo: c.Memo}
if c.Count > 1 {
return bot.createBatchFromConfirm(ctx, c, params, msg)
}
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
}
bot.tryDeleteMessage(msg)
bot.sendNoteCreated(ctx, user.Telegram, live[0])
return ctx, nil
}
// sendNoteCreated sends the QR and the note text with its buttons.
func (bot *TipBot) sendNoteCreated(ctx context.Context, to *tb.User, n *lnurlcash.Note) {
bot.sendNoteQR(to, n)
lnurlw, _, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
log.Errorf("[lnurlcash] note strings: %v", err)
return
}
text := fmt.Sprintf(TranslateUser(ctx, "noteCreatedMessage"), formatSat(n.ReportedMsat), lnurlcash.ShortID(n.ID), lnurlw)
bot.trySendMessageEditable(to, text, noteKeyboard(ctx, n, false))
}
// noteMintHandler cycles the dialog to the next usable mint and re-quotes.
func (bot *TipBot) noteMintHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
mints := bot.LNURLCash.Mints().All()
var usable []*lnurlcash.Mint
for _, m := range mints {
if m.Usable() {
usable = append(usable, m)
}
}
if len(usable) < 2 {
bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteOnlyOneMintMessage"))
return ctx, nil
}
next := usable[0]
for i, m := range usable {
if m.ID == c.Quote.MintID {
next = usable[(i+1)%len(usable)]
break
}
}
q, err := bot.LNURLCash.Quote(ctx, next, c.ValueMsat, c.Count)
if err != nil {
bot.trySendMessage(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
c.Quote = q
bot.tryEditMessage(ctx.Callback().Message, noteConfirmText(ctx, c), noteConfirmKeyboard(ctx, c.ID))
return ctx, c.Set(c, bot.Bunt)
}
// noteCancelHandler runs when the user pressed Cancel.
func (bot *TipBot) noteCancelHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
c, err := bot.loadNoteConfirm(ctx)
if err != nil {
return ctx, err
}
bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "noteCancelledMessage"), &tb.ReplyMarkup{})
return ctx, c.Inactivate(c, bot.Bunt)
}
// createNoteInGroup creates a note without a confirm step, posts it in the
// group and sends the receipt privately.
func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q lnurlcash.Quote, memo string) (intercept.Context, error) {
m := ctx.Message()
receipt, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteCreatingMessage"))
if !ok {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: q, Memo: memo, ChatID: m.Chat.ID}
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(receipt, lnurlcashErrorText(ctx, err))
return ctx, err
}
n := live[0]
_, bech, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
return ctx, err
}
qr, err := qrcodeEncode(bech)
if err != nil {
return ctx, err
}
caption := fmt.Sprintf(Translate(ctx, "noteGroupMessage"), formatSat(n.ReportedMsat), GetUserStrMd(m.Sender), bech)
if memo != "" {
caption += fmt.Sprintf(Translate(ctx, "noteViewMemo"), str.MarkdownEscape(memo))
}
post := bot.tryReplyMessage(m, &tb.Photo{File: tb.File{FileReader: qr}, Caption: caption})
if post != nil {
_ = bot.LNURLCash.Store().UpdateNote(n.ID, map[string]interface{}{"chat_id": post.Chat.ID, "message_id": strconv.Itoa(post.ID)})
}
lnurlw, _, _ := bot.LNURLCash.NoteStrings(n)
text := fmt.Sprintf(TranslateUser(ctx, "noteReceiptMessage"), formatSat(n.ReportedMsat), formatSat(q.FeeMsat), q.MintName, lnurlcash.ShortID(n.ID), lnurlw)
bot.tryEditMessage(receipt, text, noteKeyboard(ctx, n, false))
log.Infof("[lnurlcash] %s created group note %s (%d msat) in chat %d", GetUserStr(m.Sender), n.ID, n.ReportedMsat, m.Chat.ID)
return ctx, nil
}
// noteStatusHandler answers the Check status button.
func (bot *TipBot) noteStatusHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
state, value, err := bot.LNURLCash.Status(ctx, n)
var text string
switch {
case errors.Is(err, lnurlcashgoPending()):
text = TranslateUser(ctx, "noteStatusPendingMessage")
case err != nil:
text = TranslateUser(ctx, "noteMintUnavailableMessage")
case state == lnurlcash.NoteClaimed:
text = TranslateUser(ctx, "noteStatusClaimedMessage")
case state == lnurlcash.NoteLive:
text = fmt.Sprintf(TranslateUser(ctx, "noteStatusLiveMessage"), formatSat(value))
default:
text = fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, state))
}
bot.trySendMessageEditable(ctx.Sender(), text)
if ctx.Callback().Message != nil {
_, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false))
}
return ctx, nil
}
// noteReclaimHandler answers the Reclaim button.
func (bot *TipBot) noteReclaimHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
n, err = bot.LNURLCash.Reclaim(ctx, n.ID)
if err != nil {
bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteReclaimRequestedMessage"), formatSat(n.ReportedMsat)))
if ctx.Callback().Message != nil {
_, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false))
}
(&lnurlcashNotifier{bot: bot}).GroupNoteState(n)
return ctx, nil
}
// noteQRHandler answers the Show QR button.
func (bot *TipBot) noteQRHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
if n.State != lnurlcash.NoteLive {
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, n.State)))
return ctx, nil
}
bot.sendNoteCreated(ctx, ctx.Sender(), n)
return ctx, nil
}
// lnurlcashgoPending is the library's pending sentinel, kept behind a
// function so this file does not import the library for one value.
func lnurlcashgoPending() error { return lnurlcash.ErrNotePending }
+117
View File
@@ -0,0 +1,117 @@
package telegram
import (
"errors"
"fmt"
"strings"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// LNURLCashNoteParams is what HandleLNURL returns for a withdraw link that
// publishes a mintPubkey: an LNURLcash note rather than a plain withdraw.
type LNURLCashNoteParams struct {
URL string
}
var (
btnRedeemOK = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_ok")
btnRedeemCancel = (&tb.ReplyMarkup{}).Data("", "lnc_redeem_no")
)
// redeemHandler handles /redeem <note>. In a group the command is deleted
// at once because it carries the secret, and the flow continues privately.
func (bot *TipBot) redeemHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
if !m.Private() {
bot.tryDeleteMessage(m)
}
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
parts := strings.Fields(m.Text)
if len(parts) < 2 {
if _, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "redeemHelpMessage")); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
return bot.redeemInput(ctx, user.Name, user.Telegram.LanguageCode, parts[1], !m.Private())
}
// redeemInput previews a pasted note and offers to add it to the balance.
// Everything goes to the user's private chat.
func (bot *TipBot) redeemInput(ctx intercept.Context, userName, lang, input string, fromGroup bool) (intercept.Context, error) {
sender := ctx.Sender()
preview, err := bot.LNURLCash.RedeemInfo(ctx, userName, lang, input)
if err != nil {
if errors.Is(err, lnurlcash.ErrNotANote) && !fromGroup {
// the caller decides (the /lnurl flow falls back to a plain withdraw)
return ctx, err
}
text := lnurlcashErrorText(ctx, err)
if _, ok := bot.sendPrivate(sender, text); !ok && fromGroup {
bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, err
}
text := fmt.Sprintf(TranslateUser(ctx, "redeemPreviewMessage"), formatSat(preview.ValueMsat), preview.MintHost)
if !preview.KnownMint {
text += "\n\n" + TranslateUser(ctx, "redeemUnknownMintWarning")
}
menu := &tb.ReplyMarkup{}
menu.Inline(menu.Row(
menu.Data(TranslateUser(ctx, "redeemAddButton"), "lnc_redeem_ok", preview.Redeem.ID),
menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_redeem_no", preview.Redeem.ID)))
if _, ok := bot.sendPrivate(sender, text, menu); !ok && fromGroup {
bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, nil
}
// redeemConfirmHandler runs when Add to balance was pressed.
func (bot *TipBot) redeemConfirmHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
user := LoadUser(ctx)
msg := ctx.Callback().Message
bot.tryEditMessage(msg, TranslateUser(ctx, "redeemInFlightMessage"), &tb.ReplyMarkup{})
r, err := bot.LNURLCash.Redeem(ctx, ctx.Data(), user.Name)
if err != nil {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
}
log.Infof("[lnurlcash] %s redeems %s (%d msat)", GetUserStr(ctx.Sender()), r.ID, r.ReportedMsat)
bot.tryEditMessage(msg, fmt.Sprintf(TranslateUser(ctx, "redeemRequestedMessage"), formatSat(r.ReportedMsat)), &tb.ReplyMarkup{})
return ctx, nil
}
// redeemCancelHandler runs when Cancel was pressed on a preview.
func (bot *TipBot) redeemCancelHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
r, err := bot.LNURLCash.Store().Redeem(ctx.Data())
if err != nil || r.UserName != LoadUser(ctx).Name {
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
_ = bot.LNURLCash.Store().TransitionRedeem(r.ID, lnurlcash.RedeemInfo, lnurlcash.RedeemFailed, map[string]interface{}{"last_error": "cancelled"})
bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "redeemCancelledMessage"), &tb.ReplyMarkup{})
return ctx, nil
}
// LNURLKind satisfies go-lnurl's LNURLParams so HandleLNURL can return a note.
func (LNURLCashNoteParams) LNURLKind() string { return "lnurlcash-note" }
+233
View File
@@ -0,0 +1,233 @@
package telegram
import (
"bytes"
"context"
"fmt"
"strings"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
btnBatchExportPDF = (&tb.ReplyMarkup{}).Data("", "lnc_exp_pdf")
btnBatchExportJSON = (&tb.ReplyMarkup{}).Data("", "lnc_exp_json")
btnBatchExportCSV = (&tb.ReplyMarkup{}).Data("", "lnc_exp_csv")
btnBatchRefresh = (&tb.ReplyMarkup{}).Data("", "lnc_brefresh")
btnBatchReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_breclaim")
)
// parseBatchCommand reads "/notes <amount> x <count> [memo]". ok is false
// when the text is not a batch command.
func parseBatchCommand(text string) (amount int64, count int, memo string, ok bool) {
parts := strings.Fields(text)
if len(parts) < 4 {
return 0, 0, "", false
}
sep := strings.ToLower(parts[2])
if sep != "x" && sep != "×" && sep != "*" {
return 0, 0, "", false
}
amount, err := GetAmount(parts[1])
if err != nil {
return 0, 0, "", false
}
var n int
if _, err := fmt.Sscanf(parts[3], "%d", &n); err != nil || n < 1 {
return 0, 0, "", false
}
return amount, n, GetMemoFromCommand(text, 4), true
}
// noteBatchStart quotes a batch and shows the confirm dialog privately.
func (bot *TipBot) noteBatchStart(ctx intercept.Context, user *lnbits.User, amount int64, count int, memo string) (intercept.Context, error) {
m := ctx.Message()
svc := bot.LNURLCash
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
mint, ok := svc.Mints().ForUser(user.Name)
if !ok {
bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage"))
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
q, err := svc.Quote(ctx, mint, amount*1000, count)
if err == nil {
err = svc.CheckCaps(ctx, user.Name, q, false)
}
if err != nil {
if _, ok := bot.sendPrivate(m.Sender, lnurlcashErrorText(ctx, err)); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, err
}
confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))),
UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: count}
if _, ok := bot.sendPrivate(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)); !ok {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, confirm.Set(confirm, bot.Bunt)
}
// createBatchFromConfirm runs after Create was pressed on a batch dialog.
func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) (intercept.Context, error) {
total := c.Count
key := "lnc-progress-" + c.ID
params.Progress = func(done, total int) {
bot.tryEditStack(msg, key, fmt.Sprintf(TranslateUser(ctx, "notesBatchProgressMessage"), done, total, MakeProgressbar(int64(done), int64(total))))
}
batch, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
}
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchCreatedMessage"), len(live), total, lnurlcash.ShortID(batch.ID))
if err != nil {
text += "\n" + fmt.Sprintf(TranslateUser(ctx, "notesBatchPartialMessage"), lnurlcashErrorText(ctx, err))
}
text += "\n\n" + TranslateUser(ctx, "notesBatchFormatMessage")
bot.tryEditMessage(msg, text, batchKeyboard(ctx, batch.ID))
return ctx, nil
}
// batchKeyboard offers the export formats and the batch actions.
func batchKeyboard(ctx context.Context, batchID string) *tb.ReplyMarkup {
menu := &tb.ReplyMarkup{}
cfg := bot_lnurlcash_cfg()
var formats []tb.Btn
if cfg.HasFormat("pdf") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportPdfButton"), "lnc_exp_pdf", batchID))
}
if cfg.HasFormat("json") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportJsonButton"), "lnc_exp_json", batchID))
}
if cfg.HasFormat("csv") {
formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportCsvButton"), "lnc_exp_csv", batchID))
}
rows := []tb.Row{}
if len(formats) > 0 {
rows = append(rows, menu.Row(formats...))
}
rows = append(rows, menu.Row(
menu.Data(TranslateUser(ctx, "notesRefreshButton"), "lnc_brefresh", batchID),
menu.Data(TranslateUser(ctx, "notesReclaimUnclaimedButton"), "lnc_breclaim", batchID)))
menu.Inline(rows...)
return menu
}
// batchViewText renders a batch with its counts.
func (bot *TipBot) batchViewText(ctx context.Context, b *lnurlcash.Batch) string {
sum, _ := bot.LNURLCash.Summarize(b.ID)
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchOpenMessage"), lnurlcash.ShortID(b.ID), b.Count, formatSat(b.ValueMsat), b.MintID,
b.CreatedAt.UTC().Format("2 Jan 06 15:04"), sum.Live, sum.Claimed, sum.Reclaimed, sum.Failed+sum.Pending)
if b.Memo != "" {
text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), b.Memo)
}
return text
}
// loadOwnBatch loads the batch behind a callback and checks ownership.
func (bot *TipBot) loadOwnBatch(ctx intercept.Context) (*lnurlcash.Batch, error) {
b, err := bot.LNURLCash.Store().Batch(ctx.Data())
if err != nil {
return nil, tiperrors.Create(tiperrors.NotActiveError)
}
if b.UserName != LoadUser(ctx).Name {
return nil, lnurlcash.ErrNotOwner
}
return b, nil
}
func (bot *TipBot) batchExportHandler(format string) intercept.Func {
return func(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
if !bot_lnurlcash_cfg().HasFormat(format) {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
// files only ever go to the private chat
if msg := ctx.Callback().Message; msg != nil && !msg.Private() {
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
data, err := bot.LNURLCash.ExportBatch(b.ID, LoadUser(ctx).Name)
if err != nil {
bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err))
return ctx, err
}
var buf bytes.Buffer
var mime string
switch format {
case "pdf":
err, mime = export.PDF(&buf, data), "application/pdf"
case "json":
err, mime = export.JSON(&buf, data), "application/json"
case "csv":
err, mime = export.CSV(&buf, data), "text/csv"
}
if err != nil {
log.Errorf("[lnurlcash] export %s of %s: %v", format, b.ID, err)
bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteErrorMessage"))
return ctx, err
}
doc := &tb.Document{File: tb.File{FileReader: &buf}, FileName: fmt.Sprintf("notes-%s.%s", lnurlcash.ShortID(b.ID), format), MIME: mime,
Caption: fmt.Sprintf(TranslateUser(ctx, "notesExportCaption"), len(data.Notes), lnurlcash.ShortID(b.ID))}
bot.trySendMessageEditable(ctx.Sender(), doc)
return ctx, nil
}
}
// batchRefreshHandler probes every live note of the batch and re-renders it.
func (bot *TipBot) batchRefreshHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
notes, _ := bot.LNURLCash.Store().NotesInBatch(b.ID)
for _, n := range notes {
if n.Kind == lnurlcash.KindUser && n.State == lnurlcash.NoteLive {
_, _, _ = bot.LNURLCash.Status(ctx, n)
}
}
b, _ = bot.LNURLCash.Store().Batch(b.ID)
bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
// batchReclaimHandler reclaims every unclaimed note of the batch.
func (bot *TipBot) batchReclaimHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
mutex.LockWithContext(ctx, ctx.Data())
defer mutex.UnlockWithContext(ctx, ctx.Data())
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
sent, err := bot.LNURLCash.ReclaimBatch(ctx, b.ID, LoadUser(ctx).Name)
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchReclaimMessage"), sent)
if err != nil {
text += "\n" + lnurlcashErrorText(ctx, err)
}
bot.trySendMessageEditable(ctx.Sender(), text)
b, _ = bot.LNURLCash.Store().Batch(b.ID)
bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
+205
View File
@@ -0,0 +1,205 @@
package telegram
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
const notesPerPage = 8
var (
btnNotesPage = (&tb.ReplyMarkup{}).Data("", "lnc_page")
btnNotesOpen = (&tb.ReplyMarkup{}).Data("", "lnc_open")
btnNotesOpenB = (&tb.ReplyMarkup{}).Data("", "lnc_openb")
)
// NotesList is a user's open /notes list; pages are computed from the DB.
type NotesList struct {
*storage.Base
UserName string `json:"user_name"`
}
type notesEntry struct {
id string
batch bool
created time.Time
label string
}
// notesHandler handles /notes and /notes <amount> x <count> [memo].
func (bot *TipBot) notesHandler(ctx intercept.Context) (intercept.Context, error) {
if !bot.lnurlcashReady(ctx) {
return ctx, nil
}
m := ctx.Message()
user, ok := bot.noteCommandUser(ctx)
if !ok {
return ctx, tiperrors.Create(tiperrors.UserNoWalletError)
}
if amount, count, memo, isBatch := parseBatchCommand(m.Text); isBatch {
return bot.noteBatchStart(ctx, user, amount, count, memo)
}
if len(strings.Fields(m.Text)) > 1 {
bot.sendPrivate(m.Sender, TranslateUser(ctx, "notesHelpMessage"))
return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError)
}
if !m.Private() {
NewMessage(m, WithDuration(0, bot))
}
list := &NotesList{Base: storage.New(storage.ID(fmt.Sprintf("lncl-%d-%s", m.Sender.ID, RandStringRunes(6)))), UserName: user.Name}
text, kb := bot.notesPage(ctx, list, 0)
if _, ok := bot.sendPrivate(m.Sender, text, kb); !ok && !m.Private() {
bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
return ctx, list.Set(list, bot.Bunt)
}
// notesEntries lists single notes and batches, newest first.
func (bot *TipBot) notesEntries(ctx context.Context, user string) []notesEntry {
store := bot.LNURLCash.Store()
var entries []notesEntry
batches, _ := store.UserBatches(user)
inBatch := map[string]bool{}
for _, b := range batches {
inBatch[b.ID] = true
sum, _ := bot.LNURLCash.Summarize(b.ID)
entries = append(entries, notesEntry{id: b.ID, batch: true, created: b.CreatedAt,
label: fmt.Sprintf(TranslateUser(ctx, "notesBatchItem"), b.Count, formatSat(b.ValueMsat), sum.Live, sum.Claimed, lnurlcash.ShortID(b.ID))})
}
notes, _ := store.UserNotes(user, nil)
for _, n := range notes {
if n.BatchID != nil && inBatch[*n.BatchID] {
continue
}
value := n.ReportedMsat
if value == 0 {
value = n.ValueMsat
}
memo := n.Memo
if len(memo) > 20 {
memo = memo[:19] + "…"
}
entries = append(entries, notesEntry{id: n.ID, created: n.CreatedAt,
label: fmt.Sprintf(TranslateUser(ctx, "notesListItem"), noteStateEmoji(n.State), formatSat(value), lnurlcash.ShortID(n.ID), memo)})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].created.After(entries[j].created) })
return entries
}
func noteStateEmoji(state string) string {
switch state {
case lnurlcash.NoteLive:
return "🟢"
case lnurlcash.NoteClaimed:
return "✅"
case lnurlcash.NoteReclaimed:
return "↩️"
case lnurlcash.NoteReclaiming:
return "🔄"
case lnurlcash.NoteFailed:
return "🚫"
}
return "⏳"
}
// notesPage renders one page of the list with its buttons.
func (bot *TipBot) notesPage(ctx context.Context, list *NotesList, page int) (string, *tb.ReplyMarkup) {
entries := bot.notesEntries(ctx, list.UserName)
menu := &tb.ReplyMarkup{}
if len(entries) == 0 {
return TranslateUser(ctx, "notesListEmpty"), menu
}
pages := (len(entries) + notesPerPage - 1) / notesPerPage
if page < 0 {
page = 0
}
if page >= pages {
page = pages - 1
}
start := page * notesPerPage
end := start + notesPerPage
if end > len(entries) {
end = len(entries)
}
var rows []tb.Row
text := fmt.Sprintf(TranslateUser(ctx, "notesListHeader"), len(entries), page+1, pages) + "\n"
for i, e := range entries[start:end] {
text += fmt.Sprintf("\n%d. %s", start+i+1, str.MarkdownEscape(e.label))
unique := "lnc_open"
if e.batch {
unique = "lnc_openb"
}
rows = append(rows, menu.Row(menu.Data(fmt.Sprintf("%d · %s", start+i+1, lnurlcash.ShortID(e.id)), unique, e.id)))
}
var nav []tb.Btn
if page > 0 {
nav = append(nav, menu.Data("◀️", "lnc_page", list.ID+":"+strconv.Itoa(page-1)))
}
if page < pages-1 {
nav = append(nav, menu.Data("▶️", "lnc_page", list.ID+":"+strconv.Itoa(page+1)))
}
if len(nav) > 0 {
rows = append(rows, menu.Row(nav...))
}
menu.Inline(rows...)
return text, menu
}
// notesPageHandler scrolls the list.
func (bot *TipBot) notesPageHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
id, pageStr, _ := strings.Cut(ctx.Data(), ":")
page, _ := strconv.Atoi(pageStr)
tx := &NotesList{Base: storage.New(storage.ID(id))}
got, err := tx.Get(tx, bot.Bunt)
if err != nil {
return ctx, err
}
list := got.(*NotesList)
if list.UserName != LoadUser(ctx).Name {
return ctx, tiperrors.Create(tiperrors.UnknownError)
}
text, kb := bot.notesPage(ctx, list, page)
bot.tryEditMessage(ctx.Callback().Message, text, kb)
return ctx, nil
}
// notesOpenHandler shows one note with its actions.
func (bot *TipBot) notesOpenHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
n, err := bot.loadOwnNote(ctx)
if err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), noteViewText(ctx, n), noteKeyboard(ctx, n, true))
return ctx, nil
}
// notesOpenBatchHandler shows one batch with its actions.
func (bot *TipBot) notesOpenBatchHandler(ctx intercept.Context) (intercept.Context, error) {
if bot.LNURLCash == nil {
return ctx, nil
}
b, err := bot.loadOwnBatch(ctx)
if err != nil {
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID))
return ctx, nil
}
+3 -1
View File
@@ -213,7 +213,7 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payData.Invoice}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
err = fmt.Errorf("%s", i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
@@ -224,6 +224,8 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
return ctx, err
}
payData.Hash = invoice.PaymentHash
// the invoice is paid, a second press must not pay it again
payData.Active = false
// do balance check for keyboard update
_, err = bot.GetUserBalance(user)
+56
View File
@@ -0,0 +1,56 @@
package telegram
import (
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
)
// cashuTokenPattern matches a Cashu ecash token (a bearer instrument).
var cashuTokenPattern = regexp.MustCompile(`(?i)^cashu[a-z][a-z0-9_-]+$`)
// redactForLog returns text with everything that is money or a credential
// replaced by a placeholder, so the message log never holds bolt11 invoices,
// LNURLs, ecash tokens or node credentials (`/node add lnd <host> <macaroon>`).
func redactForLog(text string) string {
fields := strings.Fields(text)
if len(fields) == 0 {
return text
}
// /nostr takes a public key, but users paste their private key by mistake
if cmd := strings.ToLower(fields[0]); strings.HasPrefix(cmd, "/node") || strings.HasPrefix(cmd, "/nostr") {
return fields[0] + " <redacted>"
}
for i, f := range fields {
lower := strings.ToLower(f)
switch {
case lightning.IsInvoice(lower) || strings.HasPrefix(lower, "lntb") || strings.HasPrefix(lower, "lnbcrt"):
fields[i] = fmt.Sprintf("<invoice len=%d>", len(f))
case lightning.IsLnurl(lower) || strings.HasPrefix(lower, "lnurl"):
fields[i] = fmt.Sprintf("<lnurl len=%d>", len(f))
case strings.HasPrefix(lower, "nsec1"):
fields[i] = "<nsec redacted>"
case cashuTokenPattern.MatchString(f):
fields[i] = fmt.Sprintf("<cashu-token len=%d>", len(f))
case strings.Contains(lower, "k1="):
// an LNURLcash note or withdraw link in URL form: the spend is in the query
fields[i] = fmt.Sprintf("<note-url len=%d>", len(f))
}
}
return strings.Join(fields, " ")
}
// errorForLog returns err without the URL of a failed HTTP request. The
// *url.Error text embeds the full URL, and an LNURL-withdraw link carries its
// claim token (k1) in the query.
func errorForLog(err error) string {
var ue *url.Error
if errors.As(err, &ue) {
return fmt.Sprintf("%s failed: %v", ue.Op, ue.Err)
}
return err.Error()
}
+36
View File
@@ -0,0 +1,36 @@
package telegram
import (
"errors"
"net/http"
"strings"
"testing"
)
func TestRedactForLogCredentials(t *testing.T) {
nsec := "nsec1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"
for _, in := range []string{"/nostr add " + nsec, "/nostr " + nsec, "please use " + nsec} {
if out := redactForLog(in); strings.Contains(out, "nsec1qqq") {
t.Errorf("%q leaked: %q", in, out)
}
}
if out := redactForLog("/pay lntb10u1pabcdefghijklmnopqrstuvwxyz0123456789"); strings.Contains(out, "lntb10u1p") {
t.Errorf("testnet invoice leaked: %q", out)
}
}
func TestErrorForLogDropsURLQuery(t *testing.T) {
_, err := http.Get("http://127.0.0.1:1/w?tag=withdrawRequest&k1=SECRETK1")
if err == nil {
t.Skip("unexpectedly reachable")
}
if !strings.Contains(err.Error(), "SECRETK1") {
t.Fatal("test premise: the url.Error text should contain the URL")
}
if got := errorForLog(err); strings.Contains(got, "SECRETK1") {
t.Errorf("k1 leaked: %q", got)
}
if got := errorForLog(errors.New("plain")); got != "plain" {
t.Errorf("plain error changed: %q", got)
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.Backe
var pem []byte
if splitlen == 6 {
cert := splits[5]
pem := parseCertificateToPem(cert)
pem = parseCertificateToPem(cert)
if len(pem) < 1 {
return params, fmt.Errorf("certificate has invalid format")
}
+14 -2
View File
@@ -43,7 +43,7 @@ func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, err
return bot.payHandler(ctx)
}
if lightning.IsLnurl(anyText) {
m.Text = "/lnurl " + anyText
m.Text = "/lnurl " + preserveNoteCase(m.Text)
return bot.lnurlHandler(ctx)
}
if c := stateCallbackMessage[user.StateKey]; c != nil {
@@ -123,5 +123,17 @@ func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, e
ResetUserState(user, bot)
return ctx, errors.Create(errors.InvalidSyntaxError)
}
return ctx, nil
}
// preserveNoteCase lowercases pasted LNURL text the way it always was, except
// for an lnurlw:// link, whose path may be case-sensitive at the mint. Only
// the scheme is lowercased there.
func preserveNoteCase(text string) string {
lower := strings.ToLower(text)
for _, prefix := range []string{"lightning:lnurlw://", "lnurlw://"} {
if strings.HasPrefix(lower, prefix) {
return prefix + text[len(prefix):]
}
}
return lower
}
+30 -21
View File
@@ -34,6 +34,9 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
log.Traceln("[TICKET] I am not an admin of this group")
return ctx, fmt.Errorf("no admin rights")
}
// state of one joiner. Joiners of the same chat must not share keys, or a
// later joiner overwrites the payer of an earlier one.
eventID := fmt.Sprintf("%s:%d", id, ctx.Sender().ID)
user := LoadUser(ctx)
// if the user does not have an account we put his Telegram user here
// because we will need it after the invoice callback has been triggered in stopJoinTicketTimer
@@ -72,7 +75,7 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
ticketEvent := TicketEvent{
// invoice event is used for invoice callbacks (do not kick if invoice is paid)
InvoiceEvent: &InvoiceEvent{
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", id))),
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", eventID))),
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
PaymentRequest: invoice.PaymentRequest,
Amount: ticket.Ticket.Price,
@@ -84,7 +87,7 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
LanguageCode: ctx.Value("publicLanguageCode").(string),
},
Group: group,
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", id))),
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", eventID))),
}
captionText := fmt.Sprintf("⚠️ %s, this group requires you to pay *%d sat* to join. You have 15 minutes to pay or you will be kicked for one day.", GetUserStrMd(ctx.Message().Sender), ticket.Ticket.Price)
@@ -183,10 +186,33 @@ func (bot *TipBot) stopJoinTicketTimer(event Event) {
}
}
// expireTicket bans the member of an unpaid ticket and removes the ticket.
func (bot *TipBot) expireTicket(ticket JoinTicket) {
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
if err != nil {
log.Errorln("🧨 could not fetch / ban chat member")
return
}
// ban user
err = bot.Telegram.Ban(ticket.Message.Chat, member)
if err != nil {
log.Errorln(err)
}
err = bot.Bunt.Delete(ticket.Key(), &ticket)
if err != nil {
log.Errorln(err)
}
bot.tryDeleteMessage(ticket.Message)
}
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
// check if ticket is already expired
// A ticket that ran out while the bot was down is still unpaid (a paid
// ticket is deleted), so it is enforced now instead of being skipped.
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
if ticket.Message != nil && ticket.Message.Chat != nil {
bot.expireTicket(ticket)
}
return
}
// ticket is valid. create duration until kick
@@ -195,24 +221,7 @@ func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
t := runtime.NewResettableFunction(ticket.Key(),
runtime.WithTimer(time.NewTimer(ticketDuration)))
// run the ticket callback function
t.Do(func() {
// ticket expired
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
if err != nil {
log.Errorln("🧨 could not fetch / ban chat member")
return
}
// ban user
err = bot.Telegram.Ban(ticket.Message.Chat, member)
if err != nil {
log.Errorln(err)
}
err = bot.Bunt.Delete(ticket.Key(), &ticket)
if err != nil {
log.Errorln(err)
}
bot.tryDeleteMessage(ticket.Message)
})
t.Do(func() { bot.expireTicket(ticket) })
}
// restartPersistedTickets kicks of all ticket timers
+2 -2
View File
@@ -153,7 +153,7 @@ func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error)
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
log.Errorf("%s", err.Error())
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
}
@@ -252,7 +252,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
inlineTipjar := fn.(*InlineTipjar)
to := inlineTipjar.To
if !inlineTipjar.Active {
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
log.Errorf("%s", fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
}
+2 -2
View File
@@ -66,13 +66,13 @@ func TestMessage_getTooltipMessage(t *testing.T) {
name: "1",
args: args{botUserName: "@test-bot", notInitializedWallet: true},
fields: fields{Message: Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
want: "🏅 10 sat (by @username1)\n🗑 Chat with @test-bot to manage your wallet.",
want: "🏅 10 sat (by @username1)\n🗑 Chat with @test-bot 👈 to manage your wallet.",
},
{
name: "2",
args: args{botUserName: "@test-bot", notInitializedWallet: true},
fields: fields{Message: Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
want: "🏅 100 sat (6 tips by @username1, @username2, @username3, @username4, @username5, ... and others)\n🗑 Chat with @test-bot to manage your wallet.",
want: "🏅 100 sat (6 tips by @username1, @username2, @username3, @username4, @username5, ... and others)\n🗑 Chat with @test-bot 👈 to manage your wallet.",
},
}
for _, tt := range tests {
+8 -3
View File
@@ -78,7 +78,7 @@ func (t *Transaction) Send() (success bool, err error) {
// save transaction to db
tx := t.Bot.DB.Transactions.Save(t)
if tx.Error != nil {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", tx.Error.Error())
log.Errorln(errMsg)
}
return success, err
@@ -88,6 +88,11 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
fromUserStr := GetUserStr(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
// nobody can spend from the wallet of a shared placeholder user
if isPlaceholderSender(to.Telegram) {
return false, fmt.Errorf("cannot send to placeholder user %s", toUserStr)
}
t.FromWallet = from.Wallet.ID
t.FromLNbitsID = from.ID
@@ -102,7 +107,7 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
if balance < amount {
errmsg := fmt.Sprintf("balance too low.")
log.Warnf("Balance of user %s too low", fromUserStr)
return false, fmt.Errorf(errmsg)
return false, fmt.Errorf("%s", errmsg)
}
t.ToWallet = to.ID
@@ -125,7 +130,7 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
log.Warnf(errmsg)
log.Warnf("%s", errmsg)
return false, err
}
+3
View File
@@ -100,6 +100,9 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
if isPlaceholderSender(tbUser) {
return nil, fmt.Errorf("no wallet for placeholder sender %d", tbUser.ID)
}
// failsafe: do not create wallet for existing user
if _, exists := bot.UserExists(tbUser); exists {
return nil, fmt.Errorf("user already exists")
+4
View File
@@ -82,6 +82,10 @@ func startApiServer(bot *telegram.TipBot) {
// start internal admin server
adminService := admin.New(bot)
internalAdminServer := api.NewServer(internal.Configuration.Bot.AdminAPIHost)
if internal.Configuration.Bot.AdminAPIToken == "" {
log.Warnln("[ADMIN] bot.admin_api_token is not set, the admin API rejects all requests")
}
internalAdminServer.Use(api.AdminTokenMiddleware(internal.Configuration.Bot.AdminAPIToken))
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
+81
View File
@@ -403,3 +403,84 @@ Pro připojení ke skupině si promluv s %s a v soukromé zprávě napiš `/join
generateDalleHelpMessage = """Vytvořit obrázky pomocí OpenAI DALLE 2.\nPoužití: `/generate <prompt>`\nCena: 1000 sat"""
generateDallePayInvoiceMessage = """Zaplať tuto invoice pro vytvoření 4 obrázků 👇"""
generateDalleGeneratingMessage = """Tvé obrázky se generují. Chvilku strpení..."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 LNURLcash noty nejsou v tomto botovi zapnuté."""
lnurlcashStartPrivateFirstMessage = """👋 Nejdřív se mnou začni soukromý chat a pak to zkus znovu."""
noteHelpMessage = """🎫 *LNURLcash noty*\n\n_Nota je odkaz na doručitele v hodnotě pevného počtu satů. Kdo ji naskenuje první, dostane saty._\n\n*/note* 🎫 Vytvoří jednu notu: `/note <částka> [poznámka]`\n*/notes* 📚 Vypíše tvé noty a balíčky: `/notes`\n*/notes* 📚 Vytvoří balíček: `/notes <částka> x <počet> [poznámka]`\n*/redeem* 📥 Připíše přijatou notu na tvůj zůstatek (nebo ji prostě vlož): `/redeem <nota>`\n*/lnurlmints* 🏭 Zobrazí minty a nastaví výchozí: `/lnurlmints`\n*/lnurlhelp* 📖 Zobrazí tuto nápovědu: `/lnurlhelp`"""
notesHelpMessage = """📖 Použití: `/notes` nebo `/notes <částka> x <počet> [poznámka]`"""
redeemHelpMessage = """📖 Použití: `/redeem <nota>` — nebo notu vlož, případně pošli fotku jejího QR kódu v soukromém chatu."""
noteConfirmMessage = """🎫 *Vytvořit %d not(u/y)?*\n\n💸 Hodnota: %s sat za kus\n🏦 Poplatek mintu: %s sat\n💰 Celkem: %s sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Vytvořit"""
noteChangeMintButton = """🏭 Změnit mint"""
noteCancelButton = """🚫 Zrušit"""
noteCancelledMessage = """🚫 Zrušeno."""
noteCreatingMessage = """🧮 Vytvářím tvou notu, může to chvíli trvat..."""
noteCreatedMessage = """🎫 Nota v hodnotě *%s sat* vytvořena (id `%s`).\n\nSdílej QR kód nebo tento odkaz. Vyhrává první sken:\n`%s`"""
noteGroupMessage = """🎫 Nota v hodnotě *%s sat* od %s. Vyhrává první sken!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Tato nota v hodnotě %s sat už byla vyzvednuta."""
noteGroupWithdrawnMessage = """↩️ Tuto notu v hodnotě %s sat stáhl její tvůrce."""
noteReceiptMessage = """🧾 *Nota zveřejněna ve skupině*\n\n💸 Hodnota: %s sat\n🏦 Poplatek mintu: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Vzít zpět"""
noteStatusButton = """🔎 Zkontrolovat stav"""
noteShowQrButton = """🔳 Zobrazit QR"""
noteStatusLiveMessage = """🟢 Nota zatím nebyla vyzvednuta a má hodnotu %s sat."""
noteStatusClaimedMessage = """✅ Nota byla vyzvednuta."""
noteStatusPendingMessage = """⏳ Mint ještě zpracovává operaci s touto notou. Zkus to za chvíli znovu."""
noteStatusOtherMessage = """ℹ️ Stav noty: %s"""
noteInFlightMessage = """⏳ Stále probíhá: Lightning platba mintu ještě nebyla dokončena. Dokončím to na pozadí a dám ti vědět."""
noteReclaimRequestedMessage = """↩️ Požádáno o vrácení %s sat. Dám ti vědět, až dorazí."""
noteReclaimedMessage = """↩️ %s sat z noty `%s` je zpět na tvém zůstatku."""
noteClaimedNotifyMessage = """✅ Tvá nota `%[2]s` v hodnotě %[1]s sat byla vyzvednuta. %[3]s"""
noteBatchDigestMessage = """✅ Vyzvednuto %d not(a/y) z balíčku `%s` (zatím %d z %d)."""
noteNothingToReclaimMessage = """ℹ️ Z této noty není co vracet."""
noteNotOwnerMessage = """🚫 To není tvá nota."""
noteOnlyOneMintMessage = """ℹ️ K dispozici je jen jeden mint."""
noteCapValueMessage = """🚫 Nota musí mít hodnotu mezi %d a %d sat (ve skupině nejvýše %d sat)."""
noteCapBatchMessage = """🚫 Balíček může obsahovat nejvýše %d not a celkem %d sat."""
noteCapOutstandingMessage = """🚫 Už máš příliš mnoho nevyzvednutých not (limit: %d not nebo %d sat)."""
noteInsufficientFundsMessage = """🚫 Tvůj zůstatek nepokryje notu, poplatek mintu a rezervu na Lightning routování (alespoň 1 sat)."""
noteMintUnavailableMessage = """🚫 Mint teď není dostupný. Zkus to později."""
noteMintRangeMessage = """🚫 Mint tuto částku nepřijímá."""
noteErrorMessage = """🚫 Něco se pokazilo. Zkus to později."""
noteStateLive = """nevyzvednuta"""
noteStateClaimed = """vyzvednuta"""
noteStateReclaiming = """vrací se"""
noteStateReclaimed = """vrácena"""
noteStateFailed = """selhala"""
noteStatePending = """čeká"""
noteViewMessage = """🎫 *Nota* `%s`\n\n💸 Hodnota: %s sat\n📍 Stav: %s\n🏭 Mint: %s\n🕓 Vytvořena: %s"""
notesListHeader = """🎫 *Tvé noty a balíčky* (%d, strana %d/%d)"""
notesListEmpty = """Zatím nemáš žádné noty. Vytvoř si jednu pomocí `/note <částka>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d nevyzvednuto, %d vyzvednuto · %s"""
notesBatchOpenMessage = """📦 *Balíček* `%s`\n\n🎫 %d not po %s sat\n🏭 Mint: %s\n🕓 Vytvořen: %s\n\n🟢 Nevyzvednuto: %d\n✅ Vyzvednuto: %d\n↩️ Vráceno: %d\n⏳ Ostatní: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d nevyzvednutých not z balíčku `%s`. Tento soubor nikomu nedávej: obsahuje samotné noty."""
notesRefreshButton = """🔄 Obnovit stav"""
notesReclaimUnclaimedButton = """↩️ Vzít zpět nevyzvednuté"""
notesBatchProgressMessage = """🧮 Vytvářím noty... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 Vytvořeno %d z %d not (balíček `%s`)."""
notesBatchPartialMessage = """⚠️ Některé noty se nepodařilo vytvořit: %s\nZbývající prostředky se vrací na tvůj zůstatek."""
notesBatchFormatMessage = """Vyber formát pro export not:"""
notesBatchReclaimMessage = """↩️ Požádáno o vrácení %d not(y)."""
redeemPreviewMessage = """🎫 Tato nota má hodnotu *%s sat* u `%s`.\n\nPřipsat na tvůj zůstatek?"""
redeemUnknownMintWarning = """⚠️ Tento mint není na seznamu tohoto bota. Proplácíš na vlastní riziko."""
redeemAddButton = """💰 Připsat na zůstatek"""
redeemInFlightMessage = """⏳ Proplácím..."""
redeemRequestedMessage = """⏳ Mint vyplácí %s sat. Dám ti vědět, až dorazí."""
redeemDoneMessage = """✅ %s sat z noty bylo připsáno na tvůj zůstatek."""
redeemPendingMessage = """⏳ Mint ještě zpracovává operaci s touto notou. Zkus to za chvíli znovu."""
redeemNotANoteMessage = """🚫 To není LNURLcash nota."""
redeemFractionalMessage = """🚫 Hodnota této noty není celý počet satů a nepodařilo se ji rozdělit."""
redeemOwnNoteMessage = """ℹ️ To je jedna z tvých vlastních not. Použij místo toho její tlačítko Vzít zpět."""
redeemCancelledMessage = """🚫 Proplacení zrušeno."""
lnurlmintsHeader = """🏭 *LNURLcash minty*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · poplatek: %s"""
lnurlmintsNoFee = """žádný"""
lnurlmintsFee = """%s sat + %s%% z částky"""
lnurlmintsSetButton = """Použít %s"""
lnurlmintsSetMessage = """⭐️ %s je teď tvůj výchozí mint."""
+81
View File
@@ -360,3 +360,84 @@ inlineTipjarHelpText = """📖 Ups, das hat nicht geklappt. %
*Befehl:* `/tipjar <betrag> <pro_user>`
*Beispiel:* `/tipjar 210 21`"""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 LNURLcash-Notes sind bei diesem Bot nicht aktiviert."""
lnurlcashStartPrivateFirstMessage = """👋 Starte zuerst einen privaten Chat mit mir und versuche es dann noch einmal."""
noteHelpMessage = """🎫 *LNURLcash-Notes*\n\n_Eine Note ist ein Inhaber-Link im Wert einer festen Anzahl Sats. Wer sie zuerst scannt, bekommt die Sats._\n\n*/note* 🎫 Erstellt eine Note: `/note <Betrag> [Memo]`\n*/notes* 📚 Zeigt deine Notes und Stapel: `/notes`\n*/notes* 📚 Erstellt einen Stapel: `/notes <Betrag> x <Anzahl> [Memo]`\n*/redeem* 📥 Schreibt eine erhaltene Note deinem Guthaben gut (oder füge sie einfach ein): `/redeem <Note>`\n*/lnurlmints* 🏭 Zeigt die Mints und legt deinen Standard fest: `/lnurlmints`\n*/lnurlhelp* 📖 Zeigt diese Hilfe: `/lnurlhelp`"""
notesHelpMessage = """📖 Verwendung: `/notes` oder `/notes <Betrag> x <Anzahl> [Memo]`"""
redeemHelpMessage = """📖 Verwendung: `/redeem <Note>` — oder füge die Note ein bzw. schicke ein Foto ihres QR-Codes im privaten Chat."""
noteConfirmMessage = """🎫 *%d Note(s) erstellen?*\n\n💸 Wert: je %s Sat\n🏦 Mint-Gebühr: %s Sat\n💰 Gesamt: %s Sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Erstellen"""
noteChangeMintButton = """🏭 Mint wechseln"""
noteCancelButton = """🚫 Abbrechen"""
noteCancelledMessage = """🚫 Abgebrochen."""
noteCreatingMessage = """🧮 Deine Note wird erstellt, das kann einen Moment dauern..."""
noteCreatedMessage = """🎫 Note über *%s Sat* erstellt (ID `%s`).\n\nTeile den QR-Code oder diesen Link. Der erste Scan gewinnt:\n`%s`"""
noteGroupMessage = """🎫 Eine Note im Wert von *%s Sat* von %s. Der erste Scan gewinnt!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Diese Note über %s Sat wurde eingelöst."""
noteGroupWithdrawnMessage = """↩️ Diese Note über %s Sat wurde vom Ersteller zurückgezogen."""
noteReceiptMessage = """🧾 *Note in der Gruppe gepostet*\n\n💸 Wert: %s Sat\n🏦 Mint-Gebühr: %s Sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Zurückholen"""
noteStatusButton = """🔎 Status prüfen"""
noteShowQrButton = """🔳 QR anzeigen"""
noteStatusLiveMessage = """🟢 Die Note ist noch nicht eingelöst und %s Sat wert."""
noteStatusClaimedMessage = """✅ Die Note wurde eingelöst."""
noteStatusPendingMessage = """⏳ Der Mint verarbeitet noch einen Vorgang zu dieser Note. Versuche es gleich noch einmal."""
noteStatusOtherMessage = """ℹ️ Status der Note: %s"""
noteInFlightMessage = """⏳ Läuft noch: Die Lightning-Zahlung an den Mint ist noch nicht abgeschlossen. Ich erledige es im Hintergrund und sage dir Bescheid."""
noteReclaimRequestedMessage = """↩️ Zurückholen von %s Sat angefragt. Du wirst benachrichtigt, sobald es angekommen ist."""
noteReclaimedMessage = """↩️ %s Sat aus Note `%s` sind wieder auf deinem Guthaben."""
noteClaimedNotifyMessage = """✅ Deine Note `%[2]s` über %[1]s Sat wurde eingelöst. %[3]s"""
noteBatchDigestMessage = """✅ %d Note(s) aus Stapel `%s` wurden eingelöst (bisher %d von %d)."""
noteNothingToReclaimMessage = """ℹ️ Bei dieser Note gibt es nichts zurückzuholen."""
noteNotOwnerMessage = """🚫 Das ist nicht deine Note."""
noteOnlyOneMintMessage = """ℹ️ Es ist nur ein Mint verfügbar."""
noteCapValueMessage = """🚫 Eine Note muss zwischen %d und %d Sat liegen (in einer Gruppe höchstens %d Sat)."""
noteCapBatchMessage = """🚫 Ein Stapel darf höchstens %d Notes und insgesamt %d Sat enthalten."""
noteCapOutstandingMessage = """🚫 Du hast bereits zu viele offene Notes (Limit: %d Notes oder %d Sat)."""
noteInsufficientFundsMessage = """🚫 Dein Guthaben reicht nicht für die Note, die Mint-Gebühr und die Lightning-Routing-Reserve (mindestens 1 sat)."""
noteMintUnavailableMessage = """🚫 Der Mint ist gerade nicht erreichbar. Versuche es später noch einmal."""
noteMintRangeMessage = """🚫 Der Mint akzeptiert diesen Betrag nicht."""
noteErrorMessage = """🚫 Etwas ist schiefgelaufen. Versuche es später noch einmal."""
noteStateLive = """nicht eingelöst"""
noteStateClaimed = """eingelöst"""
noteStateReclaiming = """wird zurückgeholt"""
noteStateReclaimed = """zurückgeholt"""
noteStateFailed = """fehlgeschlagen"""
noteStatePending = """in Bearbeitung"""
noteViewMessage = """🎫 *Note* `%s`\n\n💸 Wert: %s Sat\n📍 Status: %s\n🏭 Mint: %s\n🕓 Erstellt: %s"""
notesListHeader = """🎫 *Deine Notes und Stapel* (%d, Seite %d/%d)"""
notesListEmpty = """Du hast noch keine Notes. Erstelle eine mit `/note <Betrag>`."""
notesListItem = """%s %s Sat · %s %s"""
notesBatchItem = """📦 %d × %s Sat · %d offen, %d eingelöst · %s"""
notesBatchOpenMessage = """📦 *Stapel* `%s`\n\n🎫 %d Notes über je %s Sat\n🏭 Mint: %s\n🕓 Erstellt: %s\n\n🟢 Offen: %d\n✅ Eingelöst: %d\n↩️ Zurückgeholt: %d\n⏳ Sonstige: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d offene Note(s) aus Stapel `%s`. Halte diese Datei geheim: sie enthält die Notes selbst."""
notesRefreshButton = """🔄 Status aktualisieren"""
notesReclaimUnclaimedButton = """↩️ Offene zurückholen"""
notesBatchProgressMessage = """🧮 Notes werden erstellt... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d von %d Notes erstellt (Stapel `%s`)."""
notesBatchPartialMessage = """⚠️ Einige Notes konnten nicht erstellt werden: %s\nDer Rest geht zurück auf dein Guthaben."""
notesBatchFormatMessage = """Wähle ein Format für den Export der Notes:"""
notesBatchReclaimMessage = """↩️ Zurückholen für %d Note(s) angefragt."""
redeemPreviewMessage = """🎫 Diese Note ist *%s Sat* wert bei `%s`.\n\nDeinem Guthaben gutschreiben?"""
redeemUnknownMintWarning = """⚠️ Dieser Mint steht nicht auf der Liste dieses Bots. Einlösen auf eigenes Risiko."""
redeemAddButton = """💰 Gutschreiben"""
redeemInFlightMessage = """⏳ Wird eingelöst..."""
redeemRequestedMessage = """⏳ Der Mint zahlt %s Sat aus. Du wirst benachrichtigt, sobald es angekommen ist."""
redeemDoneMessage = """✅ %s Sat aus der Note wurden deinem Guthaben gutgeschrieben."""
redeemPendingMessage = """⏳ Der Mint verarbeitet noch einen Vorgang zu dieser Note. Versuche es gleich noch einmal."""
redeemNotANoteMessage = """🚫 Das ist keine LNURLcash-Note."""
redeemFractionalMessage = """🚫 Der Wert dieser Note ist keine ganze Zahl von Sats und konnte nicht aufgeteilt werden."""
redeemOwnNoteMessage = """ℹ️ Das ist eine deiner eigenen Notes. Nutze stattdessen ihren Zurückholen-Button."""
redeemCancelledMessage = """🚫 Einlösen abgebrochen."""
lnurlmintsHeader = """🏭 *LNURLcash-Mints*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · Gebühr: %s"""
lnurlmintsNoFee = """keine"""
lnurlmintsFee = """%s Sat + %s%% des Betrags"""
lnurlmintsSetButton = """%s verwenden"""
lnurlmintsSetMessage = """⭐️ %s ist jetzt dein Standard-Mint."""
+82 -1
View File
@@ -125,6 +125,7 @@ advancedMessage = """%s
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/lnurlhelp* 🎫 LNURLcash notes: `/lnurlhelp` (create, share and redeem bearer notes)
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Group chat features: `/group`
@@ -409,4 +410,84 @@ For users (in private chat): `/join <group_name>`\nExample: `/join TheBestBitcoi
# DALLE GENERATE
generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
generateDallePayInvoiceMessage = """Pay this invoice to generate four images 👇"""
generateDalleGeneratingMessage = """Your images are being generated. Please wait..."""
generateDalleGeneratingMessage = """Your images are being generated. Please wait..."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 LNURLcash notes are not enabled on this bot."""
lnurlcashStartPrivateFirstMessage = """👋 Start a private chat with me first, then try again."""
noteHelpMessage = """🎫 *LNURLcash notes*\n\n_A note is a bearer link worth a fixed number of sats. Whoever scans it first gets the sats._\n\n*/note* 🎫 Creates one note: `/note <amount> [memo]`\n*/notes* 📚 Lists your notes and batches: `/notes`\n*/notes* 📚 Creates a batch: `/notes <amount> x <count> [memo]`\n*/redeem* 📥 Adds a received note to your balance (or just paste it): `/redeem <note>`\n*/lnurlmints* 🏭 Shows the mints and sets your default: `/lnurlmints`\n*/lnurlhelp* 📖 Shows this help: `/lnurlhelp`"""
notesHelpMessage = """📖 Usage: `/notes` or `/notes <amount> x <count> [memo]`"""
redeemHelpMessage = """📖 Usage: `/redeem <note>` — or paste the note or send a photo of its QR code in private chat."""
noteConfirmMessage = """🎫 *Create %d note(s)?*\n\n💸 Value: %s sat each\n🏦 Mint fee: %s sat\n💰 Total: %s sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Create"""
noteChangeMintButton = """🏭 Change mint"""
noteCancelButton = """🚫 Cancel"""
noteCancelledMessage = """🚫 Cancelled."""
noteCreatingMessage = """🧮 Creating your note, this can take a moment..."""
noteCreatedMessage = """🎫 Note of *%s sat* created (id `%s`).\n\nShare the QR code or this link. The first scan wins:\n`%s`"""
noteGroupMessage = """🎫 A note worth *%s sat* from %s. First scan wins!\n\n`%s`"""
noteGroupClaimedMessage = """✅ This %s sat note has been claimed."""
noteGroupWithdrawnMessage = """↩️ This %s sat note was withdrawn by its creator."""
noteReceiptMessage = """🧾 *Note posted in the group*\n\n💸 Value: %s sat\n🏦 Mint fee: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Reclaim"""
noteStatusButton = """🔎 Check status"""
noteShowQrButton = """🔳 Show QR"""
noteStatusLiveMessage = """🟢 The note is unclaimed and worth %s sat."""
noteStatusClaimedMessage = """✅ The note has been claimed."""
noteStatusPendingMessage = """⏳ The mint is still settling an operation on this note. Try again in a moment."""
noteStatusOtherMessage = """ℹ️ Note status: %s"""
noteInFlightMessage = """⏳ Still in progress: the Lightning payment to the mint has not settled yet. I will finish it in the background and let you know."""
noteReclaimRequestedMessage = """↩️ Reclaim requested for %s sat. You will be notified when it arrives."""
noteReclaimedMessage = """↩️ %s sat from note `%s` are back in your balance."""
noteClaimedNotifyMessage = """✅ Your %s sat note `%s` has been claimed. %s"""
noteBatchDigestMessage = """✅ %d note(s) of batch `%s` were claimed (%d of %d so far)."""
noteNothingToReclaimMessage = """ℹ️ There is nothing to reclaim on this note."""
noteNotOwnerMessage = """🚫 That is not your note."""
noteOnlyOneMintMessage = """ℹ️ Only one mint is available."""
noteCapValueMessage = """🚫 A note must be between %d and %d sat (at most %d sat in a group)."""
noteCapBatchMessage = """🚫 A batch may hold at most %d notes and %d sat in total."""
noteCapOutstandingMessage = """🚫 You already have too many unclaimed notes (limit: %d notes or %d sat)."""
noteInsufficientFundsMessage = """🚫 Your balance does not cover the note, the mint fee and the Lightning routing reserve (at least 1 sat)."""
noteMintUnavailableMessage = """🚫 The mint is not available right now. Try again later."""
noteMintRangeMessage = """🚫 The mint does not accept this amount."""
noteErrorMessage = """🚫 Something went wrong. Try again later."""
noteStateLive = """unclaimed"""
noteStateClaimed = """claimed"""
noteStateReclaiming = """being reclaimed"""
noteStateReclaimed = """reclaimed"""
noteStateFailed = """failed"""
noteStatePending = """pending"""
noteViewMessage = """🎫 *Note* `%s`\n\n💸 Value: %s sat\n📍 Status: %s\n🏭 Mint: %s\n🕓 Created: %s"""
notesListHeader = """🎫 *Your notes and batches* (%d, page %d/%d)"""
notesListEmpty = """You have no notes yet. Create one with `/note <amount>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d unclaimed, %d claimed · %s"""
notesBatchOpenMessage = """📦 *Batch* `%s`\n\n🎫 %d notes of %s sat\n🏭 Mint: %s\n🕓 Created: %s\n\n🟢 Unclaimed: %d\n✅ Claimed: %d\n↩️ Reclaimed: %d\n⏳ Other: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d unclaimed note(s) of batch `%s`. Keep this file private: it holds the notes themselves."""
notesRefreshButton = """🔄 Refresh status"""
notesReclaimUnclaimedButton = """↩️ Reclaim unclaimed"""
notesBatchProgressMessage = """🧮 Creating notes... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d of %d notes created (batch `%s`)."""
notesBatchPartialMessage = """⚠️ Some notes could not be created: %s\nThe remaining funds are returned to your balance."""
notesBatchFormatMessage = """Pick a format to export the notes:"""
notesBatchReclaimMessage = """↩️ Reclaim requested for %d note(s)."""
redeemPreviewMessage = """🎫 This note is worth *%s sat* at `%s`.\n\nAdd it to your balance?"""
redeemUnknownMintWarning = """⚠️ This mint is not on this bot's list. Redeem at your own risk."""
redeemAddButton = """💰 Add to balance"""
redeemInFlightMessage = """⏳ Redeeming..."""
redeemRequestedMessage = """⏳ The mint is paying out %s sat. You will be notified when it arrives."""
redeemDoneMessage = """✅ %s sat from the note were added to your balance."""
redeemPendingMessage = """⏳ The mint is still settling an operation on this note. Try again in a moment."""
redeemNotANoteMessage = """🚫 That is not an LNURLcash note."""
redeemFractionalMessage = """🚫 This note's value is not a whole number of sats and could not be split."""
redeemOwnNoteMessage = """ℹ️ That is one of your own notes. Use its Reclaim button instead."""
redeemCancelledMessage = """🚫 Redeem cancelled."""
lnurlmintsHeader = """🏭 *LNURLcash mints*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · fee: %s"""
lnurlmintsNoFee = """none"""
lnurlmintsFee = """%s sat + %s%% of the amount"""
lnurlmintsSetButton = """Use %s"""
lnurlmintsSetMessage = """⭐️ %s is now your default mint."""
+81
View File
@@ -347,3 +347,84 @@ inlineTipjarHelpText = """📖 Oops, eso no funcionó. %s
*Uso:* `/tipjar <capacidad> <por_usuario>`
*Ejemplo:* `/tipjar 210 21`"""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 Las notas LNURLcash no están activadas en este bot."""
lnurlcashStartPrivateFirstMessage = """👋 Primero inicia un chat privado conmigo y vuelve a intentarlo."""
noteHelpMessage = """🎫 *Notas LNURLcash*\n\n_Una nota es un enlace al portador que vale una cantidad fija de sats. Quien la escanee primero se lleva los sats._\n\n*/note* 🎫 Crea una nota: `/note <cantidad> [memo]`\n*/notes* 📚 Lista tus notas y lotes: `/notes`\n*/notes* 📚 Crea un lote: `/notes <cantidad> x <número> [memo]`\n*/redeem* 📥 Añade una nota recibida a tu saldo (o simplemente pégala): `/redeem <nota>`\n*/lnurlmints* 🏭 Muestra los mints y fija el que usas por defecto: `/lnurlmints`\n*/lnurlhelp* 📖 Muestra esta ayuda: `/lnurlhelp`"""
notesHelpMessage = """📖 Uso: `/notes` o `/notes <cantidad> x <número> [memo]`"""
redeemHelpMessage = """📖 Uso: `/redeem <nota>` — o pega la nota o envía una foto de su código QR en el chat privado."""
noteConfirmMessage = """🎫 *¿Crear %d nota(s)?*\n\n💸 Valor: %s sat cada una\n🏦 Comisión del mint: %s sat\n💰 Total: %s sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Crear"""
noteChangeMintButton = """🏭 Cambiar mint"""
noteCancelButton = """🚫 Cancelar"""
noteCancelledMessage = """🚫 Cancelado."""
noteCreatingMessage = """🧮 Creando tu nota, puede tardar un momento..."""
noteCreatedMessage = """🎫 Nota de *%s sat* creada (id `%s`).\n\nComparte el código QR o este enlace. El primer escaneo gana:\n`%s`"""
noteGroupMessage = """🎫 Una nota de *%s sat* de %s. ¡El primer escaneo gana!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Esta nota de %s sat ya ha sido reclamada."""
noteGroupWithdrawnMessage = """↩️ Esta nota de %s sat fue retirada por su creador."""
noteReceiptMessage = """🧾 *Nota publicada en el grupo*\n\n💸 Valor: %s sat\n🏦 Comisión del mint: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Recuperar"""
noteStatusButton = """🔎 Ver estado"""
noteShowQrButton = """🔳 Mostrar QR"""
noteStatusLiveMessage = """🟢 La nota sigue sin reclamar y vale %s sat."""
noteStatusClaimedMessage = """✅ La nota ha sido reclamada."""
noteStatusPendingMessage = """⏳ El mint aún está procesando una operación sobre esta nota. Inténtalo de nuevo en un momento."""
noteStatusOtherMessage = """ℹ️ Estado de la nota: %s"""
noteInFlightMessage = """⏳ Sigue en curso: el pago Lightning al mint aún no se ha completado. Lo terminaré en segundo plano y te avisaré."""
noteReclaimRequestedMessage = """↩️ Recuperación de %s sat solicitada. Te avisaré cuando lleguen."""
noteReclaimedMessage = """↩️ %s sat de la nota `%s` han vuelto a tu saldo."""
noteClaimedNotifyMessage = """✅ Tu nota `%[2]s` de %[1]s sat ha sido reclamada. %[3]s"""
noteBatchDigestMessage = """✅ %d nota(s) del lote `%s` han sido reclamadas (%d de %d hasta ahora)."""
noteNothingToReclaimMessage = """ℹ️ No hay nada que recuperar en esta nota."""
noteNotOwnerMessage = """🚫 Esa nota no es tuya."""
noteOnlyOneMintMessage = """ℹ️ Solo hay un mint disponible."""
noteCapValueMessage = """🚫 Una nota debe estar entre %d y %d sat (como máximo %d sat en un grupo)."""
noteCapBatchMessage = """🚫 Un lote puede tener como máximo %d notas y %d sat en total."""
noteCapOutstandingMessage = """🚫 Ya tienes demasiadas notas sin reclamar (límite: %d notas o %d sat)."""
noteInsufficientFundsMessage = """🚫 Tu saldo no cubre la nota, la comisión del mint y la reserva de enrutamiento Lightning (al menos 1 sat)."""
noteMintUnavailableMessage = """🚫 El mint no está disponible ahora mismo. Inténtalo más tarde."""
noteMintRangeMessage = """🚫 El mint no acepta esta cantidad."""
noteErrorMessage = """🚫 Algo salió mal. Inténtalo más tarde."""
noteStateLive = """sin reclamar"""
noteStateClaimed = """reclamada"""
noteStateReclaiming = """recuperándose"""
noteStateReclaimed = """recuperada"""
noteStateFailed = """fallida"""
noteStatePending = """pendiente"""
noteViewMessage = """🎫 *Nota* `%s`\n\n💸 Valor: %s sat\n📍 Estado: %s\n🏭 Mint: %s\n🕓 Creada: %s"""
notesListHeader = """🎫 *Tus notas y lotes* (%d, página %d/%d)"""
notesListEmpty = """Aún no tienes notas. Crea una con `/note <cantidad>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d sin reclamar, %d reclamadas · %s"""
notesBatchOpenMessage = """📦 *Lote* `%s`\n\n🎫 %d notas de %s sat\n🏭 Mint: %s\n🕓 Creado: %s\n\n🟢 Sin reclamar: %d\n✅ Reclamadas: %d\n↩️ Recuperadas: %d\n⏳ Otras: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d nota(s) sin reclamar del lote `%s`. Mantén este archivo en privado: contiene las notas en sí."""
notesRefreshButton = """🔄 Actualizar estado"""
notesReclaimUnclaimedButton = """↩️ Recuperar las no reclamadas"""
notesBatchProgressMessage = """🧮 Creando notas... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d de %d notas creadas (lote `%s`)."""
notesBatchPartialMessage = """⚠️ Algunas notas no se pudieron crear: %s\nLos fondos restantes vuelven a tu saldo."""
notesBatchFormatMessage = """Elige un formato para exportar las notas:"""
notesBatchReclaimMessage = """↩️ Recuperación solicitada para %d nota(s)."""
redeemPreviewMessage = """🎫 Esta nota vale *%s sat* en `%s`.\n\n¿Añadirla a tu saldo?"""
redeemUnknownMintWarning = """⚠️ Este mint no está en la lista de este bot. Canjéala bajo tu propia responsabilidad."""
redeemAddButton = """💰 Añadir al saldo"""
redeemInFlightMessage = """⏳ Canjeando..."""
redeemRequestedMessage = """⏳ El mint está pagando %s sat. Te avisaré cuando lleguen."""
redeemDoneMessage = """✅ %s sat de la nota se han añadido a tu saldo."""
redeemPendingMessage = """⏳ El mint aún está procesando una operación sobre esta nota. Inténtalo de nuevo en un momento."""
redeemNotANoteMessage = """🚫 Eso no es una nota LNURLcash."""
redeemFractionalMessage = """🚫 El valor de esta nota no es un número entero de sats y no se pudo dividir."""
redeemOwnNoteMessage = """ℹ️ Esa es una de tus propias notas. Usa su botón Recuperar."""
redeemCancelledMessage = """🚫 Canje cancelado."""
lnurlmintsHeader = """🏭 *Mints LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · comisión: %s"""
lnurlmintsNoFee = """ninguna"""
lnurlmintsFee = """%s sat + %s%% de la cantidad"""
lnurlmintsSetButton = """Usar %s"""
lnurlmintsSetMessage = """⭐️ %s es ahora tu mint por defecto."""
+82 -1
View File
@@ -409,4 +409,85 @@ Käyttäjille (yksityskeskusteluissa): `/join <group_name>`\nEsimerkki: `/join T
# DALLE GENERATE
generateDalleHelpMessage = """Luo OpenAI DALLE 2. -kuvia\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
generateDallePayInvoiceMessage = """Maksa tämä lasku ja neljä kuvaa luotaan 👇"""
generateDalleGeneratingMessage = """Kuvia luodaan. Odota hetkinen..."""
generateDalleGeneratingMessage = """Kuvia luodaan. Odota hetkinen..."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 LNURLcash-setelit eivät ole käytössä tässä botissa."""
lnurlcashStartPrivateFirstMessage = """👋 Aloita ensin yksityiskeskustelu kanssani ja yritä sitten uudelleen."""
noteHelpMessage = """🎫 *LNURLcash-setelit*\n\n_Seteli on haltijalinkki, jonka arvo on kiinteä määrä sateja. Se, joka skannaa sen ensin, saa satit._\n\n*/note* 🎫 Luo yhden setelin: `/note <summa> [viesti]`\n*/notes* 📚 Listaa setelisi ja erät: `/notes`\n*/notes* 📚 Luo erän: `/notes <summa> x <määrä> [viesti]`\n*/redeem* 📥 Lisää vastaanotetun setelin saldoosi (tai liitä se vain): `/redeem <seteli>`\n*/lnurlmints* 🏭 Näyttää mintit ja asettaa oletuksen: `/lnurlmints`\n*/lnurlhelp* 📖 Näyttää tämän ohjeen: `/lnurlhelp`"""
notesHelpMessage = """📖 Käyttö: `/notes` tai `/notes <summa> x <määrä> [viesti]`"""
redeemHelpMessage = """📖 Käyttö: `/redeem <seteli>` — tai liitä seteli tai lähetä kuva sen QR-koodista yksityiskeskustelussa."""
noteConfirmMessage = """🎫 *Luodaanko %d seteli(ä)?*\n\n💸 Arvo: %s sat kukin\n🏦 Mintin maksu: %s sat\n💰 Yhteensä: %s sat\n🏭 Mintti: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Luo"""
noteChangeMintButton = """🏭 Vaihda minttiä"""
noteCancelButton = """🚫 Peruuta"""
noteCancelledMessage = """🚫 Peruutettu."""
noteCreatingMessage = """🧮 Luon seteliäsi, tässä voi kestää hetki..."""
noteCreatedMessage = """🎫 *%s sat* seteli luotu (id `%s`).\n\nJaa QR-koodi tai tämä linkki. Ensimmäinen skannaus voittaa:\n`%s`"""
noteGroupMessage = """🎫 *%s sat* seteli käyttäjältä %s. Ensimmäinen skannaus voittaa!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Tämä %s sat seteli on lunastettu."""
noteGroupWithdrawnMessage = """↩️ Luoja veti tämän %s sat setelin takaisin."""
noteReceiptMessage = """🧾 *Seteli julkaistu ryhmässä*\n\n💸 Arvo: %s sat\n🏦 Mintin maksu: %s sat\n🏭 Mintti: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Palauta"""
noteStatusButton = """🔎 Tarkista tila"""
noteShowQrButton = """🔳 Näytä QR"""
noteStatusLiveMessage = """🟢 Seteliä ei ole vielä lunastettu, ja sen arvo on %s sat."""
noteStatusClaimedMessage = """✅ Seteli on lunastettu."""
noteStatusPendingMessage = """⏳ Mintti käsittelee vielä tämän setelin toimintoa. Yritä hetken päästä uudelleen."""
noteStatusOtherMessage = """ℹ️ Setelin tila: %s"""
noteInFlightMessage = """⏳ Vielä kesken: Lightning-maksu mintille ei ole vielä valmistunut. Hoidan sen loppuun taustalla ja ilmoitan sinulle."""
noteReclaimRequestedMessage = """↩️ %s sat palautus pyydetty. Ilmoitan, kun se on perillä."""
noteReclaimedMessage = """↩️ %s sat setelistä `%s` on taas saldossasi."""
noteClaimedNotifyMessage = """✅ Setelisi `%[2]s` (%[1]s sat) on lunastettu. %[3]s"""
noteBatchDigestMessage = """✅ %d seteli(ä) erästä `%s` on lunastettu (tähän mennessä %d/%d)."""
noteNothingToReclaimMessage = """ℹ️ Tästä setelistä ei ole mitään palautettavaa."""
noteNotOwnerMessage = """🚫 Tuo ei ole sinun setelisi."""
noteOnlyOneMintMessage = """ℹ️ Vain yksi mintti on käytettävissä."""
noteCapValueMessage = """🚫 Setelin on oltava %d–%d sat (ryhmässä enintään %d sat)."""
noteCapBatchMessage = """🚫 Erässä voi olla enintään %d seteliä ja yhteensä %d sat."""
noteCapOutstandingMessage = """🚫 Sinulla on jo liikaa lunastamattomia seteleitä (raja: %d seteliä tai %d sat)."""
noteInsufficientFundsMessage = """🚫 Saldosi ei kata seteliä, mintin maksua ja Lightning-reitityksen varausta (vähintään 1 sat)."""
noteMintUnavailableMessage = """🚫 Mintti ei ole juuri nyt käytettävissä. Yritä myöhemmin uudelleen."""
noteMintRangeMessage = """🚫 Mintti ei hyväksy tätä summaa."""
noteErrorMessage = """🚫 Jokin meni pieleen. Yritä myöhemmin uudelleen."""
noteStateLive = """lunastamatta"""
noteStateClaimed = """lunastettu"""
noteStateReclaiming = """palautetaan"""
noteStateReclaimed = """palautettu"""
noteStateFailed = """epäonnistui"""
noteStatePending = """odottaa"""
noteViewMessage = """🎫 *Seteli* `%s`\n\n💸 Arvo: %s sat\n📍 Tila: %s\n🏭 Mintti: %s\n🕓 Luotu: %s"""
notesListHeader = """🎫 *Setelisi ja eräsi* (%d, sivu %d/%d)"""
notesListEmpty = """Sinulla ei ole vielä seteleitä. Luo yksi komennolla `/note <summa>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d lunastamatta, %d lunastettu · %s"""
notesBatchOpenMessage = """📦 *Erä* `%s`\n\n🎫 %d seteliä à %s sat\n🏭 Mintti: %s\n🕓 Luotu: %s\n\n🟢 Lunastamatta: %d\n✅ Lunastettu: %d\n↩️ Palautettu: %d\n⏳ Muut: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d lunastamatonta seteliä erästä `%s`. Pidä tiedosto salassa: se sisältää itse setelit."""
notesRefreshButton = """🔄 Päivitä tila"""
notesReclaimUnclaimedButton = """↩️ Palauta lunastamattomat"""
notesBatchProgressMessage = """🧮 Luon seteleitä... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d/%d seteliä luotu (erä `%s`)."""
notesBatchPartialMessage = """⚠️ Joitakin seteleitä ei voitu luoda: %s\nLoput varat palautuvat saldoosi."""
notesBatchFormatMessage = """Valitse muoto setelien vientiin:"""
notesBatchReclaimMessage = """↩️ Palautus pyydetty %d setelille."""
redeemPreviewMessage = """🎫 Tämän setelin arvo on *%s sat* mintissä `%s`.\n\nLisätäänkö saldoosi?"""
redeemUnknownMintWarning = """⚠️ Tämä mintti ei ole tämän botin listalla. Lunasta omalla vastuullasi."""
redeemAddButton = """💰 Lisää saldoon"""
redeemInFlightMessage = """⏳ Lunastetaan..."""
redeemRequestedMessage = """⏳ Mintti maksaa %s sat. Ilmoitan, kun se on perillä."""
redeemDoneMessage = """✅ %s sat setelistä lisättiin saldoosi."""
redeemPendingMessage = """⏳ Mintti käsittelee vielä tämän setelin toimintoa. Yritä hetken päästä uudelleen."""
redeemNotANoteMessage = """🚫 Tuo ei ole LNURLcash-seteli."""
redeemFractionalMessage = """🚫 Setelin arvo ei ole kokonaisluku sateja, eikä sitä voitu jakaa."""
redeemOwnNoteMessage = """ℹ️ Tuo on yksi omista seteleistäsi. Käytä sen Palauta-painiketta."""
redeemCancelledMessage = """🚫 Lunastus peruutettu."""
lnurlmintsHeader = """🏭 *LNURLcash-mintit*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · maksu: %s"""
lnurlmintsNoFee = """ei maksua"""
lnurlmintsFee = """%s sat + %s%% summasta"""
lnurlmintsSetButton = """Käytä: %s"""
lnurlmintsSetMessage = """⭐️ %s on nyt oletusminttisi."""
+81
View File
@@ -308,3 +308,84 @@ inlineReceiveCreateWalletMessage = """Chat avec %s 👈 pour gérer votre wallet
inlineReceiveYourselfMessage = """📖 Vous ne pouvez pas vous envoyer de pourboires."""
inlineReceiveFailedMessage = """🚫 La réception a échoué."""
inlineReceiveCancelledMessage = """🚫 Réception annulée."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 Les notes LNURLcash ne sont pas activées sur ce bot."""
lnurlcashStartPrivateFirstMessage = """👋 Commence d'abord une conversation privée avec moi, puis réessaie."""
noteHelpMessage = """🎫 *Notes LNURLcash*\n\n_Une note est un lien au porteur d'une valeur fixe en sats. Le premier qui la scanne reçoit les sats._\n\n*/note* 🎫 Crée une note: `/note <montant> [memo]`\n*/notes* 📚 Liste tes notes et tes lots: `/notes`\n*/notes* 📚 Crée un lot: `/notes <montant> x <nombre> [memo]`\n*/redeem* 📥 Ajoute une note reçue à ton solde (ou colle-la simplement): `/redeem <note>`\n*/lnurlmints* 🏭 Affiche les mints et définit celui par défaut: `/lnurlmints`\n*/lnurlhelp* 📖 Affiche cette aide: `/lnurlhelp`"""
notesHelpMessage = """📖 Utilisation : `/notes` ou `/notes <montant> x <nombre> [memo]`"""
redeemHelpMessage = """📖 Utilisation : `/redeem <note>` — ou colle la note, ou envoie une photo de son QR code en privé."""
noteConfirmMessage = """🎫 *Créer %d note(s) ?*\n\n💸 Valeur : %s sat chacune\n🏦 Frais du mint : %s sat\n💰 Total : %s sat\n🏭 Mint : %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Créer"""
noteChangeMintButton = """🏭 Changer de mint"""
noteCancelButton = """🚫 Annuler"""
noteCancelledMessage = """🚫 Annulé."""
noteCreatingMessage = """🧮 Création de ta note, cela peut prendre un instant..."""
noteCreatedMessage = """🎫 Note de *%s sat* créée (id `%s`).\n\nPartage le QR code ou ce lien. Le premier scan gagne :\n`%s`"""
noteGroupMessage = """🎫 Une note de *%s sat* de %s. Le premier scan gagne !\n\n`%s`"""
noteGroupClaimedMessage = """✅ Cette note de %s sat a été réclamée."""
noteGroupWithdrawnMessage = """↩️ Cette note de %s sat a été retirée par son créateur."""
noteReceiptMessage = """🧾 *Note publiée dans le groupe*\n\n💸 Valeur : %s sat\n🏦 Frais du mint : %s sat\n🏭 Mint : %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Récupérer"""
noteStatusButton = """🔎 Vérifier l'état"""
noteShowQrButton = """🔳 Afficher le QR"""
noteStatusLiveMessage = """🟢 La note n'est pas encore réclamée et vaut %s sat."""
noteStatusClaimedMessage = """✅ La note a été réclamée."""
noteStatusPendingMessage = """⏳ Le mint traite encore une opération sur cette note. Réessaie dans un instant."""
noteStatusOtherMessage = """ℹ️ État de la note : %s"""
noteInFlightMessage = """⏳ Toujours en cours : le paiement Lightning vers le mint n'est pas encore finalisé. Je termine en arrière-plan et je te préviens."""
noteReclaimRequestedMessage = """↩️ Récupération de %s sat demandée. Tu seras prévenu à l'arrivée."""
noteReclaimedMessage = """↩️ %s sat de la note `%s` sont de retour sur ton solde."""
noteClaimedNotifyMessage = """✅ Ta note `%[2]s` de %[1]s sat a été réclamée. %[3]s"""
noteBatchDigestMessage = """✅ %d note(s) du lot `%s` ont été réclamées (%d sur %d jusqu'ici)."""
noteNothingToReclaimMessage = """ℹ️ Il n'y a rien à récupérer sur cette note."""
noteNotOwnerMessage = """🚫 Ce n'est pas ta note."""
noteOnlyOneMintMessage = """ℹ️ Un seul mint est disponible."""
noteCapValueMessage = """🚫 Une note doit valoir entre %d et %d sat (au plus %d sat dans un groupe)."""
noteCapBatchMessage = """🚫 Un lot peut contenir au plus %d notes et %d sat au total."""
noteCapOutstandingMessage = """🚫 Tu as déjà trop de notes non réclamées (limite : %d notes ou %d sat)."""
noteInsufficientFundsMessage = """🚫 Ton solde ne couvre pas la note, les frais du mint et la réserve de routage Lightning (au moins 1 sat)."""
noteMintUnavailableMessage = """🚫 Le mint n'est pas disponible pour le moment. Réessaie plus tard."""
noteMintRangeMessage = """🚫 Le mint n'accepte pas ce montant."""
noteErrorMessage = """🚫 Quelque chose a mal tourné. Réessaie plus tard."""
noteStateLive = """non réclamée"""
noteStateClaimed = """réclamée"""
noteStateReclaiming = """en cours de récupération"""
noteStateReclaimed = """récupérée"""
noteStateFailed = """échouée"""
noteStatePending = """en attente"""
noteViewMessage = """🎫 *Note* `%s`\n\n💸 Valeur : %s sat\n📍 État : %s\n🏭 Mint : %s\n🕓 Créée : %s"""
notesListHeader = """🎫 *Tes notes et lots* (%d, page %d/%d)"""
notesListEmpty = """Tu n'as pas encore de notes. Crées-en une avec `/note <montant>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d non réclamées, %d réclamées · %s"""
notesBatchOpenMessage = """📦 *Lot* `%s`\n\n🎫 %d notes de %s sat\n🏭 Mint : %s\n🕓 Créé : %s\n\n🟢 Non réclamées : %d\n✅ Réclamées : %d\n↩️ Récupérées : %d\n⏳ Autres : %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d note(s) non réclamée(s) du lot `%s`. Garde ce fichier privé : il contient les notes elles-mêmes."""
notesRefreshButton = """🔄 Actualiser l'état"""
notesReclaimUnclaimedButton = """↩️ Récupérer les non réclamées"""
notesBatchProgressMessage = """🧮 Création des notes... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d note(s) sur %d créée(s) (lot `%s`)."""
notesBatchPartialMessage = """⚠️ Certaines notes n'ont pas pu être créées : %s\nLes fonds restants reviennent sur ton solde."""
notesBatchFormatMessage = """Choisis un format pour exporter les notes :"""
notesBatchReclaimMessage = """↩️ Récupération demandée pour %d note(s)."""
redeemPreviewMessage = """🎫 Cette note vaut *%s sat* chez `%s`.\n\nL'ajouter à ton solde ?"""
redeemUnknownMintWarning = """⚠️ Ce mint n'est pas dans la liste de ce bot. Encaisse à tes risques et périls."""
redeemAddButton = """💰 Ajouter au solde"""
redeemInFlightMessage = """⏳ Encaissement..."""
redeemRequestedMessage = """⏳ Le mint verse %s sat. Tu seras prévenu à l'arrivée."""
redeemDoneMessage = """✅ %s sat de la note ont été ajoutés à ton solde."""
redeemPendingMessage = """⏳ Le mint traite encore une opération sur cette note. Réessaie dans un instant."""
redeemNotANoteMessage = """🚫 Ce n'est pas une note LNURLcash."""
redeemFractionalMessage = """🚫 La valeur de cette note n'est pas un nombre entier de sats et n'a pas pu être divisée."""
redeemOwnNoteMessage = """ℹ️ C'est une de tes propres notes. Utilise plutôt son bouton Récupérer."""
redeemCancelledMessage = """🚫 Encaissement annulé."""
lnurlmintsHeader = """🏭 *Mints LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · frais : %s"""
lnurlmintsNoFee = """aucuns"""
lnurlmintsFee = """%s sat + %s%% du montant"""
lnurlmintsSetButton = """Utiliser %s"""
lnurlmintsSetMessage = """⭐️ %s est maintenant ton mint par défaut."""
+81
View File
@@ -316,3 +316,84 @@ inlineReceiveCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola do
inlineReceiveYourselfMessage = """📖 Kamu tidak dapat membayar diri mu sendiri."""
inlineReceiveFailedMessage = """🚫 Penerimaan gagal."""
inlineReceiveCancelledMessage = """🚫 Penerimaan dibatalkan."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 Note LNURLcash tidak diaktifkan di bot ini."""
lnurlcashStartPrivateFirstMessage = """👋 Mulai obrolan pribadi dengan saya dulu, lalu coba lagi."""
noteHelpMessage = """🎫 *Note LNURLcash*\n\n_Note adalah tautan atas unjuk senilai sejumlah sat tetap. Siapa yang memindainya lebih dulu mendapat sat-nya._\n\n*/note* 🎫 Membuat satu note: `/note <jumlah> [memo]`\n*/notes* 📚 Menampilkan note dan batch Anda: `/notes`\n*/notes* 📚 Membuat satu batch: `/notes <jumlah> x <banyak> [memo]`\n*/redeem* 📥 Menambahkan note yang Anda terima ke saldo (atau cukup tempel saja): `/redeem <note>`\n*/lnurlmints* 🏭 Menampilkan daftar mint dan mengatur mint default Anda: `/lnurlmints`\n*/lnurlhelp* 📖 Menampilkan bantuan ini: `/lnurlhelp`"""
notesHelpMessage = """📖 Penggunaan: `/notes` atau `/notes <jumlah> x <banyak> [memo]`"""
redeemHelpMessage = """📖 Penggunaan: `/redeem <note>` — atau tempel note-nya atau kirim foto kode QR-nya di obrolan pribadi."""
noteConfirmMessage = """🎫 *Buat %d note?*\n\n💸 Nilai: %s sat per note\n🏦 Biaya mint: %s sat\n💰 Total: %s sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Buat"""
noteChangeMintButton = """🏭 Ganti mint"""
noteCancelButton = """🚫 Batal"""
noteCancelledMessage = """🚫 Dibatalkan."""
noteCreatingMessage = """🧮 Membuat note Anda, ini bisa memakan waktu sebentar..."""
noteCreatedMessage = """🎫 Note senilai *%s sat* dibuat (id `%s`).\n\nBagikan kode QR atau tautan ini. Pemindai pertama yang menang:\n`%s`"""
noteGroupMessage = """🎫 Note senilai *%s sat* dari %s. Pemindai pertama yang menang!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Note %s sat ini sudah diklaim."""
noteGroupWithdrawnMessage = """↩️ Note %s sat ini ditarik oleh pembuatnya."""
noteReceiptMessage = """🧾 *Note diposting di grup*\n\n💸 Nilai: %s sat\n🏦 Biaya mint: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Tarik kembali"""
noteStatusButton = """🔎 Cek status"""
noteShowQrButton = """🔳 Tampilkan QR"""
noteStatusLiveMessage = """🟢 Note belum diklaim dan bernilai %s sat."""
noteStatusClaimedMessage = """✅ Note sudah diklaim."""
noteStatusPendingMessage = """⏳ Mint masih memproses operasi pada note ini. Coba lagi sebentar lagi."""
noteStatusOtherMessage = """ℹ️ Status note: %s"""
noteInFlightMessage = """⏳ Masih berjalan: pembayaran Lightning ke mint belum selesai. Saya akan menyelesaikannya di latar belakang dan memberi tahu Anda."""
noteReclaimRequestedMessage = """↩️ Penarikan kembali %s sat diminta. Anda akan diberi tahu saat sudah masuk."""
noteReclaimedMessage = """↩️ %s sat dari note `%s` kembali ke saldo Anda."""
noteClaimedNotifyMessage = """✅ Note Anda `%[2]s` senilai %[1]s sat sudah diklaim. %[3]s"""
noteBatchDigestMessage = """✅ %d note dari batch `%s` sudah diklaim (sejauh ini %d dari %d)."""
noteNothingToReclaimMessage = """ℹ️ Tidak ada yang bisa ditarik kembali dari note ini."""
noteNotOwnerMessage = """🚫 Itu bukan note Anda."""
noteOnlyOneMintMessage = """ℹ️ Hanya ada satu mint yang tersedia."""
noteCapValueMessage = """🚫 Note harus antara %d dan %d sat (maksimal %d sat di grup)."""
noteCapBatchMessage = """🚫 Satu batch maksimal %d note dan total %d sat."""
noteCapOutstandingMessage = """🚫 Anda sudah punya terlalu banyak note yang belum diklaim (batas: %d note atau %d sat)."""
noteInsufficientFundsMessage = """🚫 Saldo Anda tidak cukup untuk note, biaya mint, dan cadangan routing Lightning (minimal 1 sat)."""
noteMintUnavailableMessage = """🚫 Mint sedang tidak tersedia. Coba lagi nanti."""
noteMintRangeMessage = """🚫 Mint tidak menerima jumlah ini."""
noteErrorMessage = """🚫 Terjadi kesalahan. Coba lagi nanti."""
noteStateLive = """belum diklaim"""
noteStateClaimed = """diklaim"""
noteStateReclaiming = """sedang ditarik kembali"""
noteStateReclaimed = """ditarik kembali"""
noteStateFailed = """gagal"""
noteStatePending = """tertunda"""
noteViewMessage = """🎫 *Note* `%s`\n\n💸 Nilai: %s sat\n📍 Status: %s\n🏭 Mint: %s\n🕓 Dibuat: %s"""
notesListHeader = """🎫 *Note dan batch Anda* (%d, halaman %d/%d)"""
notesListEmpty = """Anda belum punya note. Buat satu dengan `/note <jumlah>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d belum diklaim, %d diklaim · %s"""
notesBatchOpenMessage = """📦 *Batch* `%s`\n\n🎫 %d note senilai %s sat\n🏭 Mint: %s\n🕓 Dibuat: %s\n\n🟢 Belum diklaim: %d\n✅ Diklaim: %d\n↩️ Ditarik kembali: %d\n⏳ Lainnya: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d note belum diklaim dari batch `%s`. Rahasiakan berkas ini: isinya adalah note-nya sendiri."""
notesRefreshButton = """🔄 Perbarui status"""
notesReclaimUnclaimedButton = """↩️ Tarik kembali yang belum diklaim"""
notesBatchProgressMessage = """🧮 Membuat note... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d dari %d note dibuat (batch `%s`)."""
notesBatchPartialMessage = """⚠️ Beberapa note tidak bisa dibuat: %s\nSisa dananya dikembalikan ke saldo Anda."""
notesBatchFormatMessage = """Pilih format untuk mengekspor note:"""
notesBatchReclaimMessage = """↩️ Penarikan kembali diminta untuk %d note."""
redeemPreviewMessage = """🎫 Note ini bernilai *%s sat* di `%s`.\n\nTambahkan ke saldo Anda?"""
redeemUnknownMintWarning = """⚠️ Mint ini tidak ada di daftar bot ini. Tukarkan dengan risiko Anda sendiri."""
redeemAddButton = """💰 Tambahkan ke saldo"""
redeemInFlightMessage = """⏳ Menukarkan..."""
redeemRequestedMessage = """⏳ Mint sedang membayar %s sat. Anda akan diberi tahu saat sudah masuk."""
redeemDoneMessage = """✅ %s sat dari note ditambahkan ke saldo Anda."""
redeemPendingMessage = """⏳ Mint masih memproses operasi pada note ini. Coba lagi sebentar lagi."""
redeemNotANoteMessage = """🚫 Itu bukan note LNURLcash."""
redeemFractionalMessage = """🚫 Nilai note ini bukan bilangan bulat sat dan tidak bisa dibagi."""
redeemOwnNoteMessage = """ℹ️ Itu salah satu note Anda sendiri. Gunakan tombol Tarik kembali miliknya."""
redeemCancelledMessage = """🚫 Penukaran dibatalkan."""
lnurlmintsHeader = """🏭 *Mint LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · biaya: %s"""
lnurlmintsNoFee = """tidak ada"""
lnurlmintsFee = """%s sat + %s%% dari jumlah"""
lnurlmintsSetButton = """Pakai %s"""
lnurlmintsSetMessage = """⭐️ %s sekarang mint default Anda."""
+391 -310
View File
@@ -1,310 +1,391 @@
# COMMANDS
helpCommandStr = """aiuto"""
basicsCommandStr = """informazioni"""
tipCommandStr = """mancia"""
balanceCommandStr = """saldo"""
sendCommandStr = """invia"""
invoiceCommandStr = """invoice"""
payCommandStr = """paga"""
donateCommandStr = """dona"""
advancedCommandStr = """avanzate"""
transactionsCommandStr = """traduzioni"""
logCommandStr = """log"""
listCommandStr = """lista"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """distribuzione"""
tipjarCommandStr = """salvadanaio"""
receiveCommandStr = """ricevi"""
hideCommandStr = """nascondi"""
volcanoCommandStr = """vulcano"""
showCommandStr = """mostra"""
optionsCommandStr = """opzioni"""
settingsCommandStr = """impostazioni"""
saveCommandStr = """salva"""
deleteCommandStr = """cancella"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """Funzione non disponibile."""
cantClickMessage = """Pulsante non selezionabile."""
balanceTooLowMessage = """Saldo non sufficiente."""
# BUTTONS
sendButtonMessage = """✅ Invia"""
payButtonMessage = """✅ Paga"""
payReceiveButtonMessage = """💸 Paga"""
receiveButtonMessage = """✅ Ricevi"""
cancelButtonMessage = """🚫 Cancella"""
collectButtonMessage = """✅ Incassa"""
nextButtonMessage = """Prossimo"""
backButtonMessage = """Indietro"""
acceptButtonMessage = """Consenti"""
denyButtonMessage = """Rifiuta"""
tipButtonMessage = """Mancia"""
revealButtonMessage = """Rivela"""
showButtonMessage = """Mostra"""
hideButtonMessage = """Nascondi"""
joinButtonMessage = """Unisciti"""
optionsButtonMessage = """Opzioni"""
settingsButtonMessage = """Impostazioni"""
saveButtonMessage = """Salva"""
deleteButtonMessage = """Cancella"""
infoButtonMessage = """Info"""
# HELP
helpMessage = """⚡️ *Wallet*
_Questo bot è un Wallet Bitcoin Lightning con cui puoi inviare ricompense via Telegram. Per inviare, aggiungi il bot come partecipante a una chat di gruppo. L'unità di conto per questi invii di piccolo importo è il Satoshi (sat). 100,000,000 sat = 1 Bitcoin. Digita 📚 /basics per maggiori informazioni._
❤️ *Dona*
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`
%s
⚙️ *Comandi*
*/tip* 🏅 Rispondi così a un messaggio per inviare una mancia: `/tip <ammontare> [<memo>]`
*/balance* 👑 Verifica il tuo saldo residuo: `/balance`
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<memo>]`
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<memo>]`
*/pay* ⚡️ Paga attraverso Lightning: `/pay <invoice>`
*/donate* ❤️ Dona per supportare questo progetto: `/donate 1000`
*/advanced* 🤖 Funzioni avanzate.
*/help* 📖 Richiama questo elenco."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Il tuo indirizzo Lightning è `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin è la valuta di internet. È una rete libera e decentralizzata a cui tutti possono partecipare, senza una autorità di controllo centrale. Bitcoin è una moneta ma anche un sistema di pagamento più veloce, sicuro e inclusivo del sistema finanziario tradizionale._
🧮 *Economnics*
_La più piccola unità in cui è divisibile un Bitcoin è un Satoshi (sat) e 100,000,000 sat equivalgono a 1 Bitcoin. Esistono solamente 21 milioni di Bitcoin. Il valore di Bitcoin espresso in valuta tradizionale può variare ogni giorno. In ogni caso, se la tua valuta di riferimento è Bitcoin, 1 sat varrà sempre 1 sat._
⚡️ *Lightning Network*
_Lightning Network è un protocollo di pagamento che consente pagamenti in Bitcoin veloci ed economici, praticamente senza consumare energia. È il sistema che consentirà di diffondere Bitcoin a miliardi di persone nel mondo._
📲 *Lightning Wallets*
_I tuoi fondi conservati in questo bot possono essere mandati a un altro wallet Lightning e viceversa. Altri wallet Lightning per il tuo smartphone sono_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), oppure_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(semplice da usare)_.
📄 *Open Source*
_Questo bot è software libero e_ [open source](https://github.com/LightningTipBot/LightningTipBot) _. Puoi farlo girare sul tuo computer e usarlo per la tua comunità._
✈️ *Telegram*
_Aggiungi questo bot a una chat di gruppo Telegram per inviare una /tip. Se concedi al bot i privilegi di amministratore della chat, il bot si occuperà automaticamente di eliminare i comandi inviati per tenere la chat pulita._
🏛 *Termini e condizioni*
_Noi non siamo custodi dei tuoi fondi. Agiremo sempre nel tuo migliore interesse, ma siamo consapevoli che operare senza il riconoscimento formale dei Clienti (KYC) è un terreno accidentato finché non troviamo qualche soluzione alternativa. Qualsiasi ammontare caricato nel wallet sarà formalmente considerato una donazione. Non inviarci tutto il tuo denaro! Sii consapevole che questo bot è ancora in fase di sviluppo, e puoi usarlo a tuo rischio e pericolo._
❤️ *Dona*
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Per favore imposta un nome utente Telegram."""
advancedMessage = """%s
👉 *Comandi in linea*
*send* 💸 Invia alcuni sat a una chat: `%s send <ammontare> [<utente>] [<memo>]`
*receive* 🏅 Richiedi un pagamento: `... receive <ammontare> [<utente>] [<memo>]`
*faucet* 🚰 Crea una distribuzione: `... faucet <totale> <per_utente> [<memo>]`
*tipjar* 🍯 Crea un tipjar: `... tipjar <totale> <per_utente> [<memo>]`
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
⚙️ *Comandi avanzati*
*/transactions* 📊 List transactions
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
enterAmountMessage = """💯 Imposta un ammontare."""
enterUserMessage = """👤 Imposta un utente."""
errorReasonMessage = """🚫 Errore: %s"""
# START
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
startWalletCreatedMessage = """🧮 Wallet creato."""
startWalletReadyMessage = """✅ *Il tuo wallet è pronto.*"""
startWalletErrorMessage = """🚫 Errore di inizializzazione del wallet. Riprova più tardi."""
startNoUsernameMessage = """☝️ Sembra che tu non abbia un nome utente Telegram @username. Non è obbligatorio per utilizzare questo bot, ma consente di abilitare ulteriori funzioni. Per usare al meglio il tuo wallet, imposta un nome utente nelle impostazioni Telegram e poi inserisci /balance in modo che il bot possa aggiornarsi."""
# BALANCE
balanceMessage = """👑 *Il tuo saldo è:* %d sat"""
balanceErrorMessage = """🚫 Non riesco a recupare il tuo saldo. Per favore riprova più tardi."""
# TIP
tipDidYouReplyMessage = """Hai risposto a un messaggio per inviare una mancia? Per rispondere a un messaggio, clicca con il tasto destro -> Rispondi sul tuo computer o fai swipe sul tuo smartphone. Se vuoi inviare direttamente a un altro utente, usa il comando /send."""
tipInviteGroupMessage = """ℹ️ In ogni caso, puoi invitare questo bot in qualsiasi chat di gruppo per incominciare a inviare mance."""
tipEnterAmountMessage = """Hai inserito un ammontare?"""
tipValidAmountMessage = """Hai inserito un ammontare valido?"""
tipYourselfMessage = """📖 Non puoi inviare una mancia a te stesso."""
tipSentMessage = """💸 %d sat inviati a %s."""
tipReceivedMessage = """🏅 %s ti ha inviato una mancia di %d sat."""
tipErrorMessage = """🚫 Invio mancia non riuscito."""
tipUndefinedErrorMsg = """Per favore riprova più tardi."""
tipHelpText = """📖 Ops, non funziona. %s
*Usage:* `/tip <ammontare> [<memo>]`
*Example:* `/tip 1000 meme fantastico!`"""
# SEND
sendValidAmountMessage = """Hai inserito un ammontare valido?"""
sendUserHasNoWalletMessage = """🚫 L'utente %s non ha ancora creato un wallet."""
sendSentMessage = """💸 %d sat inviati a %s."""
sendPublicSentMessage = """💸 %d sat inviati da %s a %s."""
sendReceivedMessage = """🏅 %s ti ha inviato %d sat."""
sendErrorMessage = """🚫 Invio non riuscito."""
confirmSendMessage = """Vuoi inviare un pagamento a %s?\n\n💸 Ammontare: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Invio cancellato."""
errorTryLaterMessage = """🚫 Errore. Per favore riprova più tardi."""
sendSyntaxErrorMessage = """Hai specificato un ammontare e un destinatario? Puoi usare il comando /send per inviare sia a utenti Telegram come %s sia a un indirizzo Lightning del tipo LightningTipBot@ln.tips."""
sendHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/send <ammontare> <utente> [<memo>]`
*Esempio:* `/send 1000 @LightningTipBot Amo questo bot ❤️`
*Esempio:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Hai ricevuto %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
invoiceHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/invoice <ammontare> [<memo>]`
*Esempio:* `/invoice 1000 Grazie!`"""
# PAY
paymentCancelledMessage = """🚫 Pagamento cancellato."""
invoicePaidMessage = """⚡️ Pagamento inviato."""
invoicePublicPaidMessage = """⚡️ Pagamento inviato da %s."""
invalidInvoiceHelpMessage = """Hai inserito una invoice Lightning valida? Prova /send se vuoi inviare fondi a un utente Telegram o a un indirizzo Lightning."""
invoiceNoAmountMessage = """🚫 Non è possibile pagare questa invoice senza specificare un ammontare."""
insufficientFundsMessage = """🚫 Fondi insufficienti. Hai in portafoglio %d sat ma servono almeno %d sat per l'invio."""
feeReserveMessage = """⚠️ Inviare il tuo intero saldo potrebbe non essere possibile a causa della incidenza delle commissioni di rete. Se l'invio non va a buon fine, prova a inviare un ammontare leggermente inferiore."""
invoicePaymentFailedMessage = """🚫 Pagamento non riuscito: %s"""
invoiceUndefinedErrorMessage = """Non è stato possibile pagare questa invoice."""
confirmPayInvoiceMessage = """Vuoi inviare questo pagamento?\n\n💸 Amount: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/pay <invoice>`
*Esempio:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Grazie per la donazione."""
donationErrorMessage = """🚫 Oh no, la tua donazione non è andata a buon fine."""
donationProgressMessage = """🧮 Sto preparando la donazione..."""
donationFailedMessage = """🚫 La donazione non è andata a buon fine: %s"""
donateEnterAmountMessage = """Hai inserito un ammontare?"""
donateValidAmountMessage = """Hai inserito un ammontare valido?"""
donateHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/donate <ammontare>`
*Esepio:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Non sono riuscito a riconoscere una invoice Lightning o un LNURL. Cerca cortesemente di centrare meglio il codice QR oppure prova a ritagliare o ingrandire l'immagine."""
photoQrRecognizedMessage = """✅ Codice QR:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Puoi usare questo LNURL statico per ricevere pagamenti."""
lnurlResolvingUrlMessage = """🧮 Recupero indirizzo..."""
lnurlGettingUserMessage = """🧮 Preparazione pagamento..."""
lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
lnurlHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/lnurl [ammontare] <lnurl>`
*Esempio:* `/lnurl LNURL1DP68GUR...`"""
# LINK
walletConnectMessage = """🔗 *Collega il tuo wallet*
⚠️ Non mostrare mai la URL il codice QR, altrimenti qualcuno potrebbe avere accesso ai tuoi fondi.
- *BlueWallet:* Premi *+ (Aggiungi Portafoglio)*, *Importa portafoglio*, *scansionare un codice QR*, e scansiona il codice QR .
- *Zeus:* Copia la URL qui sotto, premi *Add a new node*, *Import* (incolla la URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Non sono riuscito a collegare il tuo wallet. Per favore riprova più tardi."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Crea una distribuzione di fondi."""
inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione da %s.
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
%s"""
inlineFaucetEndedMessage = """🚰 Distribuzione completata 🍺\n\n🏅 %d sat distribuiti a %d utenti."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
inlineFaucetCancelledMessage = """🚫 Distribuzione cancellata."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Ammontare per utente non è una frazione intera del totale."""
inlineFaucetInvalidAmountMessage = """🚫 Ammontare non valido."""
inlineFaucetSentMessage = """🚰 %d sat inviati a %s."""
inlineFaucetReceivedMessage = """🚰 %s ti ha inviato %d sat."""
inlineFaucetHelpFaucetInGroup = """Crea una distribuzione in un gruppo in cui sia presente il bot oppure usa il 👉 comando in linea (/advanced per ulteriori funzionalità)."""
inlineFaucetHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/faucet <totale> <per_utente>`
*Esempio:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Invia pagamento in una chat."""
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<utente>] [<memo>]"""
inlineResultSendTitle = """💸 Invio %d sat."""
inlineResultSendDescription = """👉 Clicca per inviare %d sat in questa chat."""
inlineSendMessage = """Premi ✅ per ricevere un pagamento da %s.\n\n💸 Ammontare: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
inlineSendCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
sendYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
inlineSendFailedMessage = """🚫 Invio non riuscito."""
inlineSendInvalidAmountMessage = """🚫 L'ammontare deve essere maggiore di 0."""
inlineSendBalanceLowMessage = """🚫 Il tuo saldo è insufficiente (%d sat)."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Richiedi un pagamento in una chat."""
inlineQueryReceiveDescription = """Sintassi: @%s receive <ammontare> [<utente>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Ricevi %d sat."""
inlineResultReceiveDescription = """👉 Clicca per richiedere un pagamento di %d sat."""
inlineReceiveMessage = """Premi 💸 per inviare un pagamento a %s.\n\n💸 Ammontare: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
inlineReceiveCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
inlineReceiveYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
inlineReceiveFailedMessage = """🚫 Pagamento non riuscito."""
inlineReceiveCancelledMessage = """🚫 Pagamento cancellato."""
# COMMANDS
helpCommandStr = """aiuto"""
basicsCommandStr = """informazioni"""
tipCommandStr = """mancia"""
balanceCommandStr = """saldo"""
sendCommandStr = """invia"""
invoiceCommandStr = """invoice"""
payCommandStr = """paga"""
donateCommandStr = """dona"""
advancedCommandStr = """avanzate"""
transactionsCommandStr = """traduzioni"""
logCommandStr = """log"""
listCommandStr = """lista"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """distribuzione"""
tipjarCommandStr = """salvadanaio"""
receiveCommandStr = """ricevi"""
hideCommandStr = """nascondi"""
volcanoCommandStr = """vulcano"""
showCommandStr = """mostra"""
optionsCommandStr = """opzioni"""
settingsCommandStr = """impostazioni"""
saveCommandStr = """salva"""
deleteCommandStr = """cancella"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """Funzione non disponibile."""
cantClickMessage = """Pulsante non selezionabile."""
balanceTooLowMessage = """Saldo non sufficiente."""
# BUTTONS
sendButtonMessage = """✅ Invia"""
payButtonMessage = """✅ Paga"""
payReceiveButtonMessage = """💸 Paga"""
receiveButtonMessage = """✅ Ricevi"""
cancelButtonMessage = """🚫 Cancella"""
collectButtonMessage = """✅ Incassa"""
nextButtonMessage = """Prossimo"""
backButtonMessage = """Indietro"""
acceptButtonMessage = """Consenti"""
denyButtonMessage = """Rifiuta"""
tipButtonMessage = """Mancia"""
revealButtonMessage = """Rivela"""
showButtonMessage = """Mostra"""
hideButtonMessage = """Nascondi"""
joinButtonMessage = """Unisciti"""
optionsButtonMessage = """Opzioni"""
settingsButtonMessage = """Impostazioni"""
saveButtonMessage = """Salva"""
deleteButtonMessage = """Cancella"""
infoButtonMessage = """Info"""
# HELP
helpMessage = """⚡️ *Wallet*
_Questo bot è un Wallet Bitcoin Lightning con cui puoi inviare ricompense via Telegram. Per inviare, aggiungi il bot come partecipante a una chat di gruppo. L'unità di conto per questi invii di piccolo importo è il Satoshi (sat). 100,000,000 sat = 1 Bitcoin. Digita 📚 /basics per maggiori informazioni._
❤️ *Dona*
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`
%s
⚙️ *Comandi*
*/tip* 🏅 Rispondi così a un messaggio per inviare una mancia: `/tip <ammontare> [<memo>]`
*/balance* 👑 Verifica il tuo saldo residuo: `/balance`
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<memo>]`
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<memo>]`
*/pay* ⚡️ Paga attraverso Lightning: `/pay <invoice>`
*/donate* ❤️ Dona per supportare questo progetto: `/donate 1000`
*/advanced* 🤖 Funzioni avanzate.
*/help* 📖 Richiama questo elenco."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Il tuo indirizzo Lightning è `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin è la valuta di internet. È una rete libera e decentralizzata a cui tutti possono partecipare, senza una autorità di controllo centrale. Bitcoin è una moneta ma anche un sistema di pagamento più veloce, sicuro e inclusivo del sistema finanziario tradizionale._
🧮 *Economnics*
_La più piccola unità in cui è divisibile un Bitcoin è un Satoshi (sat) e 100,000,000 sat equivalgono a 1 Bitcoin. Esistono solamente 21 milioni di Bitcoin. Il valore di Bitcoin espresso in valuta tradizionale può variare ogni giorno. In ogni caso, se la tua valuta di riferimento è Bitcoin, 1 sat varrà sempre 1 sat._
⚡️ *Lightning Network*
_Lightning Network è un protocollo di pagamento che consente pagamenti in Bitcoin veloci ed economici, praticamente senza consumare energia. È il sistema che consentirà di diffondere Bitcoin a miliardi di persone nel mondo._
📲 *Lightning Wallets*
_I tuoi fondi conservati in questo bot possono essere mandati a un altro wallet Lightning e viceversa. Altri wallet Lightning per il tuo smartphone sono_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), oppure_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(semplice da usare)_.
📄 *Open Source*
_Questo bot è software libero e_ [open source](https://github.com/LightningTipBot/LightningTipBot) _. Puoi farlo girare sul tuo computer e usarlo per la tua comunità._
✈️ *Telegram*
_Aggiungi questo bot a una chat di gruppo Telegram per inviare una /tip. Se concedi al bot i privilegi di amministratore della chat, il bot si occuperà automaticamente di eliminare i comandi inviati per tenere la chat pulita._
🏛 *Termini e condizioni*
_Noi non siamo custodi dei tuoi fondi. Agiremo sempre nel tuo migliore interesse, ma siamo consapevoli che operare senza il riconoscimento formale dei Clienti (KYC) è un terreno accidentato finché non troviamo qualche soluzione alternativa. Qualsiasi ammontare caricato nel wallet sarà formalmente considerato una donazione. Non inviarci tutto il tuo denaro! Sii consapevole che questo bot è ancora in fase di sviluppo, e puoi usarlo a tuo rischio e pericolo._
❤️ *Dona*
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Per favore imposta un nome utente Telegram."""
advancedMessage = """%s
👉 *Comandi in linea*
*send* 💸 Invia alcuni sat a una chat: `%s send <ammontare> [<utente>] [<memo>]`
*receive* 🏅 Richiedi un pagamento: `... receive <ammontare> [<utente>] [<memo>]`
*faucet* 🚰 Crea una distribuzione: `... faucet <totale> <per_utente> [<memo>]`
*tipjar* 🍯 Crea un tipjar: `... tipjar <totale> <per_utente> [<memo>]`
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
⚙️ *Comandi avanzati*
*/transactions* 📊 List transactions
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
enterAmountMessage = """💯 Imposta un ammontare."""
enterUserMessage = """👤 Imposta un utente."""
errorReasonMessage = """🚫 Errore: %s"""
# START
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
startWalletCreatedMessage = """🧮 Wallet creato."""
startWalletReadyMessage = """✅ *Il tuo wallet è pronto.*"""
startWalletErrorMessage = """🚫 Errore di inizializzazione del wallet. Riprova più tardi."""
startNoUsernameMessage = """☝️ Sembra che tu non abbia un nome utente Telegram @username. Non è obbligatorio per utilizzare questo bot, ma consente di abilitare ulteriori funzioni. Per usare al meglio il tuo wallet, imposta un nome utente nelle impostazioni Telegram e poi inserisci /balance in modo che il bot possa aggiornarsi."""
# BALANCE
balanceMessage = """👑 *Il tuo saldo è:* %d sat"""
balanceErrorMessage = """🚫 Non riesco a recupare il tuo saldo. Per favore riprova più tardi."""
# TIP
tipDidYouReplyMessage = """Hai risposto a un messaggio per inviare una mancia? Per rispondere a un messaggio, clicca con il tasto destro -> Rispondi sul tuo computer o fai swipe sul tuo smartphone. Se vuoi inviare direttamente a un altro utente, usa il comando /send."""
tipInviteGroupMessage = """ℹ️ In ogni caso, puoi invitare questo bot in qualsiasi chat di gruppo per incominciare a inviare mance."""
tipEnterAmountMessage = """Hai inserito un ammontare?"""
tipValidAmountMessage = """Hai inserito un ammontare valido?"""
tipYourselfMessage = """📖 Non puoi inviare una mancia a te stesso."""
tipSentMessage = """💸 %d sat inviati a %s."""
tipReceivedMessage = """🏅 %s ti ha inviato una mancia di %d sat."""
tipErrorMessage = """🚫 Invio mancia non riuscito."""
tipUndefinedErrorMsg = """Per favore riprova più tardi."""
tipHelpText = """📖 Ops, non funziona. %s
*Usage:* `/tip <ammontare> [<memo>]`
*Example:* `/tip 1000 meme fantastico!`"""
# SEND
sendValidAmountMessage = """Hai inserito un ammontare valido?"""
sendUserHasNoWalletMessage = """🚫 L'utente %s non ha ancora creato un wallet."""
sendSentMessage = """💸 %d sat inviati a %s."""
sendPublicSentMessage = """💸 %d sat inviati da %s a %s."""
sendReceivedMessage = """🏅 %s ti ha inviato %d sat."""
sendErrorMessage = """🚫 Invio non riuscito."""
confirmSendMessage = """Vuoi inviare un pagamento a %s?\n\n💸 Ammontare: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Invio cancellato."""
errorTryLaterMessage = """🚫 Errore. Per favore riprova più tardi."""
sendSyntaxErrorMessage = """Hai specificato un ammontare e un destinatario? Puoi usare il comando /send per inviare sia a utenti Telegram come %s sia a un indirizzo Lightning del tipo LightningTipBot@ln.tips."""
sendHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/send <ammontare> <utente> [<memo>]`
*Esempio:* `/send 1000 @LightningTipBot Amo questo bot ❤️`
*Esempio:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Hai ricevuto %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
invoiceHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/invoice <ammontare> [<memo>]`
*Esempio:* `/invoice 1000 Grazie!`"""
# PAY
paymentCancelledMessage = """🚫 Pagamento cancellato."""
invoicePaidMessage = """⚡️ Pagamento inviato."""
invoicePublicPaidMessage = """⚡️ Pagamento inviato da %s."""
invalidInvoiceHelpMessage = """Hai inserito una invoice Lightning valida? Prova /send se vuoi inviare fondi a un utente Telegram o a un indirizzo Lightning."""
invoiceNoAmountMessage = """🚫 Non è possibile pagare questa invoice senza specificare un ammontare."""
insufficientFundsMessage = """🚫 Fondi insufficienti. Hai in portafoglio %d sat ma servono almeno %d sat per l'invio."""
feeReserveMessage = """⚠️ Inviare il tuo intero saldo potrebbe non essere possibile a causa della incidenza delle commissioni di rete. Se l'invio non va a buon fine, prova a inviare un ammontare leggermente inferiore."""
invoicePaymentFailedMessage = """🚫 Pagamento non riuscito: %s"""
invoiceUndefinedErrorMessage = """Non è stato possibile pagare questa invoice."""
confirmPayInvoiceMessage = """Vuoi inviare questo pagamento?\n\n💸 Amount: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/pay <invoice>`
*Esempio:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Grazie per la donazione."""
donationErrorMessage = """🚫 Oh no, la tua donazione non è andata a buon fine."""
donationProgressMessage = """🧮 Sto preparando la donazione..."""
donationFailedMessage = """🚫 La donazione non è andata a buon fine: %s"""
donateEnterAmountMessage = """Hai inserito un ammontare?"""
donateValidAmountMessage = """Hai inserito un ammontare valido?"""
donateHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/donate <ammontare>`
*Esepio:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Non sono riuscito a riconoscere una invoice Lightning o un LNURL. Cerca cortesemente di centrare meglio il codice QR oppure prova a ritagliare o ingrandire l'immagine."""
photoQrRecognizedMessage = """✅ Codice QR:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Puoi usare questo LNURL statico per ricevere pagamenti."""
lnurlResolvingUrlMessage = """🧮 Recupero indirizzo..."""
lnurlGettingUserMessage = """🧮 Preparazione pagamento..."""
lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
lnurlHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/lnurl [ammontare] <lnurl>`
*Esempio:* `/lnurl LNURL1DP68GUR...`"""
# LINK
walletConnectMessage = """🔗 *Collega il tuo wallet*
⚠️ Non mostrare mai la URL il codice QR, altrimenti qualcuno potrebbe avere accesso ai tuoi fondi.
- *BlueWallet:* Premi *+ (Aggiungi Portafoglio)*, *Importa portafoglio*, *scansionare un codice QR*, e scansiona il codice QR .
- *Zeus:* Copia la URL qui sotto, premi *Add a new node*, *Import* (incolla la URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Non sono riuscito a collegare il tuo wallet. Per favore riprova più tardi."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Crea una distribuzione di fondi."""
inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione da %s.
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
%s"""
inlineFaucetEndedMessage = """🚰 Distribuzione completata 🍺\n\n🏅 %d sat distribuiti a %d utenti."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
inlineFaucetCancelledMessage = """🚫 Distribuzione cancellata."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Ammontare per utente non è una frazione intera del totale."""
inlineFaucetInvalidAmountMessage = """🚫 Ammontare non valido."""
inlineFaucetSentMessage = """🚰 %d sat inviati a %s."""
inlineFaucetReceivedMessage = """🚰 %s ti ha inviato %d sat."""
inlineFaucetHelpFaucetInGroup = """Crea una distribuzione in un gruppo in cui sia presente il bot oppure usa il 👉 comando in linea (/advanced per ulteriori funzionalità)."""
inlineFaucetHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/faucet <totale> <per_utente>`
*Esempio:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Invia pagamento in una chat."""
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<utente>] [<memo>]"""
inlineResultSendTitle = """💸 Invio %d sat."""
inlineResultSendDescription = """👉 Clicca per inviare %d sat in questa chat."""
inlineSendMessage = """Premi ✅ per ricevere un pagamento da %s.\n\n💸 Ammontare: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
inlineSendCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
sendYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
inlineSendFailedMessage = """🚫 Invio non riuscito."""
inlineSendInvalidAmountMessage = """🚫 L'ammontare deve essere maggiore di 0."""
inlineSendBalanceLowMessage = """🚫 Il tuo saldo è insufficiente (%d sat)."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Richiedi un pagamento in una chat."""
inlineQueryReceiveDescription = """Sintassi: @%s receive <ammontare> [<utente>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Ricevi %d sat."""
inlineResultReceiveDescription = """👉 Clicca per richiedere un pagamento di %d sat."""
inlineReceiveMessage = """Premi 💸 per inviare un pagamento a %s.\n\n💸 Ammontare: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
inlineReceiveCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
inlineReceiveYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
inlineReceiveFailedMessage = """🚫 Pagamento non riuscito."""
inlineReceiveCancelledMessage = """🚫 Pagamento cancellato."""
# LNURLCASH
lnurlcashDisabledMessage = """🚫 Le note LNURLcash non sono attive su questo bot."""
lnurlcashStartPrivateFirstMessage = """👋 Avvia prima una chat privata con me, poi riprova."""
noteHelpMessage = """🎫 *Note LNURLcash*\n\n_Una nota è un link al portatore del valore di un numero fisso di sat. Chi la scansiona per primo riceve i sat._\n\n*/note* 🎫 Crea una nota: `/note <importo> [memo]`\n*/notes* 📚 Elenca le tue note e i tuoi lotti: `/notes`\n*/notes* 📚 Crea un lotto: `/notes <importo> x <numero> [memo]`\n*/redeem* 📥 Aggiunge una nota ricevuta al tuo saldo (oppure incollala e basta): `/redeem <nota>`\n*/lnurlmints* 🏭 Mostra i mint e imposta quello predefinito: `/lnurlmints`\n*/lnurlhelp* 📖 Mostra questo aiuto: `/lnurlhelp`"""
notesHelpMessage = """📖 Uso: `/notes` oppure `/notes <importo> x <numero> [memo]`"""
redeemHelpMessage = """📖 Uso: `/redeem <nota>` — oppure incolla la nota o invia una foto del suo codice QR in chat privata."""
noteConfirmMessage = """🎫 *Creare %d nota/e?*\n\n💸 Valore: %s sat ciascuna\n🏦 Commissione del mint: %s sat\n💰 Totale: %s sat\n🏭 Mint: %s"""
noteViewMemo = """\n✉️ %s"""
noteCreateButton = """✅ Crea"""
noteChangeMintButton = """🏭 Cambia mint"""
noteCancelButton = """🚫 Annulla"""
noteCancelledMessage = """🚫 Annullato."""
noteCreatingMessage = """🧮 Sto creando la tua nota, può volerci un momento..."""
noteCreatedMessage = """🎫 Nota da *%s sat* creata (id `%s`).\n\nCondividi il codice QR o questo link. Vince la prima scansione:\n`%s`"""
noteGroupMessage = """🎫 Una nota da *%s sat* di %s. Vince la prima scansione!\n\n`%s`"""
noteGroupClaimedMessage = """✅ Questa nota da %s sat è stata riscattata."""
noteGroupWithdrawnMessage = """↩️ Questa nota da %s sat è stata ritirata da chi l'ha creata."""
noteReceiptMessage = """🧾 *Nota pubblicata nel gruppo*\n\n💸 Valore: %s sat\n🏦 Commissione del mint: %s sat\n🏭 Mint: %s\n🆔 `%s`\n\n`%s`"""
noteReclaimButton = """↩️ Recupera"""
noteStatusButton = """🔎 Controlla stato"""
noteShowQrButton = """🔳 Mostra QR"""
noteStatusLiveMessage = """🟢 La nota non è ancora stata riscattata e vale %s sat."""
noteStatusClaimedMessage = """✅ La nota è stata riscattata."""
noteStatusPendingMessage = """⏳ Il mint sta ancora elaborando un'operazione su questa nota. Riprova tra un momento."""
noteStatusOtherMessage = """ℹ️ Stato della nota: %s"""
noteInFlightMessage = """⏳ Ancora in corso: il pagamento Lightning al mint non è ancora stato completato. La completo in background e ti avviso."""
noteReclaimRequestedMessage = """↩️ Recupero di %s sat richiesto. Ti avviserò all'arrivo."""
noteReclaimedMessage = """↩️ %s sat della nota `%s` sono tornati nel tuo saldo."""
noteClaimedNotifyMessage = """✅ La tua nota `%[2]s` da %[1]s sat è stata riscattata. %[3]s"""
noteBatchDigestMessage = """✅ %d nota/e del lotto `%s` sono state riscattate (%d su %d finora)."""
noteNothingToReclaimMessage = """ℹ️ Non c'è nulla da recuperare su questa nota."""
noteNotOwnerMessage = """🚫 Quella nota non è tua."""
noteOnlyOneMintMessage = """ℹ️ È disponibile un solo mint."""
noteCapValueMessage = """🚫 Una nota deve valere tra %d e %d sat (al massimo %d sat in un gruppo)."""
noteCapBatchMessage = """🚫 Un lotto può contenere al massimo %d note e %d sat in totale."""
noteCapOutstandingMessage = """🚫 Hai già troppe note non riscattate (limite: %d note o %d sat)."""
noteInsufficientFundsMessage = """🚫 Il tuo saldo non copre la nota, la commissione del mint e la riserva di routing Lightning (almeno 1 sat)."""
noteMintUnavailableMessage = """🚫 Il mint non è disponibile al momento. Riprova più tardi."""
noteMintRangeMessage = """🚫 Il mint non accetta questo importo."""
noteErrorMessage = """🚫 Qualcosa è andato storto. Riprova più tardi."""
noteStateLive = """non riscattata"""
noteStateClaimed = """riscattata"""
noteStateReclaiming = """in recupero"""
noteStateReclaimed = """recuperata"""
noteStateFailed = """fallita"""
noteStatePending = """in sospeso"""
noteViewMessage = """🎫 *Nota* `%s`\n\n💸 Valore: %s sat\n📍 Stato: %s\n🏭 Mint: %s\n🕓 Creata: %s"""
notesListHeader = """🎫 *Le tue note e i tuoi lotti* (%d, pagina %d/%d)"""
notesListEmpty = """Non hai ancora note. Creane una con `/note <importo>`."""
notesListItem = """%s %s sat · %s %s"""
notesBatchItem = """📦 %d × %s sat · %d non riscattate, %d riscattate · %s"""
notesBatchOpenMessage = """📦 *Lotto* `%s`\n\n🎫 %d note da %s sat\n🏭 Mint: %s\n🕓 Creato: %s\n\n🟢 Non riscattate: %d\n✅ Riscattate: %d\n↩️ Recuperate: %d\n⏳ Altre: %d"""
notesExportPdfButton = """📄 PDF"""
notesExportJsonButton = """🧾 JSON"""
notesExportCsvButton = """📊 CSV"""
notesExportCaption = """%d nota/e non riscattata/e del lotto `%s`. Tieni questo file privato: contiene le note stesse."""
notesRefreshButton = """🔄 Aggiorna stato"""
notesReclaimUnclaimedButton = """↩️ Recupera le non riscattate"""
notesBatchProgressMessage = """🧮 Creazione delle note... %d/%d\n%s"""
notesBatchCreatedMessage = """📦 %d note su %d create (lotto `%s`)."""
notesBatchPartialMessage = """⚠️ Alcune note non sono state create: %s\nI fondi rimanenti tornano nel tuo saldo."""
notesBatchFormatMessage = """Scegli un formato per esportare le note:"""
notesBatchReclaimMessage = """↩️ Recupero richiesto per %d nota/e."""
redeemPreviewMessage = """🎫 Questa nota vale *%s sat* presso `%s`.\n\nAggiungerla al tuo saldo?"""
redeemUnknownMintWarning = """⚠️ Questo mint non è nella lista di questo bot. Riscatta a tuo rischio."""
redeemAddButton = """💰 Aggiungi al saldo"""
redeemInFlightMessage = """⏳ Riscatto in corso..."""
redeemRequestedMessage = """⏳ Il mint sta pagando %s sat. Ti avviserò all'arrivo."""
redeemDoneMessage = """✅ %s sat della nota sono stati aggiunti al tuo saldo."""
redeemPendingMessage = """⏳ Il mint sta ancora elaborando un'operazione su questa nota. Riprova tra un momento."""
redeemNotANoteMessage = """🚫 Questa non è una nota LNURLcash."""
redeemFractionalMessage = """🚫 Il valore di questa nota non è un numero intero di sat e non è stato possibile dividerla."""
redeemOwnNoteMessage = """ℹ️ Questa è una delle tue note. Usa invece il suo pulsante Recupera."""
redeemCancelledMessage = """🚫 Riscatto annullato."""
lnurlmintsHeader = """🏭 *Mint LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · commissione: %s"""
lnurlmintsNoFee = """nessuna"""
lnurlmintsFee = """%s sat + %s%% dell'importo"""
lnurlmintsSetButton = """Usa %s"""
lnurlmintsSetMessage = """⭐️ %s è ora il tuo mint predefinito."""

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