claim.go raw
1 // Package claim is the server-side Cashu claim path.
2 //
3 // It does one thing that the prototype did not: after a swap it decodes the
4 // mint's response, unblinds every output with the blinding scalar that created
5 // it, and persists the resulting proofs. The host therefore owns the value it
6 // received instead of merely proving that a token was spent.
7 //
8 // The package is also the seller-side counterpart used by the sales service:
9 // Receive takes a token from a buyer, ForwardP2PK hands the net value to the
10 // seller as a P2PK-locked token.
11 package claim
12
13 import (
14 "bytes"
15 "crypto/rand"
16 "crypto/sha256"
17 "encoding/hex"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "io"
22 "net/http"
23 "strings"
24 "sync"
25 "time"
26
27 "github.com/decred/dcrd/dcrec/secp256k1/v4"
28 "github.com/elnosh/gonuts/cashu"
29 "github.com/elnosh/gonuts/cashu/nuts/nut03"
30 "github.com/elnosh/gonuts/crypto"
31 )
32
33 // ErrSpentAfterSwap marks a failure that happened after the mint accepted the
34 // swap. The inputs are spent, so the caller must not clear its replay marker or
35 // the value can be double-claimed locally.
36 var ErrSpentAfterSwap = fmt.Errorf("spent after swap")
37
38 // Store is the minimal persistence surface the claim path needs. It is
39 // satisfied by database.Database.
40 type Store interface {
41 GetMarker(key string) ([]byte, error)
42 SetMarker(key string, value []byte) error
43 }
44
45 // Minter receives, swaps, forwards, and stores Cashu proofs.
46 type Minter struct {
47 store Store
48 http *http.Client
49
50 mu sync.Mutex
51 seen map[string]int64
52 lastPrune time.Time
53 // allowInsecureHTTP permits plain HTTP to a mint on a private network. It
54 // exists for local labs; a public deployment must leave it false.
55 allowInsecureHTTP bool
56 }
57
58 // SetAllowInsecureHTTP permits a plain-HTTP mint on a private network. Only a
59 // lab should call it; production mints must use HTTPS.
60 func (m *Minter) SetAllowInsecureHTTP(v bool) {
61 m.mu.Lock()
62 m.allowInsecureHTTP = v
63 m.mu.Unlock()
64 }
65
66 func (m *Minter) insecureAllowed() bool {
67 m.mu.Lock()
68 defer m.mu.Unlock()
69 return m.allowInsecureHTTP
70 }
71
72 // New creates a Minter. A nil HTTP client gets a 30-second default.
73 func New(store Store, httpClient *http.Client) *Minter {
74 if httpClient == nil {
75 httpClient = &http.Client{Timeout: 30 * time.Second}
76 }
77 return &Minter{
78 store: store,
79 http: httpClient,
80 seen: make(map[string]int64),
81 lastPrune: time.Now(),
82 }
83 }
84
85 // storedKey is the marker holding the proofs owned for a mint.
86 func storedKey(mintURL string) string { return "cashu:proofs:" + mintURL }
87
88 // Receive validates a token, swaps it at the mint, unblinds the result, and
89 // persists the proofs. The token may name its own mint; when it does, that mint
90 // must be the one the caller expects (or the caller passes an empty mint to
91 // accept the token's).
92 func (m *Minter) Receive(tokenStr, acceptedMint string, minSats uint64) (cashu.Proofs, error) {
93 return m.receive(tokenStr, acceptedMint, minSats, "", true)
94 }
95
96 // ReceiveLocked is Receive with the fresh proofs P2PK-locked to lockPubHex, so
97 // only that key can spend them. It is the artist-payout path: the host proves
98 // and takes custody of the value, then hands the artist a token the host cannot
99 // redeem. The proofs are not added to the host's own balance.
100 func (m *Minter) ReceiveLocked(tokenStr, acceptedMint string, minSats uint64, lockPubHex string) (cashu.Proofs, error) {
101 return m.receive(tokenStr, acceptedMint, minSats, lockPubHex, false)
102 }
103
104 func (m *Minter) receive(tokenStr, acceptedMint string, minSats uint64, lockPubHex string, persist bool) (cashu.Proofs, error) {
105 tokenHash := sha256.Sum256([]byte(tokenStr))
106 tokenID := hex.EncodeToString(tokenHash[:])
107
108 m.mu.Lock()
109 if _, seen := m.seen[tokenID]; seen {
110 m.mu.Unlock()
111 return nil, fmt.Errorf("token already used")
112 }
113 m.seen[tokenID] = time.Now().Unix()
114 m.pruneLocked()
115 m.mu.Unlock()
116
117 reject := func(format string, args ...any) (cashu.Proofs, error) {
118 m.mu.Lock()
119 delete(m.seen, tokenID)
120 m.mu.Unlock()
121 return nil, fmt.Errorf(format, args...)
122 }
123
124 // Validate the configured mint before the token, so a plain-HTTP remote
125 // mint is refused for that reason rather than for a mismatch.
126 if acceptedMint != "" && !strings.HasPrefix(acceptedMint, "https://") &&
127 !isLocalMint(acceptedMint) && !m.insecureAllowed() {
128 return reject("mint URL must use HTTPS")
129 }
130
131 token, err := cashu.DecodeToken(tokenStr)
132 if err != nil {
133 return reject("invalid token: %v", err)
134 }
135 proofs := token.Proofs()
136 if len(proofs) == 0 {
137 return reject("token has no proofs")
138 }
139 if total := proofs.Amount(); total < minSats {
140 return reject("insufficient amount: got %d, need %d", total, minSats)
141 }
142 mintURL := token.Mint()
143 if mintURL == "" {
144 mintURL = acceptedMint
145 } else if acceptedMint != "" && !sameMint(mintURL, acceptedMint) {
146 return reject("token is from mint %s, expected %s", mintURL, acceptedMint)
147 }
148 if mintURL == "" {
149 return reject("token names no mint and no mint was supplied")
150 }
151
152 received, err := m.Swap(mintURL, proofs, lockPubHex)
153 if err != nil {
154 if errors.Is(err, ErrSpentAfterSwap) {
155 // The inputs are spent; keep the replay marker so a retry cannot
156 // claim a second time from local state.
157 return nil, fmt.Errorf("swap failed: %w", err)
158 }
159 return reject("swap failed: %v", err)
160 }
161 if persist {
162 if err = m.persist(mintURL, received); err != nil {
163 return nil, fmt.Errorf("persist received proofs: %w", err)
164 }
165 }
166 return received, nil
167 }
168
169 // Swap exchanges proofs for fresh outputs. When lockPubHex is non-empty the new
170 // proofs are locked with a NUT-10 P2PK condition to that public key; the caller
171 // holds the matching secret and can spend them later.
172 func (m *Minter) Swap(mintURL string, proofs cashu.Proofs, lockPubHex string) (cashu.Proofs, error) {
173 if !strings.HasPrefix(mintURL, "https://") && !isLocalMint(mintURL) && !m.insecureAllowed() {
174 return nil, fmt.Errorf("mint URL must use HTTPS")
175 }
176 keysets, err := m.fetchKeysets(mintURL)
177 if err != nil {
178 return nil, err
179 }
180 active := activeSatKeyset(keysets)
181 if active == nil {
182 return nil, fmt.Errorf("no active sat keyset")
183 }
184
185 // NUT-02 input fees are paid out of the inputs. The mint will reject a swap
186 // whose outputs equal the inputs when a fee applies.
187 fee := uint64(0)
188 for _, p := range proofs {
189 if ks := keysets[p.Id]; ks != nil {
190 fee += ks.InputFeePPK
191 }
192 }
193 fee = (fee + 999) / 1000
194 total := proofs.Amount()
195 if fee >= total {
196 return nil, fmt.Errorf("payment does not cover the mint input fee")
197 }
198 amounts := cashu.AmountSplit(total - fee)
199 blinded := make(cashu.BlindedMessages, len(amounts))
200 secrets := make([]string, len(amounts))
201 rs := make([]*secp256k1.PrivateKey, len(amounts))
202
203 for i, amount := range amounts {
204 r, err := secp256k1.GeneratePrivateKey()
205 if err != nil {
206 return nil, fmt.Errorf("generate blinding key: %v", err)
207 }
208 nonce := make([]byte, 16)
209 if _, err = rand.Read(nonce); err != nil {
210 return nil, fmt.Errorf("generate secret nonce: %v", err)
211 }
212 var secret string
213 if lockPubHex != "" {
214 secret = p2pkSecret(hex.EncodeToString(nonce), lockPubHex)
215 } else {
216 secret = hex.EncodeToString(nonce)
217 }
218 B_, _, err := crypto.BlindMessage(secret, r)
219 if err != nil {
220 return nil, fmt.Errorf("blind message: %v", err)
221 }
222 blinded[i] = cashu.BlindedMessage{
223 Amount: amount,
224 Id: active.ID,
225 B_: hex.EncodeToString(B_.SerializeCompressed()),
226 }
227 secrets[i] = secret
228 rs[i] = r
229 }
230
231 body, err := json.Marshal(nut03.PostSwapRequest{Inputs: proofs, Outputs: blinded})
232 if err != nil {
233 return nil, fmt.Errorf("marshal swap request: %v", err)
234 }
235 resp, err := m.http.Post(mintURL+"/v1/swap", "application/json", bytes.NewReader(body))
236 if err != nil {
237 return nil, fmt.Errorf("swap request failed: %v", err)
238 }
239 defer resp.Body.Close()
240 if resp.StatusCode != http.StatusOK {
241 b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
242 return nil, fmt.Errorf("swap rejected (status %d): %s", resp.StatusCode, string(b))
243 }
244 var swapResp nut03.PostSwapResponse
245 if err = json.NewDecoder(resp.Body).Decode(&swapResp); err != nil {
246 return nil, fmt.Errorf("%w: SPENT BUT unreadable swap response: %v", ErrSpentAfterSwap, err)
247 }
248 sigs := swapResp.Signatures
249 if len(sigs) != len(secrets) {
250 return nil, fmt.Errorf("%w: SPENT BUT signature count mismatch: %d vs %d", ErrSpentAfterSwap, len(sigs), len(secrets))
251 }
252
253 out := make(cashu.Proofs, len(sigs))
254 for i, sig := range sigs {
255 ks := keysets[sig.Id]
256 if ks == nil {
257 ks = active
258 }
259 pub, ok := ks.Keys[sig.Amount]
260 if !ok {
261 return nil, fmt.Errorf("%w: SPENT BUT no key for amount %d in keyset %s", ErrSpentAfterSwap, sig.Amount, sig.Id)
262 }
263 C_bytes, err := hex.DecodeString(sig.C_)
264 if err != nil {
265 return nil, fmt.Errorf("%w: SPENT BUT decode C_ for output %d: %v", ErrSpentAfterSwap, i, err)
266 }
267 C_, err := secp256k1.ParsePubKey(C_bytes)
268 if err != nil {
269 return nil, fmt.Errorf("%w: SPENT BUT parse C_ for output %d: %v", ErrSpentAfterSwap, i, err)
270 }
271 // NUT-12: verify the mint's DLEQ proof when it supplies one. A wrong
272 // signature from a malicious mint must not become spendable value here.
273 var dleq *cashu.DLEQProof
274 if sig.DLEQ == nil {
275 return nil, fmt.Errorf("%w: SPENT BUT mint returned no DLEQ proof", ErrSpentAfterSwap)
276 }
277 if sig.DLEQ != nil {
278 eB, err := hex.DecodeString(sig.DLEQ.E)
279 if err != nil {
280 return nil, fmt.Errorf("%w: SPENT BUT decode DLEQ e: %v", ErrSpentAfterSwap, err)
281 }
282 sB, err := hex.DecodeString(sig.DLEQ.S)
283 if err != nil {
284 return nil, fmt.Errorf("%w: SPENT BUT decode DLEQ s: %v", ErrSpentAfterSwap, err)
285 }
286 bBytes, err := hex.DecodeString(blinded[i].B_)
287 if err != nil {
288 return nil, fmt.Errorf("%w: SPENT BUT decode blinded output: %v", ErrSpentAfterSwap, err)
289 }
290 B_, err := secp256k1.ParsePubKey(bBytes)
291 if err != nil {
292 return nil, fmt.Errorf("%w: SPENT BUT parse blinded output: %v", ErrSpentAfterSwap, err)
293 }
294 if !crypto.VerifyDLEQ(secp256k1.PrivKeyFromBytes(eB), secp256k1.PrivKeyFromBytes(sB), pub, B_, C_) {
295 return nil, fmt.Errorf("%w: SPENT BUT mint DLEQ proof failed to verify", ErrSpentAfterSwap)
296 }
297 dleq = &cashu.DLEQProof{
298 E: sig.DLEQ.E,
299 S: sig.DLEQ.S,
300 R: hex.EncodeToString(rs[i].Serialize()),
301 }
302 }
303 C := crypto.UnblindSignature(C_, rs[i], pub)
304 out[i] = cashu.Proof{
305 Amount: sig.Amount,
306 Id: sig.Id,
307 Secret: secrets[i],
308 C: hex.EncodeToString(C.SerializeCompressed()),
309 DLEQ: dleq,
310 }
311 }
312 return out, nil
313 }
314
315 // ForwardP2PK swaps proofs into a P2PK-locked token for the recipient and
316 // returns the serialized token. The recipient spends it with a NUT-11 witness
317 // signature; the sender never needs the recipient's cooperation to create it.
318 func (m *Minter) ForwardP2PK(mintURL string, proofs cashu.Proofs, recipientPubHex string) (string, error) {
319 recipientPubHex = strings.TrimSpace(recipientPubHex)
320 if recipientPubHex == "" {
321 return "", fmt.Errorf("claim: empty recipient pubkey")
322 }
323 locked, err := m.Swap(mintURL, proofs, recipientPubHex)
324 if err != nil {
325 return "", err
326 }
327 token, err := cashu.NewTokenV3(locked, mintURL, cashu.Sat, false)
328 if err != nil {
329 return "", fmt.Errorf("claim: encode token: %v", err)
330 }
331 return token.Serialize()
332 }
333
334 // p2pkSecret builds the NUT-10 well-known P2PK secret. The format is fixed by
335 // NUT-10, so building it here avoids a dependency on the mint-side nut10
336 // package.
337 func p2pkSecret(nonce, pubHex string) string {
338 pubHex = strings.TrimSpace(pubHex)
339 // NUT-11 uses the 33-byte compressed key. Nostr x-only keys are 32 bytes,
340 // so add the even-y prefix.
341 if len(pubHex) == 64 {
342 pubHex = "02" + pubHex
343 }
344 return fmt.Sprintf(`["P2PK", {"nonce":"%s","data":"%s","tags":[]}]`, nonce, pubHex)
345 }
346
347 // StoredProofs returns the proofs this host holds for a mint.
348 func (m *Minter) StoredProofs(mintURL string) cashu.Proofs {
349 data, err := m.store.GetMarker(storedKey(mintURL))
350 if err != nil || len(data) == 0 {
351 return nil
352 }
353 var proofs cashu.Proofs
354 if err = json.Unmarshal(data, &proofs); err != nil {
355 return nil
356 }
357 return proofs
358 }
359
360 // Balance returns the total sats held at a mint.
361 func (m *Minter) Balance(mintURL string) uint64 { return m.StoredProofs(mintURL).Amount() }
362
363 func (m *Minter) persist(mintURL string, proofs cashu.Proofs) error {
364 m.mu.Lock()
365 defer m.mu.Unlock()
366 all := append(m.loadLocked(mintURL), proofs...)
367 b, err := json.Marshal(all)
368 if err != nil {
369 return err
370 }
371 return m.store.SetMarker(storedKey(mintURL), b)
372 }
373
374 func (m *Minter) loadLocked(mintURL string) cashu.Proofs {
375 data, err := m.store.GetMarker(storedKey(mintURL))
376 if err != nil || len(data) == 0 {
377 return nil
378 }
379 var proofs cashu.Proofs
380 if err = json.Unmarshal(data, &proofs); err != nil {
381 return nil
382 }
383 return proofs
384 }
385
386 // pruneLocked drops replay entries older than the mint's own proof lifetime.
387 func (m *Minter) pruneLocked() {
388 if time.Since(m.lastPrune) < 10*time.Minute {
389 return
390 }
391 cutoff := time.Now().Add(-24 * time.Hour).Unix()
392 for id, ts := range m.seen {
393 if ts < cutoff {
394 delete(m.seen, id)
395 }
396 }
397 m.lastPrune = time.Now()
398 }
399
400 // Prune drops all replay entries older than maxAge.
401 func (m *Minter) Prune(maxAge time.Duration) {
402 cutoff := time.Now().Add(-maxAge).Unix()
403 m.mu.Lock()
404 for id, ts := range m.seen {
405 if ts < cutoff {
406 delete(m.seen, id)
407 }
408 }
409 m.mu.Unlock()
410 }
411
412 // mintKeyset is the subset of a NUT-01 keyset response the claim path needs.
413 type mintKeyset struct {
414 ID string
415 Unit string
416 Active bool
417 InputFeePPK uint64
418 Keys map[uint64]*secp256k1.PublicKey
419 }
420
421 // fetchKeysets merges /v1/keysets (unit, active flag, input fee) with
422 // /v1/keys (the public keys). The fee lives only in the keysets response, so a
423 // single /v1/keys fetch would silently compute a zero fee and produce a swap the
424 // mint rejects as unbalanced.
425 func (m *Minter) fetchKeysets(mintURL string) (map[string]*mintKeyset, error) {
426 out := make(map[string]*mintKeyset)
427
428 metaResp, err := m.http.Get(mintURL + "/v1/keysets")
429 if err != nil {
430 return nil, fmt.Errorf("get keysets: %v", err)
431 }
432 defer metaResp.Body.Close()
433 if metaResp.StatusCode != http.StatusOK {
434 b, _ := io.ReadAll(io.LimitReader(metaResp.Body, 512))
435 return nil, fmt.Errorf("keysets endpoint status %d: %s", metaResp.StatusCode, string(b))
436 }
437 var meta struct {
438 Keysets []struct {
439 ID string `json:"id"`
440 Unit string `json:"unit"`
441 Active bool `json:"active"`
442 InputFeePPK uint64 `json:"input_fee_ppk"`
443 } `json:"keysets"`
444 }
445 if err = json.NewDecoder(metaResp.Body).Decode(&meta); err != nil {
446 return nil, fmt.Errorf("decode keysets: %v", err)
447 }
448 for _, ks := range meta.Keysets {
449 out[ks.ID] = &mintKeyset{
450 ID: ks.ID, Unit: ks.Unit, Active: ks.Active,
451 InputFeePPK: ks.InputFeePPK,
452 Keys: make(map[uint64]*secp256k1.PublicKey),
453 }
454 }
455
456 keysResp, err := m.http.Get(mintURL + "/v1/keys")
457 if err != nil {
458 return nil, fmt.Errorf("get keys: %v", err)
459 }
460 defer keysResp.Body.Close()
461 if keysResp.StatusCode != http.StatusOK {
462 b, _ := io.ReadAll(io.LimitReader(keysResp.Body, 512))
463 return nil, fmt.Errorf("keys endpoint status %d: %s", keysResp.StatusCode, string(b))
464 }
465 var payload struct {
466 Keysets []struct {
467 ID string `json:"id"`
468 Unit string `json:"unit"`
469 Keys map[string]string `json:"keys"`
470 } `json:"keysets"`
471 }
472 if err = json.NewDecoder(keysResp.Body).Decode(&payload); err != nil {
473 return nil, fmt.Errorf("decode keys: %v", err)
474 }
475 for _, ks := range payload.Keysets {
476 k := out[ks.ID]
477 if k == nil {
478 k = &mintKeyset{ID: ks.ID, Unit: ks.Unit,
479 Keys: make(map[uint64]*secp256k1.PublicKey)}
480 out[ks.ID] = k
481 }
482 for amtStr, pubHex := range ks.Keys {
483 var amt uint64
484 if _, err = fmt.Sscanf(amtStr, "%d", &amt); err != nil {
485 continue
486 }
487 pb, err := hex.DecodeString(pubHex)
488 if err != nil {
489 continue
490 }
491 pub, err := secp256k1.ParsePubKey(pb)
492 if err != nil {
493 continue
494 }
495 k.Keys[amt] = pub
496 }
497 }
498 return out, nil
499 }
500
501 func activeSatKeyset(keysets map[string]*mintKeyset) *mintKeyset {
502 for _, ks := range keysets {
503 if ks.Active && ks.Unit == "sat" {
504 return ks
505 }
506 }
507 for _, ks := range keysets {
508 if ks.Unit == "sat" {
509 return ks
510 }
511 }
512 return nil
513 }
514
515 // InputFee returns the NUT-02 input fee, in the mint's unit, for a proof set.
516 // fee = ceil(sum(input_fee_ppk) / 1000) over the keysets the proofs use.
517 func (m *Minter) InputFee(mintURL string, proofs cashu.Proofs) (uint64, error) {
518 keysets, err := m.fetchKeysets(mintURL)
519 if err != nil {
520 return 0, err
521 }
522 var ppk uint64
523 for _, p := range proofs {
524 if ks := keysets[p.Id]; ks != nil {
525 ppk += ks.InputFeePPK
526 }
527 }
528 return (ppk + 999) / 1000, nil
529 }
530
531 func sameMint(a, b string) bool {
532 return strings.EqualFold(strings.TrimRight(a, "/"), strings.TrimRight(b, "/"))
533 }
534
535 func isLocalMint(mintURL string) bool {
536 return strings.HasPrefix(mintURL, "http://127.0.0.1") ||
537 strings.HasPrefix(mintURL, "http://localhost") ||
538 strings.HasPrefix(mintURL, "http://[::1]")
539 }
540
541 // Peek decodes a token without spending it, so a caller can compute the input
542 // fee before it calls Receive. It never mutates the replay set.
543 func (m *Minter) Peek(tokenStr string) (cashu.Proofs, string, error) {
544 token, err := cashu.DecodeToken(tokenStr)
545 if err != nil {
546 return nil, "", fmt.Errorf("claim: decode token: %v", err)
547 }
548 proofs := token.Proofs()
549 if len(proofs) == 0 {
550 return nil, "", fmt.Errorf("claim: token has no proofs")
551 }
552 return proofs, token.Mint(), nil
553 }
554