Add the LNURLcash note service: create, status, reclaim, redeem

Every secret is written encrypted before the first request leaves. Notes
are carved out of one funding note by split so each is a whole number of
sats, which LUD-25's exact-amount melt needs against LNbits' whole-sat
invoices. Tested against an in-memory LUD-25 mint and ledger, including
a dropped connection after an applied split and fractional external notes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-13 21:52:37 +00:00
co-authored by Claude Fable 5.1
parent 1fc9a81cd2
commit e695443f7f
4 changed files with 1412 additions and 5 deletions
+5 -5
View File
@@ -165,9 +165,6 @@ func (m *fakeMint) withdraw(w http.ResponseWriter, q map[string][]string, pub st
}
pr, amount, p1, p2 := get("pr"), get("amount"), get("p1"), get("p2")
switch {
case pr == "" && amount == "" && p1 == "" && len(k1s) == 1:
// informational GET by k1
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w", "k1": k1s[0], "minWithdrawable": total, "maxWithdrawable": total, "defaultDescription": "fake", "mintPubkey": pub})
case pr != "":
if m.meltReason != "" {
errJSON(w, m.meltReason)
@@ -181,13 +178,13 @@ func (m *fakeMint) withdraw(w http.ResponseWriter, q map[string][]string, pub st
m.pending[hs[0]] = true
m.melts = append(m.melts, fakeMelt{h: hs[0], pr: pr})
writeJSON(w, map[string]string{"status": "OK"})
case amount != "":
case p1 != "" && amount != "":
if m.refuseSplit != "" {
errJSON(w, m.refuseSplit)
return
}
a, _ := strconv.ParseInt(amount, 10, 64)
if p1 == "" || p2 == "" {
if p2 == "" {
errJSON(w, "p1 and p2 required")
return
}
@@ -218,6 +215,9 @@ func (m *fakeMint) withdraw(w http.ResponseWriter, q map[string][]string, pub st
}
m.notes[p1] = total
writeJSON(w, map[string]string{"status": "OK"})
case len(k1s) == 1:
// informational GET by k1; amount is display-only and ignored (LUD-25)
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w", "k1": k1s[0], "minWithdrawable": total, "maxWithdrawable": total, "defaultDescription": "fake", "mintPubkey": pub})
default:
errJSON(w, "bad request")
}
+376
View File
@@ -0,0 +1,376 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// Reference prefixes carried on LNbits invoice events so a settlement can be
// matched back to its row.
const (
RefNote = "lnurlcash-note:"
RefRedeem = "lnurlcash-redeem:"
)
// ErrOwnNote is returned by RedeemInfo when the pasted note is one this user
// created; it should be reclaimed through its own buttons instead.
type ErrOwnNote struct{ NoteID string }
func (e *ErrOwnNote) Error() string { return "lnurlcash: this is your own note " + e.NoteID }
// Reclaim melts one of the user's own notes back into their balance. A nil
// error means the melt is in flight; the invoice settlement finishes it.
func (s *Service) Reclaim(ctx context.Context, noteID string) (*Note, error) {
unlock := lockNote(noteID)
defer unlock()
n, err := s.store.Note(noteID)
if err != nil {
return nil, err
}
switch n.State {
case NoteReclaiming:
return n, ErrInFlight
case NoteClaimed:
return n, ErrNoteClaimed
case NoteReclaimed, NoteFailed, NoteSpent:
return n, ErrNothingToReclaim
case NoteLive:
default:
return n, ErrNoteNotLive
}
state, value, err := s.Status(ctx, n)
if errors.Is(err, lnurlcash.ErrNotePending) {
return n, ErrNotePending
}
if err != nil {
return n, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
if state == NoteClaimed {
return n, ErrNoteClaimed
}
if value%1000 != 0 {
// a bot-minted note is whole-sat by construction; anything else cannot be
// melted exactly into an LNbits invoice (LUD-25 melt is exact-amount)
return n, ErrFractionalValue
}
k1, err := s.secret(n)
if err != nil {
return n, err
}
pr, hash, err := s.ledger.CreateInvoice(ctx, n.UserName, value/1000, "LNURLcash reclaim "+ShortID(n.ID), RefNote+n.ID)
if err != nil {
return n, err
}
if err := s.store.TransitionNote(n.ID, NoteLive, NoteReclaiming, map[string]interface{}{"invoice_pr": pr, "invoice_hash": hash, "last_error": ""}); err != nil {
return n, err
}
n.State, n.InvoicePR, n.InvoiceHash = NoteReclaiming, pr, hash
return n, s.melt(ctx, n, k1, pr)
}
// melt sends one melt and maps its outcome onto the note. Never retried.
func (s *Service) melt(ctx context.Context, n *Note, k1, pr string) error {
_, err := s.client.MeltNote(ctx, n.MintURLCallback(), k1, pr)
switch {
case err == nil:
log.Infof("[lnurlcash] note %s (%s): melt in flight", n.ID, n.Hash[:8])
return nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": "pending at the mint"})
n.State = NoteLive
return ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
t := s.now()
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_error": err.Error()})
n.State = NoteClaimed
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
return ErrNoteClaimed
case lnurlcash.IsAmbiguous(err):
if secrets := lnurlcash.NewSecrets(err); len(secrets) > 0 {
log.Errorf("[lnurlcash] note %s: a melt error carried %d new secrets, which a melt never mints", n.ID, len(secrets))
}
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteUnknown, map[string]interface{}{"last_error": err.Error()})
n.State = NoteUnknown
log.Warnf("[lnurlcash] note %s: melt outcome unknown, left for recovery", n.ID)
return ErrInFlight
default:
_ = s.store.TransitionNote(n.ID, NoteReclaiming, NoteLive, map[string]interface{}{"last_error": err.Error()})
n.State = NoteLive
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
// Settlement is what SettleInvoice resolved.
type Settlement struct {
Note *Note
Redeem *Redeem
}
// SettleInvoice records that an LNbits invoice with this payment hash was
// paid: a reclaim or a redeem is done. It returns nil, nil when the hash is
// not one of ours.
func (s *Service) SettleInvoice(ctx context.Context, hash string) (*Settlement, error) {
if n, err := s.store.NoteByInvoiceHash(hash); err == nil {
unlock := lockNote(n.ID)
defer unlock()
n, _ = s.store.Note(n.ID)
if n.State == NoteReclaimed {
return nil, nil
}
t := s.now()
if err := s.store.TransitionNote(n.ID, "", NoteReclaimed, map[string]interface{}{"reclaimed_at": t, "last_error": ""}); err != nil {
return nil, err
}
n.State, n.ReclaimedAt = NoteReclaimed, &t
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
log.Infof("[lnurlcash] note %s reclaimed (%d msat)", n.ID, n.ReportedMsat)
return &Settlement{Note: n}, nil
}
if r, err := s.store.RedeemByInvoiceHash(hash); err == nil {
unlock := lockNote(r.ID)
defer unlock()
r, _ = s.store.Redeem(r.ID)
if r.State == RedeemSettled {
return nil, nil
}
if err := s.store.TransitionRedeem(r.ID, "", RedeemSettled, map[string]interface{}{"last_error": ""}); err != nil {
return nil, err
}
r.State = RedeemSettled
if r.SplitNoteID != nil {
_ = s.store.TransitionNote(*r.SplitNoteID, "", NoteReclaimed, nil)
}
log.Infof("[lnurlcash] redeem %s settled (%d msat)", r.ID, r.ReportedMsat)
return &Settlement{Redeem: r}, nil
}
return nil, nil
}
// ---- redeem ----
// RedeemPreview is what the user sees before adding a note to their balance.
type RedeemPreview struct {
Redeem *Redeem
ValueMsat int64
MintHost string
KnownMint bool
}
// RedeemInfo resolves pasted input to a note, asks the mint what it is worth
// and records a redeem in state info. ErrNotANote means the input is not an
// LNURLcash note (no mintPubkey, or not a withdraw link at all).
func (s *Service) RedeemInfo(ctx context.Context, user, lang, input string) (*RedeemPreview, error) {
input = strings.TrimSpace(input)
if i := strings.Index(strings.ToLower(input), "lightning:"); i == 0 {
input = input[len("lightning:"):]
}
noteURL := lnurlcash.ResolveNoteInput(input)
if noteURL == "" {
return nil, ErrNotANote
}
k1 := lnurlcash.NoteK1(noteURL)
if lnurlcash.IsPreimage(k1) {
if h, err := lnurlcash.HashK1(k1); err == nil {
if own, err := s.store.NoteByHash(h); err == nil {
if own.UserName == user {
return nil, &ErrOwnNote{NoteID: own.ID}
}
}
}
}
info, err := s.client.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
return nil, ErrNotePending
case lnurlcash.IsSpent(err):
return nil, ErrNoteClaimed
case lnurlcash.IsUnknownNote(err):
return nil, ErrNoteClaimed
default:
var p *lnurlcash.ProtocolError
if errors.As(err, &p) {
return nil, fmt.Errorf("%w: %v", ErrNotANote, err)
}
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
enc, err := s.cipher.Seal(noteURL)
if err != nil {
return nil, err
}
noteID, _ := lnurlcash.NoteIDOf(k1)
host, _ := lnurlcash.SpendDomainOf(noteURL)
_, known := s.mints.ByHost(noteURL)
r := &Redeem{ID: newID("redeem"), UserName: user, MintHost: host, KnownMint: known, NoteID: noteID,
NoteURLEnc: enc, ReportedMsat: info.MaxWithdrawableMsat, State: RedeemInfo, LanguageCode: lang}
if err := s.store.CreateRedeem(r); err != nil {
return nil, err
}
return &RedeemPreview{Redeem: r, ValueMsat: info.MaxWithdrawableMsat, MintHost: host, KnownMint: known}, nil
}
// Redeem melts a previewed note into the user's balance. A nil error means
// the melt is in flight.
func (s *Service) Redeem(ctx context.Context, redeemID, user string) (*Redeem, error) {
unlock := lockNote(redeemID)
defer unlock()
r, err := s.store.Redeem(redeemID)
if err != nil {
return nil, err
}
if r.UserName != user {
return r, ErrNotOwner
}
if r.State != RedeemInfo {
return r, ErrInFlight
}
noteURL, err := s.cipher.Open(r.NoteURLEnc)
if err != nil {
return r, err
}
info, err := s.client.FetchNoteInfo(ctx, noteURL)
switch {
case err == nil:
case errors.Is(err, lnurlcash.ErrNotePending):
return r, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
_ = s.store.TransitionRedeem(r.ID, RedeemInfo, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
return r, ErrNoteClaimed
default:
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
if err := s.store.TransitionRedeem(r.ID, RedeemInfo, RedeemConfirmed, map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat}); err != nil {
return r, err
}
r.State, r.ReportedMsat = RedeemConfirmed, info.MaxWithdrawableMsat
meltK1, meltCallback, valueMsat := lnurlcash.NoteK1(noteURL), info.Callback, info.MaxWithdrawableMsat
if valueMsat%1000 != 0 {
split, err := s.splitWholeSat(ctx, r, noteURL, info)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
return r, err
}
meltK1, _ = s.secret(split)
meltCallback, valueMsat = split.MintURLCallback(), split.ReportedMsat
sid := split.ID
r.SplitNoteID = &sid
}
pr, hash, err := s.ledger.CreateInvoice(ctx, user, valueMsat/1000, "LNURLcash redeem "+ShortID(r.ID), RefRedeem+r.ID)
if err != nil {
_ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemInfo, map[string]interface{}{"last_error": err.Error()})
return r, err
}
if err := s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemMelting, map[string]interface{}{"invoice_pr": pr, "invoice_hash": hash}); err != nil {
return r, err
}
r.State, r.InvoicePR, r.InvoiceHash = RedeemMelting, pr, hash
_, err = s.client.MeltNote(ctx, meltCallback, meltK1, pr)
switch {
case err == nil:
log.Infof("[lnurlcash] redeem %s: melt in flight at %s (%d msat)", r.ID, r.MintHost, valueMsat)
return r, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemInfo, map[string]interface{}{"last_error": "pending"})
r.State = RedeemInfo
return r, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemFailed
return r, ErrNoteClaimed
case lnurlcash.IsAmbiguous(err):
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemUnknown, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemUnknown
return r, ErrInFlight
default:
_ = s.store.TransitionRedeem(r.ID, RedeemMelting, RedeemFailed, map[string]interface{}{"last_error": err.Error()})
r.State = RedeemFailed
return r, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
// splitWholeSat carves the largest whole-sat note off a fractional external
// note so it can be melted exactly. The remainder stays at the mint as dust
// owned by the bot. Both secrets are persisted before the split is sent.
func (s *Service) splitWholeSat(ctx context.Context, r *Redeem, noteURL string, info lnurlcash.WithdrawInfo) (*Note, error) {
k1 := lnurlcash.NoteK1(noteURL)
link := lnurlcash.FromLud17(strings.SplitN(noteURL, "?", 2)[0])
mk := func(kind string) (*Note, error) {
secret, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(secret)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(secret)
if err != nil {
return nil, err
}
owner := r.UserName
if kind == KindDust {
owner = "bot"
}
return &Note{ID: newID("note"), UserName: owner, MintID: "external:" + r.MintHost, MintURL: link,
MintPubkey: info.MintPubkey, Hash: h, SecretEnc: enc, Kind: kind, State: NotePendingCarve,
LanguageCode: r.LanguageCode, Memo: "redeem " + r.ID}, nil
}
target, err := mk(KindRedeemSplit)
if err != nil {
return nil, err
}
dust, err := mk(KindDust)
if err != nil {
return nil, err
}
if err := s.store.CreateNotes(nil, []*Note{target, dust}); err != nil {
return nil, err
}
sats := info.MaxWithdrawableMsat / 1000
for attempt := 0; attempt < 3 && sats > 0; attempt++ {
amount := sats * 1000
_, err := s.client.SplitNoteWithHash(ctx, info.Callback, []string{k1}, amount, target.Hash, dust.Hash)
if err == nil {
change := info.MaxWithdrawableMsat - amount
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
_ = s.store.TransitionNote(dust.ID, "", NoteLive, map[string]interface{}{"value_msat": change, "reported_msat": change})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
_ = s.store.TransitionRedeem(r.ID, "", RedeemConfirmed, map[string]interface{}{"split_note_id": target.ID})
return target, nil
}
if lnurlcash.IsAmbiguous(err) || lnurlcash.IsAlreadyInUse(err) || lnurlcash.IsSpent(err) || lnurlcash.IsUnknownNote(err) {
// the split may have landed: the output decides
if _, perr := s.client.FetchNoteInfoByHash(ctx, link, target.Hash); perr == nil {
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
return target, nil
}
if lnurlcash.IsAmbiguous(err) {
_ = s.store.TransitionNote(target.ID, "", NoteUnknown, map[string]interface{}{"last_error": err.Error()})
return nil, ErrInFlight
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, ErrNoteClaimed
}
if strings.Contains(strings.ToLower(err.Error()), "insufficient") {
sats--
continue
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
_ = s.store.TransitionNote(target.ID, "", NoteFailed, map[string]interface{}{"last_error": "could not split a whole-sat amount"})
_ = s.store.TransitionNote(dust.ID, "", NoteFailed, nil)
return nil, ErrFractionalValue
}
+655
View File
@@ -0,0 +1,655 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
// Ledger is what the service needs from LNbits. user is lnbits.User.Name.
type Ledger interface {
// CreateInvoice makes an incoming invoice on the user's wallet. ref is an
// opaque reference the implementation may attach to the invoice event so
// that a settlement webhook can find the note or redeem it belongs to.
CreateInvoice(ctx context.Context, user string, amountSat int64, memo, ref string) (pr, hash string, err error)
// PayInvoice pays a bolt11 from the user's wallet and returns its payment hash.
// A failure whose outcome is unknown must be returned as *AmbiguousLedgerError.
PayInvoice(ctx context.Context, user, pr string) (hash string, err error)
// InvoicePaid reports whether an invoice on the user's wallet settled.
InvoicePaid(ctx context.Context, user, hash string) (bool, error)
// PaymentSucceeded reports whether an outgoing payment settled: paid, failed
// (definitively), or still pending.
PaymentSucceeded(ctx context.Context, user, hash string) (paid, pending bool, err error)
BalanceMsat(ctx context.Context, user string) (int64, error)
}
// AmbiguousLedgerError wraps a ledger failure whose outcome is unknown (a
// timeout, a dropped connection): the payment may still have been made.
type AmbiguousLedgerError struct{ Err error }
func (e *AmbiguousLedgerError) Error() string { return "ledger outcome unknown: " + e.Err.Error() }
func (e *AmbiguousLedgerError) Unwrap() error { return e.Err }
// IsAmbiguousLedger reports whether a ledger error carries an unknown outcome.
func IsAmbiguousLedger(err error) bool {
var a *AmbiguousLedgerError
return errors.As(err, &a)
}
// Sentinel errors handlers turn into messages.
var (
ErrInFlight = errors.New("lnurlcash: the operation is still in flight; the recovery job will finish it")
ErrCapNoteValue = errors.New("lnurlcash: note value outside the allowed range")
ErrCapBatch = errors.New("lnurlcash: batch too large")
ErrCapOutstanding = errors.New("lnurlcash: outstanding notes cap reached")
ErrInsufficientFunds = errors.New("lnurlcash: insufficient balance")
ErrNoMint = errors.New("lnurlcash: no usable mint")
ErrMintRange = errors.New("lnurlcash: amount outside what the mint accepts")
ErrNoteNotLive = errors.New("lnurlcash: note is not live")
ErrNoteClaimed = errors.New("lnurlcash: note was already claimed")
ErrNotePending = errors.New("lnurlcash: the mint is still settling an operation on this note")
ErrNotANote = errors.New("lnurlcash: not an LNURLcash note")
ErrFractionalValue = errors.New("lnurlcash: note value is not a whole number of sats and cannot be split")
ErrNotOwner = errors.New("lnurlcash: not the owner")
ErrMintUnavailable = errors.New("lnurlcash: mint unavailable")
ErrNothingToReclaim = errors.New("lnurlcash: nothing to reclaim")
ErrDisabledPrecondition = errors.New("lnurlcash: feature not configured")
)
// Service creates, watches, reclaims and redeems notes.
type Service struct {
cfg *Config
store *Store
mints *Registry
ledger Ledger
cipher *Cipher
client *lnurlcash.Client
// now is replaceable in tests.
now func() time.Time
// sleep between settlement polls, replaceable in tests.
pollEvery time.Duration
}
// NewService wires the service. The registry supplies the LNURLcash client.
func NewService(cfg *Config, store *Store, mints *Registry, ledger Ledger, cipher *Cipher) *Service {
return &Service{cfg: cfg, store: store, mints: mints, ledger: ledger, cipher: cipher,
client: mints.Client(), now: time.Now, pollEvery: 2 * time.Second}
}
// Store exposes the store to the Telegram layer for read-only listing.
func (s *Service) Store() *Store { return s.store }
// Mints exposes the registry.
func (s *Service) Mints() *Registry { return s.mints }
// Config exposes the configuration.
func (s *Service) Config() *Config { return s.cfg }
const idRunes = "abcdefghijklmnopqrstuvwxyz0123456789"
func newID(prefix string) string {
b := make([]byte, 10)
for i := range b {
b[i] = idRunes[rand.Intn(len(idRunes))]
}
return prefix + "-" + string(b)
}
// ShortID is the part of a note id shown to people.
func ShortID(id string) string {
if i := strings.IndexByte(id, '-'); i >= 0 && len(id) > i+6 {
return id[i+1 : i+7]
}
return id
}
func (s *Service) secret(n *Note) (string, error) {
return s.cipher.Open(n.SecretEnc)
}
// ---- quoting ----
// Quote is what a creation will cost.
type Quote struct {
MintID string
MintName string
ValueMsat int64 // per note
Count int
GrossMsat int64 // the invoice the user pays
FeeMsat int64 // GrossMsat - Count*ValueMsat: mint fee plus carving margin
Fee lnurlcash.MintFee
Strategy string
}
// NetMsat is what the user's notes are worth together.
func (q Quote) NetMsat() int64 { return q.ValueMsat * int64(q.Count) }
// carveMargin keeps the last change above zero whatever the mint's rounding.
const carveMargin int64 = 1000
// grossFor returns the smallest whole-sat invoice whose net after the mint
// fee carves count notes of valueMsat, each split costing the base fee.
func grossFor(valueMsat int64, count int64, fee lnurlcash.MintFee) int64 {
needed := count*valueMsat + count*fee.BaseFeeMsat + carveMargin
gross := lnurlcash.GrossUpForMintFee(needed, fee)
if rem := gross % 1000; rem != 0 {
gross += 1000 - rem
}
return gross
}
// Quote prices count notes of valueMsat at a mint. With strategy "invoices"
// each note gets its own invoice, so the fee is paid count times.
func (s *Service) Quote(ctx context.Context, mint *Mint, valueMsat int64, count int) (Quote, error) {
if mint == nil || !mint.Usable() {
return Quote{}, ErrNoMint
}
if count < 1 {
count = 1
}
fee := mint.Fee()
q := Quote{MintID: mint.ID, MintName: mint.ID, ValueMsat: valueMsat, Count: count, Fee: fee, Strategy: s.cfg.BatchStrategy}
var gross int64
switch {
case count == 1 || s.cfg.BatchStrategy == StrategyInvoices:
per := grossFor(valueMsat, 1, fee)
if per < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && per > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
gross = per * int64(count)
q.Strategy = StrategyInvoices
if count == 1 {
q.Strategy = StrategySplit
}
default:
gross = grossFor(valueMsat, int64(count), fee)
if gross < mint.MinSendableMsat || (mint.MaxSendableMsat > 0 && gross > mint.MaxSendableMsat) {
return Quote{}, ErrMintRange
}
}
q.GrossMsat = gross
q.FeeMsat = gross - q.NetMsat()
return q, nil
}
// CheckCaps enforces the configured limits for a creation.
func (s *Service) CheckCaps(ctx context.Context, user string, q Quote, inGroup bool) error {
valueSat := q.ValueMsat / 1000
if q.ValueMsat%1000 != 0 || valueSat < s.cfg.MinNoteSat || valueSat > s.cfg.MaxNoteSat {
return ErrCapNoteValue
}
if inGroup && valueSat > s.cfg.GroupNoteMaxSat {
return ErrCapNoteValue
}
if int64(q.Count) > s.cfg.MaxBatchSize || (q.Count > 1 && q.NetMsat()/1000 > s.cfg.MaxBatchTotalSat) {
return ErrCapBatch
}
count, sum, err := s.store.Outstanding(user)
if err != nil {
return err
}
if count+int64(q.Count) > s.cfg.MaxOutstandingNotesPerUser || (sum+q.NetMsat())/1000 > s.cfg.MaxOutstandingSatPerUser {
return ErrCapOutstanding
}
balance, err := s.ledger.BalanceMsat(ctx, user)
if err != nil {
return err
}
if balance < q.GrossMsat {
return ErrInsufficientFunds
}
return nil
}
// ---- creation ----
// CreateParams describes one creation request.
type CreateParams struct {
User string
LanguageCode string
Quote Quote
Memo string
ChatID int64 // group chat, 0 for private
// Progress is called after every carved note (batches).
Progress func(done, total int)
}
// unit is one mint invoice and the notes carved out of it.
type unit struct {
funding *Note
notes []*Note // user notes, in order
dust []*Note // dust_i is the change of split i
}
// Create mints the notes of a quote. It returns the batch and the user notes
// that are live. ErrInFlight means the recovery job will finish the rest.
func (s *Service) Create(ctx context.Context, p CreateParams) (*Batch, []*Note, error) {
q := p.Quote
mint, ok := s.mints.Get(q.MintID)
if !ok || !mint.Usable() {
return nil, nil, ErrNoMint
}
if err := s.CheckCaps(ctx, p.User, q, p.ChatID != 0); err != nil {
return nil, nil, err
}
units := 1
perUnit := q.Count
if q.Strategy == StrategyInvoices && q.Count > 1 {
units, perUnit = q.Count, 1
}
unitGross := q.GrossMsat / int64(units)
batch := &Batch{ID: newID("batch"), UserName: p.User, MintID: mint.ID, Memo: p.Memo, Count: q.Count,
ValueMsat: q.ValueMsat, TotalGrossMsat: q.GrossMsat, FeeMsat: q.FeeMsat, Strategy: q.Strategy,
State: BatchPendingInvoice, ChatID: p.ChatID, LanguageCode: p.LanguageCode}
var all []*unit
index := 0
for u := 0; u < units; u++ {
un := &unit{}
f, err := s.newNote(batch, mint, p, KindFunding, 0, unitGross)
if err != nil {
return nil, nil, err
}
f.State = NotePendingInvoice
un.funding = f
for i := 0; i < perUnit; i++ {
index++
n, err := s.newNote(batch, mint, p, KindUser, index, 0)
if err != nil {
return nil, nil, err
}
d, err := s.newNote(batch, mint, p, KindDust, index, 0)
if err != nil {
return nil, nil, err
}
un.notes = append(un.notes, n)
un.dust = append(un.dust, d)
}
all = append(all, un)
}
if units == 1 {
batch.FundingNoteID = all[0].funding.ID
}
// Every secret is on disk before the first request leaves.
err := s.store.Transaction(func(tx *gorm.DB) error {
if err := s.store.CreateBatch(tx, batch); err != nil {
return err
}
for _, un := range all {
rows := append([]*Note{un.funding}, un.notes...)
rows = append(rows, un.dust...)
if err := s.store.CreateNotes(tx, rows); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, nil, err
}
log.Infof("[lnurlcash] batch %s: %d note(s) of %d msat at %s for user %s (gross %d msat)", batch.ID, q.Count, q.ValueMsat, mint.ID, p.User, q.GrossMsat)
var live []*Note
done := 0
var firstErr error
for _, un := range all {
err := s.fundAndCarve(ctx, batch, mint, un, func() {
done++
if p.Progress != nil {
p.Progress(done, q.Count)
}
})
for _, n := range un.notes {
if n.State == NoteLive {
live = append(live, n)
}
}
if err != nil {
firstErr = err
break
}
}
s.settleBatchState(batch.ID)
b, _ := s.store.Batch(batch.ID)
if b == nil {
b = batch
}
return b, live, firstErr
}
func (s *Service) newNote(batch *Batch, mint *Mint, p CreateParams, kind string, index int, gross int64) (*Note, error) {
k1, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(k1)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(k1)
if err != nil {
return nil, err
}
bid := batch.ID
n := &Note{ID: newID("note"), BatchID: &bid, UserName: p.User, MintID: mint.ID, MintURL: mint.WithdrawLink,
MintPubkey: mint.PinnedPubkey, Hash: h, SecretEnc: enc, Memo: p.Memo, Kind: kind, Index: index,
State: NotePendingCarve, LanguageCode: p.LanguageCode, ChatID: p.ChatID}
if kind == KindUser {
n.ValueMsat = p.Quote.ValueMsat
}
if kind == KindFunding {
n.GrossMsat = gross
n.ValueMsat = gross
}
return n, nil
}
// fundAndCarve requests and pays the mint invoice of a unit, waits for the
// note to appear, then carves the user notes out of it.
func (s *Service) fundAndCarve(ctx context.Context, batch *Batch, mint *Mint, un *unit, progress func()) error {
f := un.funding
if f.State == NotePendingInvoice {
inv, err := s.client.RequestMintInvoiceWithHash(ctx, mint.PayCallback, f.GrossMsat, f.Hash)
if err != nil {
s.failUnit(batch, un, "mint invoice: "+err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
patch := map[string]interface{}{"invoice_pr": inv.PR, "verify_url": inv.VerifyURL}
if err := s.store.TransitionNote(f.ID, NotePendingInvoice, NotePendingSettle, patch); err != nil {
return err
}
f.State, f.InvoicePR, f.VerifyURL = NotePendingSettle, inv.PR, inv.VerifyURL
_ = s.store.TransitionBatch(batch.ID, "", BatchPendingSettle, nil)
hash, err := s.ledger.PayInvoice(ctx, batch.UserName, inv.PR)
if err != nil {
if IsAmbiguousLedger(err) {
_ = s.store.UpdateNote(f.ID, map[string]interface{}{"last_error": err.Error()})
log.Warnf("[lnurlcash] batch %s funding %s: pay outcome unknown, left for recovery", batch.ID, f.Hash)
return ErrInFlight
}
s.failUnit(batch, un, "pay: "+err.Error())
return err
}
_ = s.store.UpdateNote(f.ID, map[string]interface{}{"invoice_hash": hash})
f.InvoiceHash = hash
}
if f.State == NotePendingSettle {
found, err := s.waitFunding(ctx, f, s.cfg.InvoiceWaitTimeout)
if err != nil {
return err
}
if !found {
return ErrInFlight
}
}
return s.carve(ctx, batch, un, progress)
}
// waitFunding polls until the funding note exists at the mint or the timeout
// passes. It returns found=false on timeout.
func (s *Service) waitFunding(ctx context.Context, f *Note, timeout time.Duration) (bool, error) {
deadline := s.now().Add(timeout)
for {
info, err := s.client.FetchNoteInfoByHash(ctx, f.MintURL, f.Hash)
if err == nil {
patch := map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature, "last_probe": s.now()}
if err := s.store.TransitionNote(f.ID, NotePendingSettle, NoteLive, patch); err != nil && !errors.Is(err, ErrStale) {
return false, err
}
f.State, f.ReportedMsat = NoteLive, info.MaxWithdrawableMsat
return true, nil
}
if lnurlcash.IsSpent(err) {
// burned already: the funding note was carved by a previous run
f.State = NoteSpent
_ = s.store.TransitionNote(f.ID, "", NoteSpent, nil)
return true, nil
}
if !s.now().Before(deadline) || ctx.Err() != nil {
return false, nil
}
select {
case <-ctx.Done():
return false, nil
case <-time.After(s.pollEvery):
}
}
}
// carve splits the user notes off the funding note, one after the other.
// Idempotent: a note that already exists at the mint is taken as carved.
func (s *Service) carve(ctx context.Context, batch *Batch, un *unit, progress func()) error {
_ = s.store.TransitionBatch(batch.ID, "", BatchCarving, nil)
current := un.funding
for i, n := range un.notes {
if IsFinalNoteState(n.State) || n.State == NoteLive {
if n.State == NoteLive {
progress()
}
current = un.dust[i]
continue
}
if current.State != NoteLive {
// the previous change note is gone: nothing left to carve from
s.failRemaining(batch, un, i, "no change note to carve from")
return fmt.Errorf("%w: carve input not live", ErrMintUnavailable)
}
dust := un.dust[i]
k1, err := s.secret(current)
if err != nil {
return err
}
_, err = s.client.SplitNoteWithHash(ctx, current.MintURLCallback(), []string{k1}, n.ValueMsat, n.Hash, dust.Hash)
if err != nil {
switch {
case lnurlcash.IsAmbiguous(err):
// the library already retried; the answer is lost. Probe the output.
if _, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break // it landed
}
_ = s.store.TransitionNote(n.ID, "", NoteUnknown, map[string]interface{}{"last_error": err.Error()})
_ = s.store.TransitionBatch(batch.ID, "", BatchUnknown, nil)
n.State = NoteUnknown
log.Warnf("[lnurlcash] batch %s note %s: split outcome unknown, left for recovery", batch.ID, n.Hash)
return ErrInFlight
case lnurlcash.IsAlreadyInUse(err), lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
// either the input was burned by an earlier attempt that did land,
// or the output is taken. The output's existence decides.
if _, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil {
break
}
s.failRemaining(batch, un, i, err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
default:
s.failRemaining(batch, un, i, err.Error())
return fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
}
fee := s.mintFee(n.MintID)
changeMsat := current.ReportedMsat - n.ValueMsat - fee.BaseFeeMsat
if err := s.store.TransitionNote(n.ID, "", NoteLive, map[string]interface{}{"reported_msat": n.ValueMsat, "last_probe": s.now()}); err != nil {
return err
}
n.State, n.ReportedMsat = NoteLive, n.ValueMsat
_ = s.store.TransitionNote(dust.ID, "", NoteLive, map[string]interface{}{"reported_msat": changeMsat, "value_msat": changeMsat})
dust.State, dust.ReportedMsat, dust.ValueMsat = NoteLive, changeMsat, changeMsat
_ = s.store.TransitionNote(current.ID, "", NoteSpent, nil)
current.State = NoteSpent
progress()
current = dust
// the mint's own word on the two outputs, best effort
if info, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); perr == nil && info.MaxWithdrawableMsat != n.ReportedMsat {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "certificate": info.Signature})
n.ReportedMsat = info.MaxWithdrawableMsat
}
}
return nil
}
// MintURLCallback is the callback mutations go to. LUD-25 mints use the
// withdraw link itself as callback; the informational GET confirms it, but
// the link is what every note of this bot was built on.
func (n *Note) MintURLCallback() string { return n.MintURL }
func (s *Service) mintFee(mintID string) lnurlcash.MintFee {
if m, ok := s.mints.Get(mintID); ok {
return m.Fee()
}
return lnurlcash.MintFee{}
}
func (s *Service) failUnit(batch *Batch, un *unit, reason string) {
_ = s.store.TransitionNote(un.funding.ID, "", NoteFailed, map[string]interface{}{"last_error": reason})
un.funding.State = NoteFailed
s.failRemaining(batch, un, 0, reason)
}
func (s *Service) failRemaining(batch *Batch, un *unit, from int, reason string) {
for i := from; i < len(un.notes); i++ {
if un.notes[i].State == NoteLive || IsFinalNoteState(un.notes[i].State) {
continue
}
_ = s.store.TransitionNote(un.notes[i].ID, "", NoteFailed, map[string]interface{}{"last_error": reason})
un.notes[i].State = NoteFailed
_ = s.store.TransitionNote(un.dust[i].ID, "", NoteFailed, nil)
un.dust[i].State = NoteFailed
}
}
// settleBatchState derives the batch state from its notes.
func (s *Service) settleBatchState(batchID string) {
notes, err := s.store.NotesInBatch(batchID)
if err != nil {
return
}
var live, claimed, reclaimed, failed, pending, total int
for _, n := range notes {
if n.Kind != KindUser {
continue
}
total++
switch n.State {
case NoteLive, NoteReclaiming:
live++
case NoteClaimed:
claimed++
case NoteReclaimed:
reclaimed++
case NoteFailed:
failed++
default:
pending++
}
}
state := BatchLive
switch {
case total == 0:
return
case pending > 0:
state = BatchCarving
case failed == total:
state = BatchFailed
case failed > 0:
state = BatchPartial
case claimed == total:
state = BatchClaimed
case claimed+reclaimed == total:
state = BatchReclaimed
}
_ = s.store.TransitionBatch(batchID, "", state, nil)
}
// ---- status ----
// Status asks the mint about a note and updates the row. It returns the
// note's new state.
func (s *Service) Status(ctx context.Context, n *Note) (string, int64, error) {
if IsFinalNoteState(n.State) {
return n.State, n.ReportedMsat, nil
}
info, err := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash)
now := s.now()
switch {
case err == nil:
patch := map[string]interface{}{"reported_msat": info.MaxWithdrawableMsat, "last_probe": now, "last_error": ""}
if info.Signature != "" {
patch["certificate"] = info.Signature
}
if n.State == NoteUnknown || n.State == NotePendingSettle || n.State == NotePendingCarve {
// it exists: it is live, whatever we feared
_ = s.store.TransitionNote(n.ID, n.State, NoteLive, patch)
n.State = NoteLive
} else {
_ = s.store.UpdateNote(n.ID, patch)
}
n.ReportedMsat = info.MaxWithdrawableMsat
return n.State, n.ReportedMsat, nil
case errors.Is(err, lnurlcash.ErrNotePending):
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now})
return n.State, n.ReportedMsat, ErrNotePending
case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err):
if n.State == NoteLive {
t := now
if terr := s.store.TransitionNote(n.ID, NoteLive, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_probe": now}); terr == nil {
n.State, n.ClaimedAt = NoteClaimed, &t
if n.BatchID != nil {
s.settleBatchState(*n.BatchID)
}
}
} else {
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
}
return n.State, n.ReportedMsat, nil
default:
_ = s.store.UpdateNote(n.ID, map[string]interface{}{"last_probe": now, "last_error": err.Error()})
return n.State, n.ReportedMsat, err
}
}
// NoteURL builds the lnurlw:// form of a note. The URL is never stored.
func (s *Service) NoteURL(n *Note) (string, error) {
k1, err := s.secret(n)
if err != nil {
return "", err
}
value := n.ReportedMsat
if value <= 0 {
value = n.ValueMsat
}
u := lnurlcash.BuildNoteURL(n.MintURL, k1, value)
if u == "" {
return "", errors.New("lnurlcash: note URL does not build")
}
if n.Certificate != "" {
u = lnurlcash.WithNewK1(u, k1, value, n.Certificate)
}
return u, nil
}
// NoteStrings returns the lnurlw:// form and the bech32 LNURL of a note.
func (s *Service) NoteStrings(n *Note) (lnurlw, bech32 string, err error) {
u, err := s.NoteURL(n)
if err != nil {
return "", "", err
}
b, err := lnurlcash.ToBech32Lnurl(u)
if err != nil {
return "", "", err
}
return lnurlcash.ToLud17w(u), b, nil
}
// lockNote serialises work on one note across handlers and jobs.
func lockNote(id string) func() {
mutex.Lock("lnurlcash:" + id)
return func() { mutex.Unlock("lnurlcash:" + id) }
}
+376
View File
@@ -0,0 +1,376 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
)
// fakeLedger is an in-memory LNbits: invoices on user wallets, payments of
// fake-mint invoices, balances in msat.
type fakeLedger struct {
mu sync.Mutex
mint *fakeMint
balances map[string]int64
invoices map[string]*fakeLedgerInvoice // hash -> invoice
payFails bool
payAmbig bool
seq int
}
type fakeLedgerInvoice struct {
user string
sat int64
ref string
paid bool
}
func newFakeLedger(m *fakeMint) *fakeLedger {
return &fakeLedger{mint: m, balances: map[string]int64{}, invoices: map[string]*fakeLedgerInvoice{}}
}
func (l *fakeLedger) CreateInvoice(ctx context.Context, user string, sat int64, memo, ref string) (string, string, error) {
l.mu.Lock()
defer l.mu.Unlock()
l.seq++
hash := fmt.Sprintf("%064d", l.seq)
l.invoices[hash] = &fakeLedgerInvoice{user: user, sat: sat, ref: ref}
return "lnbcfake" + hash[:8], hash, nil
}
func (l *fakeLedger) PayInvoice(ctx context.Context, user, pr string) (string, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.payAmbig {
return "", &AmbiguousLedgerError{Err: errors.New("timeout")}
}
if l.payFails {
return "", errors.New("payment failed: no route")
}
l.seq++
hash := fmt.Sprintf("%064d", l.seq)
inv := l.mint.inv[pr]
if inv == nil {
return "", errors.New("unknown invoice")
}
l.balances[user] -= inv.amount
l.mu.Unlock()
l.mint.settle(pr)
l.mu.Lock()
return hash, nil
}
func (l *fakeLedger) InvoicePaid(ctx context.Context, user, hash string) (bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
inv, ok := l.invoices[hash]
return ok && inv.paid, nil
}
func (l *fakeLedger) PaymentSucceeded(ctx context.Context, user, hash string) (bool, bool, error) {
return true, false, nil
}
func (l *fakeLedger) BalanceMsat(ctx context.Context, user string) (int64, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.balances[user], nil
}
// settleIncoming marks an invoice on a user wallet paid (the melt arrived).
func (l *fakeLedger) settleIncoming(hash string) {
l.mu.Lock()
defer l.mu.Unlock()
inv := l.invoices[hash]
inv.paid = true
l.balances[inv.user] += inv.sat * 1000
}
type harness struct {
mint *fakeMint
ledger *fakeLedger
store *Store
reg *Registry
svc *Service
cfg *Config
}
func newHarness(t *testing.T) *harness {
t.Helper()
fm := newFakeMint(t)
s := testStore(t)
cfg := testConfig(fm.url())
cfg.InvoiceWaitTimeout = 2 * time.Second
reg := NewRegistry(cfg, s, nil, nil)
if err := reg.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
ledger := newFakeLedger(fm)
ledger.balances["42"] = 10_000_000 // 10k sat
cipher, _ := NewCipher(testKey)
svc := NewService(cfg, s, reg, ledger, cipher)
svc.pollEvery = 10 * time.Millisecond
return &harness{mint: fm, ledger: ledger, store: s, reg: reg, svc: svc, cfg: cfg}
}
func TestGrossUpAgainstLiveFee(t *testing.T) {
fee := lnurlcash.MintFee{BaseFeeMsat: 1000, FeePpm: 100}
for _, count := range []int64{1, 3, 100} {
gross := grossFor(1000_000, count, fee)
if gross%1000 != 0 {
t.Fatalf("gross must be whole sats: %d", gross)
}
net := lnurlcash.ApplyMintFee(gross, fee)
if net < count*1000_000+count*fee.BaseFeeMsat+carveMargin {
t.Fatalf("count %d: net %d does not cover the notes and the splits", count, net)
}
if net-(count*1000_000+count*fee.BaseFeeMsat+carveMargin) > 1000 {
t.Fatalf("count %d: overpaying by more than a sat: %d", count, net)
}
}
}
func TestCreateSingleNoteAndReclaim(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 1000_000, 1)
if err != nil {
t.Fatal(err)
}
if want := grossFor(1000_000, 1, mint.Fee()); q.GrossMsat != want || q.FeeMsat != want-1000_000 || q.GrossMsat%1000 != 0 {
t.Fatalf("unexpected quote %+v (want gross %d)", q, want)
}
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", LanguageCode: "en", Quote: q, Memo: "hi"})
if err != nil {
t.Fatal(err)
}
if len(live) != 1 || batch.State != BatchLive {
t.Fatalf("expected one live note, got %d, batch %s", len(live), batch.State)
}
n := live[0]
if v, ok := h.mint.value(n.Hash); !ok || v != 1000_000 {
t.Fatalf("mint holds %d for the note (ok=%v)", v, ok)
}
if n.ReportedMsat != 1000_000 {
t.Fatalf("reported %d", n.ReportedMsat)
}
if h.ledger.balances["42"] != 10_000_000-q.GrossMsat {
t.Fatalf("balance %d", h.ledger.balances["42"])
}
// the user's note URL is a valid note at the fake mint
lnurlw, bech, err := h.svc.NoteStrings(n)
if err != nil || !strings.HasPrefix(lnurlw, "lnurlw://") || !strings.HasPrefix(bech, "LNURL1") {
t.Fatalf("note strings: %q %q %v", lnurlw, bech, err)
}
if lnurlcash.ResolveNoteInput(bech) == "" {
t.Fatal("bech32 note does not resolve")
}
// every secret was persisted and is distinct
notes, _ := h.store.NotesInBatch(batch.ID)
if len(notes) != 3 {
t.Fatalf("expected funding + note + dust rows, got %d", len(notes))
}
// status: still live
state, _, err := h.svc.Status(ctx, n)
if err != nil || state != NoteLive {
t.Fatalf("status %s %v", state, err)
}
// reclaim: invoice of exactly 1000 sat, melt in flight, settle
rn, err := h.svc.Reclaim(ctx, n.ID)
if err != nil {
t.Fatal(err)
}
if rn.State != NoteReclaiming || h.ledger.invoices[rn.InvoiceHash].sat != 1000 {
t.Fatalf("reclaim state %s", rn.State)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrInFlight) {
t.Fatalf("second reclaim must report in flight: %v", err)
}
h.mint.finishMelt(n.Hash, true)
h.ledger.settleIncoming(rn.InvoiceHash)
st, err := h.svc.SettleInvoice(ctx, rn.InvoiceHash)
if err != nil || st == nil || st.Note == nil || st.Note.State != NoteReclaimed {
t.Fatalf("settle: %+v %v", st, err)
}
b, _ := h.store.Batch(batch.ID)
if b.State != BatchReclaimed {
t.Fatalf("batch state %s", b.State)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrNothingToReclaim) {
t.Fatalf("reclaimed note: %v", err)
}
}
func TestClaimDetection(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 500_000, 1)
_, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil {
t.Fatal(err)
}
n := live[0]
h.mint.claim(n.Hash)
state, _, err := h.svc.Status(ctx, n)
if err != nil || state != NoteClaimed {
t.Fatalf("expected claimed, got %s %v", state, err)
}
if _, err := h.svc.Reclaim(ctx, n.ID); !errors.Is(err, ErrNoteClaimed) {
t.Fatalf("reclaiming a claimed note: %v", err)
}
}
func TestCreateBatchSplitAndPartialFailure(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 100_000, 5)
if err != nil {
t.Fatal(err)
}
progress := 0
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q, Progress: func(done, total int) { progress = done }})
if err != nil || len(live) != 5 || batch.State != BatchLive || progress != 5 {
t.Fatalf("batch: live=%d state=%s progress=%d err=%v", len(live), batch.State, progress, err)
}
for _, n := range live {
if v, ok := h.mint.value(n.Hash); !ok || v != 100_000 {
t.Fatalf("note %d worth %d at the mint", n.Index, v)
}
}
// a split refused midway leaves the carved notes and fails the rest
h.mint.refuseSplit = "insufficient value"
q2, _ := h.svc.Quote(ctx, mint, 100_000, 3)
batch2, live2, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q2})
if err == nil || len(live2) != 0 || batch2.State != BatchFailed {
t.Fatalf("expected a failed batch, got live=%d state=%s err=%v", len(live2), batch2.State, err)
}
// the funding note is still live at the mint and owned by the bot's row
notes, _ := h.store.NotesInBatch(batch2.ID)
var funding *Note
for _, n := range notes {
if n.Kind == KindFunding {
funding = n
}
}
if funding == nil || funding.State != NoteLive {
t.Fatalf("funding note should stay live for recovery: %+v", funding)
}
}
func TestCreateAmbiguousSplitIsResolvedByProbe(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 2)
h.mint.dropAfterSplit = true
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err != nil || len(live) != 2 || batch.State != BatchLive {
t.Fatalf("dropped connection after an applied split must still carve: live=%d state=%s err=%v", len(live), batch.State, err)
}
}
func TestCreateCaps(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 1000_000, 1)
h.cfg.GroupNoteMaxSat = 500
if err := h.svc.CheckCaps(ctx, "42", q, true); !errors.Is(err, ErrCapNoteValue) {
t.Fatalf("group cap: %v", err)
}
h.ledger.balances["42"] = 1000
if err := h.svc.CheckCaps(ctx, "42", q, false); !errors.Is(err, ErrInsufficientFunds) {
t.Fatalf("balance: %v", err)
}
h.ledger.balances["42"] = 10_000_000
h.cfg.MaxOutstandingNotesPerUser = 1
q2, _ := h.svc.Quote(ctx, mint, 100_000, 2)
if err := h.svc.CheckCaps(ctx, "42", q2, false); !errors.Is(err, ErrCapOutstanding) {
t.Fatalf("outstanding: %v", err)
}
h.ledger.payFails = true
h.cfg.MaxOutstandingNotesPerUser = 200
batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if err == nil || len(live) != 0 || batch.State != BatchFailed {
t.Fatalf("failed payment must fail the batch: %v %s", err, batch.State)
}
}
func TestRedeemWholeAndFractional(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
// a note somebody else minted: a whole-sat one and a fractional one
mk := func(value int64) (string, string) {
k1, _ := lnurlcash.GenerateNoteSecret()
hh, _ := lnurlcash.HashK1(k1)
h.mint.mu.Lock()
h.mint.notes[hh] = value
h.mint.mu.Unlock()
return k1, lnurlcash.BuildNoteURL(h.mint.url()+"/w", k1, value)
}
_, whole := mk(2000_000)
prev, err := h.svc.RedeemInfo(ctx, "7", "nl", "lightning:"+whole)
if err != nil {
t.Fatal(err)
}
if prev.ValueMsat != 2000_000 || !prev.KnownMint || prev.Redeem.State != RedeemInfo {
t.Fatalf("preview %+v", prev)
}
if _, err := h.svc.Redeem(ctx, prev.Redeem.ID, "8"); !errors.Is(err, ErrNotOwner) {
t.Fatalf("owner check: %v", err)
}
r, err := h.svc.Redeem(ctx, prev.Redeem.ID, "7")
if err != nil || r.State != RedeemMelting {
t.Fatalf("redeem: %s %v", r.State, err)
}
if h.ledger.invoices[r.InvoiceHash].sat != 2000 {
t.Fatal("invoice must be exactly the note value")
}
h.ledger.settleIncoming(r.InvoiceHash)
st, err := h.svc.SettleInvoice(ctx, r.InvoiceHash)
if err != nil || st == nil || st.Redeem == nil || st.Redeem.State != RedeemSettled {
t.Fatalf("settle %+v %v", st, err)
}
// fractional: 1000.9 sat -> split off 999 sat (1000 would leave change below the base fee)
_, frac := mk(1000_900)
prev2, err := h.svc.RedeemInfo(ctx, "7", "nl", frac)
if err != nil {
t.Fatal(err)
}
r2, err := h.svc.Redeem(ctx, prev2.Redeem.ID, "7")
if err != nil || r2.State != RedeemMelting || r2.SplitNoteID == nil {
t.Fatalf("fractional redeem: %s %v", r2.State, err)
}
if got := h.ledger.invoices[r2.InvoiceHash].sat; got != 999 {
t.Fatalf("expected a 999 sat invoice, got %d", got)
}
// not a note: a plain withdraw without mintPubkey, or garbage
if _, err := h.svc.RedeemInfo(ctx, "7", "nl", "hello"); !errors.Is(err, ErrNotANote) {
t.Fatalf("garbage: %v", err)
}
// a spent note
k3, spent := mk(1000_000)
h3, _ := lnurlcash.HashK1(k3)
h.mint.claim(h3)
if _, err := h.svc.RedeemInfo(ctx, "7", "nl", spent); !errors.Is(err, ErrNoteClaimed) {
t.Fatalf("spent: %v", err)
}
// the user's own note is refused with a pointer to reclaim
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 1)
_, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
own, _ := h.svc.NoteURL(live[0])
var ownErr *ErrOwnNote
if _, err := h.svc.RedeemInfo(ctx, "42", "en", own); !errors.As(err, &ownErr) || ownErr.NoteID != live[0].ID {
t.Fatalf("own note: %v", err)
}
}