"""secp256k1, HKDF and envelope commitments. Standard library only.
Everything the protocol needs below the event layer, in one readable file. It is
not constant-time and it is not for production key handling: it exists so that
the mechanisms in this package are executable and testable, and so an implementer
has something to compare against.
Sources of truth: BIP-340 for Schnorr, RFC 5869 for HKDF, and schema/constants.json
for every label. Nothing here hardcodes a domain string.
"""
from __future__ import annotations
import hashlib
import hmac
import json
from typing import Any, Optional
from ..wire import spelling
P: int = 2**256 - 2**32 - 977
N: int = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
Gx: int = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy: int = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
G: tuple[int, int] = (Gx, Gy)
Point2D = tuple[int, int]
# ---------------------------------------------------------------- curve ----
def _inv(a: int) -> int:
return pow(a, P - 2, P)
[docs]def point_add(p: Optional[Point2D], q: Optional[Point2D]) -> Optional[Point2D]:
if p is None:
return q
if q is None:
return p
if p[0] == q[0] and (p[1] + q[1]) % P == 0:
return None
if p == q:
lam = 3 * p[0] * p[0] * _inv(2 * p[1]) % P
else:
lam = (q[1] - p[1]) * _inv(q[0] - p[0]) % P
x = (lam * lam - p[0] - q[0]) % P
return (x, (lam * (p[0] - x) - p[1]) % P)
def point_mul(k: int, p: Optional[Point2D]) -> Optional[Point2D]:
r: Optional[Point2D] = None
k = k % N
while k:
if k & 1:
r = point_add(r, p)
p = point_add(p, p)
k >>= 1
return r
[docs]def on_curve(p: Optional[Point2D]) -> bool:
return p is not None and (p[1] * p[1] - p[0] ** 3 - 7) % P == 0
[docs]def lift_x(x: int) -> Optional[Point2D]:
"""The even-y point with this x, per BIP-340. None if x is not on the curve."""
if not 0 < x < P:
return None
y2 = (pow(x, 3, P) + 7) % P
y = pow(y2, (P + 1) // 4, P)
if y * y % P != y2:
return None
return (x, y if y % 2 == 0 else P - y)
def _scalar(sk_hex: str) -> int:
"""A secret key: exactly 64 hex digits spelling 1 <= d < n. int(sk, 16)
accepted '0x', whitespace, odd lengths and anything >= n reduced mod n,
so a key spelt wrongly still signed - and signed differently from an
implementation that refused the spelling."""
if not spelling.is_hex(sk_hex, 64, upper=True):
raise ValueError('a secret key is 32 bytes of hex')
d = int(sk_hex, 16)
if not 1 <= d < N:
raise ValueError('secret key out of range')
return d
def _x_coord(pk_hex: str) -> int:
"""An x-only public key: exactly 64 hex digits."""
if not spelling.is_hex(pk_hex, 64, upper=True):
raise ValueError('a public key is 32 bytes of hex')
return int(pk_hex, 16)
def pubkey(sk_hex: str) -> str:
"""x-only public key, hex, as nostr uses."""
pt = point_mul(_scalar(sk_hex), G)
assert pt is not None
return '%064x' % pt[0]
def ecdh_x(sk_hex: str, pk_x_hex: str) -> str:
"""The shared x-coordinate. Both sides derive the same value.
Note what this is not: it is the raw x-coordinate, uniform over curve points
rather than over 256-bit strings, which is why every use of it below runs
through HKDF extract rather than being hashed directly.
"""
pt = lift_x(_x_coord(pk_x_hex))
if pt is None:
raise ValueError('counterparty key is not on the curve')
res = point_mul(_scalar(sk_hex), pt)
assert res is not None
return '%064x' % res[0]
# ----------------------------------------------------------------- HKDF ----
[docs]def hkdf(ikm: bytes, info: bytes, salt: bytes, length: int = 32) -> bytes:
"""RFC 5869. Both stages carry a domain string; see schema/constants.json.
length is 1..8160 (255 blocks of SHA-256), as the RFC bounds it."""
if isinstance(length, bool) or not isinstance(length, int) or not 1 <= length <= 255 * 32:
raise ValueError('hkdf length is 1..8160 bytes')
prk = hmac.new(salt, ikm, hashlib.sha256).digest()
okm, t, i = b'', b'', 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([i]), hashlib.sha256).digest()
okm += t
i += 1
return okm[:length]
# -------------------------------------------------------------- BIP-340 ----
def _tagged(tag: str, msg: bytes) -> bytes:
t = hashlib.sha256(tag.encode()).digest()
return hashlib.sha256(t + t + msg).digest()
def schnorr_sign(msg32: bytes, sk_hex: str, aux: bytes = b'\x00' * 32) -> str:
d0 = _scalar(sk_hex)
pt = point_mul(d0, G)
assert pt is not None
d = d0 if pt[1] % 2 == 0 else N - d0
px = pt[0].to_bytes(32, 'big')
t = (d ^ int.from_bytes(_tagged('BIP0340/aux', aux), 'big')).to_bytes(32, 'big')
k0 = int.from_bytes(_tagged('BIP0340/nonce', t + px + msg32), 'big') % N
if k0 == 0:
raise ValueError('nonce is zero')
r = point_mul(k0, G)
assert r is not None
k = k0 if r[1] % 2 == 0 else N - k0
rx = r[0].to_bytes(32, 'big')
e = int.from_bytes(_tagged('BIP0340/challenge', rx + px + msg32), 'big') % N
return (rx + ((k + e * d) % N).to_bytes(32, 'big')).hex()
def schnorr_verify(msg32: bytes, pk_x_hex: str, sig_hex: str) -> bool:
"""True if sig is a valid BIP-340 signature. Never raises on bad input."""
try:
sig = bytes.fromhex(sig_hex)
if len(sig) != 64:
return False
pt = lift_x(_x_coord(pk_x_hex))
if pt is None:
return False
r = int.from_bytes(sig[:32], 'big')
s = int.from_bytes(sig[32:], 'big')
if r >= P or s >= N:
return False
e = int.from_bytes(_tagged('BIP0340/challenge',
sig[:32] + pt[0].to_bytes(32, 'big') + msg32), 'big') % N
rp = point_add(point_mul(s, G), point_mul(N - e, pt))
return rp is not None and rp[1] % 2 == 0 and rp[0] == r
except (ValueError, TypeError):
return False
# ----------------------------------------------------------- commitment ----
# commitment.scheme in constants.json is sha256-blind/1. Nothing in this protocol
# adds two commitments together, so the homomorphism a Pedersen commitment buys
# is unused - and specifying Pedersen would mean pinning a second generator, a
# scalar mapping and a point encoding, none of which the document states.
# pedersen-secp256k1/1 is reserved for a mechanism that actually needs it.
[docs]def commit(payload_bytes: bytes, blinding_hex: str) -> str:
"""C = SHA256(blinding || payload). Binding by collision resistance, hiding
by the 32-byte blinding the subject already receives in the payload."""
return hashlib.sha256(bytes.fromhex(blinding_hex) + payload_bytes).hexdigest()
[docs]def open_commit(commitment_hex: str, payload_bytes: bytes, blinding_hex: str) -> bool:
"""True if the commitment opens to this payload under this blinding."""
return hmac.compare_digest(commit(payload_bytes, blinding_hex), commitment_hex)
[docs]def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
[docs]def canonical(obj: Any) -> bytes:
"""The serialisation every digest in this protocol is taken over.
UTF-8 with only the escapes JSON mandates: a non-ASCII character is written
as itself, never as \\uXXXX. json.dumps's ensure_ascii default is a Python
habit, not the wire, and it hashed differently from every other language."""
return json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()