"""Cashu as it crosses the wire, standard library only. The portable half
of a node's e-cash: a second implementation needs exactly this and nothing
of the rails that move money.
BDHKE (NUT-00..03) over secp256k1: hash_to_curve, blind, sign, unblind,
verify a proof. Pinned to the NUT-00 vectors in vectors/cashu.json.
Tokens: V3 (`cashuA`, JSON) and V4 (`cashuB`, CBOR); NUT-18 payment
requests (`creqA`); NUT-11 P2PK secrets.
NIP-61 Nutzaps (kind 9321): create, read the proofs, reconcile the stated
amount against what the proofs are worth, and the one proof-acceptance
policy (mint key, else a verifier that asks the mint, else refuse).
The curve arithmetic is fleetmesh_core.crypto's; a node that installed a
faster point_mul (meshnode's node/curve.py) speeds this up too, since every
multiplication goes through crypto.point_mul. Nothing here talks to a mint
or keeps state; every parse error is a ValueError with a reason a 402 body
can carry. `mint_url` is normalised by stripping trailing slashes, which
NUT-00 requires of a V4 token and which makes an allowlist comparison a
string equality.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import time
from typing import Any, Callable, Mapping, Optional, Sequence, TypedDict, cast
from ..crypto import crypto
from ..storage import store
from ..wire.cbor import CBORError, cbor_decode, cbor_encode
from ..wire.interfaces import NostrEvent
NUTZAP_KIND: int = 9321
[docs]class CashuProof(TypedDict, total=False):
"""One NUT-00 proof as it arrives in a token or a Nutzap's proof tag.
Annotations only: the mint's keyset is what makes it worth anything."""
id: str
amount: int
secret: str
C: str
witness: Optional[str]
[docs]class CashuTokenEntry(TypedDict):
mint: str
proofs: list[CashuProof]
[docs]class CashuToken(TypedDict, total=False):
token: list[CashuTokenEntry]
memo: Optional[str]
unit: Optional[str]
[docs]class DecodedTokenV4(TypedDict, total=False):
mint: str
unit: str
memo: Optional[str]
proofs: list[CashuProof]
[docs]class BlindedMessage(TypedDict, total=False):
amount: int
id: str
B_: str
[docs]class BlindSignature(TypedDict, total=False):
amount: int
id: str
C_: str
dleq: Optional[dict[str, str]]
[docs]class ProofState(TypedDict, total=False):
Y: str
state: str
witness: Optional[str]
[docs]class CborProofEntry(TypedDict, total=False):
a: int
s: str
c: bytes
w: str
[docs]class CheckStateResult(TypedDict, total=False):
states: list[ProofState]
[docs]class MintQuoteResult(TypedDict, total=False):
quote: str
request: str
state: str
expiry: int
[docs]class MeltQuoteResult(TypedDict, total=False):
quote: str
amount: int
fee_reserve: int
state: str
expiry: int
payment_preimage: Optional[str]
[docs]class SwapResult(TypedDict, total=False):
signatures: list[BlindSignature]
[docs]class PaymentRequestData(TypedDict, total=False):
a: int
u: str
m: list[str]
s: bool
i: Optional[str]
d: Optional[str]
nut10: Optional[dict[str, str]]
ProofVerifier = Callable[[Sequence[CashuProof]], bool]
# ---------------------------------------------------------------------------
# BDHKE (Blind Diffie-Hellman Key Exchange) over secp256k1
# ---------------------------------------------------------------------------
[docs]def hash_to_curve(secret: str | bytes) -> tuple[int, int]:
"""Domain-separated hash-to-curve on secp256k1 per Cashu NUT-00.
Y = PublicKey('02' || SHA256(msg_hash || counter)) with
msg_hash = SHA256(DOMAIN_SEPARATOR || x) and a little-endian uint32
counter incremented from 0 until lift_x lands on the curve. The '02'
prefix means the even-y point is always chosen, so this returns the
even-y lift and `point_to_hex` renders it as '02...'.
An earlier version re-hashed the digest itself until it lifted, which
is the pre-2024 construction. Every proof a mint knows is indexed by
this Y: NUT-07 check-state asks about Y, and NUT-03 swap recomputes Y
from the secret to verify C == k*Y. With the old construction a
nutshell 0.21 mint minted our blinded outputs fine (blinding never
shows it Y) and then refused the resulting proofs on swap, which is
the step `verify` depends on for finality. The NUT-00 test vectors are
pinned in node/tests/test_settlement.py so this cannot drift again.
"""
raw = secret.encode('utf-8') if isinstance(secret, str) else secret
msg_hash = hashlib.sha256(b'Secp256k1_HashToCurve_Cashu_' + raw).digest()
for counter in range(2 ** 32):
h = hashlib.sha256(msg_hash + counter.to_bytes(4, 'little')).digest()
pt = crypto.lift_x(int.from_bytes(h, 'big'))
if pt is not None:
return pt
raise ValueError('hash_to_curve: no point found') # unreachable in practice
[docs]def point_to_hex(pt: tuple[int, int]) -> str:
"""Format secp256k1 point as 33-byte compressed hex string (02/03 prefix)."""
x, y = pt
prefix = '02' if y % 2 == 0 else '03'
return prefix + ('%064x' % x)
[docs]def hex_to_point(h: str) -> tuple[int, int]:
"""Parse 33-byte compressed secp256k1 point hex string."""
clean = h.strip().lower()
if len(clean) != 66:
raise ValueError(f"invalid compressed point length: {len(clean)}")
prefix = clean[:2]
if prefix not in ('02', '03'):
raise ValueError(f"invalid point prefix: {prefix}")
x = int(clean[2:], 16)
pt = crypto.lift_x(x)
if pt is None:
raise ValueError("point is not on secp256k1 curve")
if prefix == '03':
return (pt[0], (crypto.P - pt[1]) % crypto.P)
return pt
[docs]def blind_message(secret: str | bytes, r: Optional[int] = None) -> tuple[str, int]:
"""Alice blinds secret x: returns (B_prime_hex, r).
B' = Y + r*G where Y = hash_to_curve(x).
"""
Y = hash_to_curve(secret)
r_val = r if r is not None else (int.from_bytes(os.urandom(32), 'big') % (crypto.N - 1) + 1)
rG = crypto.point_mul(r_val, crypto.G)
assert rG is not None
B_prime = crypto.point_add(rG, Y)
assert B_prime is not None
return point_to_hex(B_prime), r_val
[docs]def sign_blinded(B_prime_hex: str, mint_privkey_hex: str) -> str:
"""Mint signs blinded point B': returns C_prime_hex.
C' = k * B' where k is mint private key.
"""
k = int(mint_privkey_hex, 16) % crypto.N
B_prime = hex_to_point(B_prime_hex)
C_prime = crypto.point_mul(k, B_prime)
if C_prime is None:
raise ValueError('invalid mint private key or blinded point')
return point_to_hex(C_prime)
[docs]def unblind_signature(C_prime_hex: str, r: int, mint_pubkey_hex: str) -> str:
"""Alice unblinds mint signature: returns C_hex.
C = C' - r*K = C' + (N - r)*K where K is mint public key.
"""
C_prime = hex_to_point(C_prime_hex)
K = hex_to_point(mint_pubkey_hex) if len(mint_pubkey_hex) == 66 else (
crypto.lift_x(int(mint_pubkey_hex, 16))
)
if K is None:
raise ValueError('invalid mint public key')
neg_rK = crypto.point_mul(crypto.N - (r % crypto.N), K)
if neg_rK is None:
raise ValueError('invalid blinding scalar r')
C = crypto.point_add(C_prime, neg_rK)
if C is None:
raise ValueError('unblinded signature is point at infinity')
return point_to_hex(C)
[docs]def verify_proof(proof: CashuProof | Mapping[str, Any], mint_pubkey_hex: str) -> bool:
"""Structural check of a Cashu proof (secret, C) against mint public key K.
THIS IS NOT A SIGNATURE CHECK, and no caller may treat it as one. The
relation a proof asserts is C == k * hash_to_curve(secret) with K = k*G,
and deciding it from K alone is the decisional Diffie-Hellman problem:
without the mint's private key k, or a Chaum-Pedersen DLEQ proof carried
alongside the proof (NUT-12), the holder of K cannot tell a genuine C from
a random on-curve point. An earlier version of this routine computed
Y = hash_to_curve(secret) and K and then used neither, which read like a
verification step had been dropped; nothing was dropped - there is no step
available. What can be checked without k is that the proof is well formed:
the secret is a string, C parses as a compressed point on secp256k1 and K
parses. That is all this returns.
Real acceptance goes through `verify_proof_with_key` when this node IS the
mint, or through the mint's own check-state/swap endpoint when it is not.
`verify_nutzap_event` refuses, rather than skips, when neither is wired.
"""
try:
if not isinstance(proof.get('secret'), str) or not proof['secret']:
return False
hex_to_point(proof['C'])
K = hex_to_point(mint_pubkey_hex) if len(mint_pubkey_hex) == 66 else (
crypto.lift_x(int(mint_pubkey_hex, 16))
)
return K is not None
except Exception:
return False
[docs]def verify_proof_with_key(proof: CashuProof | Mapping[str, Any], mint_privkey_hex: str) -> bool:
"""Direct verification of proof by mint using private key k: C == k * Y."""
try:
k = int(mint_privkey_hex, 16) % crypto.N
secret = proof['secret']
C_hex = proof['C']
C = hex_to_point(C_hex)
Y = hash_to_curve(secret)
expected_C = crypto.point_mul(k, Y)
return C == expected_C
except Exception:
return False
# ---------------------------------------------------------------------------
# Cashu Token V3 Serialization (NUT-00)
# ---------------------------------------------------------------------------
[docs]def serialize_cashu_token(mint_url: str, proofs: Sequence[CashuProof]) -> str:
"""Serialize proofs into standard Cashu V3 token string (cashuA...)."""
token_obj = {
'token': [
{
'mint': mint_url,
'proofs': list(proofs),
}
]
}
raw = json.dumps(token_obj, separators=(',', ':')).encode('utf-8')
return 'cashuA' + base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=')
[docs]def deserialize_cashu_token(token_str: str) -> CashuToken:
"""Parse standard Cashu V3 token string (cashuA...)."""
s = token_str.strip()
if not s.startswith('cashuA'):
raise ValueError("token does not begin with 'cashuA'")
b64 = s[6:]
pad = '=' * (-len(b64) % 4)
raw = base64.urlsafe_b64decode(b64 + pad)
return json.loads(raw.decode('utf-8'))
# ---------------------------------------------------------------------------
# NIP-61 Nutzap Nostr Event (Kind 9321)
# ---------------------------------------------------------------------------
[docs]def create_nutzap_event(
sender_sk: str,
recipient_pk: str,
proofs: Sequence[CashuProof],
mint_url: str,
amount_msat: int,
target_event_id: Optional[str] = None,
comment: str = '',
unit: str = 'msat',
now: Optional[int] = None,
) -> NostrEvent:
"""Create and sign a standard NIP-61 Nutzap event (Kind 9321)."""
now_ts = int(now if now is not None else time.time())
tags: list[list[str]] = [
['p', recipient_pk.lower()],
['amount', str(amount_msat)],
['unit', unit],
['u', mint_url],
]
for p in proofs:
tags.append(['proof', json.dumps(p, separators=(',', ':'))])
if target_event_id:
tags.append(['e', target_event_id.lower()])
return store.make_signed_event(sender_sk, now_ts, NUTZAP_KIND, tags, comment)
[docs]def proofs_of(event: NostrEvent | Mapping[str, Any]) -> list[CashuProof]:
"""The proof tags of a Nutzap, parsed. Raises ValueError on a malformed one."""
out: list[CashuProof] = []
for t in event.get('tags', []):
if t and t[0] == 'proof' and len(t) > 1:
try:
p = json.loads(t[1])
except Exception as e:
raise ValueError('malformed proof tag in Nutzap: %s' % e)
if not isinstance(p, dict):
raise ValueError('proof tag is not an object')
out.append(cast(CashuProof, p))
return out
[docs]def proofs_amount_msat(proofs: Sequence[CashuProof]) -> int:
"""What the proofs are actually worth, in msat.
A Cashu proof's `amount` is denominated in the keyset's unit, and the
keysets this implementation mints and accepts are sat (NUT-00's default
and what every public mint issues), so the value is sum(amount) * 1000.
The Nutzap's `amount` tag is a free-text claim by the sender and is NOT
what the mint signed; it is reconciled against this number and never
trusted on its own. Raises ValueError for an amount that is not a
positive integer.
"""
total = 0
for p in proofs:
a = p.get('amount')
if not isinstance(a, int) or isinstance(a, bool) or a <= 0:
raise ValueError('proof amount must be a positive integer, got %r' % (a,))
total += a
return total * 1000
[docs]def stated_amount_msat(tag_map: Mapping[str, Sequence[str]]) -> Optional[int]:
"""The sender's own `amount` tag, normalised to msat by the `unit` tag.
`create_nutzap_event` writes the amount in msat and says so with
unit=msat; a wallet following NIP-61 literally writes sat. Either is a
claim about the same proofs and is held to the same reconciliation.
None when the tag is missing, not a decimal integer, or in a unit this
node does not price.
"""
amt = tag_map.get('amount') or []
if not amt or not amt[0].isdigit():
return None
unit = (tag_map.get('unit') or ['sat'])[0]
if unit == 'msat':
return int(amt[0])
if unit == 'sat':
return int(amt[0]) * 1000
return None
[docs]def verify_nutzap_event(
event: NostrEvent | Mapping[str, Any],
expected_recipient: Optional[str] = None,
mint_privkey_hex: Optional[str] = None,
proof_verifier: Optional[ProofVerifier] = None,
allow_unverified_proofs: bool = False,
) -> tuple[bool, str, int]:
"""Verify NIP-61 Nutzap event: returns (valid, reason, amount_msat).
The amount returned is the sum of the proofs, never the `amount` tag: the
tag is what the sender says, the proofs are what the mint signed, and a
grant expansion priced off the tag was a budget bypass - one 1-sat proof
plus an `amount` of a billion bought a billion msat of bytes_in.
Proof acceptance is one of three things, in this order:
- mint_privkey_hex: this node is the mint, check C == k*Y directly;
- proof_verifier: a callable that asks the real mint (check-state or
swap) whether these proofs are unspent and genuine;
- neither: REFUSED, unless the caller passes allow_unverified_proofs=True
and so says in its own code that it is accepting IOUs. Silently
skipping the check - which is what this did when no key was given -
meant a production node with no mint key accepted any JSON with a
`secret` field as payment.
"""
if event.get('kind') != NUTZAP_KIND:
return False, f"invalid kind: expected {NUTZAP_KIND}, got {event.get('kind')}", 0
if not store.verify_event(event):
return False, "invalid cryptographic signature on Nutzap event", 0
tags = event.get('tags', [])
tag_map: dict[str, list[str]] = {}
for t in tags:
if not t:
continue
if t[0] != 'proof' and t[0] not in tag_map:
tag_map[t[0]] = t[1:]
try:
proofs = proofs_of(event)
except ValueError as e:
return False, str(e), 0
p_tags = tag_map.get('p', [])
if not p_tags:
return False, "missing 'p' recipient tag", 0
recipient = p_tags[0]
if expected_recipient and recipient.lower() != expected_recipient.lower():
return False, f"recipient mismatch: expected {expected_recipient[:16]}, got {recipient[:16]}", 0
stated_msat = stated_amount_msat(tag_map)
if stated_msat is None:
return False, "missing or invalid amount tag", 0
if not proofs:
return False, "nutzap carries no cashu proofs", 0
try:
amount_msat = proofs_amount_msat(proofs)
except ValueError as e:
return False, str(e), 0
if stated_msat != amount_msat:
return False, f"amount tag {stated_msat} msat disagrees with proofs worth {amount_msat} msat", 0
ok_proofs, why = accept_proofs(proofs, mint_privkey_hex=mint_privkey_hex, proof_verifier=proof_verifier,
allow_unverified_proofs=allow_unverified_proofs)
if not ok_proofs:
return False, why, 0
return True, "valid", amount_msat
[docs]def accept_proofs(
proofs: Sequence[CashuProof],
mint_privkey_hex: Optional[str] = None,
proof_verifier: Optional[ProofVerifier] = None,
allow_unverified_proofs: bool = False,
) -> tuple[bool, str]:
"""The one proof policy (see verify_nutzap_event): mint key, else a
verifier that asks the mint, else refuse unless the caller opted into
unverified IOUs. Every path that takes proofs as money goes through
here, whatever shape they arrived in."""
if mint_privkey_hex:
for p in proofs:
if not verify_proof_with_key(p, mint_privkey_hex):
return False, f"cashu proof signature invalid for secret {p.get('secret')}"
return True, "verified by mint key"
if proof_verifier is not None:
try:
if not proof_verifier(list(proofs)):
return False, "mint did not vouch for the cashu proofs"
except Exception as e:
return False, f"proof verifier failed: {type(e).__name__}: {e}"
return True, "verified by mint"
if not allow_unverified_proofs:
return False, "no mint key or proof verifier configured: proofs cannot be verified"
return True, "unverified (allow_unverified_proofs)"
# ---------------------------------------------------------------------------
# Wire codecs: V4 tokens, NUT-18 requests, NUT-11 P2PK secrets
# ---------------------------------------------------------------------------
TOKEN_V4_PREFIX = 'cashuB'
REQUEST_PREFIX = 'creqA'
def _b64u(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=')
def _b64u_decode(s: str) -> bytes:
s = s.strip()
return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
[docs]def normalize_mint_url(url: str) -> str:
return url.strip().rstrip('/')
# ---------------------------------------------------------------------------
# NUT-00 V4 token
# ---------------------------------------------------------------------------
[docs]def encode_token_v4(mint_url: str, unit: str, proofs: Sequence[CashuProof],
memo: Optional[str] = None) -> str:
"""Proofs in the JSON shape node/payment.py uses ({amount, id, secret, C[, witness]})
become one cashuB token. Proofs are grouped by keyset id as the format requires."""
by_keyset: dict[str, list[CborProofEntry]] = {}
for p in proofs:
entry: CborProofEntry = {'a': int(p['amount']), 's': str(p['secret']), 'c': bytes.fromhex(str(p['C']))}
if p.get('witness'):
entry['w'] = p['witness'] if isinstance(p['witness'], str) else json.dumps(p['witness'], separators=(',', ':'))
by_keyset.setdefault(str(p['id']), []).append(entry)
obj = {
'm': normalize_mint_url(mint_url),
'u': unit,
't': [{'i': bytes.fromhex(kid), 'p': plist} for kid, plist in by_keyset.items()],
}
if memo:
obj['d'] = memo
return TOKEN_V4_PREFIX + _b64u(cbor_encode(obj))
[docs]def decode_token_v4(token: str) -> DecodedTokenV4:
"""A cashuB string to {mint, unit, memo, proofs: [{amount, id, secret, C[, witness]}]}.
Keyset ids come back as hex, full or short form as sent: the caller that
talks to the mint resolves a short id against the mint's keysets.
"""
s = token.strip()
if not s.startswith(TOKEN_V4_PREFIX):
raise ValueError('token is not a cashuB (V4) token')
try:
obj, _ = cbor_decode(_b64u_decode(s[len(TOKEN_V4_PREFIX):]))
except (CBORError, ValueError) as e:
raise ValueError(f'token is not valid CBOR: {e}') from None
if not isinstance(obj, dict) or not isinstance(obj.get('m'), str) or not isinstance(obj.get('u'), str):
raise ValueError('token lacks mint or unit')
entries = obj.get('t')
if not isinstance(entries, list) or not entries:
raise ValueError('token carries no proofs')
proofs: list[CashuProof] = []
for ent in entries:
if not isinstance(ent, dict) or not isinstance(ent.get('i'), (bytes, bytearray)):
raise ValueError('token keyset entry is malformed')
kid = bytes(ent['i']).hex()
plist = ent.get('p')
if not isinstance(plist, list):
raise ValueError('token keyset entry has no proof list')
for p in plist:
if (not isinstance(p, dict) or isinstance(p.get('a'), bool) or not isinstance(p.get('a'), int) or p['a'] <= 0
or not isinstance(p.get('s'), str) or not isinstance(p.get('c'), (bytes, bytearray))):
raise ValueError('token proof is malformed')
proof: CashuProof = {'amount': p['a'], 'id': kid, 'secret': p['s'], 'C': bytes(p['c']).hex()}
if isinstance(p.get('w'), str):
proof['witness'] = p['w']
proofs.append(proof)
if not proofs:
raise ValueError('token carries no proofs')
return {'mint': normalize_mint_url(obj['m']), 'unit': obj['u'],
'memo': obj.get('d') if isinstance(obj.get('d'), str) else None, 'proofs': proofs}
[docs]def token_amount(decoded: DecodedTokenV4 | Mapping[str, Any]) -> int:
return sum(int(p['amount']) for p in decoded['proofs'])
# ---------------------------------------------------------------------------
# NUT-18 payment request
# ---------------------------------------------------------------------------
[docs]def encode_payment_request(amount: int, unit: str, mints: Sequence[str],
payment_id: Optional[str] = None, description: Optional[str] = None,
single_use: bool = True, p2pk_pubkey: Optional[str] = None) -> str:
"""A creqA request with no transport: NUT-24 payment is in-band, in the
retried request's X-Cashu header. `mints` is strict (no `mp`): a token
from any other mint is refused, which is the allowlist of ยง3.5.
p2pk_pubkey, when given, is the 33-byte compressed key the proofs must be
locked to (NUT-10 kind P2PK)."""
obj = {'a': int(amount), 'u': unit, 'm': [normalize_mint_url(m) for m in mints], 's': bool(single_use)}
if payment_id:
obj['i'] = payment_id
if description:
obj['d'] = description
if p2pk_pubkey:
obj['nut10'] = {'k': 'P2PK', 'd': p2pk_pubkey.lower()}
return REQUEST_PREFIX + _b64u(cbor_encode(obj))
[docs]def decode_payment_request(req: str) -> PaymentRequestData:
s = req.strip()
if not s.startswith(REQUEST_PREFIX):
raise ValueError('payment request is not creqA')
try:
obj, _ = cbor_decode(_b64u_decode(s[len(REQUEST_PREFIX):]))
except (CBORError, ValueError) as e:
raise ValueError(f'payment request is not valid CBOR: {e}') from None
if not isinstance(obj, dict):
raise ValueError('payment request is not a map')
return cast(PaymentRequestData, obj)
[docs]class P2PKSecretBody(TypedDict, total=False):
nonce: str
data: str
tags: list[list[str]]
[docs]def p2pk_secret(pubkey_compressed_hex: str, nonce: Optional[bytes] = None,
tags: Optional[Sequence[Sequence[str]]] = None) -> str:
"""The serialised well-known secret a P2PK-locked proof carries. The mint
signs hash_to_curve(this string), so the string, not a parsed form, is
what the proof holds and what the witness signs."""
body: P2PKSecretBody = {'nonce': (nonce or os.urandom(32)).hex(), 'data': pubkey_compressed_hex.lower()}
if tags:
body['tags'] = [list(t) for t in tags]
return json.dumps(['P2PK', body], separators=(',', ':'))
[docs]def parse_well_known_secret(secret: str) -> Optional[tuple[str, P2PKSecretBody | Mapping[str, Any]]]:
"""(kind, data) for a NUT-10 secret, None for a plain random secret."""
if not secret.startswith('['):
return None
try:
val = json.loads(secret)
except ValueError:
return None
if isinstance(val, list) and len(val) == 2 and isinstance(val[0], str) and isinstance(val[1], dict):
return val[0], val[1]
return None
[docs]def p2pk_locked_to(secret: str) -> Optional[str]:
"""The x-only (32-byte) hex of the key a P2PK secret is locked to, or None."""
parsed = parse_well_known_secret(secret)
if parsed is None or parsed[0] != 'P2PK':
return None
data = parsed[1].get('data')
if not isinstance(data, str) or len(data) != 66:
return None
return data[2:].lower()
[docs]def x_only_to_compressed(x_hex: str) -> str:
"""A nostr key (x-only) as the even-y compressed key NUT-11 canonicalises
on: keys are compared by x-coordinate with the prefix ignored."""
return '02' + x_hex.lower()