// Package claim is the server-side Cashu claim path. // // It does one thing that the prototype did not: after a swap it decodes the // mint's response, unblinds every output with the blinding scalar that created // it, and persists the resulting proofs. The host therefore owns the value it // received instead of merely proving that a token was spent. // // The package is also the seller-side counterpart used by the sales service: // Receive takes a token from a buyer, ForwardP2PK hands the net value to the // seller as a P2PK-locked token. package claim import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "sync" "time" "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/elnosh/gonuts/cashu" "github.com/elnosh/gonuts/cashu/nuts/nut03" "github.com/elnosh/gonuts/crypto" ) // ErrSpentAfterSwap marks a failure that happened after the mint accepted the // swap. The inputs are spent, so the caller must not clear its replay marker or // the value can be double-claimed locally. var ErrSpentAfterSwap = fmt.Errorf("spent after swap") // Store is the minimal persistence surface the claim path needs. It is // satisfied by database.Database. type Store interface { GetMarker(key string) ([]byte, error) SetMarker(key string, value []byte) error } // Minter receives, swaps, forwards, and stores Cashu proofs. type Minter struct { store Store http *http.Client mu sync.Mutex seen map[string]int64 lastPrune time.Time // allowInsecureHTTP permits plain HTTP to a mint on a private network. It // exists for local labs; a public deployment must leave it false. allowInsecureHTTP bool } // SetAllowInsecureHTTP permits a plain-HTTP mint on a private network. Only a // lab should call it; production mints must use HTTPS. func (m *Minter) SetAllowInsecureHTTP(v bool) { m.mu.Lock() m.allowInsecureHTTP = v m.mu.Unlock() } func (m *Minter) insecureAllowed() bool { m.mu.Lock() defer m.mu.Unlock() return m.allowInsecureHTTP } // New creates a Minter. A nil HTTP client gets a 30-second default. func New(store Store, httpClient *http.Client) *Minter { if httpClient == nil { httpClient = &http.Client{Timeout: 30 * time.Second} } return &Minter{ store: store, http: httpClient, seen: make(map[string]int64), lastPrune: time.Now(), } } // storedKey is the marker holding the proofs owned for a mint. func storedKey(mintURL string) string { return "cashu:proofs:" + mintURL } // Receive validates a token, swaps it at the mint, unblinds the result, and // persists the proofs. The token may name its own mint; when it does, that mint // must be the one the caller expects (or the caller passes an empty mint to // accept the token's). func (m *Minter) Receive(tokenStr, acceptedMint string, minSats uint64) (cashu.Proofs, error) { return m.receive(tokenStr, acceptedMint, minSats, "", true) } // ReceiveLocked is Receive with the fresh proofs P2PK-locked to lockPubHex, so // only that key can spend them. It is the artist-payout path: the host proves // and takes custody of the value, then hands the artist a token the host cannot // redeem. The proofs are not added to the host's own balance. func (m *Minter) ReceiveLocked(tokenStr, acceptedMint string, minSats uint64, lockPubHex string) (cashu.Proofs, error) { return m.receive(tokenStr, acceptedMint, minSats, lockPubHex, false) } func (m *Minter) receive(tokenStr, acceptedMint string, minSats uint64, lockPubHex string, persist bool) (cashu.Proofs, error) { tokenHash := sha256.Sum256([]byte(tokenStr)) tokenID := hex.EncodeToString(tokenHash[:]) m.mu.Lock() if _, seen := m.seen[tokenID]; seen { m.mu.Unlock() return nil, fmt.Errorf("token already used") } m.seen[tokenID] = time.Now().Unix() m.pruneLocked() m.mu.Unlock() reject := func(format string, args ...any) (cashu.Proofs, error) { m.mu.Lock() delete(m.seen, tokenID) m.mu.Unlock() return nil, fmt.Errorf(format, args...) } // Validate the configured mint before the token, so a plain-HTTP remote // mint is refused for that reason rather than for a mismatch. if acceptedMint != "" && !strings.HasPrefix(acceptedMint, "https://") && !isLocalMint(acceptedMint) && !m.insecureAllowed() { return reject("mint URL must use HTTPS") } token, err := cashu.DecodeToken(tokenStr) if err != nil { return reject("invalid token: %v", err) } proofs := token.Proofs() if len(proofs) == 0 { return reject("token has no proofs") } if total := proofs.Amount(); total < minSats { return reject("insufficient amount: got %d, need %d", total, minSats) } mintURL := token.Mint() if mintURL == "" { mintURL = acceptedMint } else if acceptedMint != "" && !sameMint(mintURL, acceptedMint) { return reject("token is from mint %s, expected %s", mintURL, acceptedMint) } if mintURL == "" { return reject("token names no mint and no mint was supplied") } received, err := m.Swap(mintURL, proofs, lockPubHex) if err != nil { if errors.Is(err, ErrSpentAfterSwap) { // The inputs are spent; keep the replay marker so a retry cannot // claim a second time from local state. return nil, fmt.Errorf("swap failed: %w", err) } return reject("swap failed: %v", err) } if persist { if err = m.persist(mintURL, received); err != nil { return nil, fmt.Errorf("persist received proofs: %w", err) } } return received, nil } // Swap exchanges proofs for fresh outputs. When lockPubHex is non-empty the new // proofs are locked with a NUT-10 P2PK condition to that public key; the caller // holds the matching secret and can spend them later. func (m *Minter) Swap(mintURL string, proofs cashu.Proofs, lockPubHex string) (cashu.Proofs, error) { if !strings.HasPrefix(mintURL, "https://") && !isLocalMint(mintURL) && !m.insecureAllowed() { return nil, fmt.Errorf("mint URL must use HTTPS") } keysets, err := m.fetchKeysets(mintURL) if err != nil { return nil, err } active := activeSatKeyset(keysets) if active == nil { return nil, fmt.Errorf("no active sat keyset") } // NUT-02 input fees are paid out of the inputs. The mint will reject a swap // whose outputs equal the inputs when a fee applies. fee := uint64(0) for _, p := range proofs { if ks := keysets[p.Id]; ks != nil { fee += ks.InputFeePPK } } fee = (fee + 999) / 1000 total := proofs.Amount() if fee >= total { return nil, fmt.Errorf("payment does not cover the mint input fee") } amounts := cashu.AmountSplit(total - fee) blinded := make(cashu.BlindedMessages, len(amounts)) secrets := make([]string, len(amounts)) rs := make([]*secp256k1.PrivateKey, len(amounts)) for i, amount := range amounts { r, err := secp256k1.GeneratePrivateKey() if err != nil { return nil, fmt.Errorf("generate blinding key: %v", err) } nonce := make([]byte, 16) if _, err = rand.Read(nonce); err != nil { return nil, fmt.Errorf("generate secret nonce: %v", err) } var secret string if lockPubHex != "" { secret = p2pkSecret(hex.EncodeToString(nonce), lockPubHex) } else { secret = hex.EncodeToString(nonce) } B_, _, err := crypto.BlindMessage(secret, r) if err != nil { return nil, fmt.Errorf("blind message: %v", err) } blinded[i] = cashu.BlindedMessage{ Amount: amount, Id: active.ID, B_: hex.EncodeToString(B_.SerializeCompressed()), } secrets[i] = secret rs[i] = r } body, err := json.Marshal(nut03.PostSwapRequest{Inputs: proofs, Outputs: blinded}) if err != nil { return nil, fmt.Errorf("marshal swap request: %v", err) } resp, err := m.http.Post(mintURL+"/v1/swap", "application/json", bytes.NewReader(body)) if err != nil { return nil, fmt.Errorf("swap request failed: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) return nil, fmt.Errorf("swap rejected (status %d): %s", resp.StatusCode, string(b)) } var swapResp nut03.PostSwapResponse if err = json.NewDecoder(resp.Body).Decode(&swapResp); err != nil { return nil, fmt.Errorf("%w: SPENT BUT unreadable swap response: %v", ErrSpentAfterSwap, err) } sigs := swapResp.Signatures if len(sigs) != len(secrets) { return nil, fmt.Errorf("%w: SPENT BUT signature count mismatch: %d vs %d", ErrSpentAfterSwap, len(sigs), len(secrets)) } out := make(cashu.Proofs, len(sigs)) for i, sig := range sigs { ks := keysets[sig.Id] if ks == nil { ks = active } pub, ok := ks.Keys[sig.Amount] if !ok { return nil, fmt.Errorf("%w: SPENT BUT no key for amount %d in keyset %s", ErrSpentAfterSwap, sig.Amount, sig.Id) } C_bytes, err := hex.DecodeString(sig.C_) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT decode C_ for output %d: %v", ErrSpentAfterSwap, i, err) } C_, err := secp256k1.ParsePubKey(C_bytes) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT parse C_ for output %d: %v", ErrSpentAfterSwap, i, err) } // NUT-12: verify the mint's DLEQ proof when it supplies one. A wrong // signature from a malicious mint must not become spendable value here. var dleq *cashu.DLEQProof if sig.DLEQ == nil { return nil, fmt.Errorf("%w: SPENT BUT mint returned no DLEQ proof", ErrSpentAfterSwap) } if sig.DLEQ != nil { eB, err := hex.DecodeString(sig.DLEQ.E) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT decode DLEQ e: %v", ErrSpentAfterSwap, err) } sB, err := hex.DecodeString(sig.DLEQ.S) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT decode DLEQ s: %v", ErrSpentAfterSwap, err) } bBytes, err := hex.DecodeString(blinded[i].B_) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT decode blinded output: %v", ErrSpentAfterSwap, err) } B_, err := secp256k1.ParsePubKey(bBytes) if err != nil { return nil, fmt.Errorf("%w: SPENT BUT parse blinded output: %v", ErrSpentAfterSwap, err) } if !crypto.VerifyDLEQ(secp256k1.PrivKeyFromBytes(eB), secp256k1.PrivKeyFromBytes(sB), pub, B_, C_) { return nil, fmt.Errorf("%w: SPENT BUT mint DLEQ proof failed to verify", ErrSpentAfterSwap) } dleq = &cashu.DLEQProof{ E: sig.DLEQ.E, S: sig.DLEQ.S, R: hex.EncodeToString(rs[i].Serialize()), } } C := crypto.UnblindSignature(C_, rs[i], pub) out[i] = cashu.Proof{ Amount: sig.Amount, Id: sig.Id, Secret: secrets[i], C: hex.EncodeToString(C.SerializeCompressed()), DLEQ: dleq, } } return out, nil } // ForwardP2PK swaps proofs into a P2PK-locked token for the recipient and // returns the serialized token. The recipient spends it with a NUT-11 witness // signature; the sender never needs the recipient's cooperation to create it. func (m *Minter) ForwardP2PK(mintURL string, proofs cashu.Proofs, recipientPubHex string) (string, error) { recipientPubHex = strings.TrimSpace(recipientPubHex) if recipientPubHex == "" { return "", fmt.Errorf("claim: empty recipient pubkey") } locked, err := m.Swap(mintURL, proofs, recipientPubHex) if err != nil { return "", err } token, err := cashu.NewTokenV3(locked, mintURL, cashu.Sat, false) if err != nil { return "", fmt.Errorf("claim: encode token: %v", err) } return token.Serialize() } // p2pkSecret builds the NUT-10 well-known P2PK secret. The format is fixed by // NUT-10, so building it here avoids a dependency on the mint-side nut10 // package. func p2pkSecret(nonce, pubHex string) string { pubHex = strings.TrimSpace(pubHex) // NUT-11 uses the 33-byte compressed key. Nostr x-only keys are 32 bytes, // so add the even-y prefix. if len(pubHex) == 64 { pubHex = "02" + pubHex } return fmt.Sprintf(`["P2PK", {"nonce":"%s","data":"%s","tags":[]}]`, nonce, pubHex) } // StoredProofs returns the proofs this host holds for a mint. func (m *Minter) StoredProofs(mintURL string) cashu.Proofs { data, err := m.store.GetMarker(storedKey(mintURL)) if err != nil || len(data) == 0 { return nil } var proofs cashu.Proofs if err = json.Unmarshal(data, &proofs); err != nil { return nil } return proofs } // Balance returns the total sats held at a mint. func (m *Minter) Balance(mintURL string) uint64 { return m.StoredProofs(mintURL).Amount() } func (m *Minter) persist(mintURL string, proofs cashu.Proofs) error { m.mu.Lock() defer m.mu.Unlock() all := append(m.loadLocked(mintURL), proofs...) b, err := json.Marshal(all) if err != nil { return err } return m.store.SetMarker(storedKey(mintURL), b) } func (m *Minter) loadLocked(mintURL string) cashu.Proofs { data, err := m.store.GetMarker(storedKey(mintURL)) if err != nil || len(data) == 0 { return nil } var proofs cashu.Proofs if err = json.Unmarshal(data, &proofs); err != nil { return nil } return proofs } // pruneLocked drops replay entries older than the mint's own proof lifetime. func (m *Minter) pruneLocked() { if time.Since(m.lastPrune) < 10*time.Minute { return } cutoff := time.Now().Add(-24 * time.Hour).Unix() for id, ts := range m.seen { if ts < cutoff { delete(m.seen, id) } } m.lastPrune = time.Now() } // Prune drops all replay entries older than maxAge. func (m *Minter) Prune(maxAge time.Duration) { cutoff := time.Now().Add(-maxAge).Unix() m.mu.Lock() for id, ts := range m.seen { if ts < cutoff { delete(m.seen, id) } } m.mu.Unlock() } // mintKeyset is the subset of a NUT-01 keyset response the claim path needs. type mintKeyset struct { ID string Unit string Active bool InputFeePPK uint64 Keys map[uint64]*secp256k1.PublicKey } // fetchKeysets merges /v1/keysets (unit, active flag, input fee) with // /v1/keys (the public keys). The fee lives only in the keysets response, so a // single /v1/keys fetch would silently compute a zero fee and produce a swap the // mint rejects as unbalanced. func (m *Minter) fetchKeysets(mintURL string) (map[string]*mintKeyset, error) { out := make(map[string]*mintKeyset) metaResp, err := m.http.Get(mintURL + "/v1/keysets") if err != nil { return nil, fmt.Errorf("get keysets: %v", err) } defer metaResp.Body.Close() if metaResp.StatusCode != http.StatusOK { b, _ := io.ReadAll(io.LimitReader(metaResp.Body, 512)) return nil, fmt.Errorf("keysets endpoint status %d: %s", metaResp.StatusCode, string(b)) } var meta struct { Keysets []struct { ID string `json:"id"` Unit string `json:"unit"` Active bool `json:"active"` InputFeePPK uint64 `json:"input_fee_ppk"` } `json:"keysets"` } if err = json.NewDecoder(metaResp.Body).Decode(&meta); err != nil { return nil, fmt.Errorf("decode keysets: %v", err) } for _, ks := range meta.Keysets { out[ks.ID] = &mintKeyset{ ID: ks.ID, Unit: ks.Unit, Active: ks.Active, InputFeePPK: ks.InputFeePPK, Keys: make(map[uint64]*secp256k1.PublicKey), } } keysResp, err := m.http.Get(mintURL + "/v1/keys") if err != nil { return nil, fmt.Errorf("get keys: %v", err) } defer keysResp.Body.Close() if keysResp.StatusCode != http.StatusOK { b, _ := io.ReadAll(io.LimitReader(keysResp.Body, 512)) return nil, fmt.Errorf("keys endpoint status %d: %s", keysResp.StatusCode, string(b)) } var payload struct { Keysets []struct { ID string `json:"id"` Unit string `json:"unit"` Keys map[string]string `json:"keys"` } `json:"keysets"` } if err = json.NewDecoder(keysResp.Body).Decode(&payload); err != nil { return nil, fmt.Errorf("decode keys: %v", err) } for _, ks := range payload.Keysets { k := out[ks.ID] if k == nil { k = &mintKeyset{ID: ks.ID, Unit: ks.Unit, Keys: make(map[uint64]*secp256k1.PublicKey)} out[ks.ID] = k } for amtStr, pubHex := range ks.Keys { var amt uint64 if _, err = fmt.Sscanf(amtStr, "%d", &amt); err != nil { continue } pb, err := hex.DecodeString(pubHex) if err != nil { continue } pub, err := secp256k1.ParsePubKey(pb) if err != nil { continue } k.Keys[amt] = pub } } return out, nil } func activeSatKeyset(keysets map[string]*mintKeyset) *mintKeyset { for _, ks := range keysets { if ks.Active && ks.Unit == "sat" { return ks } } for _, ks := range keysets { if ks.Unit == "sat" { return ks } } return nil } // InputFee returns the NUT-02 input fee, in the mint's unit, for a proof set. // fee = ceil(sum(input_fee_ppk) / 1000) over the keysets the proofs use. func (m *Minter) InputFee(mintURL string, proofs cashu.Proofs) (uint64, error) { keysets, err := m.fetchKeysets(mintURL) if err != nil { return 0, err } var ppk uint64 for _, p := range proofs { if ks := keysets[p.Id]; ks != nil { ppk += ks.InputFeePPK } } return (ppk + 999) / 1000, nil } func sameMint(a, b string) bool { return strings.EqualFold(strings.TrimRight(a, "/"), strings.TrimRight(b, "/")) } func isLocalMint(mintURL string) bool { return strings.HasPrefix(mintURL, "http://127.0.0.1") || strings.HasPrefix(mintURL, "http://localhost") || strings.HasPrefix(mintURL, "http://[::1]") } // Peek decodes a token without spending it, so a caller can compute the input // fee before it calls Receive. It never mutates the replay set. func (m *Minter) Peek(tokenStr string) (cashu.Proofs, string, error) { token, err := cashu.DecodeToken(tokenStr) if err != nil { return nil, "", fmt.Errorf("claim: decode token: %v", err) } proofs := token.Proofs() if len(proofs) == 0 { return nil, "", fmt.Errorf("claim: token has no proofs") } return proofs, token.Mint(), nil }