Compare commits

..
559 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
callebtcandGitHub 7c55e40966 Add setting file (#497)
* add user currency for incoming payments

* also add currency to incoming LNURL payments

* add setting file
2023-12-05 16:02:42 +01:00
callebtcandGitHub 5adf090969 Display fiat currency (#496)
* add user currency for incoming payments

* also add currency to incoming LNURL payments
2023-12-05 15:54:53 +01:00
callebtcandGitHub 0be3d26e56 do not store lnurl comments below amount threshold (#493) 2023-11-23 11:59:35 -03:00
callebtcandGitHub 8b2fb73fe8 allow lnurlp comments only for 21 sats or more (#491) 2023-11-15 21:36:37 -03:00
callebtcandGitHub 7ba59512de lnurlp: filter links for small payments (#490) 2023-11-15 21:31:56 -03:00
callebtcandGitHub 432da6da71 disable preview in lnurl comments (#488) 2023-11-14 11:02:31 -03:00
callebtcandGitHub 532dbfe23b show error on wrong send message (#487) 2023-10-31 21:15:44 -03:00
gohumbleandGitHub d88b04afb9 update inputmode to decimal (ios keyboard) (#416) 2023-08-13 15:17:50 +02:00
Massimo MusumeciandGitHub c4f6d31779 Fix in config example file (#472)
* added massmux full install guide

* config example file fix
2023-08-13 15:17:32 +02:00
callebtcandGitHub 991954493b add amountsMap (#483) 2023-08-13 15:12:56 +02:00
307780200a add logs (#479)
* added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits

* Revert "added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits"

This reverts commit 69e66450a3e6b5d3296280675c51ac54ded09d01.

* update CommentAllowed

* update donate

* fix amount

* Update database.go

---------

Co-authored-by: gohumble <humble@gmail.com>
2023-06-29 14:44:56 +02:00
gohumbleandGitHub 6a9c5f4a8a fix amount (#478)
* added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits

* Revert "added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits"

This reverts commit 69e66450a3e6b5d3296280675c51ac54ded09d01.

* update CommentAllowed

* update donate

* fix amount
2023-06-29 13:40:45 +02:00
gohumbleandGitHub 8e9c03d0e5 update CommentAllowed and donate
* update CommentAllowed

* update donate
2023-06-29 13:28:41 +02:00
calleandGitHub 84951d525c max relays (#476) 2023-03-25 02:55:47 +01:00
calleandGitHub 6e6fb5d183 feedback (#474) 2023-02-28 14:11:50 +01:00
calleandGitHub a65bf8d6f7 nostr: respond on empty command for new users (#473) 2023-02-28 13:55:26 +01:00
tlindiandGitHub aeb0c4a728 Create fi.toml Translate-Finnish (#469)
* Create fi.toml Translate-Finnish

* Update localize.go
2023-02-24 19:45:24 +01:00
calleandGitHub 722c9c3c83 add /zap command for /tip (#468) 2023-02-23 23:06:34 +01:00
Massimo MusumeciandGitHub b4310b0efd added massmux full install guide (#467) 2023-02-23 10:03:55 +01:00
calleandGitHub 1090b38b73 zaps: remove necessity to add pubkey (#465) 2023-02-21 15:43:07 +01:00
calleandGitHub 4fb4f54b5d Nostr/brrrr (#463)
* readd brr

* readd brrrrr
2023-02-18 16:36:05 +01:00
calleandGitHub ba256a1452 nostr logging and new relays (#462) 2023-02-18 15:59:36 +01:00
calleandGitHub 4769764c98 Merge pull request #461 from LightningTipBot/nostr/fix_nip057_pubkey
nostr: add bot pubkey to LNURLFirst not users
2023-02-17 14:51:48 +01:00
callebtc ed17953a82 nostr: add bot pubkey to LNURLFirst not users 2023-02-17 14:51:08 +01:00
calleandGitHub 7f0c6356c3 Merge pull request #459 from LightningTipBot/nostr/nip05_add_files
add files
2023-02-16 21:20:32 +01:00
callebtc 91cbf83733 add files 2023-02-16 21:20:08 +01:00
calleandGitHub e7d1f9e7c3 add nip05 (#458) 2023-02-16 20:51:22 +01:00
calleandGitHub cc4cb1cb01 Merge pull request #457 from LightningTipBot/nostr/relay_time
clean url and wait for connect
2023-02-16 19:00:52 +01:00
callebtc bdaf46c78b clean url and wait for connect 2023-02-16 19:00:29 +01:00
calleandGitHub 4c3cb071f2 Merge pull request #456 from LightningTipBot/nostr/e_tag_optional
nostr: optional e
2023-02-16 17:00:50 +01:00
callebtc 3a6771934b nostr: optional e 2023-02-16 17:00:20 +01:00
calleandGitHub 63cbd57bc9 Merge pull request #455 from LightningTipBot/nostr/moar_relays
moar relays
2023-02-16 16:08:53 +01:00
callebtc a712f52a15 moar relays 2023-02-16 16:07:14 +01:00
calleandGitHub 603dbaa6a5 Merge pull request #454 from LightningTipBot/nostr/logging
log nostr event id
2023-02-16 13:14:39 +01:00
callebtc 1a2776ab24 log nostr event id 2023-02-16 13:13:08 +01:00
calleandGitHub b9cddbeedd Merge pull request #453 from LightningTipBot/nostr/nip57-fix-parser
fix nostr parser
2023-02-16 12:59:58 +01:00
callebtc 40e7fcaa5c fix nostr parser 2023-02-16 12:58:59 +01:00
calleandGitHub c8ef698a88 Merge pull request #452 from LightningTipBot/nostr/add_files
Nostr: add files
2023-02-16 12:33:37 +01:00
callebtc 7ab3d4627a add files 2023-02-16 12:33:19 +01:00
calleandGitHub a157521c1a Merge pull request #451 from LightningTipBot/zaps
nip57 zaps
2023-02-16 12:31:49 +01:00
callebtc 4318b48c3c nip57 zaps 2023-02-16 12:29:17 +01:00
calleandGitHub 01a8e3bd91 Merge pull request #449 from LightningTipBot/fix/api_memo
fix: memo in api
2023-02-06 12:41:36 +01:00
callebtc 8dabb381ab fix: memo in api 2023-02-06 12:41:14 +01:00
calleandGitHub 681bf390b3 Merge pull request #447 from LightningTipBot/fix/group_help
group help
2023-01-22 10:29:28 +01:00
callebtc 51f2812ac6 group help 2023-01-22 10:29:06 +01:00
calleandGitHub 6d0bc87f15 Merge pull request #446 from LightningTipBot/kick
group join ticket
2023-01-22 10:26:52 +01:00
callebtc b3bbe614ff fix strings 2023-01-22 10:26:24 +01:00
gohumble 3ea9ef0684 fix text 2023-01-20 21:10:10 +01:00
gohumble 97226991ac fix webhook 2023-01-20 20:44:19 +01:00
gohumble 0225a5998a added tryLoadUserInterceptor 2023-01-20 20:41:46 +01:00
callebtc 56318b3d0b fixes 2023-01-20 17:24:24 +01:00
gohumble ab5da78e39 commission 2023-01-19 16:27:11 +01:00
gohumble 9271668e94 cleanup 2023-01-19 15:55:53 +01:00
gohumble 7eaef102dd rename 2023-01-19 14:44:10 +01:00
gohumble ab00715f51 reset 2023-01-19 14:25:20 +01:00
gohumble 7204d85837 kick ticket initial commit 2023-01-19 14:22:45 +01:00
calleandGitHub 84fe1d7cc2 Merge pull request #445 from LightningTipBot/disable_gpt
disable gpt and remove from help
2023-01-17 00:45:02 +01:00
callebtc 0efc5c4e43 disable gpt and remove from help 2023-01-17 00:44:15 +01:00
calleandGitHub 9e64dbb2fd Merge pull request #444 from LightningTipBot/fix/remove_send_button_temp
remove send button until fixed
2023-01-16 23:30:33 +01:00
callebtc 058278046f remove send button until fixed 2023-01-16 23:30:10 +01:00
calleandGitHub 998967c81e Merge pull request #442 from LightningTipBot/lnurl/advanced_help
add memo to lnurl command
2023-01-14 19:02:13 +01:00
callebtc 1a21a1519f add memo to lnurl command 2023-01-14 19:01:56 +01:00
calleandGitHub c47038fa1c Merge pull request #441 from LightningTipBot/fix/nil_successaction
nil check for successaction context
2023-01-14 18:33:19 +01:00
callebtc 2c76764421 nil check for successaction context 2023-01-14 18:32:49 +01:00
calleandGitHub b0e43f17f0 Merge pull request #440 from LightningTipBot:fix/lnurlp/successaction-url-no-preview
no preview for urls
2023-01-14 18:27:48 +01:00
callebtc 120d7c4419 no preview for urls 2023-01-14 18:27:30 +01:00
calleandGitHub 73d87fc4bb Merge pull request #439 from LightningTipBot/lnurl/successAction
add successaction
2023-01-14 18:23:13 +01:00
callebtc 2f61a96e87 add successaction 2023-01-14 18:21:53 +01:00
calleandGitHub 3112b79c0d Merge pull request #437 from LightningTipBot/shop/remove_limit
shop: remove limit
2022-12-25 13:30:02 +01:00
callebtc b50270fe0a remove limit 2022-12-25 13:29:25 +01:00
gohumbleandGitHub 8598adb280 added chatGPT (#435) 2022-12-11 19:12:34 +01:00
calleandGitHub 74e9f7aabf Merge pull request #434 from LightningTipBot/translation/fr/fix_lnurl
fix: fr translation lnurl message
2022-12-08 14:38:36 +01:00
callebtc 8b32e5fda5 fix: fr translation lnurl message 2022-12-08 14:37:41 +01:00
gohumbleandGitHub d264650207 #432 return default http client for empty socks host configuration (#433) 2022-11-28 19:33:02 +01:00
gohumbleandGitHub c611969feb moved translation (#431) 2022-11-03 10:15:48 +01:00
sifrantandGitHub 01f4cff348 Translation cz (#425) 2022-11-03 10:04:58 +01:00
gohumbleandGitHub a67ec62054 added isOnionRegex (#430) 2022-11-03 09:32:38 +01:00
gohumbleandGitHub 895fd06a14 added GetClientForScheme (#429) 2022-11-03 09:20:32 +01:00
ChuckNorrisonandGitHub ed5ceeb095 typo in example config (#426)
fix example config filename in installation instructions
2022-10-27 20:02:52 +02:00
gohumbleandGitHub bc8c8f952a trim whitespaces in send handler (#424) 2022-10-20 09:36:59 +02:00
gohumbleandGitHub 64055db1a5 sse fix (#422)
* fix sse

* close c
2022-10-06 14:18:29 +02:00
gohumbleandGitHub ec679d5e6b removed connection keep alive header (#421) 2022-10-06 09:48:23 +02:00
gohumbleandGitHub 9e8958ece2 Update pl.toml (#419)
fix polish help text from #417
2022-09-25 20:48:27 +02:00
7a2aba59ff add polish (#417)
* add polish

* Update localize.go

LoadMessageFile

Co-authored-by: Maciej Sołtysiak <maciej@soltysiak.com>
Co-authored-by: gohumble <55599638+gohumble@users.noreply.github.com>
2022-09-25 20:25:27 +02:00
calleandGitHub 62d7dd965e Merge pull request #418 from LightningTipBot/fix/api_user_lookup
fix api lookup
2022-09-18 00:41:56 +03:00
callebtc 32a5863b25 fix api lookup 2022-09-18 00:41:14 +03:00
gohumbleandGitHub 45931c087a decode lnurl using strict functions (#415) 2022-09-07 18:47:52 +02:00
gohumbleandGitHub c561ae24d3 updated golnurl (#414) 2022-09-07 18:12:25 +02:00
calleandGitHub d5ff4867c0 Merge pull request #413 from LightningTipBot/dalle_logging_update
krass
2022-08-31 22:42:51 +02:00
callebtc 1f5a6a5a31 krass 2022-08-31 22:42:19 +02:00
calleandGitHub e8f24d99ee Merge pull request #412 from LightningTipBot/buttonfix123
button fix
2022-08-31 22:38:16 +02:00
callebtc b9bf071de9 button fix 2022-08-31 22:36:16 +02:00
gohumbleandGitHub ced9446287 update error handling and logs (#411) 2022-08-31 21:02:35 +02:00
gohumbleandGitHub 94ed7d4692 dalle admin api. Added configurable worker (#410) 2022-08-31 20:09:55 +02:00
gohumbleandGitHub d3c2fe7117 disable dalle if key is empty (#409) 2022-08-31 19:32:24 +02:00
calleandGitHub 5c950ef1be Merge pull request #408 from LightningTipBot/webapp_remove_href
remove href
2022-08-31 16:54:59 +02:00
callebtc 51ac159072 remove href 2022-08-31 16:54:19 +02:00
gohumbleandGitHub 857649150d fix format (#407) 2022-08-31 16:07:04 +02:00
calleandGitHub 842a037029 Merge pull request #404 from LightningTipBot/mutex_states
jobchan
2022-08-31 15:54:05 +02:00
gohumble 5aa76f86da Merge remote-tracking branch 'origin/mutex_states' into mutex_states
# Conflicts:
#	internal/telegram/generate.go
2022-08-31 15:47:56 +02:00
gohumble e170394eb8 add workerId 2022-08-31 15:44:29 +02:00
calleandGitHub 65842b056d Merge pull request #406 from LightningTipBot/buttons/help
readd help button
2022-08-31 15:36:21 +02:00
callebtc 979d3c58a2 readd help button 2022-08-31 15:35:47 +02:00
callebtc b4cb695e33 merge with main 2022-08-31 11:02:09 +02:00
callebtc 89552a73b7 changes from main 2022-08-31 10:58:50 +02:00
calleandGitHub d5f18a0d3a Merge pull request #405 from LightningTipBot/dalle_errormsgs
error feedback
2022-08-30 23:38:44 +02:00
callebtc e24490b05c error feedback 2022-08-30 23:38:17 +02:00
gohumble f288bb05f6 added jobchan and 2 workers 2022-08-30 23:23:40 +02:00
gohumble 3055f6d317 mutex state 2022-08-30 23:00:07 +02:00
calleandGitHub f19a6dd6cc Merge pull request #403 from LightningTipBot/dalle_refund_username
username for refund
2022-08-30 21:50:48 +02:00
callebtc cd55ee075b username for refund 2022-08-30 21:50:29 +02:00
calleandGitHub 9d3f856d02 Merge pull request #402 from LightningTipBot/dalle_require_private_chat
require private chat interceptor
2022-08-30 21:30:19 +02:00
gohumble f2b59140fa add deadlines 2022-08-30 21:26:42 +02:00
calleandGitHub c21d42d1e8 Merge pull request #401 from LightningTipBot/dalle_timeout_increase
Dalle timeout increase
2022-08-30 19:55:32 +02:00
callebtc 2dd2dde231 times 2022-08-30 19:53:19 +02:00
callebtc 5e3432fe32 timeout 5m 2022-08-30 19:52:36 +02:00
calleandGitHub c6df59e51b Merge pull request #400 from LightningTipBot/dalle_retry1
Dalle retry1
2022-08-30 19:46:56 +02:00
gohumble b4081df2fa Merge remote-tracking branch 'origin/dalle_retry1' into dalle_retry1 2022-08-30 19:46:21 +02:00
gohumble 9b9ceb8793 add deadlines 2022-08-30 19:46:04 +02:00
callebtc 3069126971 werks 2022-08-30 19:35:05 +02:00
callebtc b56f5e73b0 refund message 2022-08-30 19:12:47 +02:00
callebtc 42efc918c1 mutex 2022-08-30 19:07:24 +02:00
callebtc 8c75f2f947 refund 2022-08-30 19:05:38 +02:00
callebtc 7d9c0d0c8a retry 2022-08-30 18:56:05 +02:00
calleandGitHub b77f92c9b2 Merge pull request #399 from LightningTipBot/dalle2_deactivate
deactivate
2022-08-30 18:37:14 +02:00
callebtc ec2de611e4 deactivate 2022-08-30 18:36:42 +02:00
calleandGitHub 1b69313fc5 Merge pull request #398 from LightningTipBot/dalle_fix/fix1
prompt check
2022-08-30 18:18:13 +02:00
callebtc 55fc5eaa54 prompt check 2022-08-30 18:17:47 +02:00
calleandGitHub 6bc6ef215a Merge pull request #397 from LightningTipBot/dalle
Dalle
2022-08-30 18:06:42 +02:00
callebtc 52ac3bfc13 fix kraut 2022-08-30 18:06:16 +02:00
callebtc fea7281e29 lesgo 2022-08-30 18:05:01 +02:00
gohumble d992d5858f error handling 2022-08-30 17:51:43 +02:00
gohumble 2569f0d12e error handling 2022-08-30 17:50:48 +02:00
gohumble 6bdd24e4a3 downloadAndSendImages + log 2022-08-30 17:48:56 +02:00
callebtc 3c862d59ff docu 2022-08-30 17:43:30 +02:00
callebtc 2c4d499cd9 add dalle data folder 2022-08-30 17:40:13 +02:00
callebtc 2e4a793c20 dalle config 2022-08-30 17:32:45 +02:00
callebtc 890448ce81 ux 2022-08-30 17:16:38 +02:00
callebtc 08d6a0e369 Merge branch 'main' into dalle 2022-08-30 16:28:17 +02:00
gohumble 069029fbb3 fixes 2022-08-30 16:25:59 +02:00
gohumble 92f9ba1550 added dalle 2022-08-30 16:15:14 +02:00
gohumble 98bc70fc7c update invoice + mock 2022-08-30 15:20:41 +02:00
gohumble 1ee38a2989 initial dalle 2022-08-30 15:01:32 +02:00
calleandGitHub 3353bedc7a Merge pull request #396 from LightningTipBot/lnurlauth/button_text
adjust button text
2022-08-30 10:40:39 +02:00
callebtc 30c1e3231d oof 2022-08-30 10:40:10 +02:00
callebtc a3ed8ab931 adjust button text 2022-08-30 10:39:29 +02:00
calleandGitHub 3772f056a8 Merge pull request #394 from LightningTipBot/webapp/bootstrap6
href on qrcore
2022-08-29 02:42:53 +02:00
callebtc 65d933a6d5 href on qrcore 2022-08-29 02:42:30 +02:00
calleandGitHub 4038a03184 Merge pull request #393 from LightningTipBot/webapp/bootstrap5
fix currency index
2022-08-29 02:34:24 +02:00
callebtc 2c8a653c3a fix currency index 2022-08-29 02:34:09 +02:00
calleandGitHub 03509adcd1 Merge pull request #392 from LightningTipBot/webapp/bootstrap4
fiat floats
2022-08-29 02:25:59 +02:00
callebtc 74655219f3 fiat floats 2022-08-29 02:25:42 +02:00
calleandGitHub 74c057ce8e Merge pull request #391 from LightningTipBot/webapp/bootstrap3
fiat currencies
2022-08-29 02:22:46 +02:00
callebtc 0aeec7e488 fiat currencies 2022-08-29 02:22:25 +02:00
calleandGitHub 921395d283 Merge pull request #390 from LightningTipBot/webapp/bootstrap2
css tweaks
2022-08-29 01:51:23 +02:00
callebtc 9b2c23cab5 css tweaks 2022-08-29 01:51:07 +02:00
calleandGitHub 3c45a80627 Merge pull request #389 from LightningTipBot/webapp/bootstrap
add bootstrap
2022-08-29 01:41:30 +02:00
callebtc 62c2cbab5f add bootstrap 2022-08-29 01:41:07 +02:00
calleandGitHub ab82b49ff5 Merge pull request #388 from LightningTipBot/lnurl/fix_amount
fix amount parser
2022-08-29 00:47:43 +02:00
callebtc 025261d595 fix amount parser 2022-08-29 00:47:11 +02:00
calleandGitHub ed6ea4d33c Merge pull request #387 from LightningTipBot/lnurlp/fiat_price
allow fiat amount in lnurlp server
2022-08-28 22:36:58 +02:00
callebtc 69559f8aff allow fiat amount in lnurlp server 2022-08-28 22:36:04 +02:00
calleandGitHub 00406553e4 Merge pull request #386 from LightningTipBot/webview/number_input
number keyboard
2022-08-28 21:50:41 +02:00
callebtc c237e55a29 number keyboard 2022-08-28 21:50:20 +02:00
calleandGitHub 24b2c2413c Merge pull request #385 from LightningTipBot/webapp/scroll_up
scroll up
2022-08-28 21:32:02 +02:00
callebtc cb19e7375a scroll up 2022-08-28 21:31:35 +02:00
calleandGitHub 55ba146592 Merge pull request #384 from LightningTipBot/webapp/test2
Webapp/test2
2022-08-28 20:43:45 +02:00
callebtc 52230d486e clean 2022-08-28 20:43:18 +02:00
callebtc c8e45de27d invoices 2022-08-28 20:37:45 +02:00
callebtc 6a01936c2e Merge branch 'main' into webapp/test2 2022-08-28 19:28:52 +02:00
calleandGitHub 48374ad2a1 Merge pull request #383 from LightningTipBot/buttons/readd_send
readd send
2022-08-28 19:27:15 +02:00
callebtc 5b5f0ef6a2 readd send 2022-08-28 19:26:49 +02:00
callebtc b618b1aa41 create invoices 2022-08-28 19:16:23 +02:00
calleandGitHub c5f106187f Merge pull request #382 from LightningTipBot/webapp/test1
Webapp/test1
2022-08-28 15:20:42 +02:00
callebtc f35473b010 webapp log 2022-08-28 15:19:40 +02:00
callebtc 359ae13057 remove bs 2022-08-28 15:08:49 +02:00
callebtc 8d0bf2cce7 padding 2022-08-28 15:06:22 +02:00
callebtc f5c3d9fb55 webapp works 2022-08-28 14:59:30 +02:00
calleandGitHub 56c391b24e Merge pull request #381 from LightningTipBot/intercept/callbacks
callback responses
2022-08-27 16:40:56 +02:00
callebtc cbdc8638bd callback responses 2022-08-27 16:39:35 +02:00
calleandGitHub 046baab3e1 Merge pull request #380 from LightningTipBot/paybutton/unique
pay button with unique_id
2022-08-27 15:23:42 +02:00
callebtc f0f3a7c5d0 pay button with unique_id 2022-08-27 15:23:08 +02:00
calleandGitHub 43eb4966bc Merge pull request #379 from LightningTipBot/callebtc-patch-1
Update README.md
2022-08-22 09:43:38 +02:00
calleandGitHub 0d112e19de Update README.md 2022-08-22 09:43:30 +02:00
calleandGitHub 649be03c29 Merge pull request #378 from LightningTipBot/api_auth_refactor
auth refactor
2022-08-22 09:35:54 +02:00
callebtc 5e4c045312 log 2022-08-22 09:35:43 +02:00
callebtc 44f397e2de fix lndhub 2022-08-22 09:32:30 +02:00
callebtc 9451032552 user decoder 2022-08-22 09:13:39 +02:00
callebtc 8180d3cfae auth refactor 2022-08-22 09:09:53 +02:00
calleandGitHub f11ac3d807 Merge pull request #377 from LightningTipBot/sse123
sse
2022-08-21 12:53:33 +02:00
callebtc cb02fd557f sse 2022-08-21 12:52:54 +02:00
calleandGitHub ac3ac51d7b Merge pull request #376 from LightningTipBot/sse123
Sse123
2022-08-21 00:49:50 +02:00
callebtc ac9cc644eb config 2022-08-21 00:48:23 +02:00
gohumble 545898dbbe revert 2022-08-21 00:29:51 +02:00
gohumble d98aa26db9 fix 2022-08-21 00:29:06 +02:00
gohumble 13c0f3b70a increase timeouts 2022-08-21 00:07:31 +02:00
gohumble 3a4f99314d sse 2022-08-21 00:02:48 +02:00
gohumble a0f7cf09e6 sse 2022-08-20 23:22:04 +02:00
callebtc 0ff0d889ff sse 2022-08-20 22:33:05 +02:00
calleandGitHub 7009d3dedc Merge pull request #374 from LightningTipBot/api
Api
2022-08-20 01:05:24 +02:00
callebtc a87eac37b8 remove 2022-08-20 01:04:31 +02:00
callebtc 250c036c47 returns 2022-08-20 01:03:22 +02:00
callebtc df303ae186 invoice 2022-08-20 00:32:20 +02:00
callebtc d0d844fd4f balance check 2022-08-20 00:21:52 +02:00
gohumble dbe94b9494 fix 2022-08-20 00:19:12 +02:00
gohumble d9f373cebb Merge remote-tracking branch 'origin/api' into api
# Conflicts:
#	internal/api/lightning.go
2022-08-20 00:18:54 +02:00
gohumble d066fa9e27 set bot in api service 2022-08-20 00:17:58 +02:00
callebtc 127f95b8de boom 2022-08-20 00:17:19 +02:00
gohumble 98401546fa add user auth 2022-08-19 23:59:23 +02:00
gohumble fbc47c0fb9 fix payments 2022-08-19 23:37:28 +02:00
callebtc 0c29fec19f lnbits stuff 2022-08-19 23:36:11 +02:00
gohumble 4bcbd2fefe add auth middleware 2022-08-19 23:35:27 +02:00
gohumble a669ea86ac add api service 2022-08-19 22:55:27 +02:00
gohumble b396219792 add api service 2022-08-19 22:32:08 +02:00
calleandGitHub 4871b42f22 Merge pull request #373 from LightningTipBot/group/ticketing_name_escape
markdown escape usernames
2022-08-19 22:08:16 +02:00
callebtc 6ff264ab18 markdown escape usernames 2022-08-19 22:07:58 +02:00
calleandGitHub fff933e413 Merge pull request #372 from LightningTipBot/update_lnurl
update go-lnurl
2022-08-17 22:01:31 +02:00
callebtc 36d94ecff8 nitpick 2022-08-17 22:01:10 +02:00
gohumble aaba02020b fix fix 2022-08-17 18:06:16 +02:00
gohumble 02bbc8e5a3 fix typo 2022-08-17 17:49:30 +02:00
gohumble 61fb20e132 update go-lnurl 2022-08-17 17:44:19 +02:00
calleandGitHub 7707fbf4a5 Merge pull request #371 from LightningTipBot:lnurl/fix
again
2022-08-15 00:32:57 +02:00
callebtc dfcf576dce again 2022-08-15 00:32:34 +02:00
calleandGitHub 796abe7f96 Merge pull request #370 from LightningTipBot/lnurlp/turn_off_desc_hash_check
turn off description_hash check
2022-08-15 00:31:19 +02:00
callebtc 52e1fc043a turn off description_hash check 2022-08-15 00:30:27 +02:00
calleandGitHub 3f64ceb6c1 Merge pull request #368 from LightningTipBot/socks5
add socks5. unify client
2022-08-14 23:20:28 +02:00
gohumble 30e0ba9cdf fix example 2022-08-14 23:05:17 +02:00
gohumble f474988606 fix cfg 2022-08-14 22:44:04 +02:00
gohumble 865592b0a6 added ClientType 2022-08-14 22:04:04 +02:00
calleandGitHub 41a4946071 Merge pull request #369 from LightningTipBot:lnurlp/check_description_hash
LNULRp: check for descr hash
2022-08-14 21:53:08 +02:00
callebtc d7dc6f71aa check for descr hash 2022-08-14 21:50:14 +02:00
gohumble d9f2f87739 add socks5. unify client 2022-08-14 21:42:03 +02:00
calleandGitHub 29f03807f2 Merge pull request #366 from LightningTipBot/lnbits/errors
unpickle lnbits errors correctly
2022-08-13 12:20:36 +02:00
callebtc 042ccaf8ef unpickle lnbits errors correctly 2022-08-13 12:18:33 +02:00
calleandGitHub 4ecc65fb27 Merge pull request #365 from LightningTipBot/fix/wallet_check
check wallet nil before balance check
2022-07-26 15:12:25 +02:00
callebtc f73e027e9c check wallet nil before balance check 2022-07-26 15:12:01 +02:00
calleandGitHub b4e8721e3e Merge pull request #364 from LightningTipBot/link/silent_edit
hide link silently
2022-07-17 20:32:59 +02:00
callebtc dd87d4f6f8 hide link silently 2022-07-17 20:32:35 +02:00
calleandGitHub 8033d05f7e Merge pull request #363 from LightningTipBot/update/zeus_help
Update/zeus help
2022-07-17 20:18:20 +02:00
callebtc c27de372a5 update zeus help 2022-07-17 20:15:58 +02:00
callebtc bc849c5b03 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-06-14 16:06:27 +02:00
calleandGitHub 6f2a95609e Tip error (#362)
* tip no error message
2022-06-14 16:06:16 +02:00
callebtc d6e9f49cd1 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-06-01 19:17:53 +02:00
d2a63c07a3 Transactions int64 amount (#356)
* webln and image

* transactions with int64 amounts

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-31 10:49:42 +02:00
callebtc 8729011aaf Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-29 16:18:00 +02:00
calleandGitHub 5199e4c8c6 Anon lnurl help message (#354)
* webln and image

* anon lnurl output
2022-05-29 16:17:23 +02:00
callebtc e5928defd0 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-29 16:11:17 +02:00
calleandGitHub 1167392140 Stadress: better help (#353)
* webln and image

* Satdress: better logging and help
2022-05-09 13:44:37 +02:00
callebtc cf68245012 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-09 13:34:32 +02:00
calleandGitHub 6c06a4972e Satdress lnd tor (#352)
* webln and image

* Satdress: LND over tor
2022-05-07 21:31:47 +02:00
callebtc e7fa555506 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-07 21:30:25 +02:00
calleandGitHub 666eecf207 Userpages: site name (#351)
* webln and image

* site_name
2022-05-03 18:04:56 +02:00
callebtc 0eaf96749f Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-03 18:03:26 +02:00
calleandGitHub 672402616e webln and image (#350) 2022-05-03 17:32:35 +02:00
callebtc cfde78e639 webln and image 2022-05-03 17:31:31 +02:00
calleandGitHub fce4fb9ecc satdress timeout (#349) 2022-05-02 23:50:23 +02:00
1946a0e873 Satdress: Socks Proxy (2) (#348)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-02 23:36:51 +02:00
LightningTipBotandGitHub fd531e6719 Revert "Satdress: Socks proxy (#346)" (#347)
This reverts commit 94ff302d15.
2022-05-02 23:28:51 +02:00
94ff302d15 Satdress: Socks proxy (#346)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
2022-05-02 23:25:41 +02:00
LightningTipBotandGitHub 631c314b31 Revert "random_colors (#344)" (#345)
This reverts commit 307967b61a.
2022-04-30 13:46:57 +02:00
307967b61a random_colors (#344)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:35:03 +02:00
a53f8e307a Userpage: ln.tips link (#343)
* small note

* rem instead of px

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:08:42 +02:00
6f14fab93b send card template (#342)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:04:42 +02:00
99a866854b send_to_card (#341)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:02:33 +02:00
21f5abbb25 Userpage metadata (#340)
* new pic

* round logo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 11:22:43 +02:00
158990f46d userpage log (#339)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 10:44:06 +02:00
c00196e9d6 design (#338)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 02:30:22 +02:00
410f56aaf5 Userpage (#337)
* userpage init

* page

* files

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-29 22:05:28 +02:00
0631fd53eb WIP: Satdress (#331)
* satdress rebase

* check config

* satdress rebase

* check config

* check for invoices

* return error

* Update inline photo v5 (#332)

* update url

* round logo

* resize

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* new logo (#333)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* help (#334)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add file (#335)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* markdown (#336)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* satdress rebase

* check config

* satdress rebase

* check for invoices

* return error

* satdress works

* add lnbits

* timeout

* error checking

* small lnd

* errors

* button fix

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
2022-04-29 14:28:12 +02:00
afcd530d06 markdown (#336)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:39:12 +02:00
5aaf9452b5 add file (#335)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:35:17 +02:00
b07053172b help (#334)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:20:52 +02:00
6ebb5688fd new logo (#333)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-14 19:49:49 +02:00
2e3a1fe087 Update inline photo v5 (#332)
* update url

* round logo

* resize

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-14 15:35:34 +02:00
calleandGitHub 997faa2c45 increase timeout (#330) 2022-04-11 15:09:14 +02:00
calleandGitHub 048141908e Group help text (#329)
* group help text

* string

* add group to help
2022-04-09 21:20:20 +02:00
900ce09aa6 notify group (#328)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-03-31 23:29:58 +02:00
calleandGitHub bd41dd078b remove telebot on error log (#327) 2022-03-27 23:14:13 +02:00
bf643f103d 🪄 update telebot v3 🤖 (#325)
* 🚧 minor changes to all handlers...

* 🚧 passing callback to tryEditStack

* 🚧 edit and delete callback messages

* 🚧 refactor again

* 🚧 uncomment this

* 🚧 using ctx.Message().Text

* 🚧 refactor

* 🚧 refactor

* 🚧 uncomment

* context not queruy

* 🚧 update forked lightningtipbot

* 🚧 reset ArticleResult

* fix inline receive

* readd shop

* remove chat from shopView

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-03-27 22:19:38 +02:00
bassimandGitHub 23db317c0d Update en.toml (#326)
fixed typos in photoQrNotRecognizedMessage
2022-03-27 11:26:40 +02:00
calleandGitHub 7085b4dbf6 base_fee (#323) 2022-03-17 10:22:47 +01:00
calleandGitHub 9895498237 lower fee (#322) 2022-03-17 09:36:47 +01:00
calleandGitHub 4a93019428 ticket type fix (#321) 2022-03-17 00:29:06 +01:00
71d8aa202c Group invite link management (#310)
* group invite link

* link

* works

* ticketinvoiceevent type

* Add invoice event interface

* add AssertEventType

* generalize AssertEventType invocation

* wip: payment button

* all new

* callback

* fix TicketEvent Key()

* invoiceEvent in ticketEvent

* fix errors

* add payment button

* commission

* minimum price

* remove redundant ticket event data

* commission

* fixes

* update balance

* notify user if ticket < 10

* commission rounding error

* refactor

* refactor

* /join

* add /join handler

* fix handler

* fix /join

* fix handler

* fix /join interceptor

* add startUserInterceptor

* delete qr

* no test blyad

* fix defer

* message

Co-authored-by: gohumble <lngohumble@gmail.com>
2022-03-17 00:21:28 +01:00
gohumbleandGitHub a9f6539eaf 🪄 fix LNURL states redundant initialization (#318) 2022-02-27 15:33:04 +03:00
gohumbleandGitHub 1179800a4b 🪄 fix withdraw state handler (#316) 2022-02-26 10:53:15 +03:00
calleandGitHub a5d8c5d7e5 lnurl amounts same (#315) 2022-02-25 14:11:05 +03:00
0dcf4bd845 fix the tipjar and send a summary (#312)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-17 17:14:25 +01:00
afcbca28f2 faucet md (#309)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-14 20:44:34 +01:00
calleandGitHub 205e75d2d6 markdown fix (#308) 2022-02-11 13:24:03 +01:00
calleandGitHub 6e7886e029 payerdata hash fix (#307) 2022-02-11 12:56:30 +01:00
00b07998e6 Payerdata receive (#306)
* payerdata receive

* more

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 12:40:18 +01:00
calleandGitHub 373b4a9752 payerdata receive (#305) 2022-02-11 12:16:46 +01:00
fa46f06f2e resize image (#304)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:52:57 +01:00
24e321e5ed bot pic (#303)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:47:40 +01:00
725af545ab WIP: adding downloadMyProfilePicture and botProfilePicture to LNURL Meta (#297)
* adding downloadMyProfilePicture and botProfilePicture to serveLNURLFirst (pay)

* fix image download to ram

* add downloadProfilePicture

* add cache and download limit

* error checks

* user picture

* empty entry bug check for uuid

* check

* fix example

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:04:08 +01:00
2b09fc95dd print debug stack on empty annon id update (#299)
* print debug stack on empty annon id update

* write stack to file

* use AnnonID

* set ids

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 22:12:03 +01:00
54beceba32 add empty callback response (#301)
* add empty response

* commend

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 22:03:17 +01:00
70ecf335f2 honkhonk (#302)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 21:30:02 +01:00
d786dc58e0 Unban fix (#300)
* unban fix

* fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-30 20:41:12 +01:00
c72111dfb7 add (#296)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-23 00:57:17 +01:00
902928f794 perform graceful shutdown on SIGTERM and SIGSTOP (#281)
* perform graceful shutdown on SIGTERM and SIGSTOP

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-23 00:48:27 +01:00
96292604c7 adding lnurl auth (#294)
* adding lnurl auth poc

* add response and translation

* refactor

* simpler

* using http bot client with proxy transport

* functions

* translations

* clean

* comment

* revert

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-22 23:25:21 +01:00
9522418272 finish faucet (#295)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-22 14:04:48 +01:00
a112c1b25d add shop db path (#292)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-19 11:25:37 +01:00
72e13e841d faucet fix (#291)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 02:11:25 +01:00
83eb185634 echo fix (#290)
* echo fix

* echo fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 01:11:11 +01:00
dedc959f94 faucet summary (#289)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 00:58:59 +01:00
33776f2616 oops (#288)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-14 20:38:45 +01:00
545d20d043 Mutex fix 329823hf (#287)
* big change

* mutex

* global lock

* another lock

* fix log

* trySendMessageEditable added

* defer before return

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-14 20:34:20 +01:00
9d876cf5d5 stuck fix (#286)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:26:22 +01:00
c6087021b7 fix again (#285)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:20:00 +01:00
7c95daabfd shop stuck fix (#284)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:16:47 +01:00
95a22401b2 shop logging (#283)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-11 00:44:07 +01:00
a7b9506a9f better log (#282)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-11 00:34:59 +01:00
c1fb07fcda mutex return (#280)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 23:44:06 +01:00
5a25f07bfb callback responses (#279)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 22:20:42 +01:00
b6d1ed97f1 failsaves (#278)
* failsaves

* failsafe2

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 21:43:02 +01:00
4e812f7897 add errors to handler (#273)
* add errors to handler

* add errors to handlers

* shop fixes (#274)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* better log (#275)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add errors to map

* more errors

* rename NoWalletError

* fix one panic (#276)

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add invalid type error

* Shop panic attempt 2 (#277)

* less log

* fix shop first view

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* make errors private

* add errors to handler

* add errors to handlers

* add errors to map

* more errors

* rename NoWalletError

* add invalid type error

* make errors private

* patch

* return handlers

* add noPrivateChat

* add invalid amount err

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 21:39:09 +01:00
192930a289 Shop panic attempt 2 (#277)
* less log

* fix shop first view

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 20:01:26 +01:00
7ed34f656b fix one panic (#276)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 19:52:18 +01:00
31250273b0 better log (#275)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 12:16:05 +01:00
e70344892f shop fixes (#274)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 11:08:27 +01:00
39c727d3c4 fix the keyboard, fix the world (#272)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-07 12:13:58 +01:00
02eb0716aa lil update (#270)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-06 10:39:25 +01:00
c706ed7aaf update edit stack (#269)
* update edit stack

* update faucet

* better debug logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-06 10:33:01 +01:00
8c41fba277 no edit stack (#268)
* no edit stack

* fix typo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 22:05:18 +01:00
53c384834a lnurl update (#267)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 10:14:24 +01:00
1e66dd6a68 fix auth (#266)
* fix auth

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 02:32:39 +01:00
gohumbleandGitHub b42a9ae8b4 using UpdateUserRecord (#265) 2022-01-05 01:53:45 +01:00
88143b9a66 fix migration (#264)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 01:43:33 +01:00
8f60cb82f3 add admin service (#263)
* add admin server + service

* string fixes

* ban and unban user

* add return

* ban using admin key

* ban reason

* remove redundant func call

* add http status

* add log

* anon_id_sha256 (#262)

* anon_id_sha256

* refactor sha256 hash to strings package

* oops

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add admin server + service

* ban and unban user

* string fixes

* add return

* ban using admin key

* ban reason

* remove redundant func call

* add http status

* add log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
2022-01-05 01:40:37 +01:00
e275b8760a anon_id_sha256 (#262)
* anon_id_sha256

* refactor sha256 hash to strings package

* oops

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 01:28:17 +01:00
gohumbleandGitHub 01710f3385 separate lnurl and api server (#261)
* separate lnurl and api server

* add lndhub handler and proxy

* update proxy

* fix AppendRoute with empty methods

* add logs

* fix trace

* dump request

* parse bearer token

* exclude banned users

* exclude banned users

* fix log levels
2022-01-05 00:09:11 +01:00
ec319cc691 fix ban (#260)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 13:49:31 +01:00
c6a064b332 Banned entirely (#259)
* do not react to banned users

* do not respond to banned

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 13:32:10 +01:00
615b90ab63 print banned (#258)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 12:56:38 +01:00
a7cf6f957e edit stack fix (#257)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-01 22:26:56 +01:00
e9da937c75 Hotfix edit bug (#256)
* fix edit bug and log faucet better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 22:17:59 +01:00
d0da1560fa New logo (#255)
* speed up tx lock

* yolo master

* upload new logo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 11:13:24 +01:00
113fc02b28 Faucet problem 123 (#254)
* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 11:04:17 +01:00
1459fcb68e Fix link delete message (#253)
* fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-28 15:09:45 +01:00
3d3d7ab2f6 Send keyboard recommendation (#252)
* speed up tx lock

* yolo master

* keyboard with recent contacts

* translate message

* better query

* keyboard pops up

* log level

* skip keyboard if no entry

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-28 12:20:47 +01:00
fdb58a7f2b Fix faucet again (#251)
* speed up tx lock

* yolo master

* fix faucet again

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 19:13:07 +01:00
a9fecc1e8f Fix faucet again 123 (#250)
* speed up tx lock

* yolo master

* skip edit error

* do not return

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:48:58 +01:00
d65d6aad28 Fix faucet edit (#249)
* speed up tx lock

* yolo master

* better printing

* trace

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:31:25 +01:00
95c733459d Fix faucet edit (#248)
* speed up tx lock

* yolo master

* better printing

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:28:06 +01:00
9fe0d776c7 Mini fixes123 (#247)
* speed up tx lock

* yolo master

* fixes

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 23:37:46 +01:00
25dc9d7b34 add edit stack lifo (#231)
* add edit stack lifo

* remove log message

* Finish the faucet (#232)

* speed up tx lock

* yolo master

* finish the faucet when inactive

* delete comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add once + singleton click interceptor (#229)

* speed up tx lock

* yolo master

* add once + singleton click interceptor

* yoooo;

* stuff

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Log oncemap (#233)

* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance button (#236)

* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance on invoice (#237)

* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add mutex http endpoints (#238)

* Faucet balance update (#239)

* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Unlock admin (#240)

* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>

* fix nLocks (#241)

* using shop.base.id (#242)

* using shop.base.id

* using shop.base.id

* using shop.base.id

* Adjust log levels (#244)

* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* fix edit signature rate limiter (#234)

* Skip duplicate edits (#245)

* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* only remove on unlock (#246)

* add edit stack lifo

* finish faucet corrected

* improve edit stack

* edit.go

* uncomment faucet check

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 20:57:38 +01:00
gohumbleandGitHub 01423827b7 Fix shop v1 (#243)
* using shop.base.id

* using shop.base.id

* using shop.base.id

* remove index from delete status messages

* fix delete status messages
2021-12-26 20:46:56 +01:00
gohumbleandGitHub f1df1e6377 only remove on unlock (#246) 2021-12-26 16:58:05 +01:00
1e5f7b1169 Skip duplicate edits (#245)
* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:46:04 +01:00
gohumbleandGitHub 9c6062f317 fix edit signature rate limiter (#234) 2021-12-26 16:37:43 +01:00
fc7247c72a Adjust log levels (#244)
* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:30:27 +01:00
gohumbleandGitHub c23d69e8f1 using shop.base.id (#242)
* using shop.base.id

* using shop.base.id

* using shop.base.id
2021-12-26 15:38:26 +01:00
gohumbleandGitHub 35d5ed8d8e fix nLocks (#241) 2021-12-26 15:12:18 +01:00
07ccc6cc28 Unlock admin (#240)
* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-26 14:51:10 +01:00
2ef798e56a Faucet balance update (#239)
* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 14:46:09 +01:00
gohumbleandGitHub 24e4212a93 add mutex http endpoints (#238) 2021-12-26 14:20:50 +01:00
6851badfab Balance on invoice (#237)
* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:30:41 +01:00
cbedc5c147 Balance button (#236)
* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:05:25 +01:00
373ee844da Log oncemap (#233)
* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 00:33:00 +01:00
151ed39b04 add once + singleton click interceptor (#229)
* speed up tx lock

* yolo master

* add once + singleton click interceptor

* yoooo;

* stuff

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 00:23:58 +01:00
24108f6a1f Finish the faucet (#232)
* speed up tx lock

* yolo master

* finish the faucet when inactive

* delete comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 23:11:31 +01:00
737ab115bd Fix faucet again 1337 (#230)
* speed up tx lock

* yolo master

* fix it

* decrease limit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:52:54 +01:00
13957342df Fix faucet again 1337 (#228)
* speed up tx lock

* yolo master

* fix it

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:43:36 +01:00
fe1a921440 Faucet cool (#227)
* speed up tx lock

* yolo master

* coool

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:30:25 +01:00
39ff25beca Increase rate limit (#226)
* speed up tx lock

* yolo master

* rate limit

* decrease

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:14:53 +01:00
ec15f26c13 Increase rate limit (#225)
* speed up tx lock

* yolo master

* rate limit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:06:52 +01:00
0218191793 fix button space (#224)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 13:53:57 +01:00
5065f5af86 Fix button (#223)
* fix options and what

* fix keyboard

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 12:19:28 +01:00
6aca41835d fix options and what (#222)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 11:39:46 +01:00
6b746447e5 add initial main menu keyboard. (#221)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 02:50:58 +01:00
ca60b271fd Dont cancel faucet (#220)
* speed up tx lock

* yolo master

* faucet cancel not

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 01:42:43 +01:00
gohumbleandGitHub 1b720b498c print faucet link if available (#218) 2021-12-24 18:11:00 +01:00
gohumbleandGitHub 2066470cba send telegram messages async (#219) 2021-12-24 18:10:52 +01:00
73ada1f25b Faucet 1341 (#217)
* speed up tx lock

* yolo master

* faucet fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:32:01 +01:00
43a77fd1b2 Faucet bla 13340 (#216)
* speed up tx lock

* yolo master

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:14:08 +01:00
f968310902 Facuet cancel 1339 (#215)
* speed up tx lock

* cancel better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:10:20 +01:00
32a5a7c264 Faucet cancel 1338 (#214)
* speed up tx lock

* yp

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:02:08 +01:00
776de88041 Cancel faucet better (#213)
* speed up tx lock

* base canceled flag

* oops

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:54:07 +01:00
192a100f8d Cancel faucet if not empty (#212)
* speed up tx lock

* cancel

* check better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:47:54 +01:00
b796db1979 Cancel faucet if not empty (#211)
* speed up tx lock

* cancel

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:39:43 +01:00
gohumbleandGitHub eb07cdf117 disable rl for edit (#210) 2021-12-24 16:35:46 +01:00
9f1ce26d6e Even better faucet logging (#209)
* speed up tx lock

* faucet logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:35:27 +01:00
gohumbleandGitHub 0ce42e8f1f do not cancel inactive faucet (#208)
* fix logs

* remove cancel faucet if not active
2021-12-24 16:04:36 +01:00
46d77de38e fix faucet balance to low panic (#207)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-24 15:57:23 +01:00
09d3af411e Better longging 1337 (#206)
* speed up tx lock

* better logging and lnurl lightning: prefix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 15:34:17 +01:00
5414c82339 Logging mutex fix (#205)
* speed up tx lock

* better logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 15:00:55 +01:00
LightningTipBotandGitHub 2edc2953dc Revert "Min faucet 1 (#203)" (#204)
This reverts commit 2bc9555b53.
2021-12-24 14:46:32 +01:00
2bc9555b53 Min faucet 1 (#203)
* speed up tx lock

* reduce min faucet

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 14:37:49 +01:00
gohumbleandGitHub 47ef5baee3 fix mutex final last v2 maybe (#202)
* remove mutex on unlock

* add pprof

* fix mutex lock

* fix logs
2021-12-24 14:25:35 +01:00
78eadf1a0e Tip fix lock (#201)
* speed up tx lock

* tip fix lock

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 02:43:21 +01:00
gohumbleandGitHub 6aa05c8faa Callback response (#200)
* add answerCallbackInterceptor

* use answerCallbackInterceptor

* fix nil response
2021-12-24 02:22:41 +01:00
8f8644a1d2 Faucet panic (#199)
* speed up tx lock

* remove panic

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 01:45:07 +01:00
f9aed70869 Soft lock (#198)
* add Lock and Unlock soft

* Update mutex.go

* sync mutex

* mutex bracket

* add idInterceptor

* context lock

Co-authored-by: lngohumble <lngohumble@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 00:12:57 +01:00
036ac12f41 Lnurlpay pointer fix (#197)
* speed up tx lock

* fix pointer

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 21:52:58 +01:00
LightningTipBotandGitHub 67cff58c63 Revert "Soft lock (#195)" (#196)
This reverts commit 4730c94c84.
2021-12-23 19:29:14 +01:00
4730c94c84 Soft lock (#195)
* add Lock and Unlock soft

* Update mutex.go

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-23 19:25:55 +01:00
LightningTipBotandGitHub e53ef94306 Revert "add Lock and Unlock soft (#193)" (#194)
This reverts commit a9f2728c93.
2021-12-23 19:08:06 +01:00
gohumbleandGitHub a9f2728c93 add Lock and Unlock soft (#193) 2021-12-23 19:06:15 +01:00
gohumbleandGitHub 657fc7af1d fix mutex (#192) 2021-12-23 17:18:04 +01:00
gohumbleandGitHub 1b24072020 Interface conversion (#191)
* remove user mutex log message

* add bunt cache

* fix send and pay data pointer conversion
2021-12-23 17:07:41 +01:00
d912541391 Faucet set after validation (#190)
* speed up tx lock

* faucet set after validation

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 16:55:39 +01:00
gohumbleandGitHub 72381d0071 Bunt cache (#189)
* remove user mutex log message

* add bunt cache
2021-12-23 16:52:24 +01:00
a644c465cd Disable bunt lock (#188)
* speed up tx lock

* transaction to storage

* to base

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 16:23:57 +01:00
gohumbleandGitHub bc0d3df897 Fix log (#187)
* remove user mutex log message

* remove log

* fix bunt locks log messages
2021-12-23 15:57:48 +01:00
gohumbleandGitHub fa234d4073 remove user mutex log message (#186) 2021-12-23 15:50:41 +01:00
gohumbleandGitHub dd88c93474 add mutex package (#185)
* add mutex package

* fix cancelSendHandler
2021-12-23 15:47:18 +01:00
2469898f9f Inline lock fix (#184)
* speed up tx lock

* fix get

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 15:12:49 +01:00
ee656dc5f0 Mutex fix 420 (#183)
* speed up tx lock

* handling

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 11:16:26 +01:00
3eba0de851 Tiptopptiptiptopbranch (#182)
* speed up tx lock

* tiptooltip better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 10:43:43 +01:00
f8fadb1729 Onlysats (#181)
* speed up tx lock

* add shops

* shop

* scrolling

* 🚀 add state stateCallbackMessage 🚀

* no shop

* scroll

* add shop browser

* scroll bug

* add buttons.go

* scrolling

* shop

* lnurl print after serving

* shop deletion

* adding and removing shops

* display photo captions

* refactor

* shops

* shops

* files work

* rename shop

* error handling

* fixes

* payments

* confirm delete all shops

* adding new items fix

* own bunt db for shop

* unlock transaction

* remove double print

* add transaction.Lock(id)

* unlock getShop

* add default interceptors to shop

* more files

* go sleep

* add fileStateResetTicker

* async sleep

* add runtime.ResettableFunctionTicker

* remove default duration

* generalized concurrent mutex

* simplify function ticker

* status message ticker queue

* add start index to shopViewDeleteAllStatusMsgs

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-23 10:16:13 +01:00
gohumbleandGitHub 6b5e30dbe4 Fix tx lock (#180)
* unlock tx mutex on GET error

* log tx id on timeout
2021-12-22 19:24:51 +01:00
gohumbleandGitHub 72ef490538 unlock tx mutex on GET error (#179) 2021-12-22 19:13:21 +01:00
gohumbleandGitHub 7e2404eaf5 add transaction mutex lock (#178) 2021-12-22 18:54:06 +01:00
gohumbleandGitHub 64f9492af2 update no private chat error message (#177) 2021-12-22 18:03:03 +01:00
gohumbleandGitHub f85ec34bcc fix lock intercept (#176) 2021-12-22 17:48:30 +01:00
8b40253169 remove default interceptors (#174)
* defer intercept after before intercept error check.

* log trace level

* get rid of default interceptors

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 17:34:57 +01:00
91d38b5bb4 Faucet debug logging (#175)
* speed up tx lock

* add logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 17:33:14 +01:00
a59a7c226d defer intercept after before intercept error check (#173)
* defer intercept after before intercept error check.

* log trace level

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 14:40:48 +01:00
4b620186f1 Lnbits postgres compatible (#172)
* speed up tx lock

* webhook fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 02:35:00 +01:00
f313b5cdbe Faucet no tx error (#171)
* speed up tx lock

* remove tx timeout errors

* cacel faucet on error

* cancle faucet on error

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-21 16:16:42 +01:00
179d40178c Faucet no tx error (#170)
* speed up tx lock

* remove tx timeout errors

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-21 16:07:26 +01:00
LightningTipBotandGitHub 15d711a6fd Tipjar fix usercheck (#169)
* check for correct user for tipjar
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-19 18:51:49 +01:00
a4f5b21f1d Invoice events refactoring (#168)
* speed up tx lock

* clean up

* refactor lnurl comment notification

* fix function name

* transaction: do not check balance; refactor invoice notifications

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-19 15:41:01 +01:00
307d9cd873 Debug tip tooltip missing (#167)
* speed up tx lock

* debug for tip

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-18 18:05:48 +00:00
0f6c37a40c Check balance inline receive (#166)
* speed up tx lock

* check balance

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 20:47:22 +00:00
9e4b612c26 Invoice events for inline receive (#164)
* speed up tx lock

* receive via invoice

* update telebot to save message InlineID

* remove debug ifs

* correct response

* comment

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 20:41:13 +00:00
1815bcfaf9 Receive button order (#163)
* receive button reorder

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 09:51:52 +00:00
6299adf633 Faucet per_user minimum 5 sat, Tipjar Button reverse (#162)
* tipjar and faucet change

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-14 19:44:16 +01:00
5b93d43bc5 speed up tx lock (#161)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-14 18:06:37 +01:00
0cfb693619 int64 amounts (#159)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-11 23:17:51 +01:00
1ea9268698 better (#160)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-11 22:09:52 +01:00
f50e6ced71 test mutex (#158)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-08 22:22:11 +01:00
gohumbleandGitHub 1b922c03a9 mutex interceptor patch to prevent concurrent map read / write (#157)
* add handlerMapMutex

* cleanup
2021-12-08 09:55:56 +01:00
f6768b72ea Mutex lock per Telegram User ID (#156)
* lets go

* dunno

* fix after interceptor

* getTelegramUserFromInterface

* clean up requireUserInterceptor

* clean up bs

* cleanup

* cleanup2

* add comment

* fix before default interceptor

* async sleep

* back to 60

* remove newline

* adding defer interceptor

* handlers tighter

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-07 22:55:21 +01:00
236b095bbe new telebot (#155)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-07 20:06:17 +01:00
gohumbleandGitHub a0799b1b32 isAdminAndCanEdit fix (#154)
* Update telegram.go

* remove isAdminAndCanEdit on tryEdit

* remove isAdminAndCanEdit
2021-12-07 10:34:37 +01:00
38251600f9 tx timeout sleep faster (#153)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-06 22:37:22 +01:00
aaa8a3cc19 WIP: rate limiter per chat (#86)
* add rate limiter per chat

* differentiate between global and chat rate limiting

* remove diffs

* resolve conflicts

* resolve conflict

* refactor limiter

* rename

* rename

* logs

* remove logs

* reset buckets

* new rate limiter

* fix comments

* separate id and global limiter

* rename stuff

* reset bucket size

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-06 22:22:02 +01:00
gohumbleandGitHub 25d9b8af3b Check admin rights (#152)
* add rightsToDoAction

* comments

* comments

* typo

* check for id

* return CanEditMessages
2021-12-06 20:08:33 +01:00
ba6bf0a317 telebot fork user ID int64 (#151)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 11:24:28 +01:00
LightningTipBotandGitHub 0abe56dfba Revert "telebot fork user ID int64 (#149)" (#150)
This reverts commit 7c8ba7895d.
2021-12-01 08:59:51 +01:00
7c8ba7895d telebot fork user ID int64 (#149)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 08:52:47 +01:00
eeb9d5224e revert (#148)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 07:11:49 +01:00
79112717cf Telebot update (#146)
* update telebot

* test message

* revert

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 07:08:46 +01:00
4a9a77d5f1 Telebot update (#145)
* update telebot

* test message

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 06:05:20 +01:00
4ba892908b update telebot (#144)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 05:32:53 +01:00
3891c70344 banned prefix filter (#141)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-26 13:36:02 +01:00
6e6c9e02a4 donate message (#140)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-19 21:23:39 +01:00
488fab7f9f expressive errors (#139)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-18 22:04:29 +01:00
8f569ed4c3 send input (#138)
* send input

* remove message limiter

* write invoice into tx db

* do not delete tip twice

* hide link after 60 sedondw

* refactor button text update

* remove print

* translations enter user

* add tr

* no error on invalid user input

* printing fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-17 19:51:51 +01:00
3f26f0b44f copy handlelnurl (#137)
* copy handlelnurl

* rephrase error

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-16 20:40:19 +01:00
1f25cc6ded Add russian translation (#136)
* Add Russian translation

* turn on ru.toml

* load gently

Co-authored-by: Filiph Protsenko <filprocenko@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 16:41:34 +01:00
69b0dd5a4a Lnurl errors localized1 (#134)
* verbose errors

* add translations

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 11:42:35 +01:00
calleandGitHub e1d858752f emojis for logging (#133)
* emojis for logging

* emojis for logging
2021-11-15 10:18:57 +01:00
88bbd4d2cf Fix lnurlpserver (#132)
* fix server

* go-lnurl v1.8.4

* encode

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 01:12:52 +01:00
8c4adb4dd4 Fix lnurlpserver (#131)
* fix server

* go-lnurl v1.8.4

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 01:03:09 +01:00
9290f55fa4 fix server (#130)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 00:02:10 +01:00
0653498e0f Lnurl withdraw (#129)
* go-lnurl --> v1.8.4

* clean up comments

* delete HandleLNURL()

* lnurl-withdrawal

* actual file

* remove comments

* remove comments

* refactor translation

* translations

* add type check and

* translations

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-11-14 22:25:47 +01:00
gohumbleandGitHub dd57247266 increase lnbits pay timeout (#127) 2021-11-14 22:03:14 +01:00
gohumbleandGitHub 051174bd1c using anyChosenInlineHandler (#128)
* using anyChosenInlineHandler

* error logging
2021-11-14 21:57:54 +01:00
KotyandGitHub 5eaf380e91 Tipjar translations into Spanish and Portuguese (#122)
* For mango-selling grannies in Brazil

* Update pt-br.toml

#TIPJAR pt-br translation

* Update es.toml :)

#TIPJAR es ahora alcancía

* Update es.toml

minor fix

* Update pt-br.toml

Minor fixes to pt-br.toml file

* remove pt.toml
2021-11-14 21:53:48 +01:00
LightningTipBotandGitHub fb73c1fe08 markdown escape usernames (#126) 2021-11-11 11:56:53 +01:00
LightningTipBotandGitHub 4a03724540 fix lnurl parsing and comment saving (#125) 2021-11-09 17:54:35 +01:00
LightningTipBotandGitHub 5725a0c9c0 do not return (#123)
* do not return

* warn not error
2021-11-03 20:08:56 +01:00
LightningTipBotandGitHub d8a98ad433 fix (#120) 2021-11-01 19:03:24 +01:00
LightningTipBotandGitHub 11edce049e General amount (#118)
* generalized amount started

* add new file

* uncomment old pay

* longer comments

* lnurl pay with generalized amount input

* generalized amount for /invoice

* amount input for all commands

* remove logging

* delete old comments
2021-10-30 21:26:01 +02:00
e4833bd9c6 User cache (#117)
* adding users cache in memory

* adding users cache in memory

* adding eko/gocache and removing CopyLowercaseUser

* using UpdateUserRecord

* updateCachedUser in user states

* remove redundant updatePersistentUser

* refactor

* remove cachedUser

* remove user chan

* errors for failed invoice creation

* errors for failed invoice and failed pay

* add GetUserBalanceCached inline commands

* translation

* remove redundant set user state reset state

* update cache ttl

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-29 22:04:53 +02:00
LightningTipBotandGitHub 51c410c045 Tipjar hotfix2: translations and help (#116)
* translations and help

* shorten it
2021-10-27 15:23:01 +02:00
LightningTipBotandGitHub f0385128db add username to tipjar (#115) 2021-10-27 12:04:32 +02:00
LightningTipBotandGitHub c90cfd9d8a tipjar (#114)
* tipjar

* tipjar

* fix pointers and wallet keys

* better comment
2021-10-27 11:55:59 +02:00
LightningTipBotandGitHub 97b6e8f043 LNURL errors verbose (#110)
* internal/telegram/lnurl.go

* update gjson
2021-10-26 19:37:04 +02:00
LightningTipBotandGitHub 8da9e0c38c atoi is 32 bit only, change to ParseInt (#109) 2021-10-24 20:52:24 +02:00
fd9ad39b0c anonymous user ID for lnurl (#107)
* anonymous user ID for lnurl

* anonymous lnurl

* migrate at every start, not good

* anon id at user creation

* migrations file

* fix database migration task

* remove comment

* anon label

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-24 20:31:52 +02:00
bb00253122 Translation Indonesian (#106)
* Translation to Indonesian language

First time using github but I think I did everything correctly though.
Truly sorry if I've made a noob mistake
Trying to make the language as friendly yet polite and as formal as possible
Thanx and keep up the great work

* inline commands in english

* readd en.toml

* enable translation

Co-authored-by: hmalau <92701132+hmalau@users.noreply.github.com>
2021-10-18 20:46:59 +02:00
LightningTipBotandGitHub 10c9121cc7 lnurl for user id (#104)
* lnurl for user id

* adjust help
2021-10-18 10:30:07 +02:00
LightningTipBotandGitHub 236097a461 inline send and receive to specific user (#103) 2021-10-17 16:13:41 +02:00
LightningTipBotandGitHub 22d4ab284c turkish translations (#101)
* turkish translations

* fix

* fix

* fix

* add tr.toml
2021-10-13 17:13:28 +03:00
3a2c5b2c51 Portuguese (#100)
* For mango-selling grannies in Brazil

* fix

* rename to pt-br.toml

Co-authored-by: Koty <89604768+kotyauditore@users.noreply.github.com>
2021-10-13 09:01:06 +03:00
c7212131fa Fix fr.toml (#99)
* Create fr.toml 

French translation

* Update with correct line breaks

* typo change

* fix mistakes, enable fr.toml

Co-authored-by: Nicolas Bustamante <92287725+nbstme@users.noreply.github.com>
2021-10-13 08:43:37 +03:00
LightningTipBot 88fdb4de9b small fix 2021-10-11 18:20:25 +03:00
Bas SimonsandGitHub 693f12470c Better dutch translations (#95)
* Update nl.toml

better dutch

* Update nl.toml
2021-10-11 09:08:37 +03:00
Nicolas BustamanteandGitHub 887751cb0f small typo (#96) 2021-10-11 09:07:44 +03:00
LightningTipBotandGitHub 08c7ff5113 Fiat price hotfix2 (#94)
* INR added

* also accept currency string

* dividion by 0

* better check
2021-10-08 10:53:33 +03:00
LightningTipBotandGitHub 7c77d268f6 Fiat price hotfix2 (#93)
* INR added

* also accept currency string

* dividion by 0
2021-10-08 10:51:43 +03:00
LightningTipBotandGitHub 61bc3710c0 Fiat price hotfix2 (#92)
* INR added

* also accept currency string
2021-10-08 10:45:29 +03:00
a880d7b044 Contains -> HasPrefix || HasSuffix (#91)
Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-10-08 08:42:19 +02:00
LightningTipBotandGitHub 8c7c22b0d8 price checker (#90)
* price checker

* more currencies

* debug messages
2021-10-08 08:35:46 +02:00
94eff98f60 bunt transaction generalization (#73)
* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* some fixes

* tigher error checking

* add CreatedAt and UpdatedAt flags

* check error in GetTransaction

* add bunt transaction package and rename stuff

* use transaction.Base as function receiver for transaction functions

* add transaction.Base.Set function

* fix tiptooltip bunt index

* refactor

* auto update updated at

* refactor

* remove balance from error

* fix updated at

* faucet errors

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* some fixes

* tigher error checking

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline send

* add CreatedAt and UpdatedAt flags

* check error in GetTransaction

* add bunt transaction package and rename stuff

* use transaction.Base as function receiver for transaction functions

* add transaction.Base.Set function

* fix tiptooltip bunt index

* refactor

* auto update updated at

* fix updated at

* faucet errors

* refactor

* remove balance from error

* rebase fixes

* fix imports

* fix de string

* fix receive and send

* faucet language

* remove pay constructor

* release faucet

* remove redundant inTransaction

* remove constructor

* remove constructor

* transaction get pointer receiver

* send race condition

* inactivate in db

Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-10-08 00:46:52 +03:00
lngohumble 6a5f09fa18 Revert "price watcher"
This reverts commit 808a5a3b
2021-10-07 22:08:23 +02:00
LightningTipBot 808a5a3b72 price watcher 2021-10-07 22:53:07 +03:00
903cc3c2e2 Lnurlp comments (#89)
* lnurl comments for RECEIVING

* fix import cycle

* fix import

* rename WebhookServer to Server

* rename LNURLInvoice to Invoice

* add str package. MarkdownEscape lnurl.Invoice comment

* add str package

* check for comment length

* lnurl pay with comment

* lnurl pay with comment

* check for wallet existence

* repackage main to internal

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-07 00:21:21 +03:00
LightningTipBotandGitHub f6ef7933f5 refactor translations (#88)
* refactor translations

* fix print error

* add rest of languages

* remove unnecessary package
2021-10-06 21:32:44 +03:00
48fce72559 Italian translation (#87)
* add it.toml

* fix toml and load localizzazione

* fix commands

* update translation

* fix strings

* remove duplicate

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-06 01:40:16 +03:00
LightningTipBotandGitHub 31caa37657 Inline translations (#85)
* translate faucets

* fix faucet buttons
2021-09-27 00:57:59 +02:00
LightningTipBotandGitHub a9b9d0bfdd translate faucets (#84) 2021-09-27 00:14:35 +02:00
LightningTipBotandGitHub a7a7968d09 fix /pay message (#83) 2021-09-26 23:09:11 +02:00
LightningTipBotandGitHub 7e532f3f01 Get user hotfix1 (#82)
* database error on lookup fail

* still return user skeleton on error
2021-09-26 19:22:53 +02:00
LightningTipBotandGitHub 4d5731bf51 adjust es.toml (#81)
* adjust es.toml

* adjust es.toml
2021-09-26 10:19:56 +02:00
LightningTipBotandGitHub 5784126bbd Amount k (#79)
* amounts with k

* faucet with getAmount
2021-09-25 18:08:23 +02:00
LightningTipBotandGitHub af21ad4bea hotfixes (#78) 2021-09-25 17:50:18 +02:00
LightningTipBotandGitHub 4830928352 I18n hotfix1 (#77)
* fix context for /start

* fix tip from translation
2021-09-25 15:04:53 +02:00
167b581d3e translations (#71)
* squash

* balance too low message

* add context to start

* add translations

* translation readme

* translations for all

* equalize

* new faucet empty message

* commands

* localize

* add more commands

* adjust

* add language code

* add languageCode context

* cancel handler with struct language

* inline objects use their language

* button translations

* send language

* add GetLnbitsUser

* different localizers

* fix publicLanguageCode

* translate balance and donate

* whatever bro

* translateUser

* pull bro

* asd

* Create nl.toml (#74)

* Create nl.toml

* Update nl.toml

* I18n (#75)

* Whatever brah

* Update es.toml

* Whatever brah

* Update nl.toml (#76)

* clean comments

* fix amount

Co-authored-by: lngohumble <lngohumble@gmail.com>
Co-authored-by: maxmerlin78 <91363235+maxmerlin78@users.noreply.github.com>
Co-authored-by: Koty <89604768+kotyauditore@users.noreply.github.com>
2021-09-25 14:07:29 +02:00
LightningTipBotandGitHub 2c51662a75 Send and pay data persistent (#72)
* new lookup function

* use persitant object

* rename to avoid collisions

* send with persistent structs

* add persistant pay struct

* finish up

* clean comments

* revert

* fix ID check

* less logging

* error logging fixed

* payment error verbose

* reply to interceptor for send

* reply to send command if channel
2021-09-22 21:23:53 +02:00
fbbe18d7a7 add interceptor and handler context (#69)
* add interceptor for handler context

* remove user load

* remove UserInitializedWallet

* remove getuser invocation

* add lnbits user to inlineFaucet

* set wallet client

* lnbits user to inline receive

* lnbits user to inline send

* add context to handleInlineReceiveQuery

* add handler.go

* fix help message

* fix handler registration

* rename

* check if reply to is nil

* remove unwanted stuff

* error handlers

* remove client from wallet

* rename force to require

* string fixes

* add intercept.Func

* add PrivateChat check

* remove private chat requirement for anytexthandler

* fix callback

* errors fixed

* fix callback

* loadUser

* do not require

* check type in interceptor

* check type in interceptor

* check for user wallets

* allow send for toUser with wallet but not initialized

* fix reply to context

* mdescape

* strfux

* set state columns only

* update str

* set user now

* anytext should not load user outside pm

* rename endpoint to donationEndpoint

* register uppercase endpoints and add comments

* fix photos in logMessageInterceptor

* reduce log level to trace

Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-09-21 21:35:10 +02:00
LightningTipBotandGitHub e3ba16f5d1 better errors (#68)
* better errors

* better log
2021-09-14 17:46:22 +02:00
LightningTipBotandGitHub 39ed394984 wrong balance check (#67) 2021-09-14 11:59:36 +02:00
LightningTipBotandGitHub 1b97544ad5 zapfhahn and kraan (#66) 2021-09-14 11:18:22 +02:00
LightningTipBotandGitHub 7c33234d91 faucet help (#65) 2021-09-14 09:58:54 +02:00
LightningTipBotandGitHub f23e4098e3 add peruser amount (#64)
* add peruser amount

* remove dev edit
2021-09-13 23:53:30 +02:00
LightningTipBotandGitHub 1a073b339b faucet progress bar (#63)
* faucet progress bar

* format
2021-09-13 23:39:00 +02:00
LightningTipBotandGitHub 0653b82c10 add peruser amount to message (#62) 2021-09-13 23:22:17 +02:00
LightningTipBotandGitHub 4a9dcc9601 Inline faucet (#60) 2021-09-13 22:44:43 +02:00
LightningTipBotandGitHub 34d951ee85 fix state reset (#61)
* fix state reset

* fix reference

* ask for amount explicitly
2021-09-13 20:23:59 +02:00
LightningTipBotandGitHub 8af08357d0 tooltip factor messages (#59)
* tooltip factor messages
* init user if not inited
2021-09-10 10:16:49 +02:00
LightningTipBot a19fa50bb8 readme inline send 2021-09-10 09:53:12 +02:00
LightningTipBot 079e490cac rephrase readme 2021-09-10 09:35:59 +02:00
gohumble acf0cb5af6 Initial commit 2021-09-10 08:52:44 +02:00
183 changed files with 31723 additions and 1954 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
+78 -17
View File
@@ -1,12 +1,12 @@
<p align="center">
<img alt="logo" src="resources/logo_round.png" >
<img alt="logo" width="150" src="resources/logo_round.png" >
</p>
# @LightningTipBot 🏅
A tip bot and Lightning ⚡️ Bitcoin Wallet for Telegram group chats. It can also be used as a personal Lightning wallet by anyone who has a Telegram account.
A Telegram Lightning ⚡️ Bitcoin wallet and tip bot for group chats.
This repository contains everything you need to set up and run your own tip bot. If you simply want to use this bot in your group chat without having to install anything just start a conversation with [@LightningTipBot](https://t.me/LightningTipBot) and invite it into your chat.
This repository contains everything you need to set up and run your own tip bot. If you simply want to use this bot in your group chat without having to install anything just start a conversation with [@LightningTipBot](https://t.me/LightningTipBot) and invite it into your group chat.
## Setting up the bot
@@ -18,12 +18,10 @@ To build the bot from source, clone the repository and compile the source code.
git clone https://github.com/LightningTipBot/LightningTipBot.git
cd LightningTipBot
go build .
cp config.yaml-example config.yaml
cp config.yaml.example config.yaml
```
Alternatively, you can download binary releases [here](https://github.com/LightningTipBot/LightningTipBot/releases) **(note: no realses yet)**.
After you have configured the bot, start it using the command
After the configuration (see below), start it using the command
```
./LightningTipBot
@@ -31,7 +29,7 @@ After you have configured the bot, start it using the command
### Configuration
You need to edit `config.yaml` before starting the bot.
You need to edit `config.yaml` before you can start the bot.
#### Create a Telegram bot
@@ -41,7 +39,7 @@ First, create a new Telegram bot by starting a conversation with the [@BotFather
You can either use your own LNbits instance (recommended) or create an account at [lnbits.com](https://lnbits.com/) to use their custodial service (easy).
1. Create a wallet in LNbits (`lnbits_url`).
1. Create a wallet in LNbits (reachable by the bot via `lnbits_url`).
2. Get the **Admin key** in the API Info tab of your user (`lnbits_admin_key`).
3. Enable the User Manager extension.
4. Get the **Admin ID** of the User Manager (`lnbits_admin_id`).
@@ -54,25 +52,54 @@ You can either use your own LNbits instance (recommended) or create an account a
#### More configuration
- `webhook_server`: URL that can reach the bot. This is used for creating webhooks with LNbits to receive notifications about payments (optional).
- `db_path`: User database file path.
- `transactions_path`: Transaction log file path.
- `message_dispose_duration`: Duration in seconds after which commands will be deleted from channel (only if the bot is channel admin).
- `transactions_path`: Transaction database file path.
- `buntdb_path`: Object storage database file path.
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
- `admin_api_token`: Secret for the admin API on `admin_api_host` (ban, unban, mutex, pprof). Send it as `Authorization: Bearer <token>`. Without it the admin API rejects every request.
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zeus support, optional).
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
## Features
### Commands
#### Commands
```
/tip 🏅 Reply to a message to tip it: /tip <amount> [<memo>]
/balance 👑 Check your balance: /balance
/send 💸 Send funds to a user: /send <amount> <@username> [<memo>]
/invoice ⚡️ Create a Lightning invoice to receive payments: /invoice <amount> [<memo>]
/pay ⚡️ Pay a Lightning invoice: /pay <invoice>
/send 💸 Send funds to a user: /send <amount> <@user> or <user@domain.com> [<memo>]
/invoice ⚡️ Receive over Lightning: /invoice <amount> [<memo>]
/pay ⚡️ Pay over Lightning: /pay <invoice>
/help 📖 Read this help.
/info 📚 More info.
/advanced 🤖 Read the advanced help.
/basics 📚 More info.
/donate ❤️ Donate to the project: /donate <amount>
```
#### Advanced commands
```
/link 🔗 Link your wallet to BlueWallet or Zeus
/lnurl ⚡️ Lnurl receive or pay: /lnurl or /lnurl <lnurl>
```
### Inline commands
```
send 💸 Send sats to chat: @LightningTipBot send <amount> [<memo>]
```
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and click the result, don't press enter.
### Inline send
You can use inline commands to send payments to anyone who can read your messages, even inside private chats and group chat in which the bot isn't part of. For that, you need to trigger an [inline command](https://core.telegram.org/bots/inline). Here is how it works: Enter the name of the bot (`@LightningTipBot`) and the command you want to trigger (`send 13 Hi friend!`). When the result pops up above the text field, click it to send it to the chat. Do not press enter.
<p align="center">
<img alt="Send sats inside any chat, including private conversations and groups." src="resources/inline_send.png" >
</p>
### Live tooltips
The bot replies to a tipped message to indicate to all participants how many and what amount of tips a post has received. This tooltip will be updated as new tips are given to a post.
@@ -81,13 +108,47 @@ The bot replies to a tipped message to indicate to all participants how many and
<img alt="How to set up a lnbits wallet and the User Manager extension." src="resources/tooltips.png" >
</p>
### LNURL server
Users can send and receive via . For this to work, you need to set the `lnurl_public_server` in `config.yaml`. The bot will then host a LNURL endpoint at `.well-known/lnurlp/username` which handles the data exchange with other wallets. You can set `http_proxy` in `config.yaml` to send outbound requests only via an HTTP proxy.
### Send and receive via Lightning Address
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
### Link to BlueWallet or Zeus
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
<p align="center">
<img alt="QR code payment example." src="resources/lndhub.png" >
</p>
### Pay invoices by sending QR codes
To pay a Lightning invoice, you can snap a photo of a QR code and send it directly to the bot. Note that you might need to zoom in, center the QR code, or crop the image if the bot fails to decode the QR code from the photo. By the way, you can also just send an the invoice as a string, the bot will automatically detect it and initiate a payment.
<p align="center">
<img alt="QR code payment example." src="resources/qr_code_example.jpg" >
</p>
### Auto-delete commands
To minimize the clutter all the heavy tipping can cause in a group chat, the bot will remove all failed commands (for example due to a syntax error) from the chat immediately. All successful commands will stay visible for `message_dispose_duration` seconds (default 10s) and then be removed. The tips will sill be visible for everyone in the Live tooltip. This feature only works, if the bot is made admin of the group.
## Full Guide to Install and run on a VPS
A complete guide to install and run LightningTipBot + LNBITS (on docker with PostgreSQL) on the same VPS with an external LND funding source has been prepared by Massimo Musumeci (@massmux) and it is available: [LightningTipBot full install](https://www.massmux.com/howto-complete-lightningtipbot-lnbits-setup-vps/)
## Made with
- [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
- [telebot](https://github.com/tucnak/telebot) – A Telegram bot framework in Go.
- [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/`.
-38
View File
@@ -1,38 +0,0 @@
package main
import (
"errors"
"strconv"
"strings"
)
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", errors.New("Message doesn't contain enough arguments")
}
output = strings.Split(input, " ")[which]
return output, nil
}
func decodeAmountFromCommand(input string) (amount int, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "Message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
}
amount, err = getAmount(input)
return amount, nil
}
func getAmount(input string) (amount int, err error) {
amount, err = strconv.Atoi(strings.Split(input, " ")[1])
if err != nil {
return 0, err
}
if amount < 1 {
errmsg := "Error: Amount must be greater than 0"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
}
return amount, err
}
-40
View File
@@ -1,40 +0,0 @@
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
func (bot TipBot) balanceHandler(m *tb.Message) {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
// first check whether the user is initialized
fromUser, err := GetUser(m.Sender, bot)
if err != nil {
log.Errorf("[/balance] Error: %s", err)
return
}
if !fromUser.Initialized {
bot.startHandler(m)
return
}
usrStr := GetUserStr(m.Sender)
balance, err := bot.GetUserBalance(m.Sender)
if err != nil {
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
bot.telegram.Send(m.Sender, "🚫 Error fetching your balance. Please try again later.")
return
}
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
bot.telegram.Send(m.Sender, fmt.Sprintf("👑 *Your balance:* %d sat", balance))
return
}
-127
View File
@@ -1,127 +0,0 @@
package main
import (
"fmt"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/gorm"
)
type TipBot struct {
database *gorm.DB
logger *gorm.DB
telegram *telebot.Bot
client *lnbits.Client
tips map[int][]*Message
}
var (
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
botWalletInitialisation = sync.Once{}
telegramHandlerRegistration = sync.Once{}
)
// NewBot migrates data and creates a new bot
func NewBot() TipBot {
db, txLogger := migration()
return TipBot{
database: db,
logger: txLogger,
tips: make(map[int][]*Message, 0),
}
}
// newTelegramBot will create a new telegram bot.
func newTelegramBot() *tb.Bot {
tgb, err := tb.NewBot(tb.Settings{
Token: Configuration.ApiKey,
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
ParseMode: tb.ModeMarkdown,
})
if err != nil {
panic(err)
}
return tgb
}
// initBotWallet will create / initialize the bot wallet
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
err := bot.initWallet(bot.telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
return
}
})
return nil
}
// registerTelegramHandlers will register all telegram handlers.
func (bot TipBot) registerTelegramHandlers() {
telegramHandlerRegistration.Do(func() {
// Set up handlers
var endpointHandler = map[string]interface{}{
"/tip": bot.tipHandler,
"/pay": bot.confirmPaymentHandler,
"/invoice": bot.invoiceHandler,
"/balance": bot.balanceHandler,
"/start": bot.startHandler,
"/send": bot.confirmSendHandler,
"/help": bot.helpHandler,
"/info": bot.infoHandler,
tb.OnPhoto: bot.privatePhotoHandler,
tb.OnText: bot.anyTextHandler,
}
// assign handler to endpoint
for endpoint, handler := range endpointHandler {
log.Debugf("Registering: %s", endpoint)
bot.telegram.Handle(endpoint, handler)
// if the endpoint is a string command (not photo etc)
if strings.HasPrefix(endpoint, "/") {
// register upper case versions as well
bot.telegram.Handle(strings.ToUpper(endpoint), handler)
}
}
// button handlers
// for /pay
bot.telegram.Handle(&btnPay, bot.payHandler)
bot.telegram.Handle(&btnCancelPay, bot.cancelPaymentHandler)
// for /send
bot.telegram.Handle(&btnSend, bot.sendHandler)
bot.telegram.Handle(&btnCancelSend, bot.cancelSendHandler)
})
}
// Start will initialize the telegram bot and lnbits.
func (bot TipBot) Start() {
// set up lnbits api
bot.client = lnbits.NewClient(Configuration.LnbitsKey, Configuration.LnbitsUrl)
// set up telebot
bot.telegram = newTelegramBot()
log.Infof("[Telegram] Authorized on account @%s", bot.telegram.Me.Username)
// initialize the bot wallet
err := bot.initBotWallet()
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.registerTelegramHandlers()
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
bot.telegram.Start()
}
+14 -5
View File
@@ -6,8 +6,17 @@
4 - Paste this:
help - Read the help.
balance - Check your balance.
tip - Reply to a message to tip it.
send - Send funds to a user.
invoice - Create a Lightning invoice to receive payments.
pay - Pay a Lightning invoice.
balance - Check balance.
transactions - List transactions
tip - Reply to a message to tip: /tip 50
send - Send funds to a user: /send 100 @LightningTipBot
invoice - Receive with Lightning: /invoice 1000
pay - Pay with Lightning: /pay lnbc10n1ps...
donate - Donate: /donate 1000
faucet - Create a faucet: /faucet 2100 21
advanced - Advanced help
note - Create an LNURLcash note: /note 1000 [memo]
notes - List your notes, or create a batch: /notes 100 x 10
redeem - Redeem a received note: /redeem lnurlw://...
lnurlmints - Show the LNURLcash mints and pick a default
lnurlhelp - Help for LNURLcash notes
-21
View File
@@ -1,21 +0,0 @@
package main
import "github.com/jinzhu/configor"
var Configuration = struct {
AdminKey string `json:"lnbits_admin_id" yaml:"lnbits_admin_id"`
LnbitsKey string `json:"lnbits_admin_key" yaml:"lnbits_admin_key"`
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
DbPath string `json:"db_path" yaml:"db_path"`
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
MessageDisposeDuration int64 `json:"message_dispose_duration" yaml:"message_dispose_duration"`
}{}
func init() {
err := configor.Load(&Configuration, "config.yaml")
if err != nil {
panic(err)
}
}
+60 -8
View File
@@ -1,8 +1,60 @@
telegram_api_key: "1234"
webhook_server: "http://0.0.0.0:1234"
lnbits_url: "http://*.onion:1234"
lnbits_admin_key: "1234"
lnbits_admin_id: "3212"
db_path: "data/bot.db"
transactions_path: "data/transactions.db"
message_dispose_duration: 10
bot:
socks_proxy:
host: 127.0.0.1:9996
username: test
password: username
tor_proxy:
host: 127.0.0.1:9050
http_proxy: ""
lnurl_public_host_name: "https://mylnurl.com"
lnurl_server: "http://127.0.0.1:5454" # or http://0.0.0.0:5454 depending on your configuration
lnurl_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"
lnbits:
url: "http://127.0.0.1:5000"
admin_key: "1234"
admin_id: "1234"
webhook_server: "http://0.0.0.0:5588"
lnbits_public_url: "link.mylnurl.com"
database:
db_path: "data/bot.db"
buntdb_path: "data/bunt.db"
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
groupsdb_path: "data/groups.db"
lnurlcash_path: "data/lnurlcash.db"
generate:
open_ai_bearer_token: "token_here"
dalle_key: "asd"
dalle_price: 1000
worker: 2
nostr:
private_key: "hex private key here"
lnurlcash: # LUD-25 bearer notes, see docs/lnurlcash/PLAN.md
enabled: false
mints:
# url may list several mints, comma separated (e.g. "lnurl.21mint.me,mint.600.wtf"):
# the first keeps this name, the others are named after their host. Users pick
# their own default with /lnurlmints; `default: true` is the fallback.
- name: 21mint
url: https://lnurl.21mint.me
default: true
min_note_sat: 1
max_note_sat: 100000
max_outstanding_sat_per_user: 500000
max_outstanding_notes_per_user: 200
max_batch_size: 100
max_batch_total_sat: 500000
group_note_max_sat: 1000
max_mint_fee_ppm: 20000
auto_reclaim_days: 0
status_poll_interval: 5m
invoice_wait_timeout: 60s
batch_strategy: split # or: invoices
batch_formats: [pdf, json, csv]
secret_encryption_key: "" # 64 hex chars, e.g. `openssl rand -hex 32`; required when enabled
admin_telegram_id: 0 # optional: Telegram user id that receives mint alerts
+1
View File
@@ -0,0 +1 @@
this is where dalle images are stored
-73
View File
@@ -1,73 +0,0 @@
package main
import (
"fmt"
"reflect"
"strconv"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func migration() (db *gorm.DB, txLogger *gorm.DB) {
txLogger, err := gorm.Open(sqlite.Open(Configuration.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
orm, err := gorm.Open(sqlite.Open(Configuration.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = orm.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
err = txLogger.AutoMigrate(&Transaction{})
if err != nil {
panic(err)
}
return orm, txLogger
}
// GetUser from telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
tx := bot.database.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s's info from database.", GetUserStr(u))
log.Warnln(errmsg)
return user, tx.Error
}
defer func() {
user.Wallet.Client = bot.client
}()
var err error
go func() {
if !reflect.DeepEqual(u, user.Telegram) {
// update possibly changed user details in database
user.Telegram = u
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
}
}
}()
return user, err
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
tx := bot.database.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)
return tx.Error
}
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
return nil
}
+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?
+108 -4
View File
@@ -1,17 +1,121 @@
module github.com/LightningTipBot/LightningTipBot
go 1.15
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.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/liyue201/goqr v0.0.0-20200803022322-df443203d4ea
github.com/lnurlcash/lnurlcash-go v0.3.0
github.com/makiuchi-d/gozxing v0.0.2
github.com/sirupsen/logrus v1.2.0
github.com/nbd-wtf/go-nostr v0.13.0
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/prometheus/common v0.26.0
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.7.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
gopkg.in/tucnak/telebot.v2 v2.3.5
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4
golang.org/x/net v0.62.0
golang.org/x/text v0.43.0
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
require (
github.com/kcalvinalvin/anet v0.0.0-20251112173137-d8ddc1f6dbee // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
require (
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 // indirect
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/btcsuite/btcd v0.24.2 // indirect
github.com/btcsuite/btcd/btcutil v1.2.0 // indirect
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
github.com/btcsuite/btcwallet v0.15.1 // indirect
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/decred/dcrd/lru v1.0.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-redis/redis/v8 v8.8.2 // indirect
github.com/gorilla/websocket v1.5.3
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
github.com/lightninglabs/neutrino v0.14.2 // indirect
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
github.com/mattn/go-sqlite3 v1.14.5 // indirect
github.com/miekg/dns v1.1.43 // indirect
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
github.com/pegasus-kv/thrift v0.13.0 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/tidwall/btree v0.6.1 // indirect
github.com/tidwall/grect v0.1.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/rtred v0.1.2 // indirect
github.com/tidwall/tinyqueue v0.1.1 // indirect
github.com/valyala/fastjson v1.6.3 // indirect
go.opentelemetry.io/otel v0.20.0 // indirect
go.opentelemetry.io/otel/metric v0.20.0 // indirect
go.opentelemetry.io/otel/trace v0.20.0 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/term v0.47.0 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/alecthomas/kingpin.v2 v2.2.6 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
)
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
replace github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.3
+1236 -42
View File
File diff suppressed because it is too large Load Diff
-54
View File
@@ -1,54 +0,0 @@
package main
import (
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
helpMessage = "ℹ️ *Info*\n_This bot sends Bitcoin tips on the Lightning Network⚡️. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but generates costs. If you like to support this bot, please consider a donation. To donate, just tip @LightningTipBot or try_ `/send 1000 @LightningTipBot`\n\n" +
"⚙️ *Commands*\n" +
"*/tip* 🏅 Reply to a message to tip it: `/tip <amount> [<memo>]`\n" +
"*/balance* 👑 Check your balance: `/balance`\n" +
"*/send* 💸 Send funds to a user: `/send <amount> <@username> [<memo>]`\n" +
"*/invoice* ⚡️ Receive over Lightning: `/invoice <amount> [<memo>]`\n" +
"*/pay* ⚡️ Pay over Lightning: `/pay <invoice>`\n" +
"*/help* 📖 Read this help (more: */info*).\n"
infoMessage = "🧡 *Bitcoin*\n" +
"_Bitcoin is the currency of the internet. It is permissionless and decentralized and has no masters and no controling authority. Bitcoin is sound money that is faster, more secure, and more inclusive than the legacy financial system._\n\n" +
"🧮 *Economnics*\n" +
"_The smallest unit of Bitcoin are Satoshis (sat) and 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. The fiat currency value of Bitcoin can change daily. However, if you live on a Bitcoin standard 1 sat will always equal 1 sat._\n\n" +
"⚡️ *The Lightning Network*\n" +
"_The Lightning Network is a payment protocol that enables fast and cheap Bitcoin payments that require almost no energy. It is what scales Bitcoin to the billions of people around the world._\n\n" +
"📲 *Lightning Wallets*\n" +
"_Your funds on this bot can be sent to any other Lightning wallet and vice versa. If you don't have a Lightning wallet yet, check out_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(easy)_.\n\n" +
"📄 *Open Source*\n" +
"_This bot is free and_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. You can run it on your own computer and use it in your own community. You don't have to trust anyone to keep your funds safe._\n\n" +
// "🏛 *Terms*\n" +
// "_We are not custodian of your funds. Any amount you load onto your wallet will be legally considered a donation that belongs to us. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but generates costs. If you like to support this bot, please consider a donation. To donate, just tip @LightningTipBot or try_ `/send 1000 @LightningTipBot`"
)
func (bot TipBot) helpHandler(m *tb.Message) {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
if !m.Private() {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
return
}
func (bot TipBot) infoHandler(m *tb.Message) {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
if !m.Private() {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, infoMessage, tb.NoPreview)
return
}
+15
View File
@@ -0,0 +1,15 @@
package admin
import (
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
)
type Service struct {
bot *telegram.TipBot
}
func New(b *telegram.TipBot) Service {
return Service{
bot: b,
}
}
+76
View File
@@ -0,0 +1,76 @@
package admin
import (
"fmt"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
user, err := s.getUserByTelegramId(r)
if err != nil {
log.Errorf("[ADMIN] could not ban user: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if !user.Banned && !strings.HasPrefix(user.Wallet.Adminkey, "banned_") {
log.Infof("[ADMIN] user is not banned. Aborting.")
w.WriteHeader(http.StatusBadRequest)
return
}
user.Banned = false
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
err = telegram.UpdateUserBan(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
}
log.Infof("[ADMIN] Unbanned user (%s)", user.ID)
w.WriteHeader(http.StatusOK)
}
func (s Service) BanUser(w http.ResponseWriter, r *http.Request) {
user, err := s.getUserByTelegramId(r)
if err != nil {
log.Errorf("[ADMIN] could not ban user: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if user.Banned {
w.WriteHeader(http.StatusBadRequest)
log.Infof("[ADMIN] user is already banned. Aborting.")
return
}
user.Banned = true
if reason := r.URL.Query().Get("reason"); reason != "" {
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", reason, user.Wallet.Adminkey)
}
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", "banned", user.Wallet.Adminkey)
err = telegram.UpdateUserBan(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
}
log.Infof("[ADMIN] Banned user (%s)", user.ID)
w.WriteHeader(http.StatusOK)
}
func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
user := &lnbits.User{}
v := mux.Vars(r)
if v["id"] == "" {
return nil, fmt.Errorf("invalid id")
}
tx := s.bot.DB.Users.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
if tx.Error != nil {
return nil, tx.Error
}
return user, nil
}
+14
View File
@@ -0,0 +1,14 @@
package admin
import (
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
"net/http"
)
func (s Service) DisableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = false
}
func (s Service) EnableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = true
}
+27
View File
@@ -0,0 +1,27 @@
package api
type BalanceResponse struct {
Balance int64 `json:"balance"`
}
type InvoiceStatusResponse struct {
State string `json:"state,omitempty"`
PaymentHash string `json:"payment_hash"`
Preimage int64 `json:"preimage"`
}
type CreateInvoiceResponse struct {
PaymentHash string `json:"payment_hash"`
PayRequest string `json:"pay_request"`
Preimage string `json:"preimage,omitempty"`
}
type CreateInvoiceRequest struct {
Memo string `json:"memo"`
Amount int64 `json:"amount"`
DescriptionHash string `json:"description_hash"`
UnhashedDescription string `json:"unhashed_description"`
}
type PayInvoiceRequest struct {
PayRequest string `json:"pay_req"`
}
+231
View File
@@ -0,0 +1,231 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"github.com/r3labs/sse"
)
type Service struct {
Bot *telegram.TipBot
}
type ErrorResponse struct {
Message string `json:"error"`
}
func RespondError(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
}
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
balance, err := s.Bot.GetUserBalance(user)
if err != nil {
RespondError(w, "balance check failed")
return
}
balanceResponse := BalanceResponse{
Balance: balance,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(balanceResponse)
}
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var createInvoiceRequest CreateInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: createInvoiceRequest.Amount,
Out: false,
DescriptionHash: createInvoiceRequest.DescriptionHash,
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
Memo: createInvoiceRequest.Memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
s.Bot.Client)
if err != nil {
RespondError(w, "could not create invoice")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(invoice)
}
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var payInvoiceRequest PayInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
if err != nil {
RespondError(w, "could not pay invoice: "+err.Error())
return
}
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
if err != nil {
// we assume that it's paid since thre was no error earlier
payment.Paid = true
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get payment")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
// InvoiceStatus
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
user.Wallet = &lnbits.Wallet{}
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get invoice")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
type InvoiceStream struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
// maxStreamsPerWallet bounds the SSE connections one wallet can hold open. Each
// one keeps a goroutine and a connection to LNbits alive.
const maxStreamsPerWallet = 3
var (
streamsMu sync.Mutex
streams = map[string]int{}
)
// acquireStream reserves a stream slot for the wallet.
func acquireStream(walletID string) bool {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] >= maxStreamsPerWallet {
return false
}
streams[walletID]++
return true
}
func releaseStream(walletID string) {
streamsMu.Lock()
defer streamsMu.Unlock()
if streams[walletID] <= 1 {
delete(streams, walletID)
return
}
streams[walletID]--
}
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
if !acquireStream(user.Wallet.ID) {
http.Error(w, "Too many streams", http.StatusTooManyRequests)
return
}
defer releaseStream(user.Wallet.ID)
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
client := sse.NewClient(fmt.Sprintf("%s/api/v1/payments/sse", internal.Configuration.Lnbits.Url))
client.Connection.Transport = &http.Transport{DisableCompression: true}
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
c := make(chan *sse.Event)
err := client.SubscribeChan("", c)
if err != nil {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
out:
for {
select {
case <-r.Context().Done():
// the client went away: do not wait for the next payment event
break out
case msg := <-c:
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
}
// Unsubscribe once. It blocks until the subscription goroutine takes the
// request, and that goroutine may be sending an event, so keep draining.
done := make(chan struct{})
go func() {
client.Unsubscribe(c)
close(done)
}()
for {
select {
case <-c:
case <-done:
return
}
}
}
+21
View File
@@ -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")
}
}
+154
View File
@@ -0,0 +1,154 @@
package api
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"net/http"
"net/http/httputil"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
)
func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Tracef("[%s] %s %s", prefix, r.Method, r.URL.Path)
log.Tracef("[%s]\n%s", prefix, dump(r))
r.BasicAuth()
next.ServeHTTP(w, r)
}
}
type AuthType struct {
Type string
Decoder func(s string) ([]byte, error)
}
var AuthTypeBasic = AuthType{Type: "Basic"}
var AuthTypeBearerBase64 = AuthType{Type: "Bearer", Decoder: base64.StdEncoding.DecodeString}
var AuthTypeNone = AuthType{}
// invoice key or admin key requirement
type AccessKeyType struct {
Type string
}
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if accessType.Type == "none" {
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
// check if the user is banned
if auth == "" {
w.WriteHeader(401)
log.Warn("[api] no auth")
return
}
_, password, ok := parseAuth(authType, auth)
if !ok {
w.WriteHeader(401)
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
w.WriteHeader(401)
log.Warnf("[api] Request with a banned key. Not forwarding request")
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
var tx *gorm.DB
if accessType.Type == "admin" {
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
} else if accessType.Type == "invoice" {
tx = database.Where("wallet_inkey = ? OR wallet_adminkey = ? COLLATE NOCASE", password, password).First(user)
} else {
log.Errorf("[api] route without access type")
w.WriteHeader(401)
return
}
if tx.Error != nil {
log.Warnf("[api] could not load access key: %v", tx.Error)
w.WriteHeader(401)
return
}
// The ban rewrites only the admin key, so a banned user's invoice key
// still matches above. Refuse every key of a banned user.
if user.Banned || user.Wallet == nil || strings.HasPrefix(user.Wallet.Adminkey, "banned") || strings.Contains(user.Wallet.Adminkey, "_") {
w.WriteHeader(401)
log.Warnf("[api] Request with a key of a banned user. Not forwarding request")
return
}
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
r = r.WithContext(context.WithValue(r.Context(), "user", user))
next.ServeHTTP(w, r)
}
}
// parseAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
parse := func(prefix string) (username, password string, ok bool) {
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
if authType.Decoder != nil {
c, err := authType.Decoder(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
return auth[len(prefix):], auth[len(prefix):], true
}
return parse(fmt.Sprintf("%s ", authType.Type))
}
func dump(r *http.Request) string {
x, err := httputil.DumpRequest(r, true)
if err != nil {
return ""
}
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)
}
}
}
+73
View File
@@ -0,0 +1,73 @@
package api
import (
"fmt"
"io"
"net/http"
"net/url"
"time"
log "github.com/sirupsen/logrus"
)
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
client := &http.Client{Timeout: time.Second * 30}
//http: Request.RequestURI can't be set in client requests.
//http://golang.org/src/pkg/net/http/client.go
req.RequestURI = ""
u, err := url.Parse(rawUrl)
if err != nil {
http.Error(wr, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err)
return err
}
req.URL.Host = u.Host
req.URL.Scheme = u.Scheme
req.Host = req.URL.Host
resp, err := client.Do(req)
if err != nil {
http.Error(wr, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err)
return err
}
defer resp.Body.Close()
log.Tracef("[Proxy] Proxy request status: %s", resp.Status)
if resp.StatusCode > 300 {
return fmt.Errorf("invalid response")
}
delHopHeaders(resp.Header)
copyHeader(wr.Header(), resp.Header)
wr.WriteHeader(resp.StatusCode)
_, err = io.Copy(wr, resp.Body)
return err
}
// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func delHopHeaders(header http.Header) {
for _, h := range hopHeaders {
header.Del(h)
}
}
+92
View File
@@ -0,0 +1,92 @@
package api
import (
"encoding/json"
"net/http"
"time"
"gorm.io/gorm"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Server struct {
httpServer *http.Server
router *mux.Router
}
const (
StatusError = "ERROR"
StatusOk = "OK"
)
func NewServer(address string) *Server {
srv := &http.Server{
Addr: address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 90 * time.Second,
ReadTimeout: 90 * time.Second,
}
apiServer := &Server{
httpServer: srv,
}
apiServer.router = mux.NewRouter()
apiServer.router.Use(securityHeaders)
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[api] Server started at %s", address)
return apiServer
}
func (w *Server) ListenAndServe() {
go w.httpServer.ListenAndServe()
}
// Use adds a middleware that runs for every route of the server.
func (w *Server) Use(middleware mux.MiddlewareFunc) {
w.router.Use(middleware)
}
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, accessType, handler)))
if len(methods) > 0 {
r.Methods(methods...)
}
}
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
if len(methods) > 0 {
r.Methods(methods...)
}
}
func NotFoundHandler(writer http.ResponseWriter, err error) {
log.Errorln(err)
// return 404 on any error
http.Error(writer, "404 page not found", http.StatusNotFound)
}
func WriteResponse(writer http.ResponseWriter, response interface{}) error {
jsonResponse, err := json.Marshal(response)
if err != nil {
return err
}
_, 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)
})
}
@@ -0,0 +1,79 @@
<!-- @format -->
{{define "userpage"}}
<!DOCTYPE html>
<meta charset="utf-8" />
<meta property="og:title" content="Pay to {{.Username}}@ln.tips">
<meta property="og:site_name" content="{{.Username}}@ln.tips">
<meta property="og:description" content="Send bitcoin to {{.Username}} over Lightning. Get your own Lightning address at https://ln.tips 👈">
<meta property="og:type" content="article" />
<meta property="og:image" content="{{.Image}}">
<meta property="og:url" content="https://ln.tips/@{{.Username}}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image:alt" content="Pay to {{.Username}}@ln.tips">
<meta name="lightning" content="lnurlp:{{.Username}}@ln.tips"/>
<title>{{.Username}}@ln.tips</title>
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
<style>
body {
background: rgb(36,71,247);
background: radial-gradient(circle, rgba(36,71,247,1) 0%, rgba(249,42,84,1) 100%);
margin: auto;
text-align: center;
font-family: monospace;
width: 600px;
color: #f3f3f3c5 !important;
}
.image-cropper {
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
border-radius: 50%;
}
#photo {
margin-top: 50px;
width: 100px;
}
.white {
color: #f3f3f3c5;
}
.sm {
color: #f3f3f3c5;
font-size: 1rem;
}
#qr {
display: block;
margin-top: 50px;
margin-bottom: 50px;
}
#invoice {
margin: 10px;
padding-bottom: 10px;
white-space: pre-wrap;
word-wrap: break-word;
word-break: break-all;
font-size: 1.5rem;
}
</style>
<a href="https://t.me/{{.Username}}"><img id="photo" class="image-cropper" src="{{.Image}}"/></a>
<h1>Pay to <a class="white" href="https://t.me/{{.Username}}">{{.Username}}@ln.tips</a></h1>
<div><a href="lightning:{{.LNURLPay}}" id="qr"></a></div>
<div class="white" id="invoice">{{.LNURLPay}}</div>
<div class="sm">Get your own Lightning address here: <a class="sm" href="https://ln.tips">ln.tips</a></div>
<script>
qr.appendChild(
kjua({
text: invoice.innerHTML,
rounded: 50,
size: 500,
render: 'canvas',
})
)
</script>
{{end}}
+387
View File
@@ -0,0 +1,387 @@
<!-- @format -->
{{define "webapp"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="MobileOptimized" content="176" />
<meta name="HandheldFriendly" content="True" />
<meta name="robots" content="noindex,nofollow" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>@LightningTipBot</title>
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
<script>
function setThemeClass() {
document.documentElement.className = Telegram.WebApp.colorScheme;
}
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
setThemeClass();
</script>
<style>
body {
font-family: sans-serif;
background-color: var(--tg-theme-bg-color, #ffffff);
color: var(--tg-theme-text-color, #222222);
font-size: 16px;
margin: 0;
padding: 0;
color-scheme: var(--tg-color-scheme);
}
a {
color: var(--tg-theme-link-color, #2678b6);
}
button {
display: block;
width: 100%;
font-size: 14px;
border: none;
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
cursor: pointer;
}
.btn-primary {
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
}
button[disabled] {
opacity: 0.6;
cursor: auto;
pointer-events: none;
}
input {
font-size: 14px;
text-align: center;
border: none;
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
.input-group-text {
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
section {
padding: 5px 5px 65px;
text-align: center;
}
p {
margin: 40px 0 15px;
}
ul {
text-align: left;
}
li {
color: var(--tg-theme-hint-color, #a8a8a8);
}
textarea {
width: 100%;
box-sizing: border-box;
padding: 7px;
}
pre {
background: rgba(0, 0, 0, .07);
border-radius: 4px;
padding: 4px;
margin: 7px 0;
word-break: break-all;
word-break: break-word;
white-space: pre-wrap;
text-align: left;
}
.dark pre {
background: rgba(255, 255, 255, .15);
}
.hint {
font-size: .8em;
color: var(--tg-theme-hint-color, #a8a8a8);
}
.ok {
color: green;
}
.err {
color: red;
}
#fixed_wrap {
position: fixed;
left: 0;
right: 0;
top: 0;
transform: translateY(100vh);
}
.viewport_border,
.viewport_stable_border {
position: fixed;
left: 0;
right: 0;
top: 0;
height: var(--tg-viewport-height, 100vh);
pointer-events: none;
}
.viewport_stable_border {
height: var(--tg-viewport-stable-height, 100vh);
}
.viewport_border:before,
.viewport_stable_border:before {
content: attr(text);
display: inline-block;
position: absolute;
background: gray;
right: 0;
top: 0;
font-size: 7px;
padding: 2px 4px;
vertical-align: top;
}
.viewport_stable_border:before {
background: green;
left: 0;
right: auto;
}
.viewport_border:after,
.viewport_stable_border:after {
content: '';
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
border: 2px dashed gray;
}
.viewport_stable_border:after {
border-color: green;
}
small {
font-size: 12px;
}
h1 {
font-size: 120%;
word-wrap: break-word;
margin: 0.5em;
}
.qr-container {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
.qr {
display: flex;
justify-content: center;
margin: 0px;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.qr > canvas {
max-height: 800px;
max-width: 800px;
width: 100% !important;
height: 100% !important;
}
.wrapper {
display: grid;
grid-template-columns: 3fr 2fr;
padding: 12px 20px;
column-gap: 10px;
row-gap: 1em;
align-items: center;
}
</style>
</head>
<body>
<section>
<h1 id="greeting"></h1>
<div class="qr-container">
<div class="qr" id="qr">
</div>
</div>
<div id="buttons">
<!-- <button onclick="webviewClose();">Close</button> -->
<div class="wrapper">
<label class="sr-only" for="inlineFormInputGroup">Username</label>
<div class="input-group">
<input type="number" class="form-control" min="1" inputmode="decimal" step="any" pattern="\d+(\.\d*)?" id="invoiceAmount" placeholder="amount">
<div class="input-group-append">
<div class="input-group-text" id="inputCurrency"></div>
</div>
</div>
<div>
<button class="btn btn-primary" onclick="invoiceButtonClick();" style="display: inline;" id="requestInvoice">Invoice</button>
</div>
</div>
</div>
</section>
<script type="application/javascript">
Telegram.WebApp.ready();
// render the LNURL pay QR code
var s = "{{.LNURLPay}}";
const currencies = ["sat", "USD", "EUR"];
var currency_idx = 0;
document.getElementById("inputCurrency").innerHTML = currencies[0];
renderQr(s);
// data passed form telegram server
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').textContent = "{{.Username}}@ln.tips";
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
// react to theme changes
try {
document.querySelector('#themeData').html(JSON.stringify(Telegram.WebApp.themeParams, null, 2));
Telegram.WebApp.onEvent('themeChanged', function() {
document.querySelector('#themeData').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
});
} catch (error) {
console.error(error);
}
// listen for enter in input field
var el = document.getElementById("invoiceAmount");
el.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
document.getElementById("requestInvoice").click();
}
document.getElementById("requestInvoice").innerHTML = "Invoice"
// revert color of button
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
var el = document.getElementById("inputCurrency");
el.addEventListener("click", function(event) {
currency_idx += 1;
$(this).html(currencies[currency_idx%(currencies.length)]);
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
// ------------------ functions ------------------
function invoiceButtonClick() {
var c = "{{.Callback}}";
getInvoice(this, c);
// hide keyboard and scroll up
document.getElementById("invoiceAmount").blur();
window.scrollTo(0, 0);
}
function invoiceButtonDisplayError(message) {
btn = document.getElementById("requestInvoice")
btn.innerHTML = message
// update color of button
$('#requestInvoice').removeClass('btn-primary').addClass('btn-danger');
}
function webviewClose() {
Telegram.WebApp.close();
}
function renderQr(payload) {
const qr = document.getElementById('qr');
qr.innerHTML = '';
if ( qr ) {
const qrGfx = kjua({
text: payload,
rounded: 50,
size: 500,
render: 'canvas',
});
qr.appendChild( qrGfx );
// var href_link = "lightning:" + payload;
// qr.setAttribute('href', "javascript:window.open('"+ href_link+ "');" );
}
}
function getInvoice(el, callback) {
curr_idx = currency_idx%currencies.length
var invoiceAmount = Number(document.getElementById("invoiceAmount").value);
if ((currencies[curr_idx] == "sat" && !Number.isInteger(invoiceAmount)) || invoiceAmount < 1) {
invoiceButtonDisplayError("Invalid")
return false;
}
var amountQueryParam;
if (currencies[curr_idx] == "sat") {
amountQueryParam = invoiceAmount * 1000 // sat to msat
} else {
amountQueryParam = invoiceAmount + currencies[curr_idx]
}
fetch(callback)
.then(data => {
return data.json();
})
.then(r => {
console.log(r);
console.log("requesting invoice with amount " + amountQueryParam);
fetch(r.callback + '?amount='+ amountQueryParam).then(data => {
return data.json();
})
.then(r => {
console.log(r);
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').textContent = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
}
})
})
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
{{end}}
+126
View File
@@ -0,0 +1,126 @@
package userpage
import (
"embed"
"errors"
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/PuerkitoBio/goquery"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Service struct {
bot *telegram.TipBot
}
func New(b *telegram.TipBot) Service {
return Service{
bot: b,
}
}
// validUsername matches Telegram usernames and the anon id forms (numeric,
// 0x... and 1x...) the LNURL server accepts. The path variable is reflected
// into a page that handles payments, so nothing else is rendered.
var validUsername = regexp.MustCompile(`^[a-z0-9_]{1,64}$`)
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
//go:embed static
var templates embed.FS
var userpage_tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
var qr_tmpl = template.Must(template.ParseFS(templates, "static/webapp.html"))
var Client = &http.Client{
Timeout: 10 * time.Second,
}
// thank you fiatjaf for this code
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
// with proxy:
// client, err := s.network.GetHttpClient()
// if err != nil {
// return "", err
// }
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get("https://t.me/" + username)
if err != nil {
return "", err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", err
}
url, ok := doc.Find(`meta[property="og:image"]`).First().Attr("content")
if !ok {
return "", errors.New("no image available for this user")
}
return url, nil
}
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)
if err != nil {
log.Errorln("[UserPage]", err)
return
}
image, err := s.getTelegramUserPictureURL(username)
if err != nil || image == "https://telegram.org/img/t_logo.png" {
// replace the default image
image = botImage
}
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
Username string
Image string
LNURLPay string
}{username, image, lnurlEncode}); err != nil {
log.Errorf("failed to render template")
}
}
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/app/<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering webapp of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
log.Errorln("[UserPage]", err)
return
}
if err := qr_tmpl.ExecuteTemplate(w, "webapp", struct {
Username string
LNURLPay string
Callback string
}{username, lnurlEncode, callback}); err != nil {
log.Errorf("failed to render template")
}
}
+42
View File
@@ -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")
}
}
+134
View File
@@ -0,0 +1,134 @@
package internal
import (
"fmt"
"net/url"
"os"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/jinzhu/configor"
log "github.com/sirupsen/logrus"
)
var Configuration = struct {
Bot BotConfiguration `yaml:"bot"`
Telegram TelegramConfiguration `yaml:"telegram"`
Database DatabaseConfiguration `yaml:"database"`
Lnbits LnbitsConfiguration `yaml:"lnbits"`
Generate GenerateConfiguration `yaml:"generate"`
Nostr NostrConfiguration `yaml:"nostr"`
// LNURLCash is the optional LUD-25 bearer note feature (see docs/lnurlcash).
LNURLCash lnurlcash.Config `yaml:"lnurlcash"`
}{}
type NostrConfiguration struct {
PrivateKey string `yaml:"private_key"`
}
type GenerateConfiguration struct {
OpenAiBearerToken string `yaml:"open_ai_bearer_token"`
DalleKey string `yaml:"dalle_key"`
DallePrice int64 `yaml:"dalle_price"`
Worker int `yaml:"worker"`
}
type SocksConfiguration struct {
Host string `yaml:"host"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type BotConfiguration struct {
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
AdminAPIToken string `yaml:"admin_api_token"`
}
type TelegramConfiguration struct {
MessageDisposeDuration int64 `yaml:"message_dispose_duration"`
ApiKey string `yaml:"api_key"`
}
type DatabaseConfiguration struct {
DbPath string `yaml:"db_path"`
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
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 {
AdminId string `yaml:"admin_id"`
AdminKey string `yaml:"admin_key"`
Url string `yaml:"url"`
LnbitsPublicUrl string `yaml:"lnbits_public_url"`
WebhookServer string `yaml:"webhook_server"`
WebhookServerUrl *url.URL `yaml:"-"`
}
func init() {
err := configor.Load(&Configuration, "config.yaml")
if err != nil {
panic(err)
}
webhookUrl, err := url.Parse(Configuration.Lnbits.WebhookServer)
if err != nil {
panic(err)
}
Configuration.Lnbits.WebhookServerUrl = webhookUrl
lnUrl, err := url.Parse(Configuration.Bot.LNURLServer)
if err != nil {
panic(err)
}
Configuration.Bot.LNURLServerUrl = lnUrl
hostname, err := url.Parse(Configuration.Bot.LNURLHostName)
if err != nil {
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() {
if Configuration.Lnbits.Url == "" {
panic(fmt.Errorf("please configure a lnbits url"))
}
if Configuration.Lnbits.LnbitsPublicUrl == "" {
log.Warnf("Please specify a lnbits public url otherwise users won't be able to")
} else {
if !strings.HasSuffix(Configuration.Lnbits.LnbitsPublicUrl, "/") {
Configuration.Lnbits.LnbitsPublicUrl = Configuration.Lnbits.LnbitsPublicUrl + "/"
}
}
}
+23
View File
@@ -0,0 +1,23 @@
package dalle
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal"
"io"
)
var Enabled bool
func init() {
if internal.Configuration.Generate.DalleKey != "" {
Enabled = true
}
}
type Client interface {
Generate(ctx context.Context, prompt string) (*Task, error)
ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error)
GetTask(ctx context.Context, taskID string) (*Task, error)
Download(ctx context.Context, generationID string) (io.ReadCloser, error)
Share(ctx context.Context, generationID string) (string, error)
}
+11
View File
@@ -0,0 +1,11 @@
package dalle
const (
StatusPending = "pending"
StatusRejected = "rejected"
StatusSucceeded = "succeeded"
TaskTypeText2Im = "text2im"
defaultBatchSize = 4
)
+242
View File
@@ -0,0 +1,242 @@
package dalle
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
libraryVersion = "1.0.0"
defaultUserAgent = "dalle/" + libraryVersion
baseURL = "https://labs.openai.com/api/labs"
defaultHTTPClientTimeout = 15 * time.Second
)
type option func(*HTTPClient) error
func WithHTTPClient(httpClient *http.Client) option {
return func(c *HTTPClient) error {
c.httpClient = httpClient
return nil
}
}
func WithUserAgent(userAgent string) option {
return func(c *HTTPClient) error {
c.userAgent = userAgent
return nil
}
}
type HTTPClient struct {
httpClient *http.Client
userAgent string
apiKey string
}
var _ Client = (*HTTPClient)(nil)
func NewHTTPClient(apiKey string, opts ...option) (*HTTPClient, error) {
c := &HTTPClient{
httpClient: &http.Client{Timeout: defaultHTTPClientTimeout},
userAgent: defaultUserAgent,
apiKey: apiKey,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
}
type Task struct {
Object string `json:"object"`
ID string `json:"id"`
Created int64 `json:"created"`
TaskType string `json:"task_type"`
Status string `json:"status"`
PromptID string `json:"prompt_id"`
Prompt Prompt `json:"prompt"`
Generations Generations `json:"generations"`
}
type Generations struct {
Data []GenerationData `json:"data"`
Object string `json:"object"`
}
type GenerationData struct {
Created int64 `json:"created"`
Generation Generation `json:"generation"`
GenerationType string `json:"generation_type"`
ID string `json:"id"`
}
type Generation struct {
ImagePath string `json:"image_path"`
}
type Prompt struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
PromptType string `json:"prompt_type"`
Prompt struct {
Caption string `json:"caption"`
} `json:"prompt"`
ParentGenerationID string `json:"parent_generation_id"`
}
type GenerateRequest struct {
Prompt GenerateRequestPrompt `json:"prompt"`
TaskType string `json:"task_type"`
}
type GenerateRequestPrompt struct {
BatchSize int32 `json:"batch_size"`
Caption string `json:"caption"`
}
func (c *HTTPClient) Generate(ctx context.Context, caption string) (*Task, error) {
task := &Task{}
req := &GenerateRequest{
Prompt: GenerateRequestPrompt{
BatchSize: defaultBatchSize,
Caption: caption,
},
TaskType: TaskTypeText2Im,
}
return task, c.request(ctx, "POST", "/tasks", nil, req, task)
}
type ListTasksResponse struct {
Object string `json:"object"`
Data []Task `json:"data"`
}
type ListTasksRequest struct {
Limit int32 `json:"limit"`
}
func (c *HTTPClient) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
res := &ListTasksResponse{}
url := "/tasks"
if req != nil {
if req.Limit != 0 {
url += fmt.Sprintf("?limit=%d", req.Limit)
}
}
return res, c.request(ctx, "GET", url, nil, nil, res)
}
func (c *HTTPClient) GetTask(ctx context.Context, taskID string) (*Task, error) {
task := &Task{}
return task, c.request(ctx, "GET", "/tasks/"+taskID, nil, nil, task)
}
func (c *HTTPClient) Download(ctx context.Context, generationID string) (io.ReadCloser, error) {
req, err := c.createRequest(ctx, "/generations/"+generationID+"/download", "GET", nil, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("performing request: %w", err)
}
return resp.Body, nil
}
// Share makes the generation public and returns the public url
func (c *HTTPClient) Share(ctx context.Context, generationID string) (string, error) {
res := &GenerationData{}
err := c.request(ctx, "POST", "/generations/"+generationID+"/share", nil, nil, res)
if err != nil {
return "", err
}
return res.Generation.ImagePath, nil
}
func (c *HTTPClient) createRequest(ctx context.Context, path, method string, values *url.Values, data interface{}) (*http.Request, error) {
url := baseURL + path
if values != nil {
url += "?" + values.Encode()
}
var body io.Reader
if data != nil {
b, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("parsing request data: %w", err)
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("building request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+c.apiKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
return req, nil
}
func (c *HTTPClient) request(ctx context.Context, method, path string, values *url.Values, body interface{}, result interface{}) error {
req, err := c.createRequest(ctx, path, method, values, body)
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("performing request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
// TODO: improve error handling...
if resp.StatusCode != http.StatusOK {
return Error{
Message: "unexpected non 200 status code",
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
if err = json.Unmarshal(respBody, result); err != nil {
return Error{
Message: err.Error(),
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
return nil
}
type Error struct {
Message string
StatusCode int
Details string
}
func (e Error) Error() string {
return fmt.Sprintf("dalle: %s (status: %d, details: %s)", e.Message, e.StatusCode, e.Details)
}
+62
View File
@@ -0,0 +1,62 @@
package database
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
func MigrateAnonIdInt32Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
log.Infof("[MigrateAnonIdInt32Hash] %s -> %d", u.ID, str.Int32Hash(u.ID))
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateAnonIdInt32Hash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
func MigrateAnonIdSha265Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
anon_id := str.AnonIdSha256(&u)
log.Infof("[MigrateAnonIdSha265Hash] %s -> %s", pw, anon_id)
u.AnonIDSha256 = anon_id
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateAnonIdSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
func MigrateUUIDSha265Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
uuid := str.UUIDSha256(&u)
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
u.UUID = uuid
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateUUIDSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package database
import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/gorm"
)
func FindUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
func FindUserSettings(user *lnbits.User, settingsTx *gorm.DB) (*lnbits.User, error) {
// tx := bot.DB.Users.Preload("Settings").First(user)
tx := settingsTx.First(user)
if tx.Error != nil {
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
+29
View File
@@ -0,0 +1,29 @@
package errors
import (
"encoding/json"
)
func Create(code TipBotErrorType) TipBotError {
return errMap[code]
}
func New(code TipBotErrorType, err error) TipBotError {
if err != nil {
return TipBotError{Err: err, Message: err.Error(), Code: code}
}
return Create(code)
}
type TipBotError struct {
Message string `json:"message"`
Err error
Code TipBotErrorType `json:"code"`
}
func (e TipBotError) Error() string {
j, err := json.Marshal(&e)
if err != nil {
return e.Message
}
return string(j)
}
+75
View File
@@ -0,0 +1,75 @@
package errors
import "fmt"
type TipBotErrorType int
const (
UnknownError TipBotErrorType = iota
NoReplyMessageError
InvalidSyntaxError
MaxReachedError
NoPhotoError
NoFileFoundError
NotActiveError
InvalidTypeError
)
const (
UserNoWalletError TipBotErrorType = 2000 + iota
BalanceToLowError
SelfPaymentError
NoPrivateChatError
GetBalanceError
DecodeAmountError
DecodePerUserAmountError
InvalidAmountError
InvalidAmountPerUserError
)
const (
NoShopError TipBotErrorType = 3000 + iota
NotShopOwnerError
ShopNoOwnerError
ItemIdMismatchError
)
var errMap = map[TipBotErrorType]TipBotError{
UserNoWalletError: userNoWallet,
NoReplyMessageError: noReplyMessage,
InvalidSyntaxError: invalidSyntax,
InvalidAmountPerUserError: invalidAmount,
InvalidAmountError: invalidAmountPerUser,
NoPrivateChatError: noPrivateChat,
ShopNoOwnerError: shopNoOwner,
NotShopOwnerError: notShopOwner,
MaxReachedError: maxReached,
NoShopError: noShop,
SelfPaymentError: selfPayment,
NoPhotoError: noPhoto,
ItemIdMismatchError: itemIdMismatch,
NoFileFoundError: noFileFound,
UnknownError: unknown,
NotActiveError: notActive,
InvalidTypeError: invalidType,
}
var (
userNoWallet = TipBotError{Err: fmt.Errorf("user has no wallet")}
noReplyMessage = TipBotError{Err: fmt.Errorf("no reply message")}
invalidSyntax = TipBotError{Err: fmt.Errorf("invalid syntax")}
invalidAmount = TipBotError{Err: fmt.Errorf("invalid amount")}
invalidAmountPerUser = TipBotError{Err: fmt.Errorf("invalid amount per user")}
noPrivateChat = TipBotError{Err: fmt.Errorf("no private chat")}
shopNoOwner = TipBotError{Err: fmt.Errorf("shop has no owner")}
notShopOwner = TipBotError{Err: fmt.Errorf("user is not shop owner")}
maxReached = TipBotError{Err: fmt.Errorf("maximum reached")}
noShop = TipBotError{Err: fmt.Errorf("user has no shop")}
selfPayment = TipBotError{Err: fmt.Errorf("can't pay yourself")}
noPhoto = TipBotError{Err: fmt.Errorf("no photo in message")}
itemIdMismatch = TipBotError{Err: fmt.Errorf("item id mismatch")}
noFileFound = TipBotError{Err: fmt.Errorf("no file found")}
unknown = TipBotError{Err: fmt.Errorf("unknown error")}
notActive = TipBotError{Err: fmt.Errorf("element not active")}
invalidType = TipBotError{Err: fmt.Errorf("invalid type")}
)
+102
View File
@@ -0,0 +1,102 @@
package gpt
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"net/http"
)
type Response struct {
Message struct {
ID string `json:"id"`
Role string `json:"role"`
User interface{} `json:"user"`
CreateTime interface{} `json:"create_time"`
UpdateTime interface{} `json:"update_time"`
Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
} `json:"content"`
EndTurn interface{} `json:"end_turn"`
Weight float64 `json:"weight"`
Metadata struct {
} `json:"metadata"`
Recipient string `json:"recipient"`
} `json:"message"`
ConversationID string `json:"conversation_id"`
Error interface{} `json:"error"`
}
type Request struct {
Action string `json:"action"`
ConversationId string `json:"conversation_id,omitempty"`
Messages []Messages `json:"messages"`
ParentMessageID string `json:"parent_message_id"`
Model string `json:"model"`
}
type Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
}
type Messages struct {
ID string `json:"id"`
Role string `json:"role"`
Content Content `json:"content"`
}
var dataPrefix = []byte("data: ")
var doneSequence = []byte("[DONE]")
func GetRawCompletion(ctx intercept.Context, rr Request, cb func(s string)) (*Response, error) {
rawClient := http.Client{}
r, err := json.Marshal(rr)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx.Context, "POST", "https://chat.openai.com/backend-api/conversation", bytes.NewBuffer(r))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", internal.Configuration.Generate.OpenAiBearerToken))
req.Header.Set("accept", "text/event-stream")
req.Header.Set("authority", "chat.openai.com")
req.Header.Set("accept-language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7")
req.Header.Set("Content-type", "application/json")
req.Header.Set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
resp, err := rawClient.Do(req)
if err != nil {
return nil, err
}
reader := bufio.NewReader(resp.Body)
defer resp.Body.Close()
output := new(Response)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
// make sure there isn't any extra whitespace before or after
line = bytes.TrimSpace(line)
// the completion API only returns data events
if !bytes.HasPrefix(line, dataPrefix) {
continue
}
line = bytes.TrimPrefix(line, dataPrefix)
// the stream is completed when terminated by [DONE]
if bytes.HasPrefix(line, doneSequence) {
break
}
if err := json.Unmarshal(line, output); err != nil {
return nil, fmt.Errorf("invalid json stream data: %v", err)
}
if len(output.Message.Content.Parts) > 0 {
cb(output.Message.Content.Parts[len(output.Message.Content.Parts)-1])
}
}
return output, nil
}
+55
View File
@@ -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)
}
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package i18n
import (
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
"golang.org/x/text/language"
)
var Bundle *i18n.Bundle
func init() {
Bundle = RegisterLanguages()
}
// translationsDir finds the translations directory. The bot runs from the
// repository root; go test runs from the package directory, so walk up.
func translationsDir() string {
dir := "translations"
for i := 0; i < 6; i++ {
if st, err := os.Stat(dir); err == nil && st.IsDir() {
return dir
}
dir = filepath.Join("..", dir)
}
return "translations"
}
func RegisterLanguages() *i18n.Bundle {
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
dir := translationsDir()
bundle.MustLoadMessageFile(filepath.Join(dir, "en.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "de.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "fi.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "it.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "es.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "nl.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "pl.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "fr.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "pt-br.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "tr.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "cs.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "id.toml"))
bundle.LoadMessageFile(filepath.Join(dir, "ru.toml"))
return bundle
}
func Translate(languageCode string, MessgeID string) string {
str, err := i18n.NewLocalizer(Bundle, languageCode).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
if err != nil {
log.Warnf("Error translating message %s: %s", MessgeID, err)
}
return str
}
+80 -9
View File
@@ -1,6 +1,9 @@
package lnbits
import (
"fmt"
"time"
"github.com/imroc/req"
)
@@ -8,6 +11,10 @@ import (
func NewClient(key, url string) *Client {
return &Client{
url: url,
// info: this header holds the ADMIN key for the entire API
// it can be used to create wallets for example
// if you want to check the balance of a user, use w.Inkey
// if you want to make a payment, use w.Adminkey
header: req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
@@ -74,14 +81,18 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
return
}
err = resp.ToJSON(&wal)
wal.Client = c
return
}
// Invoice creates an invoice associated with this wallet.
func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(&params))
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Post(c.url+"/api/v1/payments", invoiceHeader, req.BodyJSON(&params))
if err != nil {
return
}
@@ -99,8 +110,13 @@ func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err er
// Info returns wallet information
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Get(w.url+"/api/v1/wallet", w.header, nil)
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+"/api/v1/wallet", invoiceHeader, nil)
if err != nil {
return
}
@@ -116,6 +132,54 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
return
}
// Payments returns wallet payments
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+"/api/v1/payments?limit=60", invoiceHeader, nil)
if err != nil {
return
}
if resp.Response().StatusCode >= 300 {
var reqErr Error
resp.ToJSON(&reqErr)
err = reqErr
return
}
err = resp.ToJSON(&wtx)
return
}
// Payment state of a payment
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
if err != nil {
return
}
if resp.Response().StatusCode >= 300 {
var reqErr Error
resp.ToJSON(&reqErr)
err = reqErr
return
}
err = resp.ToJSON(&payment)
return
}
// Wallets returns all wallets belonging to an user
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
@@ -135,9 +199,16 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
}
// Pay pays a given invoice with funds from the wallet.
func (c Client) Pay(params PaymentParams, w Wallet) (wtx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(&params))
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
// custom header with admin key
adminHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Adminkey,
}
r := req.New()
r.SetTimeout(time.Hour * 24)
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(&params))
if err != nil {
return
}
+120 -35
View File
@@ -1,8 +1,17 @@
package lnbits
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/imroc/req"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Client struct {
@@ -13,31 +22,74 @@ type Client struct {
}
type User struct {
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
Initialized bool `json:"initialized"`
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
StateKey UserStateKey `json:"stateKey"`
StateData string `json:"stateData"`
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
Initialized bool `json:"initialized"`
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
StateKey UserStateKey `json:"stateKey"`
StateData string `json:"stateData"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
AnonID string `json:"anon_id"`
AnonIDSha256 string `json:"anon_id_sha256"`
UUID string `json:"uuid"`
Banned bool `json:"banned"`
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
Display DisplaySettings `gorm:"embedded;embeddedPrefix:display_"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
}
type DisplaySettings struct {
DisplayCurrency string `json:"displaycurrency"`
}
type NostrSettings struct {
PubKey string `json:"pubkey"`
}
type NodeSettings struct {
NodeType string `json:"nodetype"`
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
LNbitsParams *satdress.LNBitsParams `gorm:"embedded;embeddedPrefix:lnbitsparams_"`
}
type UserStateKey int
const (
UserStateConfirmPayment = iota + 1
UserStateConfirmSend
UserStateLNURLEnterAmount
UserStateConfirmLNURLPay
UserEnterAmount
UserHasEnteredAmount
UserEnterUser
UserHasEnteredUser
UserEnterShopTitle
UserStateShopItemSendPhoto
UserStateShopItemSendTitle
UserStateShopItemSendDescription
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
UserEnterDallePrompt
)
type UserStateKey int
func (u *User) ResetState() {
u.StateData = ""
u.StateKey = 0
}
type InvoiceParams struct {
Out bool `json:"out"`
Amount int64 `json:"amount"`
Memo string `json:"memo"` // the invoice description.
Webhook string `json:"webhook,omitempty"`
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in Satoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
}
type PaymentParams struct {
@@ -59,18 +111,14 @@ type TransferParams struct {
}
type Error struct {
Name string `json:"name"`
Message string `json:"message"`
Code int `json:"code"`
Status int `json:"status"`
Detail string `json:"detail"`
}
func (err Error) Error() string {
return err.Message
return err.Detail
}
type Wallet struct {
*Client `gorm:"-"`
ID string `json:"id" gorm:"id"`
Adminkey string `json:"adminkey"`
Inkey string `json:"inkey"`
@@ -78,23 +126,60 @@ type Wallet struct {
Name string `json:"name"`
User string `json:"user"`
}
type BitInvoice struct {
type Payment struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook interface{} `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
type LNbitsPayment struct {
Paid bool `json:"paid"`
Preimage string `json:"preimage"`
Details Payment `json:"details,omitempty"`
}
type Payments []Payment
type Invoice struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
}
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending int `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
// from fiatjaf/lnurl-go
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
seedHash := sha256.Sum256([]byte(
fmt.Sprintf("lnurlkeyseed:%s:%s",
domain, u.ID)))
return btcec.PrivKeyFromBytes(seedHash[:])
}
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
// lnurl-auth: create a key based on the user id and sign with it
sk, pk := u.LinkingKey(domain)
k1, err := hex.DecodeString(k1hex)
if err != nil {
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
}
signature := ecdsa.Sign(sk, k1)
if err != nil {
return "", "", fmt.Errorf("error signing k1: %w", err)
}
sig = hex.EncodeToString(signature.Serialize())
key = hex.EncodeToString(pk.SerializeCompressed())
return key, sig, nil
}
-91
View File
@@ -1,91 +0,0 @@
package lnbits
import (
"encoding/json"
"fmt"
"net"
"strings"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/gorilla/mux"
tb "gopkg.in/tucnak/telebot.v2"
"net/http"
"time"
)
const (
invoiceReceivedMessage = "⚡️ You've received %d sat."
)
type WebhookServer struct {
httpServer *http.Server
bot *tb.Bot
c *Client
database *gorm.DB
}
func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gorm.DB) *WebhookServer {
if !strings.Contains(webhookServer, "://") {
log.Fatal("invalid webhook server configuration. please add a scheme.")
}
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
if err != nil {
return nil
}
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &WebhookServer{
c: client,
database: database,
bot: bot,
httpServer: srv,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
return apiServer
}
func (w *WebhookServer) GetUserByWalletId(walletId string) (*User, error) {
user := &User{}
tx := w.database.Where("wallet_id = ?", walletId).First(user)
if tx.Error != nil {
return user, tx.Error
}
user.Wallet.Client = w.c
return user, nil
}
func (w *WebhookServer) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
return router
}
func (w WebhookServer) receive(writer http.ResponseWriter, request *http.Request) {
depositEvent := Webhook{}
request.Header.Del("content-length")
err := json.NewDecoder(request.Body).Decode(&depositEvent)
if err != nil {
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(depositEvent.WalletID)
if err != nil {
writer.WriteHeader(400)
return
}
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(invoiceReceivedMessage, depositEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
writer.WriteHeader(200)
}
+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)
}
}
}
+214
View File
@@ -0,0 +1,214 @@
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"
"gorm.io/gorm"
"net/http"
"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
c *lnbits.Client
database *gorm.DB
buntdb *storage.DB
}
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int64 `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: bot.Client,
database: bot.DB.Users,
bot: bot.Telegram,
httpServer: srv,
buntdb: bot.Bunt,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[Webhook] Server started at %s", internal.Configuration.Lnbits.WebhookServerUrl)
return apiServer
}
func (w *Server) GetUserByWalletId(walletId string) (*lnbits.User, error) {
user := &lnbits.User{}
tx := w.database.Where("wallet_id = ?", walletId).First(user)
if tx.Error != nil {
return user, tx.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)
return router
}
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
webhookEvent := Webhook{}
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, maxBodyBytes))
if err != nil {
log.Errorf("[Webhook] Error reading request body: %s", err.Error())
writer.WriteHeader(400)
return
}
if err = json.Unmarshal(body, &webhookEvent); err != nil {
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
writer.WriteHeader(400)
return
}
// The hash becomes part of an LNbits URL and of the replay key, so only
// the form LNbits uses is accepted.
if !verify.ValidPaymentHash(webhookEvent.PaymentHash) {
log.Errorf("[Webhook] Rejecting webhook with malformed payment_hash")
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil || user.Wallet == nil || user.Wallet.ID == "" {
log.Errorf("[Webhook] Error getting user for wallet_id %q: %v", webhookEvent.WalletID, err)
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)
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
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 {
if err := telegram.AssertEventType(txInvoiceEvent, c.Type); err != nil {
log.Errorln(err)
return
}
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"), 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)
}
+21
View File
@@ -0,0 +1,21 @@
package lndhub
import (
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"gorm.io/gorm"
)
type LndHub struct {
database *gorm.DB
}
func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
}
+517
View File
@@ -0,0 +1,517 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/eko/gocache/store"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"gorm.io/gorm"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
"github.com/nbd-wtf/go-nostr"
log "github.com/sirupsen/logrus"
)
const (
PayRequestTag = "payRequest"
Endpoint = ".well-known/lnurlp"
MinSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 2000
)
type Invoice struct {
*telegram.Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Nip57Receipt nostr.Event `json:"nip57_receipt"`
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
}
type Lnurl struct {
telegram *tb.Bot
c *lnbits.Client
database *gorm.DB
callbackHostname *url.URL
buntdb *storage.DB
WebhookServer string
cache telegram.Cache
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Lnurl {
return Lnurl{
c: bot.Client,
database: bot.DB.Users,
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
telegram: bot.Telegram,
cache: bot.Cache,
bot: bot,
}
}
func (lnurlInvoice Invoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
var err error
var response interface{}
username := mux.Vars(request)["username"]
if request.URL.RawQuery == "" {
response, err = w.serveLNURLpFirst(username)
} else {
stringAmount := request.FormValue("amount")
if stringAmount == "" {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
return
}
var amount int64
if amount, err = strconv.ParseInt(stringAmount, 10, 64); err != nil {
// if the value wasn't a clean msat denomination, parse it
amount, err = telegram.GetAmount(stringAmount)
if err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int: %v", err))
return
}
// GetAmount returns sat, we need msat
amount *= 1000
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
return
}
// payer data
payerdata := request.FormValue("payerdata")
var payerData lnurl.PayerDataValues
if len(payerdata) > 0 {
err = json.Unmarshal([]byte(payerdata), &payerData)
if err != nil {
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
}
}
// nostr NIP-57
// the "nostr" query param has a zap request which is a nostr event
// that specifies which nostr note has been zapped.
// here we check wheter its present, the event signature is valid
// and whether the event has the necessary tags that we need (p and relays are necessary, e is optional)
zapEventQuery := request.FormValue("nostr")
var zapEvent nostr.Event
if len(zapEventQuery) > 0 {
// A request that does not decode cleanly can still carry a pubkey, tags
// and sig (the library keeps the fields it read before the error), so
// it must never reach the zap path unverified.
if err = json.Unmarshal([]byte(zapEventQuery), &zapEvent); err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse nostr event: %v", err))
return
}
valid, err := zapEvent.CheckSignature()
if !valid || err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Nostr NIP-57 zap event signature invalid: %v", err))
return
}
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData, zapEvent)
}
// check if error was returned from first or second handlers
if err != nil {
// log the error
log.Errorf("[LNURL] %v", err.Error())
if response != nil {
// there is a valid error response
err = api.WriteResponse(writer, response)
if err != nil {
api.NotFoundHandler(writer, err)
}
}
return
}
// no error from first or second handler
err = api.WriteResponse(writer, response)
if err != nil {
api.NotFoundHandler(writer, err)
}
}
func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
key := fmt.Sprintf("lnurl_metadata_%s", username)
// load metadata from cache
if m, err := w.cache.Get(key); err == nil {
return m.(lnurl.Metadata)
}
// otherwise, create new metadata
metadata := w.metaData(username)
// load the user profile picture
if internal.Configuration.Bot.LNURLSendImage {
// get the user from the database
user, tx := db.FindUser(w.database, username)
if tx.Error == nil && user.Telegram != nil {
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
}
}
// save into cache
runtime.IgnoreError(w.cache.Set(key, metadata, &store.Options{Expiration: 30 * time.Minute}))
return metadata
}
// we have our custom LNURLPayParams response object here because we want to
// add nostr nip57 fields to it
type LNURLPayParamsCustom struct {
lnurl.LNURLResponse
Callback string `json:"callback"`
Tag string `json:"tag"`
MaxSendable int64 `json:"maxSendable"`
MinSendable int64 `json:"minSendable"`
EncodedMetadata string `json:"metadata"`
CommentAllowed int64 `json:"commentAllowed"`
PayerData *lnurl.PayerDataSpec `json:"payerData,omitempty"`
AllowNostr bool `json:"allowsNostr,omitempty"`
NostrPubKey string `json:"nostrPubkey,omitempty"`
Metadata lnurl.Metadata `json:"-"`
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error) {
log.Infof("[LNURL] Serving endpoint for user %s", username)
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
if err != nil {
return nil, err
}
// produce the metadata including the image
metadata := w.getMetaDataCached(username)
// check if the user has added a nostr key for nip57
var allowNostr bool = false
var nostrPubkey string = ""
// if the bot has a nostr private key
if len(internal.Configuration.Nostr.PrivateKey) > 0 {
allowNostr = true
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nostrPubkey = pub
}
return &LNURLPayParamsCustom{
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
Tag: PayRequestTag,
Callback: callbackURL.String(),
MinSendable: MinSendable,
MaxSendable: MaxSendable,
EncodedMetadata: metadata.Encode(),
CommentAllowed: CommentAllowed,
PayerData: &lnurl.PayerDataSpec{
FreeName: &lnurl.PayerDataItemSpec{},
LightningAddress: &lnurl.PayerDataItemSpec{},
Email: &lnurl.PayerDataItemSpec{},
},
AllowNostr: allowNostr,
NostrPubKey: nostrPubkey,
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues, zapEvent nostr.Event) (*lnurl.LNURLPayValues, error) {
log.Infof("[LNURL] Serving invoice for user %s", username)
if amount_msat < MinSendable || amount_msat > MaxSendable {
// amount is not ok
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d sat, max: %d sat).", MinSendable/1000, MaxSendable/1000)},
}, fmt.Errorf("amount out of bounds")
}
// check comment length
if len(comment) > CommentAllowed {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
// get rid of LNURL spam
if amount_msat < 21_000 {
comment = ""
}
user, tx := db.FindUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
}
if user.Wallet == nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
}
// get user settings
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
if err != nil {
log.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
} else {
user = user2
}
// A zap request is only honoured if it names this user (NIP-57, appendix D).
// The receipt is signed with the bot's key and is valid for any p tag, so
// the recipient must be bound to the paid user here.
if zapEvent.Sig != "" {
recipient := ""
if user.Settings != nil {
recipient = user.Settings.Nostr.PubKey
}
if err := validateZapRequest(zapEvent, amount_msat, recipient); err != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Invalid zap request."},
}, fmt.Errorf("[serveLNURLpSecond] %v", err)
}
}
// user is ok now create invoice
// set wallet lnbits client
var resp *lnurl.LNURLPayValues
var descriptionHash string
// NIP57 ZAPs
// TODO: refactor all this into nip57.go
var nip57Receipt nostr.Event
var zapEventSerializedStr string
var nip57ReceiptRelays []string
// for nip57 use the nostr event as the descriptionHash
if zapEvent.Sig != "" {
log.Infof("[LNURL] nostr zap for user %s", username)
// we calculate the descriptionHash here, create an invoice with it
// and store the invoice in the zap receipt later down the line
zapEventSerialized, err := json.Marshal(zapEvent)
zapEventSerializedStr = fmt.Sprintf("%s", zapEventSerialized)
if err != nil {
log.Println(err)
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Couldn't serialize zap event."},
}, err
}
// we extract the relays from the zap request
nip57ReceiptRelaysTags := zapEvent.Tags.GetFirst([]string{"relays"})
if len(fmt.Sprintf("%s", nip57ReceiptRelaysTags)) > 0 {
nip57ReceiptRelays = strings.Split(fmt.Sprintf("%s", nip57ReceiptRelaysTags), " ")
// this tirty method returns slice [ "[relays", "wss...", "wss...", "wss...]" ] – we need to clean it up
if len(nip57ReceiptRelays) > 1 {
// remove the first entry
nip57ReceiptRelays = nip57ReceiptRelays[1:]
// clean up the last entry
len_last_entry := len(nip57ReceiptRelays[len(nip57ReceiptRelays)-1])
nip57ReceiptRelays[len(nip57ReceiptRelays)-1] = nip57ReceiptRelays[len(nip57ReceiptRelays)-1][:len_last_entry-1]
}
// now the relay list is clean!
}
// calculate description hash from the serialized nostr event
descriptionHash = w.Nip57DescriptionHash(zapEventSerializedStr)
} else {
// calculate normal LNURL descriptionhash
// the same description_hash needs to be built in the second request
metadata := w.getMetaDataCached(username)
var payerDataByte []byte
var err error
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
payerDataByte, err = json.Marshal(payerData)
if err != nil {
return nil, err
}
} else {
payerDataByte = []byte("")
}
descriptionHash, err = w.DescriptionHash(metadata, string(payerDataByte))
if err != nil {
return nil, err
}
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: amount_msat / 1000,
Out: false,
DescriptionHash: descriptionHash,
Webhook: w.WebhookServer},
w.c)
if err != nil {
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
resp = &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Couldn't create invoice."},
}
return resp, err
}
invoiceStruct := &telegram.Invoice{
PaymentRequest: invoice.PaymentRequest,
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// nip57 - we need to store the newly created invoice in the zap receipt
if zapEvent.Sig != "" {
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nip57Receipt = nostr.Event{
PubKey: pub,
CreatedAt: time.Now(),
Kind: 9735,
Tags: nostr.Tags{
*zapEvent.Tags.GetFirst([]string{"p"}),
[]string{"bolt11", invoice.PaymentRequest},
[]string{"description", zapEventSerializedStr},
},
}
if zapEvent.Tags.GetFirst([]string{"e"}) != nil {
nip57Receipt.Tags = nip57Receipt.Tags.AppendUnique(*zapEvent.Tags.GetFirst([]string{"e"}))
}
nip57Receipt.Sign(pk)
}
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
// also holds Nip57 Zap receipt to send to nostr when invoice is paid
runtime.IgnoreError(w.buntdb.Set(
Invoice{
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
Nip57Receipt: nip57Receipt,
Nip57ReceiptRelays: nip57ReceiptRelays,
}))
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
telegram.InvoiceEvent{
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
UserCurrency: user.Settings.Display.DisplayCurrency,
}))
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
PR: invoice.PaymentRequest,
Routes: make([]struct{}, 0),
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
}, nil
}
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
var hashString string
var hash [32]byte
if len(payerData) == 0 {
hash = sha256.Sum256([]byte(metadata.Encode()))
hashString = hex.EncodeToString(hash[:])
} else {
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
hashString = hex.EncodeToString(hash[:])
}
return hashString, nil
}
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Lnurl) metaData(username string) lnurl.Metadata {
// this is a bit stupid but if the address is a UUID starting with 1x...
// we actually want to find the users username so it looks nicer in the
// metadata description
if strings.HasPrefix(username, "1x") {
user, _ := db.FindUser(w.database, username)
if user.Telegram.Username != "" {
username = user.Telegram.Username
}
}
return lnurl.Metadata{
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
}
}
// addImageMetaData add images an image to the LNURL metadata
func addImageToMetaData(tb *tb.Bot, metadata *lnurl.Metadata, username string, user *tb.User) {
metadata.Image.Ext = "jpeg"
// if the username is anonymous, add the bot's picture
if isAnonUsername(username) {
metadata.Image.Bytes = telegram.BotProfilePicture
return
}
// if the user has a profile picture, add it
picture, err := telegram.DownloadProfilePicture(tb, user)
if err != nil {
log.Debugf("[LNURL] Couldn't download user %s's profile picture: %v", username, err)
// in case the user has no image, use bot's picture
metadata.Image.Bytes = telegram.BotProfilePicture
return
}
metadata.Image.Bytes = picture
}
func isAnonUsername(username string) bool {
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
return true
} else {
return strings.HasPrefix(username, "0x")
}
}
func extractSenderFromPayerdata(payer lnurl.PayerDataValues) string {
if payer.LightningAddress != "" {
return payer.LightningAddress
}
if payer.Email != "" {
return payer.Email
}
if payer.FreeName != "" {
return payer.FreeName
}
return ""
}
+66
View File
@@ -0,0 +1,66 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
"github.com/nbd-wtf/go-nostr"
)
type Tag []string
type Tags []Tag
type NostrEvent struct {
ID string `json:"id"`
PubKey string `json:"pubkey"`
CreatedAt time.Time `json:"created_at"`
Kind int `json:"kind"`
Tags Tags `json:"tags"`
Content string `json:"content"`
Sig string `json:"sig"`
}
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) Nip57DescriptionHash(zapEventSerialized string) string {
hash := sha256.Sum256([]byte(zapEventSerialized))
hashString := hex.EncodeToString(hash[:])
return hashString
}
// validateZapRequest checks a NIP-57 zap request against the payment it is
// for: kind 9734, exactly one p tag naming the recipient, at most one e tag,
// and an amount tag (if present) equal to the amount of the payment.
// recipientPubkey is the nostr pubkey the paid user registered with the bot;
// without one the request cannot be bound to the user and is refused.
func validateZapRequest(ev nostr.Event, amountMsat int64, recipientPubkey string) error {
if ev.Kind != 9734 {
return fmt.Errorf("zap request has kind %d", ev.Kind)
}
var pTags, eTags int
for _, t := range ev.Tags {
if len(t) < 2 {
continue
}
switch t[0] {
case "p":
pTags++
if recipientPubkey == "" || t[1] != recipientPubkey {
return fmt.Errorf("zap request p tag does not name the paid user")
}
case "e":
eTags++
case "amount":
if v, err := strconv.ParseInt(t[1], 10, 64); err != nil || v != amountMsat {
return fmt.Errorf("zap request amount %q does not match %d msat", t[1], amountMsat)
}
}
}
if pTags != 1 || eTags > 1 {
return fmt.Errorf("zap request has %d p tags and %d e tags", pTags, eTags)
}
return nil
}
+37
View File
@@ -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")
}
}
+126
View File
@@ -0,0 +1,126 @@
package network
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
type ClientType string
const (
ClientTypeClearNet = "clearnet"
ClientTypeTor = "tor"
)
// checks if strings contains http(s)://*.onion
var isOnion = regexp.MustCompile("^https?\\:\\/\\/[\\w\\-\\.]+\\.onion")
// GetClientForScheme returns correct client for url scheme.
// if tld is .onion, function will also return an onion client.
func GetClientForScheme(url *url.URL) (*http.Client, error) {
if isOnion.FindString(url.String()) != "" {
return GetClient(ClientTypeTor)
}
switch url.Scheme {
case "onion":
return GetClient(ClientTypeTor)
default:
return GetClient(ClientTypeClearNet)
}
}
// directTransport returns the transport used when no proxy is configured. The
// URLs fetched with these clients come from users and remote servers, so it
// only connects to public addresses. Every client gets its own transport,
// because callers change its TLS settings (satdress.SetupHttpClient).
func directTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.DialContext = netguard.DialContext
return t
}
// The bot's own hosts may resolve to loopback (hosts file, split DNS). Paying
// a lightning address on them must keep working.
func init() {
if u := internal.Configuration.Bot.LNURLHostUrl; u != nil {
netguard.Trust(u.Hostname())
}
if u, err := url.Parse(internal.Configuration.Lnbits.Url); err == nil {
netguard.Trust(u.Hostname())
}
}
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
Transport: directTransport(),
}
var cfg *internal.SocksConfiguration
switch clientType {
case ClientTypeClearNet:
cfg = internal.Configuration.Bot.SocksProxy
case ClientTypeTor:
cfg = internal.Configuration.Bot.TorProxy
default:
return nil, fmt.Errorf("[GetClient] invalid clientType")
}
if cfg == nil {
return &client, nil
}
if cfg.Host == "" {
return &client, nil
}
proxyURL, _ := url.Parse(cfg.Host)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
var auth *proxy.Auth
if cfg.Username != "" && cfg.Password != "" {
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
}
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
log.Errorln(err)
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// The proxy resolves hostnames, so only literal addresses and
// localhost names can be refused here.
if err := netguard.CheckHost(addr); err != nil {
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
}
+56
View File
@@ -0,0 +1,56 @@
package nostr
import (
"fmt"
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/api"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/prometheus/common/log"
"gorm.io/gorm"
)
type Nostr struct {
database *gorm.DB
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Nostr {
return Nostr{
database: bot.DB.Users,
bot: bot,
}
}
func (n Nostr) Handle(writer http.ResponseWriter, request *http.Request) {
username := request.FormValue("name")
if username == "" {
api.NotFoundHandler(writer, fmt.Errorf("[NostrNip05] Form value 'name' is not set"))
return
}
user, tx := db.FindUser(n.database, username)
if tx.Error == nil && user.Telegram != nil {
user, err := db.FindUserSettings(user, n.bot.DB.Users.Preload("Settings"))
if err != nil {
log.Errorf("[NostrNip05] user settings not found")
api.NotFoundHandler(writer, fmt.Errorf("user settings error"))
return
}
if user.Settings.Nostr.PubKey != "" {
data := []byte(fmt.Sprintf(`{
"names":{
"%s":"%s"
}
}
`, username, user.Settings.Nostr.PubKey))
_, err = writer.Write(data)
if err != nil {
log.Errorf("[NostrNip05] Failed responding to user %s", username)
}
}
} else {
log.Errorf("[NostrNip05] user not found")
api.NotFoundHandler(writer, fmt.Errorf("user not found"))
}
}
+151
View File
@@ -0,0 +1,151 @@
package price
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
type PriceWatcher struct {
client *http.Client
UpdateInterval time.Duration
Currencies map[string]string
Exchanges map[string]func(string) (float64, error)
}
var (
// price is written by the watcher and read by every fiat amount, so it is
// only accessed through Get and set.
price = make(map[string]float64)
priceMu sync.RWMutex
P *PriceWatcher
)
// 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{
Timeout: time.Second * time.Duration(5),
},
// attention: $ must come after other $-denominated currencies like R$
Currencies: map[string]string{
"EUR": "€",
"GBP": "£",
"JPY": "¥",
"BRL": "R$",
"MXN": "MX$",
"USD": "$",
"RUB": "₽",
"TRY": "₺",
"INR": "₹",
},
Exchanges: make(map[string]func(string) (float64, error), 0),
UpdateInterval: time.Second * time.Duration(30),
}
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
log.Infof("[PriceWatcher] Watcher started")
P = pricewatcher
return pricewatcher
}
func (p *PriceWatcher) Start() {
go p.Watch()
}
func (p *PriceWatcher) Watch() error {
for {
for currency, _ := range p.Currencies {
avg_price := 0.0
n_responses := 0
for _, getPrice := range p.Exchanges {
fprice, err := getPrice(currency)
if err != nil {
// log.Debug(err)
// if one exchanges is down, use the next
continue
}
n_responses++
avg_price += fprice
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
time.Sleep(time.Second * time.Duration(2))
}
if n_responses == 0 {
// every exchange failed: keep the last known price
continue
}
set(currency, avg_price/float64(n_responses))
}
time.Sleep(p.UpdateInterval)
}
}
func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
coinbaseEndpoint, err := url.Parse(fmt.Sprintf("https://api.coinbase.com/v2/prices/spot?currency=%s", currency))
response, err := p.client.Get(coinbaseEndpoint.String())
if err != nil {
return 0, err
}
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Debug(err)
return 0, err
}
price := gjson.Get(string(bodyBytes), "data.amount")
if len(price.String()) > 0 {
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
} else {
return 0, fmt.Errorf("no price")
}
}
func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
var bitfinexCurrencyToPair = map[string]string{"USD": "btcusd", "EUR": "btceur", "GBP": "btcusd", "JPY": "btcjpy"}
pair := bitfinexCurrencyToPair[currency]
bitfinexEndpoint, err := url.Parse(fmt.Sprintf("https://api.bitfinex.com/v1/pubticker/%s", pair))
response, err := p.client.Get(bitfinexEndpoint.String())
if err != nil {
return 0, err
}
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Debug(err)
return 0, err
}
price := gjson.Get(string(bodyBytes), "last_price")
if len(price.String()) > 0 {
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
} else {
return 0, fmt.Errorf("no price")
}
}
+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"))
}
}
+95
View File
@@ -0,0 +1,95 @@
package rate
import (
"context"
"strconv"
"sync"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// Limiter
type Limiter struct {
keys map[string]*rate.Limiter
mu *sync.RWMutex
r rate.Limit
b int
}
var idLimiter *Limiter
var globalLimiter *rate.Limiter
// NewLimiter creates both chat and global rate limiters.
func Start() {
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
}
// NewRateLimiter .
func newIdRateLimiter(r rate.Limit, b int) *Limiter {
i := &Limiter{
keys: make(map[string]*rate.Limiter),
mu: &sync.RWMutex{},
r: r,
b: b,
}
return i
}
func CheckLimit(to interface{}) {
globalLimiter.Wait(context.Background())
var id string
switch to.(type) {
case string:
id = to.(string)
case *tb.Chat:
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
case *tb.User:
id = strconv.FormatInt(to.(*tb.User).ID, 10)
case tb.Recipient:
id = to.(tb.Recipient).Recipient()
case *tb.Message:
if to.(*tb.Message).Chat != nil {
id = strconv.FormatInt(to.(*tb.Message).Chat.ID, 10)
}
}
if len(id) > 0 {
log.Tracef("[Check Limit] limiter for %+v", id)
idLimiter.GetLimiter(id).Wait(context.Background())
return
}
log.Tracef("[Check Limit] skipping id limiter for %+v", to)
}
// Add creates a new rate limiter and adds it to the keys map,
// using the key
func (i *Limiter) Add(key string) *rate.Limiter {
i.mu.Lock()
defer i.mu.Unlock()
limiter := rate.NewLimiter(i.r, i.b)
i.keys[key] = limiter
return limiter
}
// GetLimiter returns the rate limiter for the provided key if it exists.
// Otherwise, calls Add to add key address to the map
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
i.mu.Lock()
limiter, exists := i.keys[key]
if !exists {
i.mu.Unlock()
return i.Add(key)
}
i.mu.Unlock()
return limiter
}
+15
View File
@@ -0,0 +1,15 @@
package runtime
import log "github.com/sirupsen/logrus"
// accepts error and logs error message. Used to prevent warnings when errors not caught.
func IgnoreError(err error) {
if err != nil {
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
}
}
func IgnoreErrorMultiReturn(i interface{}, err error) {
if err != nil {
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
}
}
+131
View File
@@ -0,0 +1,131 @@
package runtime
import (
cmap "github.com/orcaman/concurrent-map"
"time"
)
var functionMap cmap.ConcurrentMap
func init() {
functionMap = cmap.New()
}
var DefaultTickerDuration = time.Second * 10
// ResettableFunction will reset the user state as soon as tick is delivered.
type ResettableFunction struct {
Ticker *time.Ticker
Timer *time.Timer
ResetChan chan struct{} // channel used to reset the ticker
StopChan chan struct{} // channel used to reset the ticker
duration time.Duration
Started bool
name string
}
type ResettableFunctionTickerOption func(*ResettableFunction)
func WithTicker(t *time.Ticker) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Ticker = t
}
}
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.duration = d
}
}
func WithTimer(t *time.Timer) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Timer = t
}
}
func RemoveTicker(name string) {
functionMap.Remove(name)
}
func Get(name string) (*ResettableFunction, bool) {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction), ok
}
return nil, false
}
func GetFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction)
} else {
t := NewResettableFunction(name, option...)
functionMap.Set(name, t)
return t
}
}
func NewResettableFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
t := &ResettableFunction{
ResetChan: make(chan struct{}, 1),
StopChan: make(chan struct{}, 1),
name: name,
}
if t.duration == 0 {
t.duration = DefaultTickerDuration
}
for _, opt := range option {
opt(t)
}
return t
}
// Do will listen for timers and invoke functionCallback on tick.
func (t *ResettableFunction) Do(functionCallback func()) {
t.Started = true
// persist function
functionMap.Set(t.name, t)
go func() {
for {
if t.Timer != nil {
// timer is set. checking event
select {
case <-t.Timer.C:
functionCallback()
return
default:
}
}
if t.Ticker != nil {
// ticker is set. checking event
select {
case <-t.Ticker.C:
// ticker delivered signal. do function functionCallback
functionCallback()
return
default:
}
}
// check stop and reset channels
select {
case <-t.StopChan:
if t.Timer != nil {
t.Timer.Stop()
}
if t.Ticker != nil {
t.Ticker.Stop()
}
return
case <-t.ResetChan:
// reset signal received. creating new ticker.
if t.Ticker != nil {
t.Ticker.Reset(t.duration)
}
if t.Timer != nil {
t.Timer.Reset(t.duration)
}
default:
break
}
time.Sleep(time.Millisecond * 500)
}
}()
}
+105
View File
@@ -0,0 +1,105 @@
package mutex
import (
"context"
"fmt"
"net/http"
"sync"
"github.com/gorilla/mux"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var mutexMap cmap.ConcurrentMap
var mutexMapSync sync.Mutex
func init() {
mutexMap = cmap.New()
mutexMapSync = sync.Mutex{}
}
func IsEmpty() bool {
return mutexMap.Count() == 0
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock/{id} endpoint to mutex", len(mutexMap.Keys()), mutexMap.Keys())))
}
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
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
}
w.Write([]byte(fmt.Sprintf("Mutex %s not found!", vars["id"])))
}
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
// This happens if multiple handlers call each other and try to lock/unlock multiple times
// the same mutex.
func checkSoftLock(s string) int {
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
return v.(int)
}
return 0
}
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
// LockWithContext should be used to lock objects like faucets etc.
// The context carries a uid that is unique the each request (message, button press, etc.).
// If the uid has a lock already *for a certain object*, it increments the
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
func LockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
if len(uid) == 0 {
log.Error("[Mutex] LockWithContext: uid is empty!")
}
if len(s) == 0 {
log.Error("[Mutex] LockWithContext: s is empty!")
}
// sync mutex to sync checkSoftLock with the increment of nLocks
// same user can't lock the same object multiple times
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
if nLocks == 0 {
Lock(s)
} else {
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
}
nLocks++
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
// If it has been locked more than once
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
// nLocks == 1
func UnlockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
if len(uid) == 0 {
log.Error("[Mutex] UnlockWithContext: uid is empty!")
return
}
if len(s) == 0 {
log.Error("[Mutex] UnlockWithContext: s is empty!")
return
}
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
nLocks--
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
if nLocks == 0 {
Unlock(s)
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
}
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
+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())
}
}
+49
View File
@@ -0,0 +1,49 @@
package once
import (
"fmt"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var onceMap cmap.ConcurrentMap
func init() {
onceMap = cmap.New()
}
func New(objectKey string) {
onceMap.Set(objectKey, cmap.New())
}
// Once creates a map of keys k1 with a map of keys k2.
// The idea is that an object with ID k1 can create a list of users k2
// that have already interacted with the object. If the user k2 is in the list,
// the object is not allowed to accessed again.
func Once(k1, k2 string) error {
i, ok := onceMap.Get(k1)
if ok {
return setOrReturn(i.(cmap.ConcurrentMap), k2)
}
userMap := cmap.New()
onceMap.Set(k1, userMap)
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
return setOrReturn(userMap, k2)
}
// setOrReturn sets the key k2 in the map i if it is not already set.
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
if _, ok := objectMap.Get(k2); ok {
return fmt.Errorf("[Once] %s already consumed object", k2)
}
objectMap.Set(k2, true)
return nil
}
// Remove removes the key k1 from the map. Should be called after Once was called and
// the object k1 finished.
func Remove(k1 string) {
onceMap.Remove(k1)
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
}
+64
View File
@@ -0,0 +1,64 @@
package runtime
import (
"context"
"time"
)
// todo -- use function.go instead!
// var retryMap cmap.ConcurrentMap
// func init() {
// retryMap = cmap.New()
// }
// ResettableFunction will reset the user state as soon as tick is delivered.
type FunctionRetry struct {
Ticker *time.Ticker
duration time.Duration
ctx context.Context
name string
}
type FunctionRetryOption func(*FunctionRetry)
func WithRetryDuration(d time.Duration) FunctionRetryOption {
return func(a *FunctionRetry) {
a.duration = d
}
}
func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOption) *FunctionRetry {
t := &FunctionRetry{
name: name,
ctx: ctx,
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = DefaultTickerDuration
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
functionMap.Set(t.name, t)
go func() {
for {
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
case <-t.ctx.Done():
if t.ctx.Err() == context.DeadlineExceeded {
deadline_f()
}
if t.ctx.Err() == context.Canceled {
cancel_f()
}
return
}
}
}()
}
+324
View File
@@ -0,0 +1,324 @@
package satdress
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/network"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// Much of this is from github.com/fiatjaf/makeinvoice
// but with added "checkInvoice" and http proxy support
type LNDParams struct {
Cert []byte `json:"cert" gorm:"-"`
CertString string `json:"certstring"`
Host string `json:"host"`
Macaroon string `json:"macaroon"`
}
func (l LNDParams) getCert() []byte { return l.Cert }
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type LNBitsParams struct {
Cert string `json:"certstring"`
Host string `json:"host"`
Key string `json:"key"`
}
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type BackendParams interface {
getCert() []byte
isTor() bool
}
type Params struct {
Backend BackendParams
Msatoshi int64
Description string
DescriptionHash []byte
Label string // only used for c-lightning
}
type CheckInvoiceParams struct {
Backend BackendParams
PR string
Hash []byte
Status string
}
// SetupHttpClient returns the client for a user-supplied node. The host comes
// from a Telegram user, so it always goes through network.GetClient: that
// refuses non-public addresses (netguard) and uses the Tor proxy when one is
// configured. There is deliberately no exemption for local hosts.
func SetupHttpClient(cert []byte) (*http.Client, error) {
client, err := network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
if client.Transport == nil {
client.Transport = http.DefaultTransport.(*http.Transport).Clone()
}
// use a cert or skip TLS verification?
if len(cert) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(cert)
if !ok {
return client, fmt.Errorf("invalid root certificate")
}
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
return client, nil
}
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
// defer func(prevTransport http.RoundTripper) {
// Client.Transport = prevTransport
// }(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
var err error
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
}
// description hash?
var hexh, b64h string
if params.DescriptionHash != nil {
hexh = hex.EncodeToString(params.DescriptionHash)
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
}
switch backend := params.Backend.(type) {
case LNDParams:
log.Debugf("[MakeInvoice] LND invoice at %s", backend.Host)
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
if params.DescriptionHash == nil {
body, _ = sjson.Set(body, "memo", params.Description)
} else {
body, _ = sjson.Set(body, "description_hash", b64h)
}
req, err := http.NewRequest("POST",
backend.Host+"/v1/invoices",
bytes.NewBufferString(body),
)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
checkInvoiceParams := CheckInvoiceParams{
Backend: params.Backend,
PR: gjson.ParseBytes(b).Get("payment_request").String(),
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
Status: "OPEN",
}
if len(checkInvoiceParams.PR) == 0 {
return CheckInvoiceParams{}, errors.New("could not create invoice")
}
return checkInvoiceParams, nil
case LNBitsParams:
log.Debugf("[MakeInvoice] LNBits invoice at %s", backend.Host)
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
body, _ = sjson.Set(body, "out", false)
if params.DescriptionHash == nil {
if params.Description == "" {
body, _ = sjson.Set(body, "memo", "invoice")
} else {
body, _ = sjson.Set(body, "memo", params.Description)
}
} else {
body, _ = sjson.Set(body, "description_hash", hexh)
}
req, err := http.NewRequest("POST",
backend.Host+"/api/v1/payments",
bytes.NewBufferString(body),
)
if err != nil {
return CheckInvoiceParams{}, err
}
req.Header.Set("X-Api-Key", backend.Key)
req.Header.Set("Content-Type", "application/json")
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
checkInvoiceParams := CheckInvoiceParams{
Backend: params.Backend,
PR: gjson.ParseBytes(b).Get("payment_request").String(),
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
Status: "OPEN",
}
if len(checkInvoiceParams.PR) == 0 {
return CheckInvoiceParams{}, errors.New("could not create invoice")
}
return checkInvoiceParams, nil
default:
return CheckInvoiceParams{}, errors.New("wrong backend type")
}
}
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
// defer func(prevTransport http.RoundTripper) {
// Client.Transport = prevTransport
// }(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
var err error
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
}
switch backend := params.Backend.(type) {
case LNDParams:
log.Debugf("[CheckInvoice] LND invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
if err != nil {
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
}
hexHash := hex.EncodeToString(p)
requestUrl, err := url.Parse(fmt.Sprintf("%s/v1/invoice/%s?r_hash=%s", backend.Host, hexHash, base64.StdEncoding.EncodeToString(params.Hash)))
if err != nil {
return CheckInvoiceParams{}, err
}
requestUrl.Scheme = "https"
req, err := http.NewRequest("GET",
requestUrl.String(), nil)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
params.Status = gjson.ParseBytes(b).Get("state").String()
return params, nil
case LNBitsParams:
log.Debugf("[CheckInvoice] LNBits invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
log.Debug("Getting ", backend.Host+"/api/v1/payments/"+string(params.Hash))
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
if err != nil {
return CheckInvoiceParams{}, err
}
req.Header.Set("X-Api-Key", backend.Key)
req.Header.Set("Content-Type", "application/json")
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
status := strings.ToLower(gjson.ParseBytes(b).Get("paid").String())
if status == "true" {
params.Status = "SETTLED"
} else {
params.Status = "OPEN"
}
return params, nil
default:
return CheckInvoiceParams{}, errors.New("missing backend params")
}
}
+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)
}
}
}
+93
View File
@@ -0,0 +1,93 @@
package storage
import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"time"
"github.com/eko/gocache/store"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
Canceled bool `json:"canceled"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Inactivate(s Storable, db *DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
return err
}
log.Tracef("[Bunt Inactivate] %s", tx.ID)
return nil
}
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
cacheTx, err := transactionCache.Get(s.Key())
if err != nil {
err := db.Get(s)
if err != nil {
return s, err
}
log.Tracef("[Bunt] get object %s", s.Key())
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
}
log.Tracef("[Bunt Cache] get object %s", s.Key())
return cacheTx.(Storable), err
}
func (tx *Base) Set(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
err := db.Set(s)
if err != nil {
log.Errorf("[Bunt] could not set object: %v", err.Error())
return err
}
log.Tracef("[Bunt] set object %s", s.Key())
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
if err != nil {
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
}
log.Tracef("[Bunt Cache] set object: %s", s.Key())
return err
}
func (tx *Base) Delete(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
runtime.IgnoreError(transactionCache.Delete(s.Key()))
return db.Delete(s.Key(), s)
}
+110
View File
@@ -0,0 +1,110 @@
package storage
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
)
// Storable items must provide a function to retrieve the database key
type Storable interface {
Key() string
}
type DB struct {
*buntdb.DB
}
func NewBunt(filePath string) *DB {
db, err := buntdb.Open(filePath)
if err != nil {
log.Fatal(err)
}
return &DB{db}
}
// Exists checks is storable item exists
func (db *DB) Exists(storable Storable) (ok bool, err error) {
ok = false
err = db.View(func(tx *buntdb.Tx) error {
_, err := tx.Get(storable.Key())
if err != nil {
return err
}
return nil
})
if err != nil {
if err == buntdb.ErrNotFound {
return
}
return
}
ok = true
return
}
// Get a storable item
func (db *DB) Get(object Storable) error {
err := db.View(func(tx *buntdb.Tx) error {
val, err := tx.Get(object.Key())
if err != nil {
return err
}
err = json.Unmarshal([]byte(val), object)
if err != nil {
fmt.Println(err)
return err
}
return nil
})
return err
}
// Set a storable item.
func (db *DB) Set(object Storable) error {
err := db.Update(func(tx *buntdb.Tx) error {
b, err := json.Marshal(object)
if err != nil {
return err
}
_, _, err = tx.Set(object.Key(), string(b), nil)
return err
})
return err
}
// Delete a storable item.
func (db *DB) Delete(index string, object Storable) error {
return db.Update(func(tx *buntdb.Tx) error {
_, err := tx.Get(object.Key())
if err != nil {
return err
}
if _, err := tx.Delete(object.Key()); err != nil {
return err
}
// OLD: from gohumble:
// todo -- not ascend users index
// var delkeys []string
// runtime.IgnoreError(
// tx.Ascend(index, func(key, value string) bool {
// if key == object.Key() {
// delkeys = append(delkeys, key)
// }
// return true
// }),
// )
// for _, k := range delkeys {
// if _, err := tx.Delete(k); err != nil {
// return err
// }
// }
return nil
})
}
+57
View File
@@ -0,0 +1,57 @@
package str
import (
"crypto/sha256"
"fmt"
"hash/fnv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
)
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
var markdownEscapes = []string{"_", "*", "`", "["}
func MarkdownV2Escape(s string) string {
for _, esc := range markdownV2Escapes {
if strings.Contains(s, esc) {
s = strings.Replace(s, esc, fmt.Sprintf("\\%s", esc), -1)
}
}
return s
}
func MarkdownEscape(s string) string {
for _, esc := range markdownEscapes {
if strings.Contains(s, esc) {
s = strings.Replace(s, esc, fmt.Sprintf("\\%s", esc), -1)
}
}
return s
}
func Int32Hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}
func Int64Hash(s string) uint64 {
h := fnv.New64a()
h.Write([]byte(s))
return h.Sum64()
}
func AnonIdSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
return anon_id
}
func UUIDSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
return anon_id
}
+271
View File
@@ -0,0 +1,271 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// amountsMap maps string to int64 amounts
var amountsMap = map[string]int64{
"🍌": 777,
"🥜": 69,
}
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", fmt.Errorf("message doesn't contain enough arguments")
}
output = strings.Split(input, " ")[which]
return output, nil
}
func decodeAmountFromCommand(input string) (amount int64, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, fmt.Errorf("%s", errmsg)
}
amount, err = GetAmount(strings.Split(input, " ")[1])
return amount, err
}
// maxAmountSat is the largest amount a single command may name. The bot is a
// tip bot; anything above this is a typo or an attack on a conversion path.
const maxAmountSat int64 = 10_000_000
// checkAmount rejects amounts that must never reach a money path: results of
// a float conversion that are not a number, non-positive amounts and amounts
// above maxAmountSat.
func checkAmount(fmount float64, amount int64) (int64, error) {
if math.IsNaN(fmount) || math.IsInf(fmount, 0) {
return 0, fmt.Errorf("amount is not a number")
}
if amount <= 0 {
return 0, fmt.Errorf("amount must be greater than 0")
}
if amount > maxAmountSat {
return 0, fmt.Errorf("amount must not be greater than %d sat", maxAmountSat)
}
return amount, nil
}
// GetAmount parses an amount from a string like 1.2k or 3.50€
// and returns the value in satoshis
func GetAmount(input string) (amount int64, err error) {
// replace occurances of comma with dot
input = strings.Replace(input, ",", ".", -1)
// replace strings in amountsMap with their integer values
for k, v := range amountsMap {
input = strings.Replace(input, k, strconv.FormatInt(v, 10), -1)
}
// convert something like 1.2k into 1200
if strings.HasSuffix(strings.ToLower(input), "k") {
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
if err != nil {
return 0, err
}
return checkAmount(fmount, int64(fmount*1000))
}
// convert fiat currencies to satoshis
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
numeric_string := ""
numeric_string = strings.Replace(input, symbol, "", 1) // for symbol like $
numeric_string = strings.Replace(strings.ToLower(numeric_string), strings.ToLower(currency), "", 1) // for 1USD
fmount, err := strconv.ParseFloat(numeric_string, 64)
if err != nil {
log.Errorln(err)
return 0, err
}
if !(price.Get(currency) > 0) {
return 0, fmt.Errorf("price is zero")
}
sats := fmount / price.Get(currency) * float64(100_000_000)
return checkAmount(sats, int64(sats))
}
}
// use plain integer as satoshis
amount, err = strconv.ParseInt(input, 10, 64)
if err != nil {
return 0, err
}
return checkAmount(float64(amount), amount)
}
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
if !(price.Get(currency) > 0) {
return 0, fmt.Errorf("price is zero")
}
fiat = float64(amount) / 100_000_000 * price.Get(currency)
return fiat, nil
}
type EnterAmountStateData struct {
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
}
func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string, amountMin int64, amountMax int64, originalCommand string) (enterAmountStateData *EnterAmountStateData, err error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
}
enterAmountStateData = &EnterAmountStateData{
ID: id,
Type: eventType,
AmountMin: amountMin,
AmountMax: amountMax,
OiringalCommand: originalCommand,
}
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterAmountStateData)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
askAmountText := Translate(ctx, "enterAmountMessage")
if amountMin > 0 && amountMax >= amountMin {
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
}
// Let the user enter an amount and return
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
return
}
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
if !(user.StateKey == lnbits.UserEnterAmount) {
ResetUserState(user, bot)
return ctx, fmt.Errorf("invalid statekey")
}
var EnterAmountStateData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
if err != nil {
log.Errorf("[enterAmountHandler] %s", err.Error())
ResetUserState(user, bot)
return ctx, err
}
amount, err := GetAmount(ctx.Message().Text)
if err != nil {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return ctx, err
}
// amount not in allowed range from LNURL
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
err = fmt.Errorf("amount not in range")
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
ResetUserState(user, bot)
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// find out which type the object in bunt has waiting for an amount
// we stored this in the EnterAmountStateData before
switch EnterAmountStateData.Type {
case "LnurlPayState":
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return ctx, err
}
LnurlPayState := sn.(*LnurlPayState)
LnurlPayState.Amount = amount * 1000 // mSat
// add result to persistent struct
runtime.IgnoreError(LnurlPayState.Set(LnurlPayState, bot.Bunt))
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
return bot.lnurlPayHandlerSend(ctx)
case "LnurlWithdrawState":
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return ctx, err
}
LnurlWithdrawState := sn.(*LnurlWithdrawState)
LnurlWithdrawState.Amount = amount * 1000 // mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
return bot.lnurlWithdrawHandlerWithdraw(ctx)
case "CreateInvoiceState":
ctx.Message().Text = fmt.Sprintf("/invoice %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.invoiceHandler(ctx)
case "CreateDonationState":
ctx.Message().Text = fmt.Sprintf("/donate %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.donationHandler(ctx)
case "CreateSendState":
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
if len(splits) > 1 {
ctx.Message().Text = fmt.Sprintf("/send %d %s", amount, splits[1])
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.sendHandler(ctx)
}
return ctx, errors.Create(errors.InvalidSyntaxError)
default:
ResetUserState(user, bot)
return ctx, errors.Create(errors.InvalidSyntaxError)
}
}
+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)
}
}
}
+47
View File
@@ -0,0 +1,47 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
// check and print all commands
if len(m.Text) > 0 {
bot.anyTextHandler(ctx)
}
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
}
// first check whether the user is initialized
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
if !user.Initialized {
return bot.startHandler(ctx)
}
usrStr := GetUserStr(ctx.Sender())
balance, err := bot.GetUserBalance(user)
if err != nil {
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
bot.trySendMessage(ctx.Sender(), Translate(ctx, "balanceErrorMessage"))
return ctx, err
}
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
return ctx, nil
}
+154
View File
@@ -0,0 +1,154 @@
package telegram
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
"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"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type TipBot struct {
DB *Databases
Bunt *storage.DB
ShopBunt *storage.DB
Telegram *tb.Bot
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
}
var (
botWalletInitialisation = sync.Once{}
telegramHandlerRegistration = sync.Once{}
)
// NewBot migrates data and creates a new bot
func NewBot() TipBot {
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
gocacheStore := store.NewGoCache(gocacheClient, nil)
// create sqlite databases
dbs := AutoMigration()
limiter.Start()
return TipBot{
DB: dbs,
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
Telegram: newTelegramBot(),
Cache: Cache{GoCacheStore: gocacheStore},
}
}
// newTelegramBot will create a new Telegram bot.
func newTelegramBot() *tb.Bot {
tgb, err := tb.NewBot(tb.Settings{
Token: internal.Configuration.Telegram.ApiKey,
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
ParseMode: tb.ModeMarkdown,
Verbose: false,
})
if err != nil {
panic(err)
}
return tgb
}
// initBotWallet will create / initialize the bot wallet
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
_, err := bot.initWallet(bot.Telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
return
}
})
return nil
}
// GracefulShutdown will gracefully shutdown the bot
// It will wait for all mutex locks to unlock before shutdown.
func (bot *TipBot) GracefulShutdown() {
t := time.NewTicker(time.Second * 10)
log.Infof("[shutdown] Graceful shutdown (timeout=10s).")
for {
select {
case <-t.C:
// timer expired
log.Infof("[shutdown] Graceful shutdown timeout reached. Forcing shutdown.")
return
default:
// check if all mutex locks are unlocked
if mutex.IsEmpty() {
log.Infof("[shutdown] Graceful shutdown successful.")
return
}
}
time.Sleep(time.Second)
log.Tracef("[shutdown] Trying graceful shutdown...")
}
}
// Start will initialize the Telegram bot and lnbits.
func (bot *TipBot) Start() {
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
// initialize the bot wallet
err := bot.initBotWallet()
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
// LNURLcash notes (optional feature)
bot.initLNURLCash()
// register telegram handlers
bot.registerTelegramHandlers()
// download bot avatar once
bot.downloadMyProfilePicture()
// edit worker collects messages to edit and
// periodically edits them
bot.startEditWorker()
// register callbacks for invoices
initInvoiceEventCallbacks(bot)
// register callbacks for user state changes
initializeStateCallbackMessage(bot)
// start the telegram bot
go bot.Telegram.Start()
go bot.restartPersistedTickets()
bot.startLNURLCashJobs()
// gracefully shutdown
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
// we need to catch SIGTERM and SIGSTOP
signal.Notify(exit, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP)
<-exit
// gracefully shutdown
bot.GracefulShutdown()
}
+169
View File
@@ -0,0 +1,169 @@
package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
// MainMenuCommandWebApp = "⤵️ Recv"
// MainMenuCommandBalance = "Balance"
// MainMenuCommandInvoice = "⚡️ Invoice"
// MainMenuCommandHelp = "📖 Help"
// MainMenuCommandSend = "⤴️ Send"
// SendMenuCommandEnter = "👤 Enter"
MainMenuCommandWebApp = "🗳️ App"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
MainMenuCommandSend = "⤴️"
SendMenuCommandEnter = "👤 Enter"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
btnWebAppMainMenu = mainMenu.Text(MainMenuCommandWebApp)
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
sendToMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
sendToButtons = []tb.Btn{}
btnSendMenuEnter = mainMenu.Text(SendMenuCommandEnter)
)
func init() {
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
)
}
// buttonWrapper wrap buttons slice in rows of length i
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
buttonLength := len(buttons)
rows := make([]tb.Row, 0)
if buttonLength > length {
for i := 0; i < buttonLength; i = i + length {
buttonRow := make([]tb.Btn, length)
if i+length < buttonLength {
buttonRow = buttons[i : i+length]
} else {
buttonRow = buttons[i:]
}
rows = append(rows, markup.Row(buttonRow...))
}
return rows
}
rows = append(rows, markup.Row(buttons...))
return rows
}
// appendWebAppLinkToButton adds a WebApp object to a Button with the user's webapp page
func (bot *TipBot) appendWebAppLinkToButton(btn *tb.Btn, user *lnbits.User) {
var url string
if len(user.Telegram.Username) > 0 {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.Telegram.Username)
} else {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
}
if strings.HasPrefix(url, "https://") {
// prevent adding a link if not https is used, otherwise
// Telegram returns an error and does not show the keyboard
btn.WebApp = &tb.WebAppInfo{Url: url}
}
}
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
var user *lnbits.User
var err error
if user, err = getCachedUser(&tb.User{ID: to}, *bot); err != nil {
user, err = GetLnbitsUser(&tb.User{ID: to}, *bot)
if err != nil {
return
}
updateCachedUser(user, *bot)
}
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
}
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
)
}
}
// makeContactsButtons will create a slice of buttons for the send menu
// it will show the 5 most recently interacted contacts and one button to use a custom contact
func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
var records []Transaction
sendToButtons = []tb.Btn{}
user := LoadUser(ctx)
// get 5 most recent transactions by from_id with distint to_user
// where to_user starts with an @ and is not the user itself
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
log.Debugf("[makeContactsButtons] found %d records", len(records))
// get all contacts and add them to the buttons
for i, r := range records {
log.Tracef("[makeContactsButtons] toNames[%d] = %s (id=%d)", i, r.ToUser, r.ID)
sendToButtons = append(sendToButtons, tb.Btn{Text: r.ToUser})
}
// add the "enter a username" button to the end
sendToButtons = append(sendToButtons, tb.Btn{Text: SendMenuCommandEnter})
sendToMenu.Reply(buttonWrapper(sendToButtons, sendToMenu, 3)...)
return sendToButtons
}
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// appendMainMenu is called in telegram.go every time a user receives a PM from the bot.
// this function will only add a keyboard if this is a private chat and no force reply.
func (bot *TipBot) appendMainMenu(to int64, recipient interface{}, options []interface{}) []interface{} {
// update the balance button
if to > 0 {
bot.mainMenuBalanceButtonUpdate(to)
}
appendKeyboard := true
for _, option := range options {
if option == tb.ForceReply {
appendKeyboard = false
}
switch option.(type) {
case *tb.ReplyMarkup:
appendKeyboard = false
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
// options = append(options[:i], options[i+1:]...)
//}
}
}
// to > 0 is private chats
if to > 0 && appendKeyboard {
options = append(options, mainMenu)
}
return options
}
+344
View File
@@ -0,0 +1,344 @@
package telegram
import (
"bufio"
"crypto/sha1"
"encoding/base64"
"fmt"
"os"
"reflect"
"runtime/debug"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
Groups *gorm.DB
// LNURLCash is nil when the feature is disabled.
LNURLCash *lnurlcash.Store
}
const (
JoinTicketIndex = "join-ticket:*"
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
)
func createBunt(file string) *storage.DB {
t1 := time.Now()
// create bunt database
bunt := storage.NewBunt(file)
log.Infof("[blunt] loaded file in %s", time.Since(t1))
// create bunt database index for ascending (searching) TipTooltips
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
log.Infof("[blunt] index 1 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
err = bunt.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString)
log.Infof("[blunt] index 2 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
log.Infof("[blunt] total time: %s", time.Since(t1))
return bunt
}
func ColumnMigrationTasks(db *gorm.DB) error {
var err error
// anon_id migration (2021-11-01)
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id") {
// first we need to auto migrate the user. This will create anon_id column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running anon_id database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdInt32Hash(db)
}
// anon_id_sha256 migration (2022-01-01)
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id_sha256") {
// first we need to auto migrate the user. This will create anon_id column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running anon_id_sha256 database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdSha265Hash(db)
}
// uuid migration (2022-02-11)
if !db.Migrator().HasColumn(&lnbits.User{}, "uuid") {
// first we need to auto migrate the user. This will create uuid column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running UUID database migrations ...")
// run the migration on uuid
err = database.MigrateUUIDSha265Hash(db)
}
// todo -- add more database field migrations here in the future
return err
}
func AutoMigration() *Databases {
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = ColumnMigrationTasks(orm)
if err != nil {
panic(err)
}
err = orm.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = txLogger.AutoMigrate(&Transaction{})
if err != nil {
panic(err)
}
groupsDb, err := gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = groupsDb.AutoMigrate(&Group{})
if err != nil {
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,
}
}
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
toUserDb := &lnbits.User{}
// return error if username is too long
if len(toUserStrWithoutAt) > 100 {
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
}
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil {
err := tx.Error
if toUserDb.Wallet == nil {
err = fmt.Errorf("%s | user @%s has no wallet", tx.Error, toUserStrWithoutAt)
}
return nil, err
}
return toUserDb, nil
}
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
if us, err := bot.Cache.Get(user.Name); err == nil {
return us.(*lnbits.User), nil
}
user.Telegram = u
return user, gorm.ErrRecordNotFound
}
// GetLnbitsUser will not update the user in Database.
// this is required, because fetching lnbits.User from a incomplete tb.User
// will update the incomplete (partial) user in storage.
// this function will accept users like this:
// &tb.User{ID: toId, Username: username}
// without updating the user in storage.
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.DB.Users.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
user.Telegram = u
return user, tx.Error
}
// todo -- unblock this !
return user, nil
}
func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.DB.Users.Preload("Settings").First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetLnbitsUserWithSettings] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
user.Telegram = u
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
// GetUser from Telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
var user *lnbits.User
var err error
if user, err = getCachedUser(u, bot); err != nil {
user, err = GetLnbitsUser(u, bot)
if err != nil {
return user, err
}
updateCachedUser(user, bot)
}
if telegramUserChanged(u, user.Telegram) {
// update possibly changed user details in Database
user.Telegram = u
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
}
}
return user, err
}
func updateCachedUser(apiUser *lnbits.User, bot TipBot) {
bot.Cache.Set(apiUser.Name, apiUser, &store.Options{Expiration: 1 * time.Minute})
}
func telegramUserChanged(apiUser, stateUser *tb.User) bool {
if reflect.DeepEqual(apiUser, stateUser) {
return false
}
return true
}
func debugStack() {
stack := debug.Stack()
go func() {
hasher := sha1.New()
hasher.Write(stack)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
fo, err := os.Create(fmt.Sprintf("trace_%s.txt", sha))
log.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
if err != nil {
panic(err)
}
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
w := bufio.NewWriter(fo)
if _, err := w.Write(stack); err != nil {
panic(err)
}
if err = w.Flush(); err != nil {
panic(err)
}
}()
}
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 == "" {
debugStack()
user.AnonIDSha256 = str.AnonIdSha256(user)
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonIDSha256)
}
// TODO -- Remove this after empty anon id bug is identified
if user.AnonID == "" {
debugStack()
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
log.Errorf("[UpdateUserRecord] AnonID empty! Setting to: %s", user.AnonID)
}
// TODO -- Remove this after empty anon id bug is identified
if user.UUID == "" {
debugStack()
user.UUID = str.UUIDSha256(user)
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
db := bot.DB.Users
if keepBanState {
// leave the columns out, so a ban written since the read above stays
db = db.Omit("banned", "wallet_adminkey")
}
tx := db.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
return tx.Error
}
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
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
}
+189
View File
@@ -0,0 +1,189 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"github.com/fiatjaf/go-lnurl"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
// YOU MIGHT BREAK DONATIONS TO THE ORIGINAL PROJECT
// THE DEVELOPMENT OF LIGHTNINGTIPBOT RELIES ON DONATIONS
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
var (
donationEndpoint string
)
func helpDonateUsage(ctx context.Context, errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(Translate(ctx, "donateHelpText"), fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(Translate(ctx, "donateHelpText"), "")
}
}
func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
m := ctx.Message()
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
// // no amount was entered, set user state and ask for amount
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return ctx, err
}
amount = amount * 1000
// command is valid
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
// get invoice
r, err := http.NewRequest(http.MethodGet, donationEndpoint, nil)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// Create query parameters
params := url.Values{}
params.Set("amount", strconv.FormatInt(amount, 10))
params.Set("comment", fmt.Sprintf("from %s bot %s", GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
// Set the query parameters in the URL
r.URL.RawQuery = params.Encode()
resp, err := http.DefaultClient.Do(r)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
pv := lnurl.LNURLPayValues{}
err = json.Unmarshal(body, &pv)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
if pv.Status == "ERROR" || len(pv.PR) < 1 {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// send donation invoice
// user := LoadUser(ctx)
// bot.trySendMessage(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(pv.PR)}, bot.Client)
if err != nil {
userStr := GetUserStr(user.Telegram)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
log.Errorln(errmsg)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// hotfix because the edit doesn't work!
// todo: fix edit
// bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
bot.tryDeleteMessage(msg)
bot.trySendMessage(m.Chat, Translate(ctx, "donationSuccess"))
return ctx, nil
}
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/.jryy-xabja/yaheyc/YvtugavatGvcObg")})
if err != nil {
panic(err)
}
donationEndpoint = sb.String()
}
type rot13Reader struct {
r io.Reader
}
func (rot13 rot13Reader) Read(b []byte) (int, error) {
n, err := rot13.r.Read(b)
for i := 0; i < n; i++ {
switch {
case b[i] >= 65 && b[i] <= 90:
if b[i] <= 77 {
b[i] = b[i] + 13
} else {
b[i] = b[i] - 13
}
case b[i] >= 97 && b[i] <= 122:
if b[i] <= 109 {
b[i] = b[i] + 13
} else {
b[i] = b[i] - 13
}
}
}
return n, err
}
func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
m := ctx.Message()
arg := ""
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
arg, _ = getArgumentFromCommand(m.Text, 2)
if arg != "@"+bot.Telegram.Me.Username {
return fmt.Errorf("err")
}
}
if strings.HasPrefix(strings.ToLower(m.Text), "/tip") {
arg = GetUserStr(m.ReplyTo.Sender)
if arg != "@"+bot.Telegram.Me.Username {
return fmt.Errorf("err")
}
}
if arg == "@LightningTipBot" || len(arg) < 1 {
return fmt.Errorf("err")
}
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
return err
}
var sb strings.Builder
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
if err != nil {
panic(err)
}
donationInterceptMessage := sb.String()
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
m.Text = fmt.Sprintf("/donate %d", amount)
bot.donationHandler(ctx)
// returning nil here will abort the parent ctx (/pay or /tip)
return nil
}
+84
View File
@@ -0,0 +1,84 @@
package telegram
import (
"strings"
"time"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var editStack cmap.ConcurrentMap
type edit struct {
to tb.Editable
key string
what interface{}
options []interface{}
lastEdit time.Time
edited bool
}
func init() {
editStack = cmap.New()
}
const resultTrueError = "telebot: result is True"
const editSameStringError = "specified new message content and reply markup are exactly the same as a current content and reply markup of the message"
const retryAfterError = "retry after"
// startEditWorker will loop through the editStack and run tryEditMessage on not edited messages.
// if editFromStack is older than 5 seconds, editFromStack will be removed.
func (bot TipBot) startEditWorker() {
go func() {
for {
for _, k := range editStack.Keys() {
if e, ok := editStack.Get(k); ok {
editFromStack := e.(edit)
if !editFromStack.edited {
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
if err != nil && strings.Contains(err.Error(), retryAfterError) {
// ignore any other error than retry after
log.Errorf("[startEditWorker] Edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
} else {
if err != nil {
log.Errorf("[startEditWorker] Ignoring edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
}
log.Tracef("[startEditWorker] message from stack edited %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
editFromStack.lastEdit = time.Now()
editFromStack.edited = true
editStack.Set(k, editFromStack)
}
} else {
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
log.Tracef("[startEditWorker] removing message edit from stack %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
editStack.Remove(k)
}
}
}
}
time.Sleep(time.Millisecond * 1000)
}
}()
}
// tryEditStack will add the editable to the edit stack, if what (message) changed.
func (bot TipBot) tryEditStack(to tb.Editable, key string, what interface{}, options ...interface{}) {
sig, chat := to.MessageSig()
log.Tracef("[tryEditStack] sig=%s, chat=%d, key=%s, what=%+v, options=%+v", sig, chat, key, what, options)
// var sig = fmt.Sprintf("%s-%d", msgSig, chat)
if e, ok := editStack.Get(key); ok {
editFromStack := e.(edit)
if editFromStack.what == what.(string) {
log.Tracef("[tryEditStack] Message already in edit stack. Skipping")
return
}
}
e := edit{options: options, key: key, what: what, to: to}
editStack.Set(key, e)
log.Tracef("[tryEditStack] Added message %s to edit stack. len(editStack)=%d", key, len(editStack.Keys()))
}

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