reference.py raw

   1  from typing import Tuple, Optional, Any
   2  import hashlib
   3  import binascii
   4  
   5  # Set DEBUG to True to get a detailed debug output including
   6  # intermediate values during key generation, signing, and
   7  # verification. This is implemented via calls to the
   8  # debug_print_vars() function.
   9  #
  10  # If you want to print values on an individual basis, use
  11  # the pretty() function, e.g., print(pretty(foo)).
  12  DEBUG = False
  13  
  14  p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
  15  n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
  16  
  17  # Points are tuples of X and Y coordinates and the point at infinity is
  18  # represented by the None keyword.
  19  G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
  20       0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
  21  
  22  Point = Tuple[int, int]
  23  
  24  
  25  # This implementation can be sped up by storing the midstate after hashing
  26  # tag_hash instead of rehashing it all the time.
  27  def tagged_hash(tag: str, msg: bytes) -> bytes:
  28      tag_hash = hashlib.sha256(tag.encode()).digest()
  29      return hashlib.sha256(tag_hash + tag_hash + msg).digest()
  30  
  31  
  32  def is_infinite(P: Optional[Point]) -> bool:
  33      return P is None
  34  
  35  
  36  def x(P: Point) -> int:
  37      assert not is_infinite(P)
  38      return P[0]
  39  
  40  
  41  def y(P: Point) -> int:
  42      assert not is_infinite(P)
  43      return P[1]
  44  
  45  
  46  def point_add(P1: Optional[Point], P2: Optional[Point]) -> Optional[Point]:
  47      if P1 is None:
  48          return P2
  49      if P2 is None:
  50          return P1
  51      if (x(P1) == x(P2)) and (y(P1) != y(P2)):
  52          return None
  53      if P1 == P2:
  54          lam = (3 * x(P1) * x(P1) * pow(2 * y(P1), p - 2, p)) % p
  55      else:
  56          lam = ((y(P2) - y(P1)) * pow(x(P2) - x(P1), p - 2, p)) % p
  57      x3 = (lam * lam - x(P1) - x(P2)) % p
  58      return (x3, (lam * (x(P1) - x3) - y(P1)) % p)
  59  
  60  
  61  def point_mul(P: Optional[Point], n: int) -> Optional[Point]:
  62      R = None
  63      for i in range(256):
  64          if (n >> i) & 1:
  65              R = point_add(R, P)
  66          P = point_add(P, P)
  67      return R
  68  
  69  
  70  def bytes_from_int(x: int) -> bytes:
  71      return x.to_bytes(32, byteorder="big")
  72  
  73  
  74  def bytes_from_point(P: Point) -> bytes:
  75      return bytes_from_int(x(P))
  76  
  77  
  78  def xor_bytes(b0: bytes, b1: bytes) -> bytes:
  79      return bytes(x ^ y for (x, y) in zip(b0, b1))
  80  
  81  
  82  def lift_x(x: int) -> Optional[Point]:
  83      if x >= p:
  84          return None
  85      y_sq = (pow(x, 3, p) + 7) % p
  86      y = pow(y_sq, (p + 1) // 4, p)
  87      if pow(y, 2, p) != y_sq:
  88          return None
  89      return (x, y if y & 1 == 0 else p - y)
  90  
  91  
  92  def int_from_bytes(b: bytes) -> int:
  93      return int.from_bytes(b, byteorder="big")
  94  
  95  
  96  def hash_sha256(b: bytes) -> bytes:
  97      return hashlib.sha256(b).digest()
  98  
  99  
 100  def has_even_y(P: Point) -> bool:
 101      assert not is_infinite(P)
 102      return y(P) % 2 == 0
 103  
 104  
 105  def pubkey_gen(seckey: bytes) -> bytes:
 106      d0 = int_from_bytes(seckey)
 107      if not (1 <= d0 <= n - 1):
 108          raise ValueError('The secret key must be an integer in the range 1..n-1.')
 109      P = point_mul(G, d0)
 110      assert P is not None
 111      return bytes_from_point(P)
 112  
 113  
 114  def schnorr_sign(msg: bytes, seckey: bytes, aux_rand: bytes) -> bytes:
 115      d0 = int_from_bytes(seckey)
 116      if not (1 <= d0 <= n - 1):
 117          raise ValueError('The secret key must be an integer in the range 1..n-1.')
 118      if len(aux_rand) != 32:
 119          raise ValueError('aux_rand must be 32 bytes instead of %i.' % len(aux_rand))
 120      P = point_mul(G, d0)
 121      assert P is not None
 122      d = d0 if has_even_y(P) else n - d0
 123      t = xor_bytes(bytes_from_int(d), tagged_hash("BIP0340/aux", aux_rand))
 124      k0 = int_from_bytes(tagged_hash("BIP0340/nonce", t + bytes_from_point(P) + msg)) % n
 125      if k0 == 0:
 126          raise RuntimeError('Failure. This happens only with negligible probability.')
 127      R = point_mul(G, k0)
 128      assert R is not None
 129      k = n - k0 if not has_even_y(R) else k0
 130      e = int_from_bytes(tagged_hash("BIP0340/challenge", bytes_from_point(R) + bytes_from_point(P) + msg)) % n
 131      sig = bytes_from_point(R) + bytes_from_int((k + e * d) % n)
 132      debug_print_vars()
 133      if not schnorr_verify(msg, bytes_from_point(P), sig):
 134          raise RuntimeError('The created signature does not pass verification.')
 135      return sig
 136  
 137  
 138  def schnorr_verify(msg: bytes, pubkey: bytes, sig: bytes) -> bool:
 139      if len(pubkey) != 32:
 140          raise ValueError('The public key must be a 32-byte array.')
 141      if len(sig) != 64:
 142          raise ValueError('The signature must be a 64-byte array.')
 143      P = lift_x(int_from_bytes(pubkey))
 144      r = int_from_bytes(sig[0:32])
 145      s = int_from_bytes(sig[32:64])
 146      if (P is None) or (r >= p) or (s >= n):
 147          debug_print_vars()
 148          return False
 149      e = int_from_bytes(tagged_hash("BIP0340/challenge", sig[0:32] + pubkey + msg)) % n
 150      R = point_add(point_mul(G, s), point_mul(P, n - e))
 151      if (R is None) or (not has_even_y(R)) or (x(R) != r):
 152          debug_print_vars()
 153          return False
 154      debug_print_vars()
 155      return True
 156  
 157  
 158  #
 159  # The following code is only used to verify the test vectors.
 160  #
 161  import csv
 162  import os
 163  import sys
 164  
 165  
 166  def test_vectors() -> bool:
 167      all_passed = True
 168      with open(os.path.join(sys.path[0], 'test-vectors.csv'), newline='') as csvfile:
 169          reader = csv.reader(csvfile)
 170          reader.__next__()
 171          for row in reader:
 172              (index, seckey_hex, pubkey_hex, aux_rand_hex, msg_hex, sig_hex, result_str, comment) = row
 173              pubkey = bytes.fromhex(pubkey_hex)
 174              msg = bytes.fromhex(msg_hex)
 175              sig = bytes.fromhex(sig_hex)
 176              result = result_str == 'TRUE'
 177              print('\nTest vector', ('#' + index).rjust(3, ' ') + ':')
 178              if seckey_hex != '':
 179                  seckey = bytes.fromhex(seckey_hex)
 180                  pubkey_actual = pubkey_gen(seckey)
 181                  if pubkey != pubkey_actual:
 182                      print(' * Failed key generation.')
 183                      print('   Expected key:', pubkey.hex().upper())
 184                      print('     Actual key:', pubkey_actual.hex().upper())
 185                  aux_rand = bytes.fromhex(aux_rand_hex)
 186                  try:
 187                      sig_actual = schnorr_sign(msg, seckey, aux_rand)
 188                      if sig == sig_actual:
 189                          print(' * Passed signing test.')
 190                      else:
 191                          print(' * Failed signing test.')
 192                          print('   Expected signature:', sig.hex().upper())
 193                          print('     Actual signature:', sig_actual.hex().upper())
 194                          all_passed = False
 195                  except RuntimeError as e:
 196                      print(' * Signing test raised exception:', e)
 197                      all_passed = False
 198              result_actual = schnorr_verify(msg, pubkey, sig)
 199              if result == result_actual:
 200                  print(' * Passed verification test.')
 201              else:
 202                  print(' * Failed verification test.')
 203                  print('   Expected verification result:', result)
 204                  print('     Actual verification result:', result_actual)
 205                  if comment:
 206                      print('   Comment:', comment)
 207                  all_passed = False
 208      print()
 209      if all_passed:
 210          print('All test vectors passed.')
 211      else:
 212          print('Some test vectors failed.')
 213      return all_passed
 214  
 215  
 216  #
 217  # The following code is only used for debugging
 218  #
 219  import inspect
 220  
 221  
 222  def pretty(v: Any) -> Any:
 223      if isinstance(v, bytes):
 224          return '0x' + v.hex()
 225      if isinstance(v, int):
 226          return pretty(bytes_from_int(v))
 227      if isinstance(v, tuple):
 228          return tuple(map(pretty, v))
 229      return v
 230  
 231  
 232  def debug_print_vars() -> None:
 233      if DEBUG:
 234          current_frame = inspect.currentframe()
 235          assert current_frame is not None
 236          frame = current_frame.f_back
 237          assert frame is not None
 238          print('   Variables in function ', frame.f_code.co_name, ' at line ', frame.f_lineno, ':', sep='')
 239          for var_name, var_val in frame.f_locals.items():
 240              print('   ' + var_name.rjust(11, ' '), '==', pretty(var_val))
 241  
 242  
 243  if __name__ == '__main__':
 244      test_vectors()
 245