claim_test.go raw

   1  package claim
   2  
   3  import (
   4  	"encoding/hex"
   5  	"encoding/json"
   6  	"errors"
   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 mint with real BDHKE and NUT-12 DLEQ proofs.
  21  type stubMint struct {
  22  	srv     *httptest.Server
  23  	keys    map[uint64]*secp256k1.PrivateKey
  24  	feePpk  uint64
  25  	noDLEQ  bool
  26  	badDLEQ bool
  27  	reject  bool
  28  	garbage bool
  29  
  30  	mu    sync.Mutex
  31  	spent map[string]bool
  32  }
  33  
  34  const stubKeysetID = "00aabbccddeeff00"
  35  
  36  func newStubMint(t *testing.T) *stubMint {
  37  	t.Helper()
  38  	m := &stubMint{keys: map[uint64]*secp256k1.PrivateKey{}, spent: map[string]bool{}}
  39  	for i := 0; i < 16; i++ {
  40  		k, err := secp256k1.GeneratePrivateKey()
  41  		if err != nil {
  42  			t.Fatal(err)
  43  		}
  44  		m.keys[1<<i] = k
  45  	}
  46  	mux := http.NewServeMux()
  47  	mux.HandleFunc("/v1/keysets", func(w http.ResponseWriter, r *http.Request) {
  48  		_ = json.NewEncoder(w).Encode(map[string]any{"keysets": []map[string]any{{
  49  			"id": stubKeysetID, "unit": "sat", "active": true, "input_fee_ppk": m.feePpk,
  50  		}}})
  51  	})
  52  	mux.HandleFunc("/v1/keys/", func(w http.ResponseWriter, r *http.Request) {
  53  		pub := map[string]string{}
  54  		for amt, k := range m.keys {
  55  			pub[fmt.Sprint(amt)] = hex.EncodeToString(k.PubKey().SerializeCompressed())
  56  		}
  57  		_ = json.NewEncoder(w).Encode(map[string]any{"keysets": []map[string]any{{
  58  			"id": stubKeysetID, "unit": "sat", "keys": pub,
  59  		}}})
  60  	})
  61  	mux.HandleFunc("/v1/swap", m.swap)
  62  	m.srv = httptest.NewServer(mux)
  63  	t.Cleanup(m.srv.Close)
  64  	return m
  65  }
  66  
  67  func (m *stubMint) url() string { return m.srv.URL }
  68  
  69  func (m *stubMint) issue(t *testing.T, amount uint64) cashu.Proof {
  70  	t.Helper()
  71  	k, err := secp256k1.GeneratePrivateKey()
  72  	if err != nil {
  73  		t.Fatal(err)
  74  	}
  75  	secret := hex.EncodeToString(k.Serialize())
  76  	Y, err := crypto.HashToCurve([]byte(secret))
  77  	if err != nil {
  78  		t.Fatal(err)
  79  	}
  80  	var yJ, cJ secp256k1.JacobianPoint
  81  	Y.AsJacobian(&yJ)
  82  	secp256k1.ScalarMultNonConst(&m.keys[amount].Key, &yJ, &cJ)
  83  	cJ.ToAffine()
  84  	C := secp256k1.NewPublicKey(&cJ.X, &cJ.Y)
  85  	return cashu.Proof{Amount: amount, Id: stubKeysetID, Secret: secret,
  86  		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  	if m.garbage {
 119  		_, _ = w.Write([]byte("not json"))
 120  		return
 121  	}
 122  	sigs := make(cashu.BlindedSignatures, len(req.Outputs))
 123  	for i, o := range req.Outputs {
 124  		B_, _ := secp256k1.ParsePubKey(mustHex(o.B_))
 125  		C_ := crypto.SignBlindedMessage(B_, m.keys[o.Amount])
 126  		e, s := crypto.GenerateDLEQ(m.keys[o.Amount], B_, C_)
 127  		sig := cashu.BlindedSignature{Amount: o.Amount, Id: o.Id,
 128  			C_: hex.EncodeToString(C_.SerializeCompressed())}
 129  		if !m.noDLEQ {
 130  			if m.badDLEQ {
 131  				s, _ = secp256k1.GeneratePrivateKey()
 132  			}
 133  			sig.DLEQ = &cashu.DLEQProof{
 134  				E: hex.EncodeToString(e.Serialize()),
 135  				S: hex.EncodeToString(s.Serialize()),
 136  			}
 137  		}
 138  		sigs[i] = sig
 139  	}
 140  	_ = json.NewEncoder(w).Encode(nut03.PostSwapResponse{Signatures: sigs})
 141  }
 142  
 143  type memStore struct {
 144  	mu sync.Mutex
 145  	m  map[string][]byte
 146  }
 147  
 148  func (s *memStore) GetMarker(k string) ([]byte, error) {
 149  	s.mu.Lock()
 150  	defer s.mu.Unlock()
 151  	return s.m[k], nil
 152  }
 153  
 154  func (s *memStore) SetMarker(k string, v []byte) error {
 155  	s.mu.Lock()
 156  	defer s.mu.Unlock()
 157  	if s.m == nil {
 158  		s.m = make(map[string][]byte)
 159  	}
 160  	s.m[k] = v
 161  	return nil
 162  }
 163  
 164  func mustHex(s string) []byte {
 165  	b, _ := hex.DecodeString(s)
 166  	return b
 167  }
 168  
 169  func tokenFor(t *testing.T, mint string, proofs ...cashu.Proof) string {
 170  	t.Helper()
 171  	tok, err := cashu.NewTokenV4(proofs, mint, cashu.Sat, false)
 172  	if err != nil {
 173  		t.Fatal(err)
 174  	}
 175  	s, err := tok.Serialize()
 176  	if err != nil {
 177  		t.Fatal(err)
 178  	}
 179  	return s
 180  }
 181  
 182  func TestReceiveOwnsValue(t *testing.T) {
 183  	mint := newStubMint(t)
 184  	store := &memStore{}
 185  	m := New(store, nil)
 186  	tok := tokenFor(t, mint.url(), mint.issue(t, 64), mint.issue(t, 32), mint.issue(t, 4))
 187  
 188  	proofs, err := m.Receive(tok, mint.url(), 100)
 189  	if err != nil {
 190  		t.Fatalf("receive: %v", err)
 191  	}
 192  	if proofs.Amount() != 100 {
 193  		t.Fatalf("received %d, want 100", proofs.Amount())
 194  	}
 195  	if m.Balance(mint.url()) != 100 {
 196  		t.Fatalf("stored balance %d, want 100", m.Balance(mint.url()))
 197  	}
 198  	// Every received proof carries the DLEQ with its blinding factor.
 199  	for _, p := range proofs {
 200  		if p.DLEQ == nil || p.DLEQ.R == "" {
 201  			t.Fatal("received proof has no DLEQ/r")
 202  		}
 203  		if !crypto.Verify(p.Secret, mint.keys[p.Amount], mustPub(t, p.C)) {
 204  			t.Fatal("received proof does not verify against the mint key")
 205  		}
 206  	}
 207  	// Replay is refused locally and would also fail at the mint.
 208  	if _, err = m.Receive(tok, mint.url(), 100); err == nil || !strings.Contains(err.Error(), "already used") {
 209  		t.Fatalf("replay: %v", err)
 210  	}
 211  }
 212  
 213  func TestFeeDeducted(t *testing.T) {
 214  	mint := newStubMint(t)
 215  	mint.feePpk = 1000
 216  	m := New(&memStore{}, nil)
 217  	tok := tokenFor(t, mint.url(), mint.issue(t, 64), mint.issue(t, 2))
 218  	proofs, err := m.Receive(tok, mint.url(), 64)
 219  	if err != nil {
 220  		t.Fatalf("receive: %v", err)
 221  	}
 222  	if proofs.Amount() != 64 {
 223  		t.Fatalf("received %d, want 64 after a 2 sat fee", proofs.Amount())
 224  	}
 225  }
 226  
 227  func TestReceiveLocked(t *testing.T) {
 228  	mint := newStubMint(t)
 229  	m := New(&memStore{}, nil)
 230  	lock, err := secp256k1.GeneratePrivateKey()
 231  	if err != nil {
 232  		t.Fatal(err)
 233  	}
 234  	lockHex := hex.EncodeToString(lock.PubKey().SerializeCompressed())
 235  	tok := tokenFor(t, mint.url(), mint.issue(t, 64))
 236  	proofs, err := m.ReceiveLocked(tok, mint.url(), 64, lockHex)
 237  	if err != nil {
 238  		t.Fatalf("locked receive: %v", err)
 239  	}
 240  	if m.Balance(mint.url()) != 0 {
 241  		t.Fatal("a locked payout must not enter the host balance")
 242  	}
 243  	for _, p := range proofs {
 244  		var parts []json.RawMessage
 245  		if err := json.Unmarshal([]byte(p.Secret), &parts); err != nil {
 246  			t.Fatalf("secret is not NUT-10: %v", err)
 247  		}
 248  		var data struct{ Data string }
 249  		_ = json.Unmarshal(parts[1], &data)
 250  		if !strings.EqualFold(data.Data, lockHex) {
 251  			t.Fatalf("proof locked to %s, want %s", data.Data, lockHex)
 252  		}
 253  	}
 254  }
 255  
 256  func TestMissingDLEQRejected(t *testing.T) {
 257  	mint := newStubMint(t)
 258  	mint.noDLEQ = true
 259  	m := New(&memStore{}, nil)
 260  	tok := tokenFor(t, mint.url(), mint.issue(t, 8))
 261  	if _, err := m.Receive(tok, mint.url(), 8); err == nil ||
 262  		!strings.Contains(err.Error(), "DLEQ") {
 263  		t.Fatalf("missing DLEQ: %v", err)
 264  	}
 265  }
 266  
 267  func TestBadDLEQRejected(t *testing.T) {
 268  	mint := newStubMint(t)
 269  	mint.badDLEQ = true
 270  	m := New(&memStore{}, nil)
 271  	tok := tokenFor(t, mint.url(), mint.issue(t, 8))
 272  	if _, err := m.Receive(tok, mint.url(), 8); err == nil ||
 273  		!strings.Contains(err.Error(), "DLEQ") {
 274  		t.Fatalf("bad DLEQ: %v", err)
 275  	}
 276  }
 277  
 278  func TestPostSwapFailureKeepsTokenSpent(t *testing.T) {
 279  	mint := newStubMint(t)
 280  	mint.garbage = true
 281  	m := New(&memStore{}, nil)
 282  	tok := tokenFor(t, mint.url(), mint.issue(t, 8))
 283  	if _, err := m.Receive(tok, mint.url(), 8); err == nil ||
 284  		!errors.Is(err, ErrSpentAfterSwap) {
 285  		t.Fatalf("want a spent-after-swap error, got %v", err)
 286  	}
 287  	// The inputs are spent, so the replay marker must survive.
 288  	if _, err := m.Receive(tok, mint.url(), 8); err == nil ||
 289  		!strings.Contains(err.Error(), "already used") {
 290  		t.Fatalf("retry after lost swap: %v", err)
 291  	}
 292  }
 293  
 294  func TestRejectedSwapCanRetry(t *testing.T) {
 295  	mint := newStubMint(t)
 296  	mint.reject = true
 297  	m := New(&memStore{}, nil)
 298  	tok := tokenFor(t, mint.url(), mint.issue(t, 8))
 299  	if _, err := m.Receive(tok, mint.url(), 8); err == nil {
 300  		t.Fatal("rejecting mint accepted")
 301  	}
 302  	mint.mu.Lock()
 303  	mint.reject = false
 304  	mint.mu.Unlock()
 305  	if _, err := m.Receive(tok, mint.url(), 8); err != nil {
 306  		t.Fatalf("retry after a rejected swap: %v", err)
 307  	}
 308  }
 309  
 310  func mustPub(t *testing.T, h string) *secp256k1.PublicKey {
 311  	t.Helper()
 312  	p, err := secp256k1.ParsePubKey(mustHex(h))
 313  	if err != nil {
 314  		t.Fatal(err)
 315  	}
 316  	return p
 317  }
 318