nostr_helpers.py raw

   1  """Minimal BIP-340 Schnorr signing + Nostr event builder for tests.
   2  
   3  Pure Python, no external dependencies beyond stdlib.
   4  """
   5  
   6  import hashlib
   7  import json
   8  import os
   9  import time
  10  
  11  # secp256k1 curve parameters.
  12  _P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
  13  _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
  14  _G = (
  15      0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
  16      0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
  17  )
  18  
  19  
  20  def _modinv(a, m):
  21      g, x, _ = _egcd(a % m, m)
  22      return x % m
  23  
  24  
  25  def _egcd(a, b):
  26      if a == 0:
  27          return b, 0, 1
  28      g, x, y = _egcd(b % a, a)
  29      return g, y - (b // a) * x, x
  30  
  31  
  32  def _point_add(p1, p2):
  33      """Affine addition; one modular inverse. Kept for callers/tests."""
  34      if p1 is None:
  35          return p2
  36      if p2 is None:
  37          return p1
  38      if p1[0] == p2[0] and p1[1] != p2[1]:
  39          return None
  40      if p1 == p2:
  41          lam = (3 * p1[0] * p1[0] * _modinv(2 * p1[1], _P)) % _P
  42      else:
  43          lam = ((p2[1] - p1[1]) * _modinv(p2[0] - p1[0], _P)) % _P
  44      x = (lam * lam - p1[0] - p2[0]) % _P
  45      y = (lam * (p1[0] - x) - p1[1]) % _P
  46      return (x, y)
  47  
  48  
  49  def _jac_double(p):
  50      """Double a Jacobian point (X, Y, Z); a = 0 curve, so no a*Z^4 term."""
  51      x, y, z = p
  52      if y == 0 or z == 0:
  53          return (0, 1, 0)
  54      yy = (y * y) % _P
  55      s = (4 * x * yy) % _P
  56      m = (3 * x * x) % _P
  57      nx = (m * m - 2 * s) % _P
  58      ny = (m * (s - nx) - 8 * yy * yy) % _P
  59      nz = (2 * y * z) % _P
  60      return (nx, ny, nz)
  61  
  62  
  63  def _jac_add(p1, p2):
  64      """Add two Jacobian points; no inverse."""
  65      x1, y1, z1 = p1
  66      x2, y2, z2 = p2
  67      if z1 == 0:
  68          return p2
  69      if z2 == 0:
  70          return p1
  71      z1z1 = (z1 * z1) % _P
  72      z2z2 = (z2 * z2) % _P
  73      u1 = (x1 * z2z2) % _P
  74      u2 = (x2 * z1z1) % _P
  75      s1 = (y1 * z2z2 * z2) % _P
  76      s2 = (y2 * z1z1 * z1) % _P
  77      if u1 == u2:
  78          if s1 != s2:
  79              return (0, 1, 0)
  80          return _jac_double(p1)
  81      h = (u2 - u1) % _P
  82      r = (s2 - s1) % _P
  83      hh = (h * h) % _P
  84      hhh = (h * hh) % _P
  85      v = (u1 * hh) % _P
  86      nx = (r * r - hhh - 2 * v) % _P
  87      ny = (r * (v - nx) - s1 * hhh) % _P
  88      nz = (h * z1 * z2) % _P
  89      return (nx, ny, nz)
  90  
  91  
  92  def _jac_to_affine(p):
  93      x, y, z = p
  94      if z == 0:
  95          return None
  96      zi = _modinv(z, _P)
  97      zi2 = (zi * zi) % _P
  98      return ((x * zi2) % _P, (y * zi2 * zi) % _P)
  99  
 100  
 101  def _point_mul(k, point):
 102      """k*point.
 103  
 104      Jacobian ladder: one modular inverse for the whole multiplication instead
 105      of one per bit. The affine version cost ~65ms per signature, which made
 106      the high-volume relay tests spend 130s signing 2000 events before the
 107      relay saw any of them.
 108      """
 109      k %= _N
 110      if k == 0 or point is None:
 111          return None
 112      r = (0, 1, 0)
 113      a = (point[0], point[1], 1)
 114      while k:
 115          if k & 1:
 116              r = _jac_add(r, a)
 117          a = _jac_double(a)
 118          k >>= 1
 119      return _jac_to_affine(r)
 120  
 121  
 122  def _tagged_hash(tag, msg):
 123      t = hashlib.sha256(tag.encode()).digest()
 124      return hashlib.sha256(t + t + msg).digest()
 125  
 126  
 127  def _int_from_bytes(b):
 128      return int.from_bytes(b, "big")
 129  
 130  
 131  def _bytes_from_int(x):
 132      return x.to_bytes(32, "big")
 133  
 134  
 135  def pubkey_from_seckey(seckey: bytes) -> bytes:
 136      pt = _point_mul(_int_from_bytes(seckey), _G)
 137      return _bytes_from_int(pt[0])
 138  
 139  
 140  def schnorr_sign(msg: bytes, seckey: bytes) -> bytes:
 141      d = _int_from_bytes(seckey)
 142      pt = _point_mul(d, _G)
 143      if pt[1] % 2 != 0:
 144          d = _N - d
 145      aux = os.urandom(32)
 146      t = bytes(
 147          a ^ b for a, b in zip(_bytes_from_int(d), _tagged_hash("BIP0340/aux", aux))
 148      )
 149      rand = _tagged_hash("BIP0340/nonce", t + _bytes_from_int(pt[0]) + msg)
 150      k = _int_from_bytes(rand) % _N
 151      if k == 0:
 152          raise ValueError("bad nonce")
 153      r = _point_mul(k, _G)
 154      if r[1] % 2 != 0:
 155          k = _N - k
 156      e = (
 157          _int_from_bytes(
 158              _tagged_hash(
 159                  "BIP0340/challenge",
 160                  _bytes_from_int(r[0]) + _bytes_from_int(pt[0]) + msg,
 161              )
 162          )
 163          % _N
 164      )
 165      return _bytes_from_int(r[0]) + _bytes_from_int((k + e * d) % _N)
 166  
 167  
 168  def make_event(seckey: bytes, content: str, kind=1, tags=None, created_at=None):
 169      """Create a fully signed Nostr event."""
 170      if tags is None:
 171          tags = []
 172      if created_at is None:
 173          created_at = int(time.time())
 174      pubkey = pubkey_from_seckey(seckey).hex()
 175      serial = json.dumps(
 176          [0, pubkey, created_at, kind, tags, content], separators=(",", ":")
 177      )
 178      event_id = hashlib.sha256(serial.encode()).digest()
 179      sig = schnorr_sign(event_id, seckey)
 180      return {
 181          "id": event_id.hex(),
 182          "pubkey": pubkey,
 183          "created_at": created_at,
 184          "kind": kind,
 185          "tags": tags,
 186          "content": content,
 187          "sig": sig.hex(),
 188      }
 189  
 190  
 191  # Fixed test keypair — deterministic for reproducible tests.
 192  TEST_SECKEY = hashlib.sha256(b"smesh-test-key-do-not-use").digest()
 193  TEST_PUBKEY = pubkey_from_seckey(TEST_SECKEY).hex()
 194