Repository Public
1from typing import Tuple, Optional, Any2import hashlib34# Set DEBUG to True to get a detailed debug output including5# intermediate values during key generation, signing, and6# verification. This is implemented via calls to the7# debug_print_vars() function.8#9# If you want to print values on an individual basis, use10# the pretty() function, e.g., print(pretty(foo)).11DEBUG = False1213p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F14n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD03641411516# Points are tuples of X and Y coordinates and the point at infinity is17# represented by the None keyword.18G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)1920Point = Tuple[int, int]2122# This implementation can be sped up by storing the midstate after hashing23# tag_hash instead of rehashing it all the time.24def tagged_hash(tag: str, msg: bytes) -> bytes:25 tag_hash = hashlib.sha256(tag.encode()).digest()26 return hashlib.sha256(tag_hash + tag_hash + msg).digest()2728def is_infinite(P: Optional[Point]) -> bool:29 return P is None3031def x(P: Point) -> int:32 assert not is_infinite(P)33 return P[0]3435def y(P: Point) -> int:36 assert not is_infinite(P)37 return P[1]3839def point_add(P1: Optional[Point], P2: Optional[Point]) -> Optional[Point]:40 if P1 is None:41 return P242 if P2 is None:43 return P144 if (x(P1) == x(P2)) and (y(P1) != y(P2)):45 return None46 if P1 == P2:47 lam = (3 * x(P1) * x(P1) * pow(2 * y(P1), p - 2, p)) % p48 else:49 lam = ((y(P2) - y(P1)) * pow(x(P2) - x(P1), p - 2, p)) % p50 x3 = (lam * lam - x(P1) - x(P2)) % p51 return (x3, (lam * (x(P1) - x3) - y(P1)) % p)5253def point_mul(P: Optional[Point], n: int) -> Optional[Point]:54 R = None55 for i in range(256):56 if (n >> i) & 1:57 R = point_add(R, P)58 P = point_add(P, P)59 return R6061def bytes_from_int(x: int) -> bytes:62 return x.to_bytes(32, byteorder="big")6364def bytes_from_point(P: Point) -> bytes:65 return bytes_from_int(x(P))6667def xor_bytes(b0: bytes, b1: bytes) -> bytes:68 return bytes(x ^ y for (x, y) in zip(b0, b1))6970def lift_x(x: int) -> Optional[Point]:71 if x >= p:72 return None73 y_sq = (pow(x, 3, p) + 7) % p74 y = pow(y_sq, (p + 1) // 4, p)75 if pow(y, 2, p) != y_sq:76 return None77 return (x, y if y & 1 == 0 else p-y)7879def int_from_bytes(b: bytes) -> int:80 return int.from_bytes(b, byteorder="big")8182def hash_sha256(b: bytes) -> bytes:83 return hashlib.sha256(b).digest()8485def has_even_y(P: Point) -> bool:86 assert not is_infinite(P)87 return y(P) % 2 == 08889def pubkey_gen(seckey: bytes) -> bytes:90 d0 = int_from_bytes(seckey)91 if not (1 <= d0 <= n - 1):92 raise ValueError('The secret key must be an integer in the range 1..n-1.')93 P = point_mul(G, d0)94 assert P is not None95 return bytes_from_point(P)9697def schnorr_sign(msg: bytes, seckey: bytes, aux_rand: bytes) -> bytes:98 d0 = int_from_bytes(seckey)99 if not (1 <= d0 <= n - 1):100 raise ValueError('The secret key must be an integer in the range 1..n-1.')101 if len(aux_rand) != 32:102 raise ValueError('aux_rand must be 32 bytes instead of %i.' % len(aux_rand))103 P = point_mul(G, d0)104 assert P is not None105 d = d0 if has_even_y(P) else n - d0106 t = xor_bytes(bytes_from_int(d), tagged_hash("BIP0340/aux", aux_rand))107 k0 = int_from_bytes(tagged_hash("BIP0340/nonce", t + bytes_from_point(P) + msg)) % n108 if k0 == 0:109 raise RuntimeError('Failure. This happens only with negligible probability.')110 R = point_mul(G, k0)111 assert R is not None112 k = n - k0 if not has_even_y(R) else k0113 e = int_from_bytes(tagged_hash("BIP0340/challenge", bytes_from_point(R) + bytes_from_point(P) + msg)) % n114 sig = bytes_from_point(R) + bytes_from_int((k + e * d) % n)115 debug_print_vars()116 if not schnorr_verify(msg, bytes_from_point(P), sig):117 raise RuntimeError('The created signature does not pass verification.')118 return sig119120def schnorr_verify(msg: bytes, pubkey: bytes, sig: bytes) -> bool:121 if len(pubkey) != 32:122 raise ValueError('The public key must be a 32-byte array.')123 if len(sig) != 64:124 raise ValueError('The signature must be a 64-byte array.')125 P = lift_x(int_from_bytes(pubkey))126 r = int_from_bytes(sig[0:32])127 s = int_from_bytes(sig[32:64])128 if (P is None) or (r >= p) or (s >= n):129 debug_print_vars()130 return False131 e = int_from_bytes(tagged_hash("BIP0340/challenge", sig[0:32] + pubkey + msg)) % n132 R = point_add(point_mul(G, s), point_mul(P, n - e))133 if (R is None) or (not has_even_y(R)) or (x(R) != r):134 debug_print_vars()135 return False136 debug_print_vars()137 return True138139#140# The following code is only used to verify the test vectors.141#142import csv143import os144import sys145146def test_vectors() -> bool:147 all_passed = True148 with open(os.path.join(sys.path[0], 'test-vectors.csv'), newline='') as csvfile:149 reader = csv.reader(csvfile)150 reader.__next__()151 for row in reader:152 (index, seckey_hex, pubkey_hex, aux_rand_hex, msg_hex, sig_hex, result_str, comment) = row153 pubkey = bytes.fromhex(pubkey_hex)154 msg = bytes.fromhex(msg_hex)155 sig = bytes.fromhex(sig_hex)156 result = result_str == 'TRUE'157 print('\nTest vector', ('#' + index).rjust(3, ' ') + ':')158 if seckey_hex != '':159 seckey = bytes.fromhex(seckey_hex)160 pubkey_actual = pubkey_gen(seckey)161 if pubkey != pubkey_actual:162 print(' * Failed key generation.')163 print(' Expected key:', pubkey.hex().upper())164 print(' Actual key:', pubkey_actual.hex().upper())165 all_passed = False166 aux_rand = bytes.fromhex(aux_rand_hex)167 try:168 sig_actual = schnorr_sign(msg, seckey, aux_rand)169 if sig == sig_actual:170 print(' * Passed signing test.')171 else:172 print(' * Failed signing test.')173 print(' Expected signature:', sig.hex().upper())174 print(' Actual signature:', sig_actual.hex().upper())175 all_passed = False176 except RuntimeError as e:177 print(' * Signing test raised exception:', e)178 all_passed = False179 result_actual = schnorr_verify(msg, pubkey, sig)180 if result == result_actual:181 print(' * Passed verification test.')182 else:183 print(' * Failed verification test.')184 print(' Expected verification result:', result)185 print(' Actual verification result:', result_actual)186 if comment:187 print(' Comment:', comment)188 all_passed = False189 print()190 if all_passed:191 print('All test vectors passed.')192 else:193 print('Some test vectors failed.')194 return all_passed195196#197# The following code is only used for debugging198#199import inspect200201def pretty(v: Any) -> Any:202 if isinstance(v, bytes):203 return '0x' + v.hex()204 if isinstance(v, int):205 return pretty(bytes_from_int(v))206 if isinstance(v, tuple):207 return tuple(map(pretty, v))208 return v209210def debug_print_vars() -> None:211 if DEBUG:212 current_frame = inspect.currentframe()213 assert current_frame is not None214 frame = current_frame.f_back215 assert frame is not None216 print(' Variables in function ', frame.f_code.co_name, ' at line ', frame.f_lineno, ':', sep='')217 for var_name, var_val in frame.f_locals.items():218 print(' ' + var_name.rjust(11, ' '), '==', pretty(var_val))219220if __name__ == '__main__':221 test_vectors()222