package blossom import ( "bytes" "encoding/hex" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "sync" "testing" "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/elnosh/gonuts/cashu" "github.com/elnosh/gonuts/cashu/nuts/nut03" "github.com/elnosh/gonuts/crypto" ) // stubMint is a minimal Cashu mint for tests. It signs swap outputs with // real BDHKE and returns NUT-12 DLEQ proofs, so the payment code runs // against genuine cryptography. Knobs let tests break it on purpose. type stubMint struct { srv *httptest.Server keys map[uint64]*secp256k1.PrivateKey feePpk uint64 badDLEQ bool // return a DLEQ proof that does not verify noDLEQ bool // omit DLEQ proofs reject bool // reject swaps with 400 garbage bool // accept the swap but return an unreadable body mu sync.Mutex spent map[string]bool outputs cashu.BlindedMessages // outputs from the last swap } const stubKeysetID = "00aabbccddeeff00" func newStubMint(t *testing.T) *stubMint { t.Helper() m := &stubMint{keys: map[uint64]*secp256k1.PrivateKey{}, spent: map[string]bool{}} for i := 0; i < 16; i++ { k, err := secp256k1.GeneratePrivateKey() if err != nil { t.Fatal(err) } m.keys[1< fee 2 if ok, reason := pc.ValidatePayment(tok, meta); !ok { t.Fatalf("payment rejected: %s", reason) } decoded, _ := cashu.DecodeToken(pc.TakePayouts(artist)[0]) var total uint64 for _, p := range decoded.Proofs() { total += p.Amount } if total != 64 { t.Errorf("artist received %d sats, want 64 (66 minus 2 fee)", total) } } func TestPaymentRejectsBadDLEQ(t *testing.T) { for name, set := range map[string]func(*stubMint){ "forged proof": func(m *stubMint) { m.badDLEQ = true }, "missing proof": func(m *stubMint) { m.noDLEQ = true }, } { t.Run(name, func(t *testing.T) { mint := newStubMint(t) set(mint) pc := newChecker(t, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()} tok := token(t, mint.url(), mint.issue(t, 8)) ok, reason := pc.ValidatePayment(tok, meta) if ok { t.Fatal("payment accepted despite bad DLEQ") } if !strings.Contains(reason, "DLEQ") { t.Errorf("reason %q does not mention DLEQ", reason) } if n := len(pc.TakePayouts(artist)); n != 0 { t.Errorf("stored %d payouts from an unverified swap", n) } }) } } func TestPaymentLostAfterSwapStaysSpent(t *testing.T) { mint := newStubMint(t) mint.garbage = true pc := newChecker(t, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()} tok := token(t, mint.url(), mint.issue(t, 8)) ok, reason := pc.ValidatePayment(tok, meta) if ok || !strings.Contains(reason, "SPENT BUT") { t.Fatalf("want SPENT BUT failure, got ok=%v reason=%q", ok, reason) } // The mint already spent the inputs: the token must stay marked as used. if ok, reason := pc.ValidatePayment(tok, meta); ok || !strings.Contains(reason, "already used") { t.Errorf("retry after lost swap: ok=%v reason=%q, want 'already used'", ok, reason) } } func TestPaymentRejectedSwapCanRetry(t *testing.T) { mint := newStubMint(t) mint.reject = true pc := newChecker(t, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()} tok := token(t, mint.url(), mint.issue(t, 8)) if ok, _ := pc.ValidatePayment(tok, meta); ok { t.Fatal("payment accepted by a rejecting mint") } // Nothing was spent, so the token must not be burned in the replay map. mint.reject = false if ok, reason := pc.ValidatePayment(tok, meta); !ok { t.Errorf("retry after rejected swap failed: %s", reason) } } func TestPaymentGuards(t *testing.T) { mint := newStubMint(t) pc := newChecker(t, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 100, MintURL: mint.url()} t.Run("insufficient amount", func(t *testing.T) { ok, reason := pc.ValidatePayment(token(t, mint.url(), mint.issue(t, 8)), meta) if ok || !strings.Contains(reason, "insufficient") { t.Errorf("ok=%v reason=%q", ok, reason) } }) t.Run("replay", func(t *testing.T) { tok := token(t, mint.url(), mint.issue(t, 128)) if ok, reason := pc.ValidatePayment(tok, meta); !ok { t.Fatalf("first use rejected: %s", reason) } if ok, reason := pc.ValidatePayment(tok, meta); ok || !strings.Contains(reason, "already used") { t.Errorf("replay ok=%v reason=%q", ok, reason) } }) t.Run("garbage token", func(t *testing.T) { if ok, _ := pc.ValidatePayment("cashuBnotatoken", meta); ok { t.Error("garbage token accepted") } }) t.Run("bad artist key refused before swap", func(t *testing.T) { bad := &PaymentMetadata{ArtistPubkey: "npub1artistdemo", MinSats: 8, MintURL: mint.url()} p := mint.issue(t, 8) if ok, _ := pc.ValidatePayment(token(t, mint.url(), p), bad); ok { t.Fatal("payment accepted for an unusable artist key") } mint.mu.Lock() spent := mint.spent[p.Secret] mint.mu.Unlock() if spent { t.Error("listener proofs were spent even though the artist key is invalid") } }) t.Run("plain http remote mint refused", func(t *testing.T) { remote := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: "http://mint.example.com"} if ok, reason := pc.ValidatePayment(token(t, mint.url(), mint.issue(t, 8)), remote); ok || !strings.Contains(reason, "HTTPS") { t.Errorf("ok=%v reason=%q", ok, reason) } }) } // TestUploadStoresFreeMarker covers the free-with-tip path end to end through // the HTTP handlers: X-Min-Sats: 0 must be stored, served without a token, // and a tip must be paid to the artist. func TestUploadStoresFreeMarker(t *testing.T) { mint := newStubMint(t) s, cleanup := testSetup(t) defer cleanup() s.payment = NewPaymentChecker(s.db, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) body := []byte("free track") req := httptest.NewRequest("PUT", "/upload", bytes.NewReader(body)) req.Header.Set("Content-Type", "text/plain") req.Header.Set("X-Artist-Pubkey", artist) req.Header.Set("X-Min-Sats", "0") req.Header.Set("X-Mint-Url", mint.url()) w := httptest.NewRecorder() s.Handler().ServeHTTP(w, req) if w.Code != 200 { t.Fatalf("upload: %d %s", w.Code, w.Body.String()) } var up struct{ Sha256 string } json.Unmarshal(w.Body.Bytes(), &up) meta := s.payment.GetPaymentMetadata(up.Sha256) if meta == nil || meta.MinSats != 0 || meta.ArtistPubkey != artist { t.Fatalf("free marker not stored: %+v", meta) } get := func(tok string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", "/"+up.Sha256, nil) if tok != "" { r.Header.Set("X-Cashu", tok) } rw := httptest.NewRecorder() s.Handler().ServeHTTP(rw, r) return rw } if rw := get(""); rw.Code != 200 || rw.Body.String() != string(body) { t.Fatalf("free GET without token: %d", rw.Code) } if rw := get(token(t, mint.url(), mint.issue(t, 16), mint.issue(t, 4), mint.issue(t, 1))); rw.Code != 200 { t.Fatalf("free GET with tip: %d", rw.Code) } payouts := s.payment.TakePayouts(artist) if len(payouts) != 1 { t.Fatalf("tip not paid to artist: %d payouts", len(payouts)) } decoded, _ := cashu.DecodeToken(payouts[0]) var total uint64 for _, p := range decoded.Proofs() { total += p.Amount } if total != 21 { t.Errorf("artist tip %d sats, want 21", total) } } func TestUploadRejectsNegativeOrBadMinSats(t *testing.T) { mint := newStubMint(t) s, cleanup := testSetup(t) defer cleanup() s.payment = NewPaymentChecker(s.db, mint.url()) artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed()) for _, v := range []string{"-5", "abc"} { body := []byte("blob " + v) req := httptest.NewRequest("PUT", "/upload", bytes.NewReader(body)) req.Header.Set("X-Artist-Pubkey", artist) req.Header.Set("X-Min-Sats", v) w := httptest.NewRecorder() s.Handler().ServeHTTP(w, req) var up struct{ Sha256 string } json.Unmarshal(w.Body.Bytes(), &up) if meta := s.payment.GetPaymentMetadata(up.Sha256); meta != nil { t.Errorf("X-Min-Sats %q stored a marker: %+v", v, meta) } } }