// Package lnbitstest is a fake LNbits server for tests. It implements the // three endpoints the bot uses, with the request and response shapes of // the real server, and lets a test pay invoices, replay or drop webhooks // and take the server down. package lnbitstest import ( "bytes" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "sync" "time" ) // Key is the invoice key the fake accepts. const Key = "fake-invoice-key-0123456789abcdef" // Invoice is an invoice created through the fake. type Invoice struct { PaymentHash string Bolt11 string AmountSats int64 Memo string Webhook string Expiry int64 // seconds Paid bool // WebhooksSent counts webhook posts for this invoice. WebhooksSent int } // Server is the fake LNbits. type Server struct { HTTP *httptest.Server mu sync.Mutex // V1 makes responses look like LNbits v1.x (invoice in "bolt11"). V1 bool // DropWebhooks simulates webhooks that never arrive. DropWebhooks bool down bool invoices map[string]*Invoice order []string statusCalls int createCalls int } // New starts a fake server. func New() *Server { s := &Server{invoices: map[string]*Invoice{}} s.HTTP = httptest.NewServer(http.HandlerFunc(s.handle)) return s } // URL returns the server root to use as LNBITS_URL. func (s *Server) URL() string { return s.HTTP.URL } // Close stops the server. func (s *Server) Close() { s.HTTP.Close() } // SetDown makes every request fail with 503 while down is true. func (s *Server) SetDown(down bool) { s.mu.Lock() defer s.mu.Unlock() s.down = down } // Invoices returns copies of all invoices in creation order. func (s *Server) Invoices() []Invoice { s.mu.Lock() defer s.mu.Unlock() out := make([]Invoice, 0, len(s.order)) for _, h := range s.order { out = append(out, *s.invoices[h]) } return out } // Last returns the most recently created invoice. func (s *Server) Last() (Invoice, bool) { s.mu.Lock() defer s.mu.Unlock() if len(s.order) == 0 { return Invoice{}, false } return *s.invoices[s.order[len(s.order)-1]], true } // WaitInvoice waits until at least n invoices exist and returns the n-th. func (s *Server) WaitInvoice(n int, timeout time.Duration) (Invoice, bool) { deadline := time.Now().Add(timeout) for { s.mu.Lock() if len(s.order) >= n { inv := *s.invoices[s.order[n-1]] s.mu.Unlock() return inv, true } s.mu.Unlock() if time.Now().After(deadline) { return Invoice{}, false } time.Sleep(5 * time.Millisecond) } } // Calls returns how many create and status requests were served. func (s *Server) Calls() (creates, statuses int) { s.mu.Lock() defer s.mu.Unlock() return s.createCalls, s.statusCalls } // Pay marks an invoice as paid and, unless DropWebhooks is set, posts the // webhook the way LNbits does: once, unsigned, with the payment as body. func (s *Server) Pay(paymentHash string) error { s.mu.Lock() inv, ok := s.invoices[paymentHash] if !ok { s.mu.Unlock() return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash) } inv.Paid = true drop := s.DropWebhooks s.mu.Unlock() if drop { return nil } return s.SendWebhook(paymentHash) } // SendWebhook posts the webhook of an invoice again, which is how tests // simulate duplicate deliveries. It works for unpaid invoices too, so a // test can send a forged "paid" notification. func (s *Server) SendWebhook(paymentHash string) error { s.mu.Lock() inv, ok := s.invoices[paymentHash] if !ok { s.mu.Unlock() return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash) } url := inv.Webhook body, _ := json.Marshal(map[string]any{ "payment_hash": inv.PaymentHash, "checking_id": inv.PaymentHash, "amount": inv.AmountSats * 1000, // LNbits reports millisats "memo": inv.Memo, "bolt11": inv.Bolt11, "pending": false, "webhook": inv.Webhook, }) inv.WebhooksSent++ s.mu.Unlock() if url == "" { return nil } resp, err := http.Post(url, "application/json", bytes.NewReader(body)) if err != nil { return err } resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("lnbitstest: webhook answered %d", resp.StatusCode) } return nil } func (s *Server) handle(w http.ResponseWriter, r *http.Request) { s.mu.Lock() down := s.down s.mu.Unlock() if down { writeJSON(w, http.StatusServiceUnavailable, map[string]any{"detail": "Service Unavailable"}) return } if r.Header.Get("X-Api-Key") != Key { writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Invoice (or Admin) key required."}) return } switch { case r.Method == http.MethodGet && r.URL.Path == "/api/v1/wallet": writeJSON(w, http.StatusOK, map[string]any{"name": "test wallet", "balance": 0}) case r.Method == http.MethodPost && r.URL.Path == "/api/v1/payments": s.create(w, r) case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/v1/payments/"): s.status(w, strings.TrimPrefix(r.URL.Path, "/api/v1/payments/")) default: writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Not Found"}) } } func (s *Server) create(w http.ResponseWriter, r *http.Request) { var req struct { Out bool `json:"out"` Amount float64 `json:"amount"` Unit string `json:"unit"` Memo string `json:"memo"` Expiry int64 `json:"expiry"` Webhook string `json:"webhook"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "bad json"}) return } if req.Out { // Paying needs the admin key, which the bot must never have. writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Admin key required."}) return } if req.Amount <= 0 { writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "amount must be positive"}) return } var raw [32]byte _, _ = rand.Read(raw[:]) hash := hex.EncodeToString(raw[:]) inv := &Invoice{ PaymentHash: hash, Bolt11: fmt.Sprintf("lnbc%dn1fake%s", int64(req.Amount)*10, hash), AmountSats: int64(req.Amount), Memo: req.Memo, Webhook: req.Webhook, Expiry: req.Expiry, } s.mu.Lock() s.createCalls++ s.invoices[hash] = inv s.order = append(s.order, hash) v1 := s.V1 s.mu.Unlock() if v1 { writeJSON(w, http.StatusCreated, map[string]any{ "payment_hash": hash, "bolt11": inv.Bolt11, "checking_id": hash, "amount": inv.AmountSats * 1000, "status": "pending", }) return } writeJSON(w, http.StatusCreated, map[string]any{ "payment_hash": hash, "payment_request": inv.Bolt11, "checking_id": hash, "lnurl_response": nil, }) } func (s *Server) status(w http.ResponseWriter, hash string) { s.mu.Lock() s.statusCalls++ inv, ok := s.invoices[hash] var paid bool if ok { paid = inv.Paid } s.mu.Unlock() if !ok { writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Payment does not exist."}) return } writeJSON(w, http.StatusOK, map[string]any{ "paid": paid, "preimage": nil, "details": map[string]any{"payment_hash": hash, "pending": !paid}, }) } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(v) }