Compare commits

...
Author SHA1 Message Date
MichilisandClaude Opus 5.5 8faab56990 Harden LNURLcash, webhook replay and ticket restarts; add command aliases
- LNURLcash: mint single notes directly when the mint rounds fees to whole
  sats, recover lost direct-note funding, melt to the callback named in the
  note's own withdraw info, and poll for settlement so redeems/reclaims
  finish without waiting on the webhook. Read-only lookups use a pooled
  client; every mutation stays on the no-keep-alive client.
- Webhook: expire replay markers only for payments without an invoice event,
  so an event callback can never run twice.
- Tickets: on restart, enforce tickets that ran out while the bot was down
  unless LNbits says the invoice was paid; drop stale ones without a ban.
- Telegram: register translated /faucet and /tipjar command aliases.
- i18n: load translations from one language list and log broken files.
- Config example: one entry per mint; ignore local docs/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:20:52 +00:00
44 changed files with 1301 additions and 207 deletions
+1
View File
@@ -7,3 +7,4 @@ data/*
*.tar.gz
cashu/node_modules/
trace_*.txt
/docs/
+5 -3
View File
@@ -37,12 +37,14 @@ nostr:
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.
# One entry per mint. The name is the mint's id in the database, so do not
# rename a mint that already has notes. Users pick their own default with
# /lnurlmints; the single `default: true` entry is the fallback.
- name: 21mint
url: https://lnurl.21mint.me
default: true
- name: mint.600.wtf
url: https://mint.600.wtf
min_note_sat: 1
max_note_sat: 100000
max_outstanding_sat_per_user: 500000
+11 -12
View File
@@ -29,23 +29,22 @@ func translationsDir() string {
return "translations"
}
// Languages lists every translation file the bundle loads. English comes
// first: it is the default and the fallback for missing keys.
var Languages = []string{"en", "de", "fi", "it", "es", "nl", "pl", "fr", "pt-br", "tr", "cs", "id", "ru"}
func RegisterLanguages() *i18n.Bundle {
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
dir := translationsDir()
bundle.MustLoadMessageFile(filepath.Join(dir, "en.toml"))
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"))
for _, lang := range Languages[1:] {
// a broken file must not stop the bot, but it silently turns
// that language into English, so say so
if _, err := bundle.LoadMessageFile(filepath.Join(dir, lang+".toml")); err != nil {
log.Errorf("[i18n] could not load %s translations: %v", lang, err)
}
}
return bundle
}
func Translate(languageCode string, MessgeID string) string {
+22
View File
@@ -0,0 +1,22 @@
package i18n
import (
"path/filepath"
"testing"
"github.com/BurntSushi/toml"
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
// RegisterLanguages only logs a file that fails to load, and that language
// then falls back to English everywhere. Fail the build instead.
func TestEveryTranslationFileLoads(t *testing.T) {
bundle := goi18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
for _, lang := range Languages {
if _, err := bundle.LoadMessageFile(filepath.Join(translationsDir(), lang+".toml")); err != nil {
t.Errorf("%s: %v", lang, err)
}
}
}
+23 -9
View File
@@ -102,10 +102,22 @@ func (w *Server) settledAmount(user *lnbits.User, paymentHash string) (int64, er
}, paymentHash, user.Wallet.ID)
}
// handledTTLWithoutEvent is how long the replay marker of a payment without an
// invoice event is kept. A replay of such a payment only repeats the "you
// received" message, so the marker doesn't need to outlive LNbits' retries.
const handledTTLWithoutEvent = 7 * 24 * time.Hour
// markHandled records paymentHash and reports whether this is the first time.
func (w *Server) markHandled(paymentHash string) (first bool, err error) {
// A marker with an expiry is only safe when no invoice event exists for the
// payment: invoice events are kept forever, and replaying one after its marker
// expired would run its callback (which may pay out) a second time.
func (w *Server) markHandled(paymentHash string, hasEvent bool) (first bool, err error) {
var opts *buntdb.SetOptions
if !hasEvent {
opts = &buntdb.SetOptions{Expires: true, TTL: handledTTLWithoutEvent}
}
err = w.buntdb.Update(func(tx *buntdb.Tx) error {
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", nil)
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", opts)
first = !replaced
return err
})
@@ -155,8 +167,13 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(400)
return
}
// Handle every payment once, so a webhook can't be replayed.
first, err := w.markHandled(webhookEvent.PaymentHash)
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
eventErr := w.buntdb.Get(txInvoiceEvent)
// Handle every payment once, so a webhook can't be replayed. Any lookup
// error other than "not found" counts as an event, which keeps the marker.
first, err := w.markHandled(webhookEvent.PaymentHash, eventErr != buntdb.ErrNotFound)
if err != nil {
log.Errorf("[Webhook] Error storing payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
writer.WriteHeader(500)
@@ -172,11 +189,8 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
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)
if eventErr != nil {
log.Errorln(eventErr)
} else if txInvoiceEvent.User != nil && txInvoiceEvent.User.Wallet != nil && txInvoiceEvent.User.Wallet.ID != user.Wallet.ID {
// the event was registered for another wallet than the one LNbits paid
log.Errorf("[Webhook] Invoice event for payment_hash %s belongs to wallet %s, not %s. Not dispatching.",
+44
View File
@@ -0,0 +1,44 @@
package webhook
import (
"testing"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
)
func TestMarkHandled(t *testing.T) {
w := &Server{buntdb: storage.NewBunt(":memory:")}
for _, c := range []struct {
hash string
hasEvent bool
expires bool
}{
{"aa", true, false},
{"bb", false, true},
} {
first, err := w.markHandled(c.hash, c.hasEvent)
if err != nil || !first {
t.Fatalf("%s: first mark: %v %v", c.hash, first, err)
}
first, err = w.markHandled(c.hash, c.hasEvent)
if err != nil || first {
t.Fatalf("%s: second mark must be a repeat: %v %v", c.hash, first, err)
}
err = w.buntdb.View(func(tx *buntdb.Tx) error {
ttl, err := tx.TTL("webhook:" + c.hash)
if err != nil {
return err
}
// buntdb reports -1 for a key without expiry
if expires := ttl >= 0; expires != c.expires {
t.Errorf("%s: expires %t, want %t (ttl %s)", c.hash, expires, c.expires, ttl)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}
+54 -3
View File
@@ -1,15 +1,18 @@
package lnurlcash
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
)
@@ -34,8 +37,19 @@ type fakeMint struct {
meltReason string // reason to answer every melt with
pubkeyChange string
calls map[string]int
// satRound credits mint invoices in whole sats with the fee rounded up,
// as the live mints do; minSendable overrides the advertised minimum
satRound bool
minSendable int64
// connection bookkeeping: requests served per connection, and the
// connection of every mutation (mint invoice, melt, split)
nextConn int64
connReqs map[int64]int
mutConns []int64
}
type fakeConnKey struct{}
type fakeInvoice struct {
h string
amount int64
@@ -52,15 +66,37 @@ func newFakeMint(t *testing.T) *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{},
inv: map[string]*fakeInvoice{}, calls: map[string]int{}, connReqs: map[int64]int{},
}
m.srv = httptest.NewServer(http.HandlerFunc(m.handle))
m.srv = httptest.NewUnstartedServer(http.HandlerFunc(m.handle))
m.srv.Config.ConnContext = func(ctx context.Context, _ net.Conn) context.Context {
return context.WithValue(ctx, fakeConnKey{}, atomic.AddInt64(&m.nextConn, 1))
}
m.srv.Start()
t.Cleanup(m.srv.Close)
return m
}
func (m *fakeMint) url() string { return m.srv.URL }
// connStats reports how many mutations arrived on a connection that also
// carried another request, and whether any connection was reused at all.
func (m *fakeMint) connStats() (mutations, sharedMutations int, anyReuse bool) {
m.mu.Lock()
defer m.mu.Unlock()
for _, c := range m.mutConns {
if m.connReqs[c] > 1 {
sharedMutations++
}
}
for _, n := range m.connReqs {
if n > 1 {
anyReuse = true
}
}
return len(m.mutConns), sharedMutations, anyReuse
}
func (m *fakeMint) hashOf(k1 string) string {
raw, _ := hex.DecodeString(k1)
sum := sha256.Sum256(raw)
@@ -81,6 +117,11 @@ func (m *fakeMint) handle(w http.ResponseWriter, r *http.Request) {
defer m.mu.Unlock()
m.calls[r.URL.Path]++
q := r.URL.Query()
conn, _ := r.Context().Value(fakeConnKey{}).(int64)
m.connReqs[conn]++
if r.URL.Path == "/p/cb" || (r.URL.Path == "/w/cb" && len(q["k1"]) > 0) {
m.mutConns = append(m.mutConns, conn)
}
pub := m.pubkey
if m.pubkeyChange != "" {
pub = m.pubkeyChange
@@ -89,7 +130,7 @@ func (m *fakeMint) handle(w http.ResponseWriter, r *http.Request) {
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,
"tag": "payRequest", "callback": m.srv.URL + "/p/cb", "minSendable": m.minSendableMsat(), "maxSendable": 100_000_000_000,
"metadata": meta, "withdrawLink": m.srv.URL + "/w", "commentAllowed": 64, "mintPubkey": pub,
})
case r.URL.Path == "/p/cb":
@@ -243,9 +284,19 @@ func (m *fakeMint) settle(pr string) {
}
inv.settled = true
net := inv.amount - m.base - (inv.amount/1_000_000)*m.ppm - ((inv.amount%1_000_000)*m.ppm)/1_000_000
if m.satRound {
net -= net % 1000
}
m.notes[inv.h] = net
}
func (m *fakeMint) minSendableMsat() int64 {
if m.minSendable > 0 {
return m.minSendable
}
return 1000
}
// finishMelt completes a pending melt: paid burns the note, failed restores it.
func (m *fakeMint) finishMelt(h string, paid bool) {
m.mu.Lock()
+30 -19
View File
@@ -176,14 +176,19 @@ func (j *Jobs) recoverBatch(ctx context.Context, b *Batch) {
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
// rebuild the units: one funding note and the user/dust pairs that follow
// it. A directly minted user note (gross set) is a unit of its own.
var units, direct []*unit
byIndex := map[int][2]*Note{}
for _, n := range notes {
switch n.Kind {
case KindFunding:
units = append(units, &unit{funding: n})
case KindUser:
if n.GrossMsat > 0 {
direct = append(direct, &unit{funding: n})
continue
}
p := byIndex[n.Index]
p[0] = n
byIndex[n.Index] = p
@@ -193,22 +198,25 @@ func (j *Jobs) recoverBatch(ctx context.Context, b *Batch) {
byIndex[n.Index] = p
}
}
if len(units) > 0 {
perUnit := b.Count / len(units)
idx := 1
for _, un := range units {
for i := 0; i < perUnit; i++ {
p := byIndex[idx]
idx++
if p[0] == nil || p[1] == nil {
continue
}
un.notes = append(un.notes, p[0])
un.dust = append(un.dust, p[1])
}
}
}
units = append(units, direct...)
if len(units) == 0 {
return
}
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 {
@@ -232,10 +240,13 @@ func (j *Jobs) recoverBatch(ctx context.Context, b *Batch) {
case NoteFailed:
continue
}
if len(un.notes) == 0 {
continue // a directly minted note: nothing to carve
}
// any note carved in state unknown: ask the mint whether its hash exists
for i, n := range un.notes {
if n.State == NoteUnknown {
if _, err := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); err == nil {
if _, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); err == nil {
_ = s.store.TransitionNote(n.ID, NoteUnknown, NoteLive, map[string]interface{}{"reported_msat": n.ValueMsat, "last_error": ""})
n.State, n.ReportedMsat = NoteLive, n.ValueMsat
prev := un.funding
@@ -295,7 +306,7 @@ func (j *Jobs) recoverReclaims(ctx context.Context) {
}
}
// not settled: what does the mint say?
_, err = s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
_, err = s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
switch {
case err == nil:
// the note is outstanding again: the melt failed or never landed
@@ -358,7 +369,7 @@ func (j *Jobs) recoverRedeems(ctx context.Context) {
unlock()
continue
}
_, err = s.client.FetchNoteInfo(ctx, noteURL)
_, err = s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
// outstanding again: the melt failed. The user may try again.
@@ -368,7 +379,7 @@ func (j *Jobs) recoverRedeems(ctx context.Context) {
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 {
if _, err := s.reader.FetchNoteInfoByHash(ctx, sn.MintURL, sn.Hash); err == nil {
_ = s.store.TransitionRedeem(r.ID, r.State, RedeemInfo, map[string]interface{}{"last_error": "melt did not settle"})
unlock()
continue
+45
View File
@@ -2,6 +2,7 @@ package lnurlcash
import (
"context"
"errors"
"testing"
"time"
)
@@ -108,6 +109,50 @@ func TestRecoveryResumesCarving(t *testing.T) {
}
}
// A directly minted note whose funding outcome was lost is finished by the
// recovery job once the mint has it, and failed when nothing was requested.
func TestRecoveryResolvesDirectNote(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 1)
if !q.Direct {
t.Fatalf("expected a direct quote: %+v", q)
}
// the payment outcome is lost: the note stays pending_settle
h.ledger.payAmbig = true
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if !errors.Is(err, ErrInFlight) || len(live) != 0 {
t.Fatalf("expected in flight: %v live=%d", err, len(live))
}
h.ledger.payAmbig = false
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 1 || notes[0].State != NotePendingSettle {
t.Fatalf("expected one pending note, got %d", len(notes))
}
// the payment did go through after all
h.mint.settle(notes[0].InvoicePR)
backdateAll(h)
NewJobs(h.svc, nil).RecoverOnce(ctx)
n, _ := h.store.Note(notes[0].ID)
b, _ := h.store.Batch(batch.ID)
if n.State != NoteLive || n.ReportedMsat != 100_000 || b.State != BatchLive {
t.Fatalf("after recovery: note %s (%d msat), batch %s", n.State, n.ReportedMsat, b.State)
}
// a direct note whose invoice was never requested is failed
batch2, _, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
notes2, _ := h.store.NotesInBatch(batch2.ID)
_ = h.store.TransitionNote(notes2[0].ID, "", NotePendingInvoice, nil)
_ = h.store.TransitionBatch(batch2.ID, "", BatchPendingInvoice, nil)
backdateAll(h)
NewJobs(h.svc, nil).RecoverOnce(ctx)
if n2, _ := h.store.Note(notes2[0].ID); n2.State != NoteFailed {
t.Fatalf("never-requested note: %s", n2.State)
}
}
func backdate(t *testing.T, s *Store, id string) {
t.Helper()
if err := s.DB().Model(&Note{}).Where("id = ?", id).Update("updated_at", time.Now().Add(-time.Minute)).Error; err != nil {
+46 -11
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"strings"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
@@ -43,8 +44,9 @@ func (s *Service) Reclaim(ctx context.Context, noteID string) (*Note, error) {
default:
return n, ErrNoteNotLive
}
state, value, err := s.Status(ctx, n)
if errors.Is(err, lnurlcash.ErrNotePending) {
// the lookup that checks the note also names the callback the melt goes to
state, value, info, err := s.probe(ctx, n)
if errors.Is(err, ErrNotePending) || errors.Is(err, lnurlcash.ErrNotePending) {
return n, ErrNotePending
}
if err != nil {
@@ -70,18 +72,19 @@ func (s *Service) Reclaim(ctx context.Context, noteID string) (*Note, error) {
return n, err
}
n.State, n.InvoicePR, n.InvoiceHash = NoteReclaiming, pr, hash
return n, s.melt(ctx, n, k1, pr)
return n, s.melt(ctx, n, k1, pr, info.Callback)
}
// 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 {
// melt sends one melt to callback, the one the mint named in the note's own
// withdraw info, and maps its outcome onto the note. Never retried.
func (s *Service) melt(ctx context.Context, n *Note, k1, pr, callback string) error {
if callback == "" {
err := fmt.Errorf("the mint named no callback for note %s", ShortID(n.ID))
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": err.Error()})
n.State = NoteLive
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
_, err = s.client.MeltNote(ctx, callback, k1, pr)
_, 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])
@@ -136,6 +139,38 @@ func (s *Service) SettleInvoice(ctx context.Context, hash string) (*Settlement,
return nil, nil
}
// AwaitSettlement watches the LNbits invoice a melt pays, for at most
// timeout, and settles the reclaim or redeem it belongs to once it is paid.
// The webhook normally gets there first; this keeps the user from waiting for
// the recovery job when the webhook is late or lost. It returns nil, nil when
// the invoice did not settle in time or the webhook already settled it, so a
// caller notifies only on a non-nil Settlement and the user hears once.
func (s *Service) AwaitSettlement(ctx context.Context, user, invoiceHash string, timeout time.Duration) (*Settlement, error) {
if invoiceHash == "" {
return nil, nil
}
deadline := s.now().Add(timeout)
for attempt := 0; ; attempt++ {
paid, err := s.ledger.InvoicePaid(ctx, user, invoiceHash)
if err == nil && paid {
return s.SettleInvoice(ctx, invoiceHash)
}
// 500 ms, 1 s, then every 2 s
wait := pollDelay(settlePollMax, attempt+1)
if !s.now().Add(wait).Before(deadline) {
return nil, nil
}
select {
case <-ctx.Done():
return nil, nil
case <-time.After(wait):
}
}
}
// settlePollMax is the longest gap between two AwaitSettlement polls.
var settlePollMax = 2 * time.Second
// settleNoteLocked finishes a reclaim. The caller holds the note's lock.
func (s *Service) settleNoteLocked(noteID string) (*Settlement, error) {
n, err := s.store.Note(noteID)
@@ -209,7 +244,7 @@ func (s *Service) RedeemInfo(ctx context.Context, user, lang, input string) (*Re
}
}
}
info, err := s.client.FetchNoteInfo(ctx, noteURL)
info, err := s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
@@ -268,7 +303,7 @@ func (s *Service) Redeem(ctx context.Context, redeemID, user string) (*Redeem, e
if err != nil {
return r, err
}
info, err := s.client.FetchNoteInfo(ctx, noteURL)
info, err := s.reader.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
@@ -415,7 +450,7 @@ func (s *Service) splitWholeSat(ctx context.Context, r *Redeem, noteURL string,
}
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 {
if _, perr := s.reader.FetchNoteInfoByHash(ctx, link, target.Hash); perr == nil {
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
_ = s.store.TransitionRedeem(r.ID, "", RedeemConfirmed, map[string]interface{}{"split_note_id": target.ID})
+35 -7
View File
@@ -18,6 +18,9 @@ type Registry struct {
cfg *Config
store *Store
client *lnurlcash.Client
// reader does the read-only lookups on pooled connections. It never
// carries a mutation: see NewRegistry.
reader *lnurlcash.Client
alert func(string)
mu sync.RWMutex
@@ -25,17 +28,36 @@ type Registry struct {
}
// 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 {
// may be nil.
//
// httpClient carries every mutation (mint invoice, split, melt). It may be nil
// (then lnurlcash.NewClient's transport is used); a supplied client MUST
// disable keep-alives and MUST NOT retry.
//
// readHTTP carries only read-only lookups (note info, payRequest, mint
// address), which are safe to resend, so it keeps connections alive and saves
// a TCP and TLS handshake per lookup. nil gives a pooled default.
func NewRegistry(cfg *Config, store *Store, httpClient, readHTTP *http.Client, alert func(string)) *Registry {
client := lnurlcash.NewClient()
if httpClient != nil {
client.HTTP = httpClient
}
reader := lnurlcash.NewClient()
if readHTTP == nil {
readHTTP = &http.Client{
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment, MaxIdleConnsPerHost: 4, IdleConnTimeout: 90 * time.Second},
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
reader.HTTP = readHTTP
// a lookup is never a mutation; make sure the library cannot treat it as one
reader.MutationRetries = -1
if alert == nil {
alert = func(msg string) { log.Warnf("[lnurlcash] alert: %s", msg) }
}
r := &Registry{cfg: cfg, store: store, client: client, alert: alert, mints: map[string]*Mint{}}
r := &Registry{cfg: cfg, store: store, client: client, reader: reader, alert: alert, mints: map[string]*Mint{}}
for _, mc := range cfg.Mints {
m, err := store.Mint(mc.Name)
if err != nil {
@@ -51,9 +73,15 @@ func NewRegistry(cfg *Config, store *Store, httpClient *http.Client, alert func(
return r
}
// Client is the LNURLcash client every service call goes through.
// Client is the LNURLcash client every mutation goes through: mint invoice,
// split, melt. It never reuses a connection.
func (r *Registry) Client() *lnurlcash.Client { return r.client }
// Reader is the LNURLcash client for read-only lookups (FetchNoteInfo,
// FetchNoteInfoByHash, FetchPayRequest, FetchMintAddress). It reuses
// connections, so it MUST NOT be used for a mutation.
func (r *Registry) Reader() *lnurlcash.Client { return r.reader }
// Check validates one mint: reachable, commentAllowed >= 64, a withdrawLink,
// a fee under the cap, and a pinned mintPubkey that has not changed.
func (r *Registry) Check(ctx context.Context, id string) error {
@@ -88,7 +116,7 @@ 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)
pay, err := r.reader.FetchPayRequest(ctx, m.PayURL)
if err != nil {
return fmt.Errorf("payRequest: %w", err)
}
@@ -108,7 +136,7 @@ func (r *Registry) check(ctx context.Context, m *Mint) error {
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 {
if addr, aerr := r.reader.FetchMintAddress(ctx, addrURL); aerr == nil {
pubkey = strings.ToLower(strings.TrimSpace(addr.NodePubkey))
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ func TestRegistryCheckAndPin(t *testing.T) {
s := testStore(t)
cfg := testConfig(fm.url())
alerts := []string{}
r := NewRegistry(cfg, s, nil, func(msg string) { alerts = append(alerts, msg) })
r := NewRegistry(cfg, s, nil, nil, func(msg string) { alerts = append(alerts, msg) })
if err := r.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
@@ -52,7 +52,7 @@ func TestRegistryCheckAndPin(t *testing.T) {
t.Fatal("no usable mint expected")
}
// the pin survives a restart through the store
r2 := NewRegistry(cfg, s, nil, nil)
r2 := NewRegistry(cfg, s, nil, nil, nil)
m2, _ := r2.Get("fake")
if m2.PinnedPubkey != fm.pubkey || !m2.Disabled {
t.Fatalf("pin not persisted: %+v", m2)
+1 -1
View File
@@ -60,7 +60,7 @@ type Note struct {
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)
GrossMsat int64 // what was paid for it: funding notes, and user notes minted directly from their own invoice
FeeMsat int64
Memo string
State string `gorm:"index"`
+25 -23
View File
@@ -23,28 +23,23 @@ func (s *Store) StrandedCandidates(limit int) ([]*Note, error) {
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 {
// batchSettled reports whether a batch is done minting: delivered, partly
// delivered or failed. From then on the value left in its funding and change
// notes is the owner's. A batch still funding or carving is not settled, since
// its change notes are the input of the next split.
func (s *Service) batchSettled(b *Batch) bool {
switch b.State {
case BatchLive, BatchPartial, BatchClaimed, BatchReclaimed, BatchFailed:
return true
}
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.
// RefundStranded melts the value that a settled batch left in a bot-held
// funding or change note back into its owner's balance: the change of a
// carved batch, or what a failed one stranded. The whole-sat part is split off
// if needed and reclaimed like any note. It returns nil when there is nothing
// to do and ErrInFlight/nil once a melt is under way.
func (s *Service) RefundStranded(ctx context.Context, noteID string) error {
var reclaimID string
err := func() error {
@@ -58,7 +53,7 @@ func (s *Service) RefundStranded(ctx context.Context, noteID string) error {
return nil
}
b, err := s.store.Batch(*n.BatchID)
if err != nil || !s.batchStranded(b) {
if err != nil || !s.batchSettled(b) {
return err
}
state, value, err := s.Status(ctx, n)
@@ -140,7 +135,7 @@ func (s *Service) splitOffWholeSats(ctx context.Context, n *Note, value int64) (
_ = 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 {
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, rest.Hash); perr == nil {
change = info.MaxWithdrawableMsat
}
_ = s.store.TransitionNote(rest.ID, "", NoteLive, map[string]interface{}{"value_msat": change, "reported_msat": change})
@@ -159,7 +154,7 @@ func (s *Service) splitOffWholeSats(ctx context.Context, n *Note, value int64) (
}
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 {
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, target.Hash); perr == nil {
return landed(info.MaxWithdrawableMsat), nil
}
return nil, fmt.Errorf("refund split of %s unresolved: %w", n.ID, err)
@@ -173,8 +168,8 @@ func (s *Service) splitOffWholeSats(ctx context.Context, n *Note, value int64) (
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
// RefundStrandedOnce returns the change and stranded value of settled batches
// to their owners. A note that cannot be refunded is retried hourly and reported to the
// operator once.
func (j *Jobs) RefundStrandedOnce(ctx context.Context) {
if !j.refundMu.TryLock() {
@@ -205,7 +200,14 @@ func (j *Jobs) RefundStrandedOnce(ctx context.Context) {
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))
j.notifier.Alert(fmt.Sprintf("LNURLcash could not return %d msat held in note %s of batch %s to user %s: %v", n.ReportedMsat, n.ID, batchIDOf(n), n.UserName, err))
}
}
}
func batchIDOf(n *Note) string {
if n.BatchID == nil {
return "-"
}
return *n.BatchID
}
+51 -4
View File
@@ -95,18 +95,65 @@ func TestRefundStrandedAfterCarveFailure(t *testing.T) {
}
}
// Value of healthy batches (the dust left after a full carve) is not refunded.
func TestRefundIgnoresHealthyBatches(t *testing.T) {
// The change left after a full carve is the owner's: it is melted back.
func TestRefundReturnsChangeOfHealthyBatch(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
if _, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q}); err != nil || len(live) != 3 {
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 3 || batch.State != BatchLive {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
var change *Note
notes, _ := h.store.NotesInBatch(batch.ID)
for _, n := range notes {
if n.Kind == KindDust && n.State == NoteLive {
change = n
}
}
if change == nil || change.ReportedMsat < 1000 {
t.Fatalf("expected a whole-sat change note, got %+v", change)
}
before := h.ledger.balances["42"]
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
h.mint.finishMelt(change.Hash, true)
if settleRefunds(t, h) != 1 {
t.Fatal("the change was not refunded")
}
if got := h.ledger.balances["42"] - before; got != change.ReportedMsat {
t.Errorf("refunded %d msat, change was %d", got, change.ReportedMsat)
}
if n, _ := h.store.Note(change.ID); n.State != NoteReclaimed {
t.Errorf("change note state %s", n.State)
}
// the user's notes are untouched
if userNotes, _ := h.store.UserNotes("42", []string{NoteLive}); len(userNotes) != 3 {
t.Errorf("live user notes: %d", len(userNotes))
}
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("refund was repeated")
}
}
// A batch still carving keeps its change: it is the input of the next split.
func TestRefundIgnoresBatchStillCarving(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 3 {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
_ = h.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("a healthy batch was refunded")
t.Error("a batch that is still carving was refunded")
}
}
+158 -31
View File
@@ -71,17 +71,22 @@ type Service struct {
mints *Registry
ledger Ledger
cipher *Cipher
// client carries every mutation (mint invoice, split, melt) on a fresh
// connection; reader carries the read-only lookups on pooled connections.
// A mutation MUST NOT go through reader.
client *lnurlcash.Client
reader *lnurlcash.Client
// now is replaceable in tests.
now func() time.Time
// sleep between settlement polls, replaceable in tests.
// the longest sleep between funding polls, replaceable in tests. The first
// polls come sooner: see pollDelay.
pollEvery time.Duration
}
// NewService wires the service. The registry supplies the LNURLcash client.
func NewService(cfg *Config, store *Store, mints *Registry, ledger Ledger, cipher *Cipher) *Service {
return &Service{cfg: cfg, store: store, mints: mints, ledger: ledger, cipher: cipher,
client: mints.Client(), now: time.Now, pollEvery: 2 * time.Second}
client: mints.Client(), reader: mints.Reader(), now: time.Now, pollEvery: 2 * time.Second}
}
// Store exposes the store to the Telegram layer for read-only listing.
@@ -127,6 +132,9 @@ type Quote struct {
FeeMsat int64 // GrossMsat - Count*ValueMsat: mint fee plus carving margin
Fee lnurlcash.MintFee
Strategy string
// Direct means each note is minted straight from its own invoice, with
// no funding note, split or change.
Direct bool `json:"direct,omitempty"`
}
// NetMsat is what the user's notes are worth together.
@@ -146,8 +154,60 @@ func grossFor(valueMsat int64, count int64, fee lnurlcash.MintFee) int64 {
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.
// satCredit is what a mint that keeps notes in whole sats credits for an
// invoice: the gross less the fee, floored to the sat (the fee rounded up to
// the sat, for whole-sat amounts). The live mints do this: mint.600.wtf turned
// an 18000 msat invoice into a 14000 msat note, where ApplyMintFee says 14910.
func satCredit(grossMsat int64, fee lnurlcash.MintFee) int64 {
// the proportional fee in sats, rounded up: ceil(gross*ppm / 1e9), split
// so it cannot overflow
q, r := grossMsat/1_000_000_000, grossMsat%1_000_000_000
propSat := q*fee.FeePpm + (r*fee.FeePpm+999_999_999)/1_000_000_000
rest := grossMsat - fee.BaseFeeMsat
c := rest - rest%1000 - propSat*1000
if c < 0 {
return 0
}
return c
}
// directGross returns the smallest whole-sat invoice whose note is worth at
// least valueMsat after the mint fee, both as ApplyMintFee reads the fee and at
// a mint that rounds it to whole sats. At such a mint the note is worth
// exactly valueMsat.
func directGross(valueMsat int64, fee lnurlcash.MintFee) int64 {
g := lnurlcash.GrossUpForMintFee(valueMsat, fee)
if rem := g % 1000; rem != 0 {
g += 1000 - rem
}
for satCredit(g, fee) < valueMsat || lnurlcash.ApplyMintFee(g, fee) < valueMsat {
g += 1000
}
return g
}
// directGrossInRange prices one directly minted note within the mint's
// sendable range. A gross below the minimum is raised to it only while the
// note still comes out at the asked whole sat; ok is false otherwise.
func directGrossInRange(mint *Mint, valueMsat int64, fee lnurlcash.MintFee) (int64, bool) {
g := directGross(valueMsat, fee)
if g < mint.MinSendableMsat {
g = mint.MinSendableMsat
if g%1000 != 0 || satCredit(g, fee) >= valueMsat+1000 {
return 0, false
}
}
if mint.MaxSendableMsat > 0 && g > mint.MaxSendableMsat {
return 0, false
}
return g, true
}
// Quote prices count notes of valueMsat at a mint. A single note, and each
// note of the "invoices" strategy, is minted straight from its own invoice,
// so only the mint fee is paid on it. A single note the mint's minimum would
// overpay falls back to funding and carving. The "split" strategy carves
// every note of a batch out of one funding note.
func (s *Service) Quote(ctx context.Context, mint *Mint, valueMsat int64, count int) (Quote, error) {
if mint == nil || !mint.Usable() {
return Quote{}, ErrNoMint
@@ -160,15 +220,19 @@ func (s *Service) Quote(ctx context.Context, mint *Mint, valueMsat int64, count
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
per, ok := directGrossInRange(mint, valueMsat, fee)
q.Strategy, q.Direct = StrategyInvoices, true
if !ok {
if count > 1 {
return Quote{}, ErrMintRange
}
per = grossFor(valueMsat, 1, fee)
if per < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && per > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
q.Strategy, q.Direct = StrategySplit, false
}
gross = per * int64(count)
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) {
@@ -257,7 +321,7 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note,
}
units := 1
perUnit := q.Count
if q.Strategy == StrategyInvoices && q.Count > 1 {
if q.Direct || (q.Strategy == StrategyInvoices && q.Count > 1) {
units, perUnit = q.Count, 1
}
unitGross := q.GrossMsat / int64(units)
@@ -269,6 +333,18 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note,
index := 0
for u := 0; u < units; u++ {
un := &unit{}
if q.Direct {
// the note is minted straight from its invoice: it is its own funding
index++
n, err := s.newNote(batch, mint, p, KindUser, index, unitGross)
if err != nil {
return nil, nil, err
}
n.State = NotePendingInvoice
un.funding = n
all = append(all, un)
continue
}
f, err := s.newNote(batch, mint, p, KindFunding, 0, unitGross)
if err != nil {
return nil, nil, err
@@ -310,8 +386,12 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note,
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)
log.Infof("[lnurlcash] batch %s: %d note(s) of %d msat at %s for user %s (gross %d msat, direct %t)", batch.ID, q.Count, q.ValueMsat, mint.ID, p.User, q.GrossMsat, q.Direct)
// the recovery job takes the same lock, so it never works this batch
// while the creation is still running
unlock := lockNote(batch.ID)
defer unlock()
var live []*Note
done := 0
var firstErr error
@@ -322,6 +402,9 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note,
p.Progress(done, q.Count)
}
})
if un.funding.Kind == KindUser && un.funding.State == NoteLive {
live = append(live, un.funding)
}
for _, n := range un.notes {
if n.State == NoteLive {
live = append(live, n)
@@ -359,6 +442,7 @@ func (s *Service) newNote(batch *Batch, mint *Mint, p CreateParams, kind string,
State: NotePendingCarve, LanguageCode: p.LanguageCode, ChatID: p.ChatID}
if kind == KindUser {
n.ValueMsat = p.Quote.ValueMsat
n.GrossMsat = gross // > 0 only for a directly minted note
}
if kind == KindFunding {
n.GrossMsat = gross
@@ -406,6 +490,13 @@ func (s *Service) fundAndCarve(ctx context.Context, batch *Batch, mint *Mint, un
return ErrInFlight
}
}
if len(un.notes) == 0 {
// a directly minted note: nothing to carve
if f.State == NoteLive {
progress()
}
return nil
}
return s.carve(ctx, batch, un, progress)
}
@@ -413,17 +504,29 @@ func (s *Service) fundAndCarve(ctx context.Context, batch *Batch, mint *Mint, un
// 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)
for attempt := 0; ; attempt++ {
info, err := s.reader.FetchNoteInfoByHash(ctx, f.MintURL, f.Hash)
if err == nil {
patch := map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature, "last_probe": s.now()}
if err := s.store.TransitionNote(f.ID, NotePendingSettle, NoteLive, patch); err != nil && !errors.Is(err, ErrStale) {
return false, err
}
f.State, f.ReportedMsat = NoteLive, info.MaxWithdrawableMsat
if f.Kind == KindUser && info.MaxWithdrawableMsat%1000 != 0 {
// the user cannot reclaim a fractional note: the mint does not round
// its fee to whole sats as directGross assumes
log.Errorf("[lnurlcash] note %s: mint %s credited %d msat for a %d msat note; direct minting at this mint gives fractional notes",
f.ID, f.MintID, info.MaxWithdrawableMsat, f.ValueMsat)
}
return true, nil
}
if lnurlcash.IsSpent(err) {
if f.Kind == KindUser {
// a directly minted note that was claimed before we saw it
f.State = NoteClaimed
_ = s.store.TransitionNote(f.ID, "", NoteClaimed, map[string]interface{}{"reported_msat": f.ValueMsat, "claimed_at": s.now()})
return true, nil
}
// burned already: the funding note was carved by a previous run
f.State = NoteSpent
_ = s.store.TransitionNote(f.ID, "", NoteSpent, nil)
@@ -435,16 +538,29 @@ func (s *Service) waitFunding(ctx context.Context, f *Note, timeout time.Duratio
select {
case <-ctx.Done():
return false, nil
case <-time.After(s.pollEvery):
case <-time.After(pollDelay(s.pollEvery, attempt)):
}
}
}
// pollDelay is the sleep after poll number attempt (from 0): an eighth of max,
// then a quarter, a half, and max from then on. A mint usually credits a note
// within a second of the payment settling, so the first polls come quickly.
func pollDelay(max time.Duration, attempt int) time.Duration {
if attempt >= 3 {
return max
}
return max >> (3 - attempt)
}
// carve splits the user notes off the funding note, one after the other.
// Idempotent: a note that already exists at the mint is taken as carved.
func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress func()) error {
_ = s.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
current := un.funding
// every note of a unit lives at the same withdraw link, so the callback the
// mint names for the first input serves the whole chain
callback := ""
for i, n := range un.notes {
if IsFinalNoteState(n.State) || n.State == NoteLive {
if n.State == NoteLive {
@@ -463,18 +579,21 @@ func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress fu
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
if callback == "" {
cb, cerr := s.callbackOf(ctx, current)
if cerr != nil {
// nothing was sent: the recovery job tries again
log.Warnf("[lnurlcash] batch %s: callback of %s: %v", batch.ID, current.Hash, cerr)
return ErrInFlight
}
callback = cb
}
_, err = s.client.SplitNoteWithHash(ctx, callback, []string{k1}, n.ValueMsat, n.Hash, dust.Hash)
if err != nil {
switch {
case lnurlcash.IsAmbiguous(err):
// the library already retried; the answer is lost. Probe the output.
if _, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
if _, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break // it landed
}
_ = s.store.TransitionNote(n.ID, "", NoteUnknown, map[string]interface{}{"last_error": err.Error()})
@@ -485,7 +604,7 @@ func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress fu
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 {
if _, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break
}
s.failRemaining(batch, un, i, err.Error())
@@ -508,7 +627,7 @@ func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress fu
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 {
if info, perr := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil && info.MaxWithdrawableMsat != n.ReportedMsat {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature})
n.ReportedMsat = info.MaxWithdrawableMsat
}
@@ -521,7 +640,7 @@ func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress fu
// 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)
info, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
if err != nil {
return "", err
}
@@ -604,10 +723,18 @@ func (s *Service) settleBatchState(batchID string) {
// Status asks the mint about a note and updates the row. It returns the
// note's new state.
func (s *Service) Status(ctx context.Context, n *Note) (string, int64, error) {
state, value, _, err := s.probe(ctx, n)
return state, value, err
}
// probe is Status that also returns the mint's withdraw info when the note
// exists, so a caller about to mutate the note can use its callback without
// asking the mint a second time.
func (s *Service) probe(ctx context.Context, n *Note) (string, int64, lnurlcash.WithdrawInfo, error) {
if IsFinalNoteState(n.State) {
return n.State, n.ReportedMsat, nil
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, nil
}
info, err := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
info, err := s.reader.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
now := s.now()
switch {
case err == nil:
@@ -623,10 +750,10 @@ func (s *Service) Status(ctx context.Context, n *Note) (string, int64, error) {
_ = s.store.UpdateNote(n.ID, patch)
}
n.ReportedMsat = info.MaxWithdrawableMsat
return n.State, n.ReportedMsat, nil
return n.State, n.ReportedMsat, info, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now})
return n.State, n.ReportedMsat, ErrNotePending
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
if n.State == NoteLive {
t := now
@@ -639,10 +766,10 @@ func (s *Service) Status(ctx context.Context, n *Note) (string, int64, error) {
} else {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
}
return n.State, n.ReportedMsat, nil
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, nil
default:
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
return n.State, n.ReportedMsat, err
return n.State, n.ReportedMsat, lnurlcash.WithdrawInfo{}, err
}
}
+69 -6
View File
@@ -107,7 +107,7 @@ func newHarness(t *testing.T) *harness {
s := testStore(t)
cfg := testConfig(fm.url())
cfg.InvoiceWaitTimeout = 2 * time.Second
reg := NewRegistry(cfg, s, nil, nil)
reg := NewRegistry(cfg, s, nil, nil, nil)
if err := reg.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
@@ -136,16 +136,79 @@ func TestGrossUpAgainstLiveFee(t *testing.T) {
}
}
// The live mints' fees: a direct note costs the mint fee and nothing else, and
// a mint that rounds its fee to whole sats credits exactly the asked value.
func TestDirectGrossLiveFees(t *testing.T) {
fees := map[string]lnurlcash.MintFee{
"21mint": {BaseFeeMsat: 1000, FeePpm: 100},
"mint.600.wtf": {BaseFeeMsat: 3000, FeePpm: 5000},
"mint.lnurlcash.com": {BaseFeeMsat: 3000, FeePpm: 2000},
}
want10 := map[string]int64{"21mint": 12000, "mint.600.wtf": 14000, "mint.lnurlcash.com": 14000}
for name, fee := range fees {
if g := directGross(10_000, fee); g != want10[name] {
t.Errorf("%s: 10 sat note costs %d msat, want %d", name, g, want10[name])
}
for sat := int64(1); sat <= 100_000; sat += 7 {
v := sat * 1000
g := directGross(v, fee)
if g%1000 != 0 {
t.Fatalf("%s %d sat: gross %d is not whole sats", name, sat, g)
}
if c := satCredit(g, fee); c != v {
t.Fatalf("%s %d sat: a whole-sat mint credits %d for gross %d", name, sat, c, g)
}
if lnurlcash.ApplyMintFee(g, fee) < v || (g > 1000 && satCredit(g-1000, fee) >= v) {
t.Fatalf("%s %d sat: gross %d is not minimal", name, sat, g)
}
}
}
}
// Below the mint's minimum invoice a note is minted directly only when the
// minimum still yields the asked value; otherwise it is carved as before, or
// refused when that is out of range too.
func TestQuoteAtMintMinimum(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
h.mint.minSendable = 12000 // 21mint
if err := h.reg.Check(ctx, "fake"); err != nil {
t.Fatal(err)
}
mint, _ := h.reg.Get("fake")
if q, err := h.svc.Quote(ctx, mint, 10_000, 1); err != nil || !q.Direct || q.GrossMsat != 12000 {
t.Fatalf("10 sat: %+v %v", q, err)
}
if q, err := h.svc.Quote(ctx, mint, 9_000, 1); err != nil || q.Direct || q.GrossMsat != grossFor(9_000, 1, mint.Fee()) {
t.Fatalf("9 sat must fall back to carving: %+v %v", q, err)
}
if _, err := h.svc.Quote(ctx, mint, 5_000, 1); !errors.Is(err, ErrMintRange) {
t.Fatalf("5 sat must be out of range: %v", err)
}
// a direct note created at the minimum is worth exactly what was asked
h.mint.satRound = true
q, _ := h.svc.Quote(ctx, mint, 10_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 1 || live[0].ReportedMsat != 10_000 {
t.Fatalf("create: %v live=%d", err, len(live))
}
}
func TestCreateSingleNoteAndReclaim(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
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)
// minted straight into the note: only the mint fee, no split fee or margin
if want := directGross(1000_000, mint.Fee()); !q.Direct || q.GrossMsat != want || q.FeeMsat != want-1000_000 || q.GrossMsat%1000 != 0 {
t.Fatalf("unexpected quote %+v (want direct gross %d)", q, want)
}
if q.GrossMsat >= grossFor(1000_000, 1, mint.Fee()) {
t.Fatalf("direct gross %d is not below the carved gross", q.GrossMsat)
}
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", LanguageCode: "en", Quote: q, Memo: "hi"})
if err != nil {
@@ -172,10 +235,10 @@ func TestCreateSingleNoteAndReclaim(t *testing.T) {
if lnurlcash.ResolveNoteInput(bech) == "" {
t.Fatal("bech32 note does not resolve")
}
// every secret was persisted and is distinct
// one row: the note is its own funding, nothing is left over
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 3 {
t.Fatalf("expected funding + note + dust rows, got %d", len(notes))
if len(notes) != 1 || notes[0].Kind != KindUser || notes[0].GrossMsat != q.GrossMsat || batch.FundingNoteID != n.ID {
t.Fatalf("expected one directly minted user note, got %d rows", len(notes))
}
// status: still live
state, _, err := h.svc.Status(ctx, n)
+146
View File
@@ -0,0 +1,146 @@
package lnurlcash
import (
"context"
"testing"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
)
// Lookups ride pooled connections, but a mutation (mint invoice, split, melt)
// must always arrive on a connection of its own: net/http resends a GET on a
// reused connection, and a resent melt or split is a second burn.
func TestMutationsNeverShareAConnection(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
// a directly minted note, then reclaim it
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 1 {
t.Fatalf("create: %d %v", len(live), err)
}
if _, err := h.svc.Reclaim(ctx, live[0].ID); err != nil {
t.Fatal(err)
}
// a carved batch
qb, err := h.svc.Quote(ctx, mint, 100_000, 3)
if err != nil {
t.Fatal(err)
}
if _, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: qb}); err != nil || len(live) != 3 {
t.Fatalf("batch: %d %v", len(live), err)
}
// redeem an external whole-sat note and a fractional one (split + melt)
for _, value := range []int64{2000_000, 1000_900} {
k1, _ := lnurlcash.GenerateNoteSecret()
hh, _ := lnurlcash.HashK1(k1)
h.mint.mu.Lock()
h.mint.notes[hh] = value
h.mint.mu.Unlock()
prev, err := h.svc.RedeemInfo(ctx, "7", "en", lnurlcash.BuildNoteURL(h.mint.url()+"/w", k1, value))
if err != nil {
t.Fatal(err)
}
if _, err := h.svc.Redeem(ctx, prev.Redeem.ID, "7"); err != nil {
t.Fatal(err)
}
}
mutations, shared, anyReuse := h.mint.connStats()
// 2 mint invoices, 3 splits, 1 reclaim melt, 2 redeem melts, 1 redeem split
if mutations < 9 {
t.Fatalf("expected at least 9 mutations, saw %d", mutations)
}
if shared != 0 {
t.Fatalf("%d of %d mutations arrived on a connection that carried another request", shared, mutations)
}
if !anyReuse {
t.Fatal("lookups never reused a connection: the reader is not pooled")
}
}
// A reclaim asks the mint about the note once and melts it at the callback
// that answer names, instead of looking the note up a second time.
func TestReclaimLooksUpOnce(t *testing.T) {
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
h.mint.mu.Lock()
h.mint.calls = map[string]int{}
h.mint.mu.Unlock()
if _, err := h.svc.Reclaim(ctx, live[0].ID); err != nil {
t.Fatal(err)
}
h.mint.mu.Lock()
defer h.mint.mu.Unlock()
if h.mint.calls["/w"] != 1 || h.mint.calls["/w/cb"] != 1 || len(h.mint.melts) != 1 {
t.Fatalf("reclaim made %d lookups and %d callback requests (%d melts); want 1 and 1", h.mint.calls["/w"], h.mint.calls["/w/cb"], len(h.mint.melts))
}
}
func TestAwaitSettlement(t *testing.T) {
old := settlePollMax
settlePollMax = 20 * time.Millisecond
t.Cleanup(func() { settlePollMax = old })
h := newHarness(t)
h.mint.satRound = true
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
n, err := h.svc.Reclaim(ctx, live[0].ID)
if err != nil {
t.Fatal(err)
}
// not paid in time: nothing settles, the note stays reclaiming
if st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, 50*time.Millisecond); st != nil || err != nil {
t.Fatalf("unpaid invoice settled: %+v %v", st, err)
}
// paid while the watcher waits: it settles the reclaim
go func() {
time.Sleep(30 * time.Millisecond)
h.mint.finishMelt(n.Hash, true)
h.ledger.settleIncoming(n.InvoiceHash)
}()
st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, 2*time.Second)
if err != nil || st == nil || st.Note == nil || st.Note.State != NoteReclaimed {
t.Fatalf("watcher did not settle: %+v %v", st, err)
}
// the webhook arriving after the watcher (or the other way round) finds
// nothing left to do, so the user is told once
if st, err := h.svc.SettleInvoice(ctx, n.InvoiceHash); st != nil || err != nil {
t.Fatalf("second settlement reported again: %+v %v", st, err)
}
if st, err := h.svc.AwaitSettlement(ctx, "42", n.InvoiceHash, time.Second); st != nil || err != nil {
t.Fatalf("watcher after settlement reported again: %+v %v", st, err)
}
}
func TestPollDelay(t *testing.T) {
want := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 2 * time.Second}
for i, w := range want {
if got := pollDelay(2*time.Second, i); got != w {
t.Fatalf("poll %d: %s, want %s", i, got, w)
}
}
}
+24 -1
View File
@@ -111,7 +111,8 @@ func GetClient(clientType ClientType) (*http.Client, error) {
// 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.
// would otherwise retry on a reused connection. Every mutation goes through a
// client like this one; only read-only lookups may use NewPooledClient.
func NewNoKeepAliveClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
@@ -124,3 +125,25 @@ func NewNoKeepAliveClient(timeout time.Duration) *http.Client {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
// NewPooledClient returns a client for read-only LNURLcash lookups (note info,
// payRequest): the same proxy, netguard and redirect rules as
// NewNoKeepAliveClient, but connections are kept and reused, which saves a TCP
// and TLS handshake per request. net/http may resend a request on a reused
// connection, which is harmless for a lookup and never acceptable for a
// mutation: NEVER send a split, melt, rotate, merge or mint invoice request
// through this client.
func NewPooledClient(timeout time.Duration) *http.Client {
client, err := GetClient(ClientTypeClearNet)
if err != nil || client == nil {
client = &http.Client{Transport: directTransport()}
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = false
t.MaxIdleConnsPerHost = 4
t.IdleConnTimeout = 90 * time.Second
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
+104
View File
@@ -0,0 +1,104 @@
package telegram
import (
"context"
"regexp"
"sort"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
)
// commandWordRx is what telebot (and Telegram) accept as a command: ASCII
// letters, digits and underscores. A translated word with other characters
// could never be typed as a command, so it gets no alias.
var commandWordRx = regexp.MustCompile(`^[a-z0-9_]+$`)
// faucetAliases and tipjarAliases map each translated command word, taken
// from the translation files, to the language it belongs to. The English
// word is not in the map: English is the default language.
var (
faucetAliases = loadCommandAliases("faucet", "faucetCommandStr")
tipjarAliases = loadCommandAliases("tipjar", "tipjarCommandStr")
)
func loadCommandAliases(english, messageID string) map[string]string {
aliases := map[string]string{}
for _, lang := range i18n.Languages {
word, err := i18n2.NewLocalizer(i18n.Bundle, lang).Localize(&i18n2.LocalizeConfig{MessageID: messageID})
if err != nil {
continue
}
word = strings.ToLower(strings.TrimSpace(word))
if word == english {
continue
}
if !commandWordRx.MatchString(word) {
log.Debugf("[commandAliases] %s %s %q is not a valid command, skipping", lang, messageID, word)
continue
}
if _, taken := aliases[word]; taken {
// languages share the word; the first one in i18n.Languages wins
continue
}
aliases[word] = lang
}
return aliases
}
// commandEndpoints returns the English command followed by every alias,
// each with a leading slash, in a stable order.
func commandEndpoints(english string, aliases map[string]string) []interface{} {
words := make([]string, 0, len(aliases))
for word := range aliases {
words = append(words, word)
}
sort.Strings(words)
endpoints := []interface{}{"/" + english}
for _, word := range words {
endpoints = append(endpoints, "/"+word)
}
return endpoints
}
// commandWord normalizes the first word of a command or inline query:
// no leading slash, no @botname, lower case.
func commandWord(text string) string {
fields := strings.Fields(text)
if len(fields) == 0 {
return ""
}
word := strings.TrimPrefix(fields[0], "/")
if i := strings.Index(word, "@"); i >= 0 {
word = word[:i]
}
return strings.ToLower(word)
}
// isCommand reports whether word is the English command or one of its aliases.
func isCommand(word, english string, aliases map[string]string) bool {
if word == english {
return true
}
_, ok := aliases[word]
return ok
}
// commandTranslationMap sets the public language to the language of a
// translated command, so that a faucet or tipjar created with /zapfhahn is
// posted in German no matter which language the creator uses.
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
word := commandWord(command)
lang, ok := faucetAliases[word]
if !ok {
lang, ok = tipjarAliases[word]
}
if !ok {
return ctx
}
ctx = context.WithValue(ctx, "publicLanguageCode", lang)
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, lang))
return ctx
}
+78
View File
@@ -0,0 +1,78 @@
package telegram
import (
"context"
"testing"
)
func TestCommandAliasesFromTranslations(t *testing.T) {
wantFaucet := map[string]string{
"zapfhahn": "de", "kraan": "nl", "grifo": "es", "kran": "pl",
"hana": "fi", "keran": "id", "torneira": "pt-br", "distribuzione": "it",
}
wantTipjar := map[string]string{
"spendendose": "de", "donatiebox": "nl", "tippikulho": "fi",
"salvadanaio": "it", "cofrinho": "pt-br",
}
for name, c := range map[string]struct{ got, want map[string]string }{
"faucet": {faucetAliases, wantFaucet},
"tipjar": {tipjarAliases, wantTipjar},
} {
if len(c.got) != len(c.want) {
t.Errorf("%s aliases = %v, want %v", name, c.got, c.want)
}
for word, lang := range c.want {
if c.got[word] != lang {
t.Errorf("%s alias %q = %q, want %q", name, word, c.got[word], lang)
}
}
}
// words Telegram cannot send as a command get no alias
for _, word := range []string{"fıçı", "alcancía", "bağışkutusu"} {
if _, ok := faucetAliases[word]; ok {
t.Errorf("faucet alias %q should be skipped", word)
}
if _, ok := tipjarAliases[word]; ok {
t.Errorf("tipjar alias %q should be skipped", word)
}
}
}
func TestCommandTranslationMap(t *testing.T) {
for text, want := range map[string]string{
"/kran 100 10": "pl",
"/Kran@LightningTipBot 100 10": "pl",
"zapfhahn 100 10": "de",
"/spendendose 100 10": "de",
"/faucet 100 10": "",
"/send 100": "",
} {
ctx := TipBot{}.commandTranslationMap(context.Background(), text)
got, _ := ctx.Value("publicLanguageCode").(string)
if got != want {
t.Errorf("%q: language %q, want %q", text, got, want)
}
}
}
// an alias must not take over a command that another handler already owns
func TestCommandAliasesDoNotCollide(t *testing.T) {
seen := map[string]int{}
for i, h := range (TipBot{}).getHandler() {
for _, e := range h.Endpoints {
s, ok := e.(string)
if !ok {
continue
}
if j, dup := seen[s]; dup && j != i {
t.Errorf("endpoint %q is registered by handlers %d and %d", s, j, i)
}
seen[s] = i
}
}
for _, word := range []string{"/kran", "/hana", "/cofrinho"} {
if _, ok := seen[word]; !ok {
t.Errorf("%s is not registered", word)
}
}
}
+1 -1
View File
@@ -70,7 +70,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 5 || amount%perUserAmount != 0 {
if perUserAmount < 1 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := int(amount / perUserAmount)
+3
View File
@@ -29,6 +29,9 @@ type JoinTicket struct {
Message *tb.Message `json:"message"`
CreatedTimestamp time.Time `json:"created_timestamp"`
Ticket *Ticket `json:"ticket"`
// PaymentHash of the ticket invoice. Empty for tickets stored by older
// versions of the bot.
PaymentHash string `json:"payment_hash,omitempty"`
}
func (jt JoinTicket) Key() string {
+2 -2
View File
@@ -716,7 +716,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
{
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
Endpoints: commandEndpoints("faucet", faucetAliases),
Handler: bot.faucetHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -731,7 +731,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
{
Endpoints: []interface{}{"/tipjar", "/spendendose"},
Endpoints: commandEndpoints("tipjar", tipjarAliases),
Handler: bot.tipjarHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
+3 -24
View File
@@ -1,7 +1,6 @@
package telegram
import (
"context"
"fmt"
"reflect"
"strconv"
@@ -12,8 +11,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
@@ -119,25 +116,6 @@ func (bot TipBot) anyChosenInlineHandler(ctx intercept.Context) (intercept.Conte
return ctx, nil
}
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
switch command {
// is default, we don't have to check it
// case "faucet":
// ctx = context.WithValue(ctx, "publicLanguageCode", "en")
// ctx = context.WithValue(ctx, "publicLocalizer", i18n.NewLocalizer(i18n.Bundle, "en"))
case "zapfhahn", "spendendose":
ctx = context.WithValue(ctx, "publicLanguageCode", "de")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "de"))
case "kraan":
ctx = context.WithValue(ctx, "publicLanguageCode", "nl")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "nl"))
case "grifo":
ctx = context.WithValue(ctx, "publicLanguageCode", "es")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "es"))
}
return ctx
}
func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, error) {
if ctx.Query().Text == "" {
return bot.inlineQueryInstructions(ctx)
@@ -152,14 +130,15 @@ func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, err
return bot.handleInlineSendQuery(ctx)
}
if strings.HasPrefix(text, "faucet") || strings.HasPrefix(text, "zapfhahn") || strings.HasPrefix(text, "kraan") || strings.HasPrefix(text, "grifo") {
word := commandWord(text)
if isCommand(word, "faucet", faucetAliases) {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
}
return bot.handleInlineFaucetQuery(ctx)
}
if strings.HasPrefix(text, "tipjar") || strings.HasPrefix(text, "spendendose") {
if isCommand(word, "tipjar", tipjarAliases) {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
+45 -1
View File
@@ -37,7 +37,9 @@ func (bot *TipBot) initLNURLCash() {
panic(err)
}
notifier := &lnurlcashNotifier{bot: bot}
registry := lnurlcash.NewRegistry(cfg, bot.DB.LNURLCash, network.NewNoKeepAliveClient(30*time.Second), notifier.Alert)
// mutations on fresh connections, read-only lookups on pooled ones
registry := lnurlcash.NewRegistry(cfg, bot.DB.LNURLCash, network.NewNoKeepAliveClient(30*time.Second),
network.NewPooledClient(30*time.Second), notifier.Alert)
bot.LNURLCash = lnurlcash.NewService(cfg, bot.DB.LNURLCash, registry, &lnbitsLedger{bot: bot}, cipher)
bot.lnurlcashJobs = lnurlcash.NewJobs(bot.LNURLCash, notifier)
log.Infof("[lnurlcash] enabled with %d mint(s)", len(cfg.Mints))
@@ -168,6 +170,12 @@ func (bot *TipBot) lnurlcashSettleEvent(event Event) {
log.Errorf("[lnurlcash] settle %s: %v", ev.PaymentHash, err)
return
}
bot.notifyLNURLCashSettlement(st)
}
// notifyLNURLCashSettlement tells the user a reclaim or redeem settled. st
// may be nil (nothing settled, or another path already told them).
func (bot *TipBot) notifyLNURLCashSettlement(st *lnurlcash.Settlement) {
if st == nil {
return
}
@@ -181,6 +189,36 @@ func (bot *TipBot) lnurlcashSettleEvent(event Event) {
}
}
// lnurlcashSettleWait is how long a handler watches a melt's invoice after
// sending the melt. Later settlements reach the user through the webhook or
// the recovery job.
const lnurlcashSettleWait = 45 * time.Second
// awaitLNURLCashSettlement watches the invoice a melt pays in the background
// and tells the user as soon as it settles, whether or not the LNbits webhook
// arrives. The webhook and this watcher settle under the same lock, so the
// user hears only once.
func (bot *TipBot) awaitLNURLCashSettlement(userName, invoiceHash string) {
if bot.LNURLCash == nil || invoiceHash == "" {
return
}
go func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("[lnurlcash] settlement watcher for %s panicked: %v", invoiceHash, r)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), lnurlcashSettleWait+10*time.Second)
defer cancel()
st, err := bot.LNURLCash.AwaitSettlement(ctx, userName, invoiceHash, lnurlcashSettleWait)
if err != nil {
log.Warnf("[lnurlcash] settle %s: %v", invoiceHash, err)
return
}
bot.notifyLNURLCashSettlement(st)
}()
}
// ---- Notifier: how the jobs reach Telegram ----
type lnurlcashNotifier struct{ bot *TipBot }
@@ -222,6 +260,12 @@ func (n *lnurlcashNotifier) NoteReclaimed(note *lnurlcash.Note) {
if user, err := n.bot.userByName(note.UserName); err == nil {
runtime.IgnoreErrorMultiReturn(n.bot.GetUserBalance(user))
}
if (note.Kind == lnurlcash.KindFunding || note.Kind == lnurlcash.KindDust) && note.BatchID != nil {
// the change of a batch, a note the user never saw
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteChangeReturnedMessage"),
formatSat(note.ReportedMsat), lnurlcash.ShortID(*note.BatchID)))
return
}
n.send(note.UserName, note.LanguageCode, fmt.Sprintf(i18n.Translate(note.LanguageCode, "noteReclaimedMessage"),
formatSat(note.ReportedMsat), lnurlcash.ShortID(note.ID)))
}
+51 -12
View File
@@ -157,18 +157,47 @@ func (bot *TipBot) noteCreateHandler(ctx intercept.Context) (intercept.Context,
bot.tryEditMessage(msg, TranslateUser(ctx, "noteCreatingMessage"), &tb.ReplyMarkup{})
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: c.Quote, Memo: c.Memo}
if c.Count > 1 {
return bot.createBatchFromConfirm(ctx, c, params, msg)
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
return bot.createBatchFromConfirm(ctx, c, params, msg)
})
return ctx, nil
}
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
}
bot.tryDeleteMessage(msg)
bot.sendNoteCreated(ctx, user.Telegram, live[0])
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return err
}
bot.tryDeleteMessage(msg)
bot.sendNoteCreated(ctx, user.Telegram, live[0])
return nil
})
return ctx, nil
}
// goNoteCreate runs a note creation in the background, so the handler can
// return and release the user's lock while the mint invoice is paid and the
// note is awaited. One user's creations still run one at a time, which keeps
// the caps that Create checks from being raced.
func (bot *TipBot) goNoteCreate(ctx intercept.Context, userName string, run func(intercept.Context) error) {
bg := ctx
// keep the request's values (localizer, user) but not its lifetime
bg.Context = context.WithoutCancel(ctx.Context)
go func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("[lnurlcash] note creation for %s panicked: %v", userName, r)
}
}()
key := "lnurlcash-create:" + userName
mutex.Lock(key)
defer mutex.Unlock(key)
if err := run(bg); err != nil {
log.Warnf("[lnurlcash] note creation for %s: %v", userName, err)
}
}()
}
// sendNoteCreated sends the QR and the note text with its buttons.
func (bot *TipBot) sendNoteCreated(ctx context.Context, to *tb.User, n *lnurlcash.Note) {
bot.sendNoteQR(to, n)
@@ -245,19 +274,28 @@ func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q
return ctx, tiperrors.Create(tiperrors.NoPrivateChatError)
}
params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: q, Memo: memo, ChatID: m.Chat.ID}
bot.goNoteCreate(ctx, user.Name, func(ctx intercept.Context) error {
return bot.finishGroupNote(ctx, m, receipt, q, memo, params)
})
return ctx, nil
}
// finishGroupNote creates a group note, posts it in the group and fills in
// the private receipt. It runs in the background.
func (bot *TipBot) finishGroupNote(ctx intercept.Context, m, receipt *tb.Message, q lnurlcash.Quote, memo string, params lnurlcash.CreateParams) error {
_, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(receipt, lnurlcashErrorText(ctx, err))
return ctx, err
return err
}
n := live[0]
_, bech, err := bot.LNURLCash.NoteStrings(n)
if err != nil {
return ctx, err
return err
}
qr, err := qrcodeEncode(bech)
if err != nil {
return ctx, err
return err
}
caption := fmt.Sprintf(Translate(ctx, "noteGroupMessage"), formatSat(n.ReportedMsat), GetUserStrMd(m.Sender), bech)
if memo != "" {
@@ -271,7 +309,7 @@ func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q
text := fmt.Sprintf(TranslateUser(ctx, "noteReceiptMessage"), formatSat(n.ReportedMsat), formatSat(q.FeeMsat), q.MintName, lnurlcash.ShortID(n.ID), lnurlw)
bot.tryEditMessage(receipt, text, noteKeyboard(ctx, n, false))
log.Infof("[lnurlcash] %s created group note %s (%d msat) in chat %d", GetUserStr(m.Sender), n.ID, n.ReportedMsat, m.Chat.ID)
return ctx, nil
return nil
}
// noteStatusHandler answers the Check status button.
@@ -319,6 +357,7 @@ func (bot *TipBot) noteReclaimHandler(ctx intercept.Context) (intercept.Context,
return ctx, err
}
bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteReclaimRequestedMessage"), formatSat(n.ReportedMsat)))
bot.awaitLNURLCashSettlement(n.UserName, n.InvoiceHash)
if ctx.Callback().Message != nil {
_, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false))
}
+11 -1
View File
@@ -59,7 +59,16 @@ func (bot *TipBot) redeemInput(ctx intercept.Context, userName, lang, input stri
return ctx, err
}
text := lnurlcashErrorText(ctx, err)
if _, ok := bot.sendPrivate(sender, text); !ok && fromGroup {
var opts []interface{}
var own *lnurlcash.ErrOwnNote
if errors.As(err, &own) {
// show the note itself with its own Check status / Reclaim buttons
if n, nerr := bot.LNURLCash.Store().Note(own.NoteID); nerr == nil {
text += "\n\n" + noteViewText(ctx, n)
opts = append(opts, noteKeyboard(ctx, n, false))
}
}
if _, ok := bot.sendPrivate(sender, text, opts...); !ok && fromGroup {
bot.tryReplyMessage(ctx.Message(), Translate(ctx, "lnurlcashStartPrivateFirstMessage"))
}
return ctx, err
@@ -95,6 +104,7 @@ func (bot *TipBot) redeemConfirmHandler(ctx intercept.Context) (intercept.Contex
return ctx, err
}
log.Infof("[lnurlcash] %s redeems %s (%d msat)", GetUserStr(ctx.Sender()), r.ID, r.ReportedMsat)
bot.awaitLNURLCashSettlement(r.UserName, r.InvoiceHash)
bot.tryEditMessage(msg, fmt.Sprintf(TranslateUser(ctx, "redeemRequestedMessage"), formatSat(r.ReportedMsat)), &tb.ReplyMarkup{})
return ctx, nil
}
+4 -3
View File
@@ -79,7 +79,8 @@ func (bot *TipBot) noteBatchStart(ctx intercept.Context, user *lnbits.User, amou
}
// createBatchFromConfirm runs after Create was pressed on a batch dialog.
func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) (intercept.Context, error) {
// It runs in the background (see goNoteCreate).
func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) error {
total := c.Count
key := "lnc-progress-" + c.ID
params.Progress = func(done, total int) {
@@ -88,7 +89,7 @@ func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm,
batch, live, err := bot.LNURLCash.Create(ctx, params)
if err != nil && len(live) == 0 {
bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{})
return ctx, err
return err
}
text := fmt.Sprintf(TranslateUser(ctx, "notesBatchCreatedMessage"), len(live), total, lnurlcash.ShortID(batch.ID))
if err != nil {
@@ -96,7 +97,7 @@ func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm,
}
text += "\n\n" + TranslateUser(ctx, "notesBatchFormatMessage")
bot.tryEditMessage(msg, text, batchKeyboard(ctx, batch.ID))
return ctx, nil
return nil
}
// batchKeyboard offers the export formats and the batch actions.
+85 -10
View File
@@ -125,6 +125,7 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
ticketEvent.Message = msg
ticket.Message = msg
ticket.CreatedTimestamp = time.Now()
ticket.PaymentHash = invoice.PaymentHash
err = bot.Bunt.Set(&ticket)
if err != nil {
return ctx, err
@@ -206,13 +207,9 @@ func (bot *TipBot) expireTicket(ticket JoinTicket) {
}
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
// Tickets that already ran out are handled by restartPersistedTickets.
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
// A ticket that ran out while the bot was down is still unpaid (a paid
// ticket is deleted), so it is enforced now instead of being skipped.
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
if ticket.Message != nil && ticket.Message.Chat != nil {
bot.expireTicket(ticket)
}
return
}
// ticket is valid. create duration until kick
@@ -224,20 +221,98 @@ func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
t.Do(func() { bot.expireTicket(ticket) })
}
// maxTicketEnforceDelay is how long after it ran out a ticket is still
// enforced at startup. Older tickets are removed without a ban: the member has
// been in the group for that long already.
const maxTicketEnforceDelay = 24 * time.Hour
type ticketRestartAction int
const (
// ticketRestartTimer: the ticket has not run out, restart its timer.
ticketRestartTimer ticketRestartAction = iota
// ticketRestartDrop: remove the ticket without a ban.
ticketRestartDrop
// ticketRestartCheckPayment: the ticket ran out while the bot was down.
// Ban the member unless LNbits says the invoice was paid (the webhook for
// it may have been lost while the bot was down).
ticketRestartCheckPayment
)
// ticketActionOnRestart decides what to do with a persisted ticket at startup.
func ticketActionOnRestart(ticket JoinTicket, now time.Time) ticketRestartAction {
if ticket.Message == nil || ticket.Message.Chat == nil || ticket.Sender == nil {
return ticketRestartDrop
}
expiry := ticket.CreatedTimestamp.Add(defaultTicketDuration)
if expiry.After(now) {
return ticketRestartTimer
}
// Tickets stored by older versions have no payment hash, so whether they
// were paid can't be checked. Those versions never enforced a ticket that
// ran out while the bot was down, so neither is this one.
if ticket.PaymentHash == "" || ticket.Ticket == nil || ticket.Ticket.Creator == nil ||
ticket.Ticket.Creator.Wallet == nil || now.Sub(expiry) > maxTicketEnforceDelay {
return ticketRestartDrop
}
return ticketRestartCheckPayment
}
// restartPersistedTickets kicks of all ticket timers
func (bot *TipBot) restartPersistedTickets() {
bot.Bunt.View(func(tx *buntdb.Tx) error {
err := tx.Ascend("join-ticket", func(key, value string) bool {
type storedTicket struct {
key string
ticket JoinTicket
}
var tickets []storedTicket
// Only read here: deleting a ticket writes to bunt, and a write inside a
// read transaction deadlocks the whole database.
err := bot.Bunt.View(func(tx *buntdb.Tx) error {
return tx.Ascend("join-ticket", func(key, value string) bool {
ticket := JoinTicket{}
err := json.Unmarshal([]byte(value), &ticket)
if err != nil {
if err := json.Unmarshal([]byte(value), &ticket); err != nil {
log.Errorf("[restartPersistedTickets] could not decode %s: %v", key, err)
return true
}
bot.startTicketCallbackFunctionTimer(ticket)
tickets = append(tickets, storedTicket{key: key, ticket: ticket})
return true // continue iteration
})
})
if err != nil {
log.Errorf("[restartPersistedTickets] %v", err)
}
now := time.Now()
for _, t := range tickets {
switch ticketActionOnRestart(t.ticket, now) {
case ticketRestartTimer:
bot.startTicketCallbackFunctionTimer(t.ticket)
case ticketRestartDrop:
bot.dropTicket(t.key)
case ticketRestartCheckPayment:
payment, err := bot.Client.Payment(*t.ticket.Ticket.Creator.Wallet, t.ticket.PaymentHash)
if err != nil || payment.Paid {
// paid, or unknown: never ban someone who may have paid
log.Infof("[restartPersistedTickets] not enforcing %s (paid: %t, err: %v)", t.key, payment.Paid, err)
bot.dropTicket(t.key)
continue
}
bot.expireTicket(t.ticket)
}
}
}
// dropTicket removes a persisted ticket without banning its member.
func (bot *TipBot) dropTicket(key string) {
err := bot.Bunt.Update(func(tx *buntdb.Tx) error {
_, err := tx.Delete(key)
if err == buntdb.ErrNotFound {
return nil
}
return err
})
if err != nil {
log.Errorf("[dropTicket] %s: %v", key, err)
}
}
func getTicketCommission(ticket *Ticket) int64 {
if ticket.Price < 20 {
+88
View File
@@ -0,0 +1,88 @@
package telegram
import (
"testing"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func testJoinTicket(created time.Time, paymentHash string) JoinTicket {
return JoinTicket{
Sender: &tb.User{ID: 7},
Message: &tb.Message{ID: 1, Chat: &tb.Chat{ID: -100}},
CreatedTimestamp: created,
Ticket: &Ticket{Price: 10, Creator: &lnbits.User{Wallet: &lnbits.Wallet{ID: "w"}}},
PaymentHash: paymentHash,
}
}
func TestTicketActionOnRestart(t *testing.T) {
now := time.Now()
hash := "ab"
cases := []struct {
name string
ticket JoinTicket
want ticketRestartAction
}{
{"running", testJoinTicket(now.Add(-time.Minute), hash), ticketRestartTimer},
{"running legacy", testJoinTicket(now.Add(-time.Minute), ""), ticketRestartTimer},
{"ran out while down", testJoinTicket(now.Add(-time.Hour), hash), ticketRestartCheckPayment},
{"ran out, stored by an older version", testJoinTicket(now.Add(-time.Hour), ""), ticketRestartDrop},
{"ran out long ago", testJoinTicket(now.Add(-defaultTicketDuration-maxTicketEnforceDelay-time.Minute), hash), ticketRestartDrop},
{"no message", JoinTicket{Sender: &tb.User{ID: 7}, CreatedTimestamp: now}, ticketRestartDrop},
}
noCreator := testJoinTicket(now.Add(-time.Hour), hash)
noCreator.Ticket.Creator = nil
cases = append(cases, struct {
name string
ticket JoinTicket
want ticketRestartAction
}{"no creator wallet", noCreator, ticketRestartDrop})
for _, c := range cases {
if got := ticketActionOnRestart(c.ticket, now); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// Restarting must not write to bunt inside its read transaction: that
// deadlocks every bunt user of the bot.
func TestRestartPersistedTicketsDropsLegacyTickets(t *testing.T) {
db := storage.NewBunt(":memory:")
if err := db.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString); err != nil {
t.Fatal(err)
}
stale := []JoinTicket{
testJoinTicket(time.Now().Add(-time.Hour), ""),
testJoinTicket(time.Now().Add(-30*24*time.Hour), "ab"),
}
stale[1].Sender = &tb.User{ID: 8}
for i := range stale {
if err := db.Set(&stale[i]); err != nil {
t.Fatal(err)
}
}
bot := &TipBot{Bunt: db}
done := make(chan struct{})
go func() {
bot.restartPersistedTickets()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("restartPersistedTickets deadlocked")
}
for i := range stale {
if ok, _ := db.Exists(&stale[i]); ok {
t.Errorf("ticket %s was not removed", stale[i].Key())
}
}
}
+3 -2
View File
@@ -300,7 +300,7 @@ inlineFaucetEndedMessage = """🚰 Faucet je prázdný 🍺\n\n
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Komunikuj s %s 👈 pro správu své peněženky."""
inlineFaucetCancelledMessage = """🚫 Faucet zrušen."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Částka na uživatele musí dělit kapacitu faucetu beze zbytku nebo je příliš malá (min 5 sats)."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Částka na uživatele musí dělit kapacitu faucetu beze zbytku nebo je příliš malá (min 1 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Neplatná částka."""
inlineFaucetSentMessage = """🚰 %d sats posláno %s."""
inlineFaucetReceivedMessage = """🚰 %s ti poslal %d sats."""
@@ -432,6 +432,7 @@ noteStatusOtherMessage = """ℹ️ Stav noty: %s"""
noteInFlightMessage = """⏳ Stále probíhá: Lightning platba mintu ještě nebyla dokončena. Dokončím to na pozadí a dám ti vědět."""
noteReclaimRequestedMessage = """↩️ Požádáno o vrácení %s sat. Dám ti vědět, až dorazí."""
noteReclaimedMessage = """↩️ %s sat z noty `%s` je zpět na tvém zůstatku."""
noteChangeReturnedMessage = """↩️ %s sat drobných z dávky not `%s` je zpět na tvém zůstatku."""
noteClaimedNotifyMessage = """✅ Tvá nota `%[2]s` v hodnotě %[1]s sat byla vyzvednuta. %[3]s"""
noteBatchDigestMessage = """✅ Vyzvednuto %d not(a/y) z balíčku `%s` (zatím %d z %d)."""
noteNothingToReclaimMessage = """ℹ️ Z této noty není co vracet."""
@@ -476,7 +477,7 @@ redeemDoneMessage = """✅ %s sat z noty bylo připsáno na tvů
redeemPendingMessage = """⏳ Mint ještě zpracovává operaci s touto notou. Zkus to za chvíli znovu."""
redeemNotANoteMessage = """🚫 To není LNURLcash nota."""
redeemFractionalMessage = """🚫 Hodnota této noty není celý počet satů a nepodařilo se ji rozdělit."""
redeemOwnNoteMessage = """ℹ️ To je jedna z tvých vlastních not. Použij místo toho její tlačítko Vzít zpět."""
redeemOwnNoteMessage = """ℹ️ To je jedna z tvých vlastních not, nelze ji uplatnit. Zde můžeš zkontrolovat její stav nebo ji vzít zpět:"""
redeemCancelledMessage = """🚫 Proplacení zrušeno."""
lnurlmintsHeader = """🏭 *LNURLcash minty*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · poplatek: %s"""
+3 -2
View File
@@ -273,7 +273,7 @@ linkHiddenMessage = """🔍 Link versteckt. Gebe /link ein um ihn
# API
walletConnectMessage = """🔗 *Deine API Keys*
apiConnectMessage = """🔗 *Deine API Keys*
⚠️ Teile diese Key mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /link um dein Wallet zu verbinden.
@@ -389,6 +389,7 @@ noteStatusOtherMessage = """ℹ️ Status der Note: %s"""
noteInFlightMessage = """⏳ Läuft noch: Die Lightning-Zahlung an den Mint ist noch nicht abgeschlossen. Ich erledige es im Hintergrund und sage dir Bescheid."""
noteReclaimRequestedMessage = """↩️ Zurückholen von %s Sat angefragt. Du wirst benachrichtigt, sobald es angekommen ist."""
noteReclaimedMessage = """↩️ %s Sat aus Note `%s` sind wieder auf deinem Guthaben."""
noteChangeReturnedMessage = """↩️ %s Sat Wechselgeld aus dem Notenstapel `%s` sind wieder auf deinem Guthaben."""
noteClaimedNotifyMessage = """✅ Deine Note `%[2]s` über %[1]s Sat wurde eingelöst. %[3]s"""
noteBatchDigestMessage = """✅ %d Note(s) aus Stapel `%s` wurden eingelöst (bisher %d von %d)."""
noteNothingToReclaimMessage = """ℹ️ Bei dieser Note gibt es nichts zurückzuholen."""
@@ -433,7 +434,7 @@ redeemDoneMessage = """✅ %s Sat aus der Note wurden deinem Gut
redeemPendingMessage = """⏳ Der Mint verarbeitet noch einen Vorgang zu dieser Note. Versuche es gleich noch einmal."""
redeemNotANoteMessage = """🚫 Das ist keine LNURLcash-Note."""
redeemFractionalMessage = """🚫 Der Wert dieser Note ist keine ganze Zahl von Sats und konnte nicht aufgeteilt werden."""
redeemOwnNoteMessage = """ℹ️ Das ist eine deiner eigenen Notes. Nutze stattdessen ihren Zurückholen-Button."""
redeemOwnNoteMessage = """ℹ️ Das ist eine deiner eigenen Notes, sie kann nicht eingelöst werden. Hier kannst du ihren Status prüfen oder sie zurückholen:"""
redeemCancelledMessage = """🚫 Einlösen abgebrochen."""
lnurlmintsHeader = """🏭 *LNURLcash-Mints*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · Gebühr: %s"""
+3 -2
View File
@@ -301,7 +301,7 @@ inlineFaucetEndedMessage = """🚰 Faucet empty 🍺\n\n🏅 %d s
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chat with %s 👈 to manage your wallet."""
inlineFaucetCancelledMessage = """🚫 Faucet cancelled."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity or too low (min 5 sat)."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity or too low (min 1 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Invalid amount."""
inlineFaucetSentMessage = """🚰 %d sat sent to %s."""
inlineFaucetReceivedMessage = """🚰 %s sent you %d sat."""
@@ -439,6 +439,7 @@ noteStatusOtherMessage = """ℹ️ Note status: %s"""
noteInFlightMessage = """⏳ Still in progress: the Lightning payment to the mint has not settled yet. I will finish it in the background and let you know."""
noteReclaimRequestedMessage = """↩️ Reclaim requested for %s sat. You will be notified when it arrives."""
noteReclaimedMessage = """↩️ %s sat from note `%s` are back in your balance."""
noteChangeReturnedMessage = """↩️ %s sat of change from note batch `%s` are back in your balance."""
noteClaimedNotifyMessage = """✅ Your %s sat note `%s` has been claimed. %s"""
noteBatchDigestMessage = """✅ %d note(s) of batch `%s` were claimed (%d of %d so far)."""
noteNothingToReclaimMessage = """ℹ️ There is nothing to reclaim on this note."""
@@ -483,7 +484,7 @@ redeemDoneMessage = """✅ %s sat from the note were added to yo
redeemPendingMessage = """⏳ The mint is still settling an operation on this note. Try again in a moment."""
redeemNotANoteMessage = """🚫 That is not an LNURLcash note."""
redeemFractionalMessage = """🚫 This note's value is not a whole number of sats and could not be split."""
redeemOwnNoteMessage = """ℹ️ That is one of your own notes. Use its Reclaim button instead."""
redeemOwnNoteMessage = """ℹ️ That is one of your own notes, so it cannot be redeemed. You can check its status or reclaim it here:"""
redeemCancelledMessage = """🚫 Redeem cancelled."""
lnurlmintsHeader = """🏭 *LNURLcash mints*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · fee: %s"""
+2 -1
View File
@@ -376,6 +376,7 @@ noteStatusOtherMessage = """ℹ️ Estado de la nota: %s"""
noteInFlightMessage = """⏳ Sigue en curso: el pago Lightning al mint aún no se ha completado. Lo terminaré en segundo plano y te avisaré."""
noteReclaimRequestedMessage = """↩️ Recuperación de %s sat solicitada. Te avisaré cuando lleguen."""
noteReclaimedMessage = """↩️ %s sat de la nota `%s` han vuelto a tu saldo."""
noteChangeReturnedMessage = """↩️ %s sat de cambio del lote de notas `%s` han vuelto a tu saldo."""
noteClaimedNotifyMessage = """✅ Tu nota `%[2]s` de %[1]s sat ha sido reclamada. %[3]s"""
noteBatchDigestMessage = """✅ %d nota(s) del lote `%s` han sido reclamadas (%d de %d hasta ahora)."""
noteNothingToReclaimMessage = """ℹ️ No hay nada que recuperar en esta nota."""
@@ -420,7 +421,7 @@ redeemDoneMessage = """✅ %s sat de la nota se han añadido a t
redeemPendingMessage = """⏳ El mint aún está procesando una operación sobre esta nota. Inténtalo de nuevo en un momento."""
redeemNotANoteMessage = """🚫 Eso no es una nota LNURLcash."""
redeemFractionalMessage = """🚫 El valor de esta nota no es un número entero de sats y no se pudo dividir."""
redeemOwnNoteMessage = """ℹ️ Esa es una de tus propias notas. Usa su botón Recuperar."""
redeemOwnNoteMessage = """ℹ️ Esa es una de tus propias notas, así que no se puede canjear. Puedes comprobar su estado o recuperarla aquí:"""
redeemCancelledMessage = """🚫 Canje cancelado."""
lnurlmintsHeader = """🏭 *Mints LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · comisión: %s"""
+3 -2
View File
@@ -300,7 +300,7 @@ inlineFaucetEndedMessage = """🚰 Hana on tyhjä 🍺\n\n🏅 %d
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Hallinnoi lompakkoasti viestillä %s:lle 👈 ."""
inlineFaucetCancelledMessage = """🚫 Hana suljettu."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Hanan käyttäjäkohtainen kapasiteetti ei jakaudu tasan tai se on liian pieni (min 5 sat)."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Hanan käyttäjäkohtainen kapasiteetti ei jakaudu tasan tai se on liian pieni (min 1 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Virheellinen määrä."""
inlineFaucetSentMessage = """🚰 %d sat lähetetty %s."""
inlineFaucetReceivedMessage = """🚰 %s lähetti sinulle %d sat."""
@@ -439,6 +439,7 @@ noteStatusOtherMessage = """ℹ️ Setelin tila: %s"""
noteInFlightMessage = """⏳ Vielä kesken: Lightning-maksu mintille ei ole vielä valmistunut. Hoidan sen loppuun taustalla ja ilmoitan sinulle."""
noteReclaimRequestedMessage = """↩️ %s sat palautus pyydetty. Ilmoitan, kun se on perillä."""
noteReclaimedMessage = """↩️ %s sat setelistä `%s` on taas saldossasi."""
noteChangeReturnedMessage = """↩️ %s sat vaihtorahaa setelierästä `%s` on taas saldossasi."""
noteClaimedNotifyMessage = """✅ Setelisi `%[2]s` (%[1]s sat) on lunastettu. %[3]s"""
noteBatchDigestMessage = """✅ %d seteli(ä) erästä `%s` on lunastettu (tähän mennessä %d/%d)."""
noteNothingToReclaimMessage = """ℹ️ Tästä setelistä ei ole mitään palautettavaa."""
@@ -483,7 +484,7 @@ redeemDoneMessage = """✅ %s sat setelistä lisättiin saldoosi
redeemPendingMessage = """⏳ Mintti käsittelee vielä tämän setelin toimintoa. Yritä hetken päästä uudelleen."""
redeemNotANoteMessage = """🚫 Tuo ei ole LNURLcash-seteli."""
redeemFractionalMessage = """🚫 Setelin arvo ei ole kokonaisluku sateja, eikä sitä voitu jakaa."""
redeemOwnNoteMessage = """ℹ️ Tuo on yksi omista seteleistäsi. Käytä sen Palauta-painiketta."""
redeemOwnNoteMessage = """ℹ️ Tuo on yksi omista seteleistäsi, joten sitä ei voi lunastaa. Voit tarkistaa sen tilan tai palauttaa sen tästä:"""
redeemCancelledMessage = """🚫 Lunastus peruutettu."""
lnurlmintsHeader = """🏭 *LNURLcash-mintit*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · maksu: %s"""
+2 -1
View File
@@ -337,6 +337,7 @@ noteStatusOtherMessage = """ℹ️ État de la note : %s"""
noteInFlightMessage = """⏳ Toujours en cours : le paiement Lightning vers le mint n'est pas encore finalisé. Je termine en arrière-plan et je te préviens."""
noteReclaimRequestedMessage = """↩️ Récupération de %s sat demandée. Tu seras prévenu à l'arrivée."""
noteReclaimedMessage = """↩️ %s sat de la note `%s` sont de retour sur ton solde."""
noteChangeReturnedMessage = """↩️ %s sat de monnaie du lot de notes `%s` sont de retour sur ton solde."""
noteClaimedNotifyMessage = """✅ Ta note `%[2]s` de %[1]s sat a été réclamée. %[3]s"""
noteBatchDigestMessage = """✅ %d note(s) du lot `%s` ont été réclamées (%d sur %d jusqu'ici)."""
noteNothingToReclaimMessage = """ℹ️ Il n'y a rien à récupérer sur cette note."""
@@ -381,7 +382,7 @@ redeemDoneMessage = """✅ %s sat de la note ont été ajoutés
redeemPendingMessage = """⏳ Le mint traite encore une opération sur cette note. Réessaie dans un instant."""
redeemNotANoteMessage = """🚫 Ce n'est pas une note LNURLcash."""
redeemFractionalMessage = """🚫 La valeur de cette note n'est pas un nombre entier de sats et n'a pas pu être divisée."""
redeemOwnNoteMessage = """ℹ️ C'est une de tes propres notes. Utilise plutôt son bouton Récupérer."""
redeemOwnNoteMessage = """ℹ️ C'est une de tes propres notes, elle ne peut pas être encaissée. Tu peux vérifier son statut ou la récupérer ici :"""
redeemCancelledMessage = """🚫 Encaissement annulé."""
lnurlmintsHeader = """🏭 *Mints LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · frais : %s"""
+2 -1
View File
@@ -345,6 +345,7 @@ noteStatusOtherMessage = """ℹ️ Status note: %s"""
noteInFlightMessage = """⏳ Masih berjalan: pembayaran Lightning ke mint belum selesai. Saya akan menyelesaikannya di latar belakang dan memberi tahu Anda."""
noteReclaimRequestedMessage = """↩️ Penarikan kembali %s sat diminta. Anda akan diberi tahu saat sudah masuk."""
noteReclaimedMessage = """↩️ %s sat dari note `%s` kembali ke saldo Anda."""
noteChangeReturnedMessage = """↩️ %s sat kembalian dari batch note `%s` kembali ke saldo Anda."""
noteClaimedNotifyMessage = """✅ Note Anda `%[2]s` senilai %[1]s sat sudah diklaim. %[3]s"""
noteBatchDigestMessage = """✅ %d note dari batch `%s` sudah diklaim (sejauh ini %d dari %d)."""
noteNothingToReclaimMessage = """ℹ️ Tidak ada yang bisa ditarik kembali dari note ini."""
@@ -389,7 +390,7 @@ redeemDoneMessage = """✅ %s sat dari note ditambahkan ke saldo
redeemPendingMessage = """⏳ Mint masih memproses operasi pada note ini. Coba lagi sebentar lagi."""
redeemNotANoteMessage = """🚫 Itu bukan note LNURLcash."""
redeemFractionalMessage = """🚫 Nilai note ini bukan bilangan bulat sat dan tidak bisa dibagi."""
redeemOwnNoteMessage = """ℹ️ Itu salah satu note Anda sendiri. Gunakan tombol Tarik kembali miliknya."""
redeemOwnNoteMessage = """ℹ️ Itu salah satu note Anda sendiri, jadi tidak bisa ditukarkan. Anda bisa memeriksa statusnya atau menariknya kembali di sini:"""
redeemCancelledMessage = """🚫 Penukaran dibatalkan."""
lnurlmintsHeader = """🏭 *Mint LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · biaya: %s"""
+2 -1
View File
@@ -337,6 +337,7 @@ noteStatusOtherMessage = """ℹ️ Stato della nota: %s"""
noteInFlightMessage = """⏳ Ancora in corso: il pagamento Lightning al mint non è ancora stato completato. La completo in background e ti avviso."""
noteReclaimRequestedMessage = """↩️ Recupero di %s sat richiesto. Ti avviserò all'arrivo."""
noteReclaimedMessage = """↩️ %s sat della nota `%s` sono tornati nel tuo saldo."""
noteChangeReturnedMessage = """↩️ %s sat di resto del lotto di note `%s` sono tornati nel tuo saldo."""
noteClaimedNotifyMessage = """✅ La tua nota `%[2]s` da %[1]s sat è stata riscattata. %[3]s"""
noteBatchDigestMessage = """✅ %d nota/e del lotto `%s` sono state riscattate (%d su %d finora)."""
noteNothingToReclaimMessage = """ℹ️ Non c'è nulla da recuperare su questa nota."""
@@ -381,7 +382,7 @@ redeemDoneMessage = """✅ %s sat della nota sono stati aggiunti
redeemPendingMessage = """⏳ Il mint sta ancora elaborando un'operazione su questa nota. Riprova tra un momento."""
redeemNotANoteMessage = """🚫 Questa non è una nota LNURLcash."""
redeemFractionalMessage = """🚫 Il valore di questa nota non è un numero intero di sat e non è stato possibile dividerla."""
redeemOwnNoteMessage = """ℹ️ Questa è una delle tue note. Usa invece il suo pulsante Recupera."""
redeemOwnNoteMessage = """ℹ️ Questa è una delle tue note, quindi non può essere riscattata. Qui puoi verificarne lo stato o recuperarla:"""
redeemCancelledMessage = """🚫 Riscatto annullato."""
lnurlmintsHeader = """🏭 *Mint LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · commissione: %s"""
+3 -2
View File
@@ -246,7 +246,7 @@ lnurlHelpText = """📖 Oeps, dat werkte niet. %s
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?💸 Bedrag: %d sat"""
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?\n\n💸 Bedrag: %d sat"""
lnurlPreparingWithdraw = """🧮 Opname aan het voorbereiden..."""
lnurlWithdrawFailed = """🚫 Opname mislukt."""
lnurlWithdrawCancelled = """🚫 Opname geannuleerd."""
@@ -346,6 +346,7 @@ noteStatusOtherMessage = """ℹ️ Status van de note: %s"""
noteInFlightMessage = """⏳ Nog bezig: de Lightning-betaling aan de mint is nog niet afgerond. Ik maak het op de achtergrond af en laat het je weten."""
noteReclaimRequestedMessage = """↩️ Terughalen van %s sat aangevraagd. Je krijgt bericht zodra het binnen is."""
noteReclaimedMessage = """↩️ %s sat van note `%s` staan weer op je saldo."""
noteChangeReturnedMessage = """↩️ %s sat wisselgeld van notebatch `%s` staan weer op je saldo."""
noteClaimedNotifyMessage = """✅ Je note `%[2]s` van %[1]s sat is opgeëist. %[3]s"""
noteBatchDigestMessage = """✅ %d note(s) van batch `%s` zijn opgeëist (%d van %d tot nu toe)."""
noteNothingToReclaimMessage = """ℹ️ Er valt op deze note niets terug te halen."""
@@ -390,7 +391,7 @@ redeemDoneMessage = """✅ %s sat van de note zijn aan je saldo
redeemPendingMessage = """⏳ De mint is nog bezig met deze note. Probeer het zo opnieuw."""
redeemNotANoteMessage = """🚫 Dat is geen LNURLcash-note."""
redeemFractionalMessage = """🚫 De waarde van deze note is geen heel aantal sats en kon niet worden gesplitst."""
redeemOwnNoteMessage = """ℹ️ Dat is een van je eigen notes. Gebruik de knop Terughalen."""
redeemOwnNoteMessage = """ℹ️ Dat is een van je eigen notes, die kun je niet inwisselen. Hier kun je de status bekijken of hem terughalen:"""
redeemCancelledMessage = """🚫 Inwisselen geannuleerd."""
lnurlmintsHeader = """🏭 *LNURLcash-mints*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · kosten: %s"""
+4 -3
View File
@@ -15,7 +15,7 @@ listCommandStr = """list"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """faucet"""
faucetCommandStr = """kran"""
tipjarCommandStr = """tipjar"""
receiveCommandStr = """receive"""
@@ -301,7 +301,7 @@ inlineFaucetEndedMessage = """🚰 Kranik pusty 🍺\n\n🏅 %d s
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
inlineFaucetCancelledMessage = """🚫 Kranik anulowany."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Wartość na_użytkownika nie jest dzielnikiem pojemności lub jest za mała (min 5 sat)."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Wartość na_użytkownika nie jest dzielnikiem pojemności lub jest za mała (min 1 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
inlineFaucetSentMessage = """🚰 %d sat wysłano do %s."""
inlineFaucetReceivedMessage = """🚰 %s wysyła Ci %d sat."""
@@ -433,6 +433,7 @@ noteStatusOtherMessage = """ℹ️ Status noty: %s"""
noteInFlightMessage = """⏳ Wciąż w toku: płatność Lightning do mintu nie została jeszcze zakończona. Dokończę w tle i dam ci znać."""
noteReclaimRequestedMessage = """↩️ Zlecono odzyskanie %s sat. Powiadomię cię, gdy dotrą."""
noteReclaimedMessage = """↩️ %s sat z noty `%s` wróciło na twoje saldo."""
noteChangeReturnedMessage = """↩️ %s sat reszty z partii not `%s` wróciło na twoje saldo."""
noteClaimedNotifyMessage = """✅ Twoja nota `%[2]s` o wartości %[1]s sat została odebrana. %[3]s"""
noteBatchDigestMessage = """✅ Odebrano %d not(ę/y) z paczki `%s` (dotąd %d z %d)."""
noteNothingToReclaimMessage = """ℹ️ Na tej nocie nie ma nic do odzyskania."""
@@ -477,7 +478,7 @@ redeemDoneMessage = """✅ %s sat z noty dodano do twojego salda
redeemPendingMessage = """⏳ Mint wciąż przetwarza operację na tej nocie. Spróbuj ponownie za chwilę."""
redeemNotANoteMessage = """🚫 To nie jest nota LNURLcash."""
redeemFractionalMessage = """🚫 Wartość tej noty nie jest całkowitą liczbą satów i nie udało się jej podzielić."""
redeemOwnNoteMessage = """ℹ️ To jedna z twoich własnych not. Użyj jej przycisku Odzyskaj."""
redeemOwnNoteMessage = """ℹ️ To jedna z twoich własnych not, nie można jej zrealizować. Tutaj możesz sprawdzić jej status lub ją odzyskać:"""
redeemCancelledMessage = """🚫 Wymianę anulowano."""
lnurlmintsHeader = """🏭 *Minty LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · opłata: %s"""
+3 -2
View File
@@ -252,7 +252,7 @@ loginCancelledMessage = """🚫 Login cancelado."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n\n💸 Quantia: %d sat"""
lnurlPreparingWithdraw = """🧮 Preparando o saque..."""
lnurlWithdrawFailed = """🚫 Saque falhou."""
lnurlWithdrawCancelled = """🚫 Saque cancelado."""
@@ -376,6 +376,7 @@ noteStatusOtherMessage = """ℹ️ Status da nota: %s"""
noteInFlightMessage = """⏳ Ainda em andamento: o pagamento Lightning ao mint ainda não foi concluído. Vou concluir em segundo plano e te avisar."""
noteReclaimRequestedMessage = """↩️ Recuperação de %s sat solicitada. Você será avisado quando chegar."""
noteReclaimedMessage = """↩️ %s sat da nota `%s` voltaram para o seu saldo."""
noteChangeReturnedMessage = """↩️ %s sat de troco do lote de notas `%s` voltaram para o seu saldo."""
noteClaimedNotifyMessage = """✅ Sua nota `%[2]s` de %[1]s sat foi resgatada. %[3]s"""
noteBatchDigestMessage = """✅ %d nota(s) do lote `%s` foram resgatadas (%d de %d até agora)."""
noteNothingToReclaimMessage = """ℹ️ Não há nada para recuperar nesta nota."""
@@ -420,7 +421,7 @@ redeemDoneMessage = """✅ %s sat da nota foram adicionados ao s
redeemPendingMessage = """⏳ O mint ainda está processando uma operação nesta nota. Tente de novo em instantes."""
redeemNotANoteMessage = """🚫 Isso não é uma nota LNURLcash."""
redeemFractionalMessage = """🚫 O valor desta nota não é um número inteiro de sats e não pôde ser dividido."""
redeemOwnNoteMessage = """ℹ️ Essa é uma das suas próprias notas. Use o botão Recuperar dela."""
redeemOwnNoteMessage = """ℹ️ Essa é uma das suas próprias notas, então não pode ser resgatada. Você pode verificar o status ou recuperá-la aqui:"""
redeemCancelledMessage = """🚫 Resgate cancelado."""
lnurlmintsHeader = """🏭 *Mints LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · taxa: %s"""
+2 -1
View File
@@ -372,6 +372,7 @@ noteStatusOtherMessage = """ℹ️ Статус ноты: %s"""
noteInFlightMessage = """⏳ Ещё выполняется: Lightning-платёж минту ещё не завершён. Я завершу в фоне и сообщу вам."""
noteReclaimRequestedMessage = """↩️ Запрошен возврат %s сат. Я сообщу, когда они поступят."""
noteReclaimedMessage = """↩️ %s сат из ноты `%s` снова на вашем балансе."""
noteChangeReturnedMessage = """↩️ %s сат сдачи из пачки нот `%s` снова на вашем балансе."""
noteClaimedNotifyMessage = """✅ Ваша нота `%[2]s` на %[1]s сат получена. %[3]s"""
noteBatchDigestMessage = """✅ Получено нот из пакета `%[2]s`: %[1]d (пока %[3]d из %[4]d)."""
noteNothingToReclaimMessage = """ℹ️ По этой ноте нечего возвращать."""
@@ -416,7 +417,7 @@ redeemDoneMessage = """✅ %s сат из ноты зачисл
redeemPendingMessage = """⏳ Минт ещё обрабатывает операцию с этой нотой. Попробуйте чуть позже."""
redeemNotANoteMessage = """🚫 Это не нота LNURLcash."""
redeemFractionalMessage = """🚫 Номинал этой ноты — не целое число сатоши, и разделить её не удалось."""
redeemOwnNoteMessage = """ℹ️ Это одна из ваших собственных нот. Используйте её кнопку «Вернуть»."""
redeemOwnNoteMessage = """ℹ️ Это одна из ваших собственных нот, её нельзя погасить. Здесь можно проверить её статус или вернуть её:"""
redeemCancelledMessage = """🚫 Обналичивание отменено."""
lnurlmintsHeader = """🏭 *Минты LNURLcash*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · комиссия: %s"""
+2 -1
View File
@@ -336,6 +336,7 @@ noteStatusOtherMessage = """ℹ️ Not durumu: %s"""
noteInFlightMessage = """⏳ Hâlâ sürüyor: mint'e yapılan Lightning ödemesi henüz tamamlanmadı. Arka planda bitirip sana haber vereceğim."""
noteReclaimRequestedMessage = """↩️ %s sat için geri alma istendi. Ulaştığında haber verilecek."""
noteReclaimedMessage = """↩️ `%[2]s` notundaki %[1]s sat bakiyene geri döndü."""
noteChangeReturnedMessage = """↩️ `%[2]s` not grubundan %[1]s sat para üstü bakiyene geri döndü."""
noteClaimedNotifyMessage = """✅ %s sat değerindeki `%s` notun alındı. %s"""
noteBatchDigestMessage = """✅ `%[2]s` paketinden %[1]d not alındı (şimdiye kadar %[3]d / %[4]d)."""
noteNothingToReclaimMessage = """ℹ️ Bu notta geri alınacak bir şey yok."""
@@ -380,7 +381,7 @@ redeemDoneMessage = """✅ Nottaki %s sat bakiyene eklendi."""
redeemPendingMessage = """⏳ Mint bu notla ilgili bir işlemi hâlâ sürdürüyor. Birazdan tekrar dene."""
redeemNotANoteMessage = """🚫 Bu bir LNURLcash notu değil."""
redeemFractionalMessage = """🚫 Bu notun değeri tam sayı sat değil ve bölünemedi."""
redeemOwnNoteMessage = """ℹ️ Bu senin kendi notlarından biri. Onun yerine Geri al düğmesini kullan."""
redeemOwnNoteMessage = """ℹ️ Bu senin kendi notlarından biri, bu yüzden bozdurulamaz. Durumunu buradan kontrol edebilir veya geri alabilirsin:"""
redeemCancelledMessage = """🚫 Bozdurma iptal edildi."""
lnurlmintsHeader = """🏭 *LNURLcash mintleri*\n"""
lnurlmintsItem = """\n%s *%s*%s\n `%s` · ücret: %s"""