payment_test.go raw

   1  package blossom
   2  
   3  import (
   4  	"bytes"
   5  	"encoding/hex"
   6  	"encoding/json"
   7  	"fmt"
   8  	"net/http"
   9  	"net/http/httptest"
  10  	"strings"
  11  	"sync"
  12  	"testing"
  13  
  14  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
  15  	"github.com/elnosh/gonuts/cashu"
  16  	"github.com/elnosh/gonuts/cashu/nuts/nut03"
  17  	"github.com/elnosh/gonuts/crypto"
  18  )
  19  
  20  // stubMint is a minimal Cashu mint for tests. It signs swap outputs with
  21  // real BDHKE and returns NUT-12 DLEQ proofs, so the payment code runs
  22  // against genuine cryptography. Knobs let tests break it on purpose.
  23  type stubMint struct {
  24  	srv     *httptest.Server
  25  	keys    map[uint64]*secp256k1.PrivateKey
  26  	feePpk  uint64
  27  	badDLEQ bool // return a DLEQ proof that does not verify
  28  	noDLEQ  bool // omit DLEQ proofs
  29  	reject  bool // reject swaps with 400
  30  	garbage bool // accept the swap but return an unreadable body
  31  
  32  	mu      sync.Mutex
  33  	spent   map[string]bool
  34  	outputs cashu.BlindedMessages // outputs from the last swap
  35  }
  36  
  37  const stubKeysetID = "00aabbccddeeff00"
  38  
  39  func newStubMint(t *testing.T) *stubMint {
  40  	t.Helper()
  41  	m := &stubMint{keys: map[uint64]*secp256k1.PrivateKey{}, spent: map[string]bool{}}
  42  	for i := 0; i < 16; i++ {
  43  		k, err := secp256k1.GeneratePrivateKey()
  44  		if err != nil {
  45  			t.Fatal(err)
  46  		}
  47  		m.keys[1<<i] = k
  48  	}
  49  	mux := http.NewServeMux()
  50  	mux.HandleFunc("/v1/keysets", func(w http.ResponseWriter, r *http.Request) {
  51  		json.NewEncoder(w).Encode(map[string]any{"keysets": []map[string]any{
  52  			{"id": stubKeysetID, "unit": "sat", "active": true, "input_fee_ppk": m.feePpk},
  53  		}})
  54  	})
  55  	mux.HandleFunc("/v1/keys/", func(w http.ResponseWriter, r *http.Request) {
  56  		pub := map[string]string{}
  57  		for amt, k := range m.keys {
  58  			pub[fmt.Sprint(amt)] = hex.EncodeToString(k.PubKey().SerializeCompressed())
  59  		}
  60  		json.NewEncoder(w).Encode(map[string]any{"keysets": []map[string]any{
  61  			{"id": stubKeysetID, "unit": "sat", "keys": pub},
  62  		}})
  63  	})
  64  	mux.HandleFunc("/v1/swap", m.swap)
  65  	m.srv = httptest.NewServer(mux)
  66  	t.Cleanup(m.srv.Close)
  67  	return m
  68  }
  69  
  70  // url uses 127.0.0.1 so the localhost HTTPS exception applies.
  71  func (m *stubMint) url() string { return m.srv.URL }
  72  
  73  // issue mints a valid unlocked proof of the given power-of-two amount.
  74  func (m *stubMint) issue(t *testing.T, amount uint64) cashu.Proof {
  75  	t.Helper()
  76  	secret := hex.EncodeToString(secp256k1.GenerateSharedSecret(mustKey(t), mustKey(t).PubKey()))
  77  	Y, err := crypto.HashToCurve([]byte(secret))
  78  	if err != nil {
  79  		t.Fatal(err)
  80  	}
  81  	var yJ, cJ secp256k1.JacobianPoint
  82  	Y.AsJacobian(&yJ)
  83  	secp256k1.ScalarMultNonConst(&m.keys[amount].Key, &yJ, &cJ)
  84  	cJ.ToAffine()
  85  	C := secp256k1.NewPublicKey(&cJ.X, &cJ.Y)
  86  	return cashu.Proof{Amount: amount, Id: stubKeysetID, Secret: secret, C: hex.EncodeToString(C.SerializeCompressed())}
  87  }
  88  
  89  func (m *stubMint) swap(w http.ResponseWriter, r *http.Request) {
  90  	var req nut03.PostSwapRequest
  91  	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || m.reject {
  92  		http.Error(w, `{"detail":"rejected"}`, http.StatusBadRequest)
  93  		return
  94  	}
  95  	var in, out uint64
  96  	for _, p := range req.Inputs {
  97  		in += p.Amount
  98  	}
  99  	for _, o := range req.Outputs {
 100  		out += o.Amount
 101  	}
 102  	fee := (m.feePpk*uint64(len(req.Inputs)) + 999) / 1000
 103  	m.mu.Lock()
 104  	defer m.mu.Unlock()
 105  	for _, p := range req.Inputs {
 106  		if m.spent[p.Secret] {
 107  			http.Error(w, `{"detail":"already spent"}`, http.StatusBadRequest)
 108  			return
 109  		}
 110  	}
 111  	if in != out+fee {
 112  		http.Error(w, `{"detail":"unbalanced"}`, http.StatusBadRequest)
 113  		return
 114  	}
 115  	for _, p := range req.Inputs {
 116  		m.spent[p.Secret] = true
 117  	}
 118  	m.outputs = req.Outputs
 119  	if m.garbage {
 120  		w.Write([]byte("not json"))
 121  		return
 122  	}
 123  	sigs := make(cashu.BlindedSignatures, len(req.Outputs))
 124  	for i, o := range req.Outputs {
 125  		k := m.keys[o.Amount]
 126  		B_, _ := secp256k1.ParsePubKey(mustHexT(o.B_))
 127  		C_ := crypto.SignBlindedMessage(B_, k)
 128  		e, s := crypto.GenerateDLEQ(k, B_, C_)
 129  		sig := cashu.BlindedSignature{Amount: o.Amount, Id: o.Id, C_: hex.EncodeToString(C_.SerializeCompressed())}
 130  		if !m.noDLEQ {
 131  			if m.badDLEQ {
 132  				s = mustKeyNoT()
 133  			}
 134  			sig.DLEQ = &cashu.DLEQProof{E: hex.EncodeToString(e.Serialize()), S: hex.EncodeToString(s.Serialize())}
 135  		}
 136  		sigs[i] = sig
 137  	}
 138  	json.NewEncoder(w).Encode(nut03.PostSwapResponse{Signatures: sigs})
 139  }
 140  
 141  func mustKey(t *testing.T) *secp256k1.PrivateKey {
 142  	k, err := secp256k1.GeneratePrivateKey()
 143  	if err != nil {
 144  		t.Fatal(err)
 145  	}
 146  	return k
 147  }
 148  
 149  func mustKeyNoT() *secp256k1.PrivateKey { k, _ := secp256k1.GeneratePrivateKey(); return k }
 150  
 151  func mustHexT(s string) []byte { b, _ := hex.DecodeString(s); return b }
 152  
 153  // token serialises proofs as a cashuB token for the given mint.
 154  func token(t *testing.T, mint string, proofs ...cashu.Proof) string {
 155  	t.Helper()
 156  	tok, err := cashu.NewTokenV4(proofs, mint, cashu.Sat, false)
 157  	if err != nil {
 158  		t.Fatal(err)
 159  	}
 160  	s, err := tok.Serialize()
 161  	if err != nil {
 162  		t.Fatal(err)
 163  	}
 164  	return s
 165  }
 166  
 167  func newChecker(t *testing.T, mint string) *PaymentChecker {
 168  	t.Helper()
 169  	s, cleanup := testSetup(t)
 170  	t.Cleanup(cleanup)
 171  	return NewPaymentChecker(s.db, mint)
 172  }
 173  
 174  // secretLockKey returns the pubkey a NUT-10 P2PK secret is locked to.
 175  func secretLockKey(t *testing.T, secret string) string {
 176  	t.Helper()
 177  	var parts []json.RawMessage
 178  	if err := json.Unmarshal([]byte(secret), &parts); err != nil || len(parts) != 2 {
 179  		t.Fatalf("secret is not a NUT-10 secret: %q", secret)
 180  	}
 181  	var kind string
 182  	json.Unmarshal(parts[0], &kind)
 183  	if kind != "P2PK" {
 184  		t.Fatalf("secret kind %q, want P2PK", kind)
 185  	}
 186  	var data struct{ Data string }
 187  	json.Unmarshal(parts[1], &data)
 188  	return data.Data
 189  }
 190  
 191  func TestArtistLockPubkey(t *testing.T) {
 192  	k := mustKey(t).PubKey()
 193  	comp := hex.EncodeToString(k.SerializeCompressed())
 194  	xonly := comp[2:]
 195  	cases := []struct {
 196  		in, want string
 197  		ok       bool
 198  	}{
 199  		{comp, comp, true},
 200  		{strings.ToUpper(comp), comp, true},
 201  		{xonly, "02" + xonly, true},
 202  		{"npub1artistdemo", "", false},
 203  		{"", "", false},
 204  		{"02" + strings.Repeat("00", 32), "", false}, // not on the curve
 205  	}
 206  	for _, c := range cases {
 207  		got, err := artistLockPubkey(c.in)
 208  		if (err == nil) != c.ok {
 209  			t.Errorf("artistLockPubkey(%q) err=%v, want ok=%v", c.in, err, c.ok)
 210  			continue
 211  		}
 212  		if c.ok && got != c.want {
 213  			t.Errorf("artistLockPubkey(%q)=%q, want %q", c.in, got, c.want)
 214  		}
 215  	}
 216  }
 217  
 218  func TestPaymentLocksProofsToArtist(t *testing.T) {
 219  	mint := newStubMint(t)
 220  	pc := newChecker(t, mint.url())
 221  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 222  	meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 100, MintURL: mint.url()}
 223  
 224  	tok := token(t, mint.url(), mint.issue(t, 64), mint.issue(t, 32), mint.issue(t, 4))
 225  	if ok, reason := pc.ValidatePayment(tok, meta); !ok {
 226  		t.Fatalf("payment rejected: %s", reason)
 227  	}
 228  
 229  	payouts := pc.TakePayouts(artist)
 230  	if len(payouts) != 1 {
 231  		t.Fatalf("want 1 payout token, got %d", len(payouts))
 232  	}
 233  	decoded, err := cashu.DecodeToken(payouts[0])
 234  	if err != nil {
 235  		t.Fatalf("payout is not a valid token: %v", err)
 236  	}
 237  	var total uint64
 238  	for _, p := range decoded.Proofs() {
 239  		total += p.Amount
 240  		if got := secretLockKey(t, p.Secret); got != artist {
 241  			t.Errorf("proof locked to %s, want artist %s", got, artist)
 242  		}
 243  		// Unblinded signature must be valid under the mint key: C == k*hash_to_curve(secret)
 244  		if !crypto.Verify(p.Secret, mint.keys[p.Amount], mustPub(t, p.C)) {
 245  			t.Errorf("proof %d sats does not verify against the mint key", p.Amount)
 246  		}
 247  		if p.DLEQ == nil || p.DLEQ.R == "" {
 248  			t.Errorf("proof missing DLEQ with blinding factor r")
 249  		}
 250  	}
 251  	if total != 100 {
 252  		t.Errorf("artist received %d sats, want 100", total)
 253  	}
 254  	if again := pc.TakePayouts(artist); len(again) != 0 {
 255  		t.Errorf("payouts not cleared after collection: %d left", len(again))
 256  	}
 257  }
 258  
 259  func mustPub(t *testing.T, h string) *secp256k1.PublicKey {
 260  	t.Helper()
 261  	p, err := secp256k1.ParsePubKey(mustHexT(h))
 262  	if err != nil {
 263  		t.Fatal(err)
 264  	}
 265  	return p
 266  }
 267  
 268  func TestPaymentDeductsMintFee(t *testing.T) {
 269  	mint := newStubMint(t)
 270  	mint.feePpk = 1000 // 1 sat per input
 271  	pc := newChecker(t, mint.url())
 272  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 273  	meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 64, MintURL: mint.url()}
 274  
 275  	tok := token(t, mint.url(), mint.issue(t, 64), mint.issue(t, 2)) // 66 in, 2 inputs -> fee 2
 276  	if ok, reason := pc.ValidatePayment(tok, meta); !ok {
 277  		t.Fatalf("payment rejected: %s", reason)
 278  	}
 279  	decoded, _ := cashu.DecodeToken(pc.TakePayouts(artist)[0])
 280  	var total uint64
 281  	for _, p := range decoded.Proofs() {
 282  		total += p.Amount
 283  	}
 284  	if total != 64 {
 285  		t.Errorf("artist received %d sats, want 64 (66 minus 2 fee)", total)
 286  	}
 287  }
 288  
 289  func TestPaymentRejectsBadDLEQ(t *testing.T) {
 290  	for name, set := range map[string]func(*stubMint){
 291  		"forged proof":  func(m *stubMint) { m.badDLEQ = true },
 292  		"missing proof": func(m *stubMint) { m.noDLEQ = true },
 293  	} {
 294  		t.Run(name, func(t *testing.T) {
 295  			mint := newStubMint(t)
 296  			set(mint)
 297  			pc := newChecker(t, mint.url())
 298  			artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 299  			meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()}
 300  			tok := token(t, mint.url(), mint.issue(t, 8))
 301  			ok, reason := pc.ValidatePayment(tok, meta)
 302  			if ok {
 303  				t.Fatal("payment accepted despite bad DLEQ")
 304  			}
 305  			if !strings.Contains(reason, "DLEQ") {
 306  				t.Errorf("reason %q does not mention DLEQ", reason)
 307  			}
 308  			if n := len(pc.TakePayouts(artist)); n != 0 {
 309  				t.Errorf("stored %d payouts from an unverified swap", n)
 310  			}
 311  		})
 312  	}
 313  }
 314  
 315  func TestPaymentLostAfterSwapStaysSpent(t *testing.T) {
 316  	mint := newStubMint(t)
 317  	mint.garbage = true
 318  	pc := newChecker(t, mint.url())
 319  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 320  	meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()}
 321  	tok := token(t, mint.url(), mint.issue(t, 8))
 322  
 323  	ok, reason := pc.ValidatePayment(tok, meta)
 324  	if ok || !strings.Contains(reason, "SPENT BUT") {
 325  		t.Fatalf("want SPENT BUT failure, got ok=%v reason=%q", ok, reason)
 326  	}
 327  	// The mint already spent the inputs: the token must stay marked as used.
 328  	if ok, reason := pc.ValidatePayment(tok, meta); ok || !strings.Contains(reason, "already used") {
 329  		t.Errorf("retry after lost swap: ok=%v reason=%q, want 'already used'", ok, reason)
 330  	}
 331  }
 332  
 333  func TestPaymentRejectedSwapCanRetry(t *testing.T) {
 334  	mint := newStubMint(t)
 335  	mint.reject = true
 336  	pc := newChecker(t, mint.url())
 337  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 338  	meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: mint.url()}
 339  	tok := token(t, mint.url(), mint.issue(t, 8))
 340  
 341  	if ok, _ := pc.ValidatePayment(tok, meta); ok {
 342  		t.Fatal("payment accepted by a rejecting mint")
 343  	}
 344  	// Nothing was spent, so the token must not be burned in the replay map.
 345  	mint.reject = false
 346  	if ok, reason := pc.ValidatePayment(tok, meta); !ok {
 347  		t.Errorf("retry after rejected swap failed: %s", reason)
 348  	}
 349  }
 350  
 351  func TestPaymentGuards(t *testing.T) {
 352  	mint := newStubMint(t)
 353  	pc := newChecker(t, mint.url())
 354  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 355  	meta := &PaymentMetadata{ArtistPubkey: artist, MinSats: 100, MintURL: mint.url()}
 356  
 357  	t.Run("insufficient amount", func(t *testing.T) {
 358  		ok, reason := pc.ValidatePayment(token(t, mint.url(), mint.issue(t, 8)), meta)
 359  		if ok || !strings.Contains(reason, "insufficient") {
 360  			t.Errorf("ok=%v reason=%q", ok, reason)
 361  		}
 362  	})
 363  	t.Run("replay", func(t *testing.T) {
 364  		tok := token(t, mint.url(), mint.issue(t, 128))
 365  		if ok, reason := pc.ValidatePayment(tok, meta); !ok {
 366  			t.Fatalf("first use rejected: %s", reason)
 367  		}
 368  		if ok, reason := pc.ValidatePayment(tok, meta); ok || !strings.Contains(reason, "already used") {
 369  			t.Errorf("replay ok=%v reason=%q", ok, reason)
 370  		}
 371  	})
 372  	t.Run("garbage token", func(t *testing.T) {
 373  		if ok, _ := pc.ValidatePayment("cashuBnotatoken", meta); ok {
 374  			t.Error("garbage token accepted")
 375  		}
 376  	})
 377  	t.Run("bad artist key refused before swap", func(t *testing.T) {
 378  		bad := &PaymentMetadata{ArtistPubkey: "npub1artistdemo", MinSats: 8, MintURL: mint.url()}
 379  		p := mint.issue(t, 8)
 380  		if ok, _ := pc.ValidatePayment(token(t, mint.url(), p), bad); ok {
 381  			t.Fatal("payment accepted for an unusable artist key")
 382  		}
 383  		mint.mu.Lock()
 384  		spent := mint.spent[p.Secret]
 385  		mint.mu.Unlock()
 386  		if spent {
 387  			t.Error("listener proofs were spent even though the artist key is invalid")
 388  		}
 389  	})
 390  	t.Run("plain http remote mint refused", func(t *testing.T) {
 391  		remote := &PaymentMetadata{ArtistPubkey: artist, MinSats: 8, MintURL: "http://mint.example.com"}
 392  		if ok, reason := pc.ValidatePayment(token(t, mint.url(), mint.issue(t, 8)), remote); ok || !strings.Contains(reason, "HTTPS") {
 393  			t.Errorf("ok=%v reason=%q", ok, reason)
 394  		}
 395  	})
 396  }
 397  
 398  // TestUploadStoresFreeMarker covers the free-with-tip path end to end through
 399  // the HTTP handlers: X-Min-Sats: 0 must be stored, served without a token,
 400  // and a tip must be paid to the artist.
 401  func TestUploadStoresFreeMarker(t *testing.T) {
 402  	mint := newStubMint(t)
 403  	s, cleanup := testSetup(t)
 404  	defer cleanup()
 405  	s.payment = NewPaymentChecker(s.db, mint.url())
 406  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 407  
 408  	body := []byte("free track")
 409  	req := httptest.NewRequest("PUT", "/upload", bytes.NewReader(body))
 410  	req.Header.Set("Content-Type", "text/plain")
 411  	req.Header.Set("X-Artist-Pubkey", artist)
 412  	req.Header.Set("X-Min-Sats", "0")
 413  	req.Header.Set("X-Mint-Url", mint.url())
 414  	w := httptest.NewRecorder()
 415  	s.Handler().ServeHTTP(w, req)
 416  	if w.Code != 200 {
 417  		t.Fatalf("upload: %d %s", w.Code, w.Body.String())
 418  	}
 419  	var up struct{ Sha256 string }
 420  	json.Unmarshal(w.Body.Bytes(), &up)
 421  
 422  	meta := s.payment.GetPaymentMetadata(up.Sha256)
 423  	if meta == nil || meta.MinSats != 0 || meta.ArtistPubkey != artist {
 424  		t.Fatalf("free marker not stored: %+v", meta)
 425  	}
 426  
 427  	get := func(tok string) *httptest.ResponseRecorder {
 428  		r := httptest.NewRequest("GET", "/"+up.Sha256, nil)
 429  		if tok != "" {
 430  			r.Header.Set("X-Cashu", tok)
 431  		}
 432  		rw := httptest.NewRecorder()
 433  		s.Handler().ServeHTTP(rw, r)
 434  		return rw
 435  	}
 436  	if rw := get(""); rw.Code != 200 || rw.Body.String() != string(body) {
 437  		t.Fatalf("free GET without token: %d", rw.Code)
 438  	}
 439  	if rw := get(token(t, mint.url(), mint.issue(t, 16), mint.issue(t, 4), mint.issue(t, 1))); rw.Code != 200 {
 440  		t.Fatalf("free GET with tip: %d", rw.Code)
 441  	}
 442  	payouts := s.payment.TakePayouts(artist)
 443  	if len(payouts) != 1 {
 444  		t.Fatalf("tip not paid to artist: %d payouts", len(payouts))
 445  	}
 446  	decoded, _ := cashu.DecodeToken(payouts[0])
 447  	var total uint64
 448  	for _, p := range decoded.Proofs() {
 449  		total += p.Amount
 450  	}
 451  	if total != 21 {
 452  		t.Errorf("artist tip %d sats, want 21", total)
 453  	}
 454  }
 455  
 456  func TestUploadRejectsNegativeOrBadMinSats(t *testing.T) {
 457  	mint := newStubMint(t)
 458  	s, cleanup := testSetup(t)
 459  	defer cleanup()
 460  	s.payment = NewPaymentChecker(s.db, mint.url())
 461  	artist := hex.EncodeToString(mustKey(t).PubKey().SerializeCompressed())
 462  	for _, v := range []string{"-5", "abc"} {
 463  		body := []byte("blob " + v)
 464  		req := httptest.NewRequest("PUT", "/upload", bytes.NewReader(body))
 465  		req.Header.Set("X-Artist-Pubkey", artist)
 466  		req.Header.Set("X-Min-Sats", v)
 467  		w := httptest.NewRecorder()
 468  		s.Handler().ServeHTTP(w, req)
 469  		var up struct{ Sha256 string }
 470  		json.Unmarshal(w.Body.Bytes(), &up)
 471  		if meta := s.payment.GetPaymentMetadata(up.Sha256); meta != nil {
 472  			t.Errorf("X-Min-Sats %q stored a marker: %+v", v, meta)
 473  		}
 474  	}
 475  }
 476