Files
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

150 lines
4.7 KiB
Go

package network
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/netguard"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
type ClientType string
const (
ClientTypeClearNet = "clearnet"
ClientTypeTor = "tor"
)
// checks if strings contains http(s)://*.onion
var isOnion = regexp.MustCompile("^https?\\:\\/\\/[\\w\\-\\.]+\\.onion")
// GetClientForScheme returns correct client for url scheme.
// if tld is .onion, function will also return an onion client.
func GetClientForScheme(url *url.URL) (*http.Client, error) {
if isOnion.FindString(url.String()) != "" {
return GetClient(ClientTypeTor)
}
switch url.Scheme {
case "onion":
return GetClient(ClientTypeTor)
default:
return GetClient(ClientTypeClearNet)
}
}
// directTransport returns the transport used when no proxy is configured. The
// URLs fetched with these clients come from users and remote servers, so it
// only connects to public addresses. Every client gets its own transport,
// because callers change its TLS settings (satdress.SetupHttpClient).
func directTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.DialContext = netguard.DialContext
return t
}
// The bot's own hosts may resolve to loopback (hosts file, split DNS). Paying
// a lightning address on them must keep working.
func init() {
if u := internal.Configuration.Bot.LNURLHostUrl; u != nil {
netguard.Trust(u.Hostname())
}
if u, err := url.Parse(internal.Configuration.Lnbits.Url); err == nil {
netguard.Trust(u.Hostname())
}
}
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
Transport: directTransport(),
}
var cfg *internal.SocksConfiguration
switch clientType {
case ClientTypeClearNet:
cfg = internal.Configuration.Bot.SocksProxy
case ClientTypeTor:
cfg = internal.Configuration.Bot.TorProxy
default:
return nil, fmt.Errorf("[GetClient] invalid clientType")
}
if cfg == nil {
return &client, nil
}
if cfg.Host == "" {
return &client, nil
}
proxyURL, _ := url.Parse(cfg.Host)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
var auth *proxy.Auth
if cfg.Username != "" && cfg.Password != "" {
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
}
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
log.Errorln(err)
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// The proxy resolves hostnames, so only literal addresses and
// localhost names can be refused here.
if err := netguard.CheckHost(addr); err != nil {
return nil, err
}
return d.Dial(network, addr)
}
client.Transport = specialTransport
return &client, nil
}
// NewNoKeepAliveClient returns a client for LNURLcash mints: the same proxy
// and netguard rules as GetClient, but keep-alives off and redirects refused,
// because every LNURLcash mutation is a non-idempotent GET that net/http
// would otherwise retry on a reused connection. 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 {
client = &http.Client{Transport: directTransport()}
}
if t, ok := client.Transport.(*http.Transport); ok {
t.DisableKeepAlives = true
}
client.Timeout = timeout
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client
}
// 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
}