Skip to content

Commit 3c22663

Browse files
committed
tests: add BIP340 Schnorr signature support to test framework
Add a pure Python implementation of BIP340 signing and verification, tested against the BIP's test vectors.
1 parent 206fb18 commit 3c22663

File tree

3 files changed

+204
-6
lines changed

3 files changed

+204
-6
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
index,secret key,public key,aux_rand,message,signature,verification result,comment
2+
0,0000000000000000000000000000000000000000000000000000000000000003,F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9,0000000000000000000000000000000000000000000000000000000000000000,0000000000000000000000000000000000000000000000000000000000000000,E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA821525F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0,TRUE,
3+
1,B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,0000000000000000000000000000000000000000000000000000000000000001,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE33418906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A,TRUE,
4+
2,C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9,DD308AFEC5777E13121FA72B9CC1B7CC0139715309B086C960E18FD969774EB8,C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906,7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C,5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1BAB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7,TRUE,
5+
3,0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710,25D1DFF95105F5253C4022F628A996AD3A0D95FBF21D468A1B33F8C160D8F517,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,7EB0509757E246F19449885651611CB965ECC1A187DD51B64FDA1EDC9637D5EC97582B9CB13DB3933705B32BA982AF5AF25FD78881EBB32771FC5922EFC66EA3,TRUE,test fails if msg is reduced modulo p or n
6+
4,,D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9,,4DF3C3F68FCC83B27E9D42C90431A72499F17875C81A599B566C9889B9696703,00000000000000000000003B78CE563F89A0ED9414F5AA28AD0D96D6795F9C6376AFB1548AF603B3EB45C9F8207DEE1060CB71C04E80F593060B07D28308D7F4,TRUE,
7+
5,,EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key not on the curve
8+
6,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A14602975563CC27944640AC607CD107AE10923D9EF7A73C643E166BE5EBEAFA34B1AC553E2,FALSE,has_even_y(R) is false
9+
7,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,1FA62E331EDBC21C394792D2AB1100A7B432B013DF3F6FF4F99FCB33E0E1515F28890B3EDB6E7189B630448B515CE4F8622A954CFE545735AAEA5134FCCDB2BD,FALSE,negated message
10+
8,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769961764B3AA9B2FFCB6EF947B6887A226E8D7C93E00C5ED0C1834FF0D0C2E6DA6,FALSE,negated s value
11+
9,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,0000000000000000000000000000000000000000000000000000000000000000123DDA8328AF9C23A94C1FEECFD123BA4FB73476F0D594DCB65C6425BD186051,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 0
12+
10,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,00000000000000000000000000000000000000000000000000000000000000017615FBAF5AE28864013C099742DEADB4DBA87F11AC6754F93780D5A1837CF197,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 1
13+
11,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,4A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is not an X coordinate on the curve
14+
12,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is equal to field size
15+
13,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141,FALSE,sig[32:64] is equal to curve order
16+
14,,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key is not a valid X coordinate because it exceeds the field size

test/functional/test_framework/key.py

Lines changed: 187 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
1-
# Copyright (c) 2019 Pieter Wuille
1+
# Copyright (c) 2019-2020 Pieter Wuille
22
# Distributed under the MIT software license, see the accompanying
33
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
44
"""Test-only secp256k1 elliptic curve implementation
55
66
WARNING: This code is slow, uses bad randomness, does not properly protect
77
keys, and is trivially vulnerable to side channel attacks. Do not use for
88
anything but tests."""
9+
import csv
10+
import hashlib
11+
import os
912
import random
13+
import sys
14+
import unittest
1015

1116
from .util import modinv
1217

18+
def TaggedHash(tag, data):
19+
ss = hashlib.sha256(tag.encode('utf-8')).digest()
20+
ss += ss
21+
ss += data
22+
return hashlib.sha256(ss).digest()
23+
24+
def xor_bytes(b0, b1):
25+
return bytes(x ^ y for (x, y) in zip(b0, b1))
26+
1327
def jacobi_symbol(n, k):
1428
"""Compute the Jacobi symbol of n modulo k
1529
@@ -68,6 +82,10 @@ def affine(self, p1):
6882
inv_3 = (inv_2 * inv) % self.p
6983
return ((inv_2 * x1) % self.p, (inv_3 * y1) % self.p, 1)
7084

85+
def has_even_y(self, p1):
86+
"""Whether the point p1 has an even Y coordinate when expressed in affine coordinates."""
87+
return not (p1[2] == 0 or self.affine(p1)[1] & 1)
88+
7189
def negate(self, p1):
7290
"""Negate a Jacobian point tuple p1."""
7391
x1, y1, z1 = p1
@@ -86,13 +104,13 @@ def is_x_coord(self, x):
86104
return jacobi_symbol(x_3 + self.a * x + self.b, self.p) != -1
87105

88106
def lift_x(self, x):
89-
"""Given an X coordinate on the curve, return a corresponding affine point."""
107+
"""Given an X coordinate on the curve, return a corresponding affine point for which the Y coordinate is even."""
90108
x_3 = pow(x, 3, self.p)
91109
v = x_3 + self.a * x + self.b
92110
y = modsqrt(v, self.p)
93111
if y is None:
94112
return None
95-
return (x, y, 1)
113+
return (x, self.p - y if y & 1 else y, 1)
96114

97115
def double(self, p1):
98116
"""Double a Jacobian tuple p1
@@ -197,7 +215,8 @@ def mul(self, ps):
197215
r = self.add(r, p)
198216
return r
199217

200-
SECP256K1 = EllipticCurve(2**256 - 2**32 - 977, 0, 7)
218+
SECP256K1_FIELD_SIZE = 2**256 - 2**32 - 977
219+
SECP256K1 = EllipticCurve(SECP256K1_FIELD_SIZE, 0, 7)
201220
SECP256K1_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8, 1)
202221
SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
203222
SECP256K1_ORDER_HALF = SECP256K1_ORDER // 2
@@ -223,7 +242,7 @@ def set(self, data):
223242
p = SECP256K1.lift_x(x)
224243
# if the oddness of the y co-ord isn't correct, find the other
225244
# valid y
226-
if (p[1] & 1) != (data[0] & 1):
245+
if data[0] & 1:
227246
p = SECP256K1.negate(p)
228247
self.p = p
229248
self.valid = True
@@ -307,6 +326,10 @@ def verify_ecdsa(self, sig, msg, low_s=True):
307326
return False
308327
return True
309328

329+
def generate_privkey():
330+
"""Generate a valid random 32-byte private key."""
331+
return random.randrange(1, SECP256K1_ORDER).to_bytes(32, 'big')
332+
310333
class ECKey():
311334
"""A secp256k1 private key"""
312335

@@ -324,7 +347,7 @@ def set(self, secret, compressed):
324347

325348
def generate(self, compressed=True):
326349
"""Generate a random private key (compressed or uncompressed)."""
327-
self.set(random.randrange(1, SECP256K1_ORDER).to_bytes(32, 'big'), compressed)
350+
self.set(generate_privkey(), compressed)
328351

329352
def get_bytes(self):
330353
"""Retrieve the 32-byte representation of this key."""
@@ -369,3 +392,161 @@ def sign_ecdsa(self, msg, low_s=True):
369392
rb = r.to_bytes((r.bit_length() + 8) // 8, 'big')
370393
sb = s.to_bytes((s.bit_length() + 8) // 8, 'big')
371394
return b'\x30' + bytes([4 + len(rb) + len(sb), 2, len(rb)]) + rb + bytes([2, len(sb)]) + sb
395+
396+
def compute_xonly_pubkey(key):
397+
"""Compute an x-only (32 byte) public key from a (32 byte) private key.
398+
399+
This also returns whether the resulting public key was negated.
400+
"""
401+
402+
assert len(key) == 32
403+
x = int.from_bytes(key, 'big')
404+
if x == 0 or x >= SECP256K1_ORDER:
405+
return (None, None)
406+
P = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, x)]))
407+
return (P[0].to_bytes(32, 'big'), not SECP256K1.has_even_y(P))
408+
409+
def tweak_add_privkey(key, tweak):
410+
"""Tweak a private key (after negating it if needed)."""
411+
412+
assert len(key) == 32
413+
assert len(tweak) == 32
414+
415+
x = int.from_bytes(key, 'big')
416+
if x == 0 or x >= SECP256K1_ORDER:
417+
return None
418+
if not SECP256K1.has_even_y(SECP256K1.mul([(SECP256K1_G, x)])):
419+
x = SECP256K1_ORDER - x
420+
t = int.from_bytes(tweak, 'big')
421+
if t >= SECP256K1_ORDER:
422+
return None
423+
x = (x + t) % SECP256K1_ORDER
424+
if x == 0:
425+
return None
426+
return x.to_bytes(32, 'big')
427+
428+
def tweak_add_pubkey(key, tweak):
429+
"""Tweak a public key and return whether the result had to be negated."""
430+
431+
assert len(key) == 32
432+
assert len(tweak) == 32
433+
434+
x_coord = int.from_bytes(key, 'big')
435+
if x_coord >= SECP256K1_FIELD_SIZE:
436+
return None
437+
P = SECP256K1.lift_x(x_coord)
438+
if P is None:
439+
return None
440+
t = int.from_bytes(tweak, 'big')
441+
if t >= SECP256K1_ORDER:
442+
return None
443+
Q = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, t), (P, 1)]))
444+
if Q is None:
445+
return None
446+
return (Q[0].to_bytes(32, 'big'), not SECP256K1.has_even_y(Q))
447+
448+
def verify_schnorr(key, sig, msg):
449+
"""Verify a Schnorr signature (see BIP 340).
450+
451+
- key is a 32-byte xonly pubkey (computed using compute_xonly_pubkey).
452+
- sig is a 64-byte Schnorr signature
453+
- msg is a 32-byte message
454+
"""
455+
assert len(key) == 32
456+
assert len(msg) == 32
457+
assert len(sig) == 64
458+
459+
x_coord = int.from_bytes(key, 'big')
460+
if x_coord == 0 or x_coord >= SECP256K1_FIELD_SIZE:
461+
return False
462+
P = SECP256K1.lift_x(x_coord)
463+
if P is None:
464+
return False
465+
r = int.from_bytes(sig[0:32], 'big')
466+
if r >= SECP256K1_FIELD_SIZE:
467+
return False
468+
s = int.from_bytes(sig[32:64], 'big')
469+
if s >= SECP256K1_ORDER:
470+
return False
471+
e = int.from_bytes(TaggedHash("BIP0340/challenge", sig[0:32] + key + msg), 'big') % SECP256K1_ORDER
472+
R = SECP256K1.mul([(SECP256K1_G, s), (P, SECP256K1_ORDER - e)])
473+
if not SECP256K1.has_even_y(R):
474+
return False
475+
if ((r * R[2] * R[2]) % SECP256K1_FIELD_SIZE) != R[0]:
476+
return False
477+
return True
478+
479+
def sign_schnorr(key, msg, aux=None):
480+
"""Create a Schnorr signature (see BIP 340)."""
481+
482+
if aux is None:
483+
aux = bytes(32)
484+
485+
assert len(key) == 32
486+
assert len(msg) == 32
487+
assert len(aux) == 32
488+
489+
sec = int.from_bytes(key, 'big')
490+
if sec == 0 or sec >= SECP256K1_ORDER:
491+
return None
492+
P = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, sec)]))
493+
if not SECP256K1.has_even_y(P):
494+
sec = SECP256K1_ORDER - sec
495+
t = (sec ^ int.from_bytes(TaggedHash("BIP0340/aux", aux), 'big')).to_bytes(32, 'big')
496+
kp = int.from_bytes(TaggedHash("BIP0340/nonce", t + P[0].to_bytes(32, 'big') + msg), 'big') % SECP256K1_ORDER
497+
assert kp != 0
498+
R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, kp)]))
499+
k = kp if SECP256K1.has_even_y(R) else SECP256K1_ORDER - kp
500+
e = int.from_bytes(TaggedHash("BIP0340/challenge", R[0].to_bytes(32, 'big') + P[0].to_bytes(32, 'big') + msg), 'big') % SECP256K1_ORDER
501+
return R[0].to_bytes(32, 'big') + ((k + e * sec) % SECP256K1_ORDER).to_bytes(32, 'big')
502+
503+
class TestFrameworkKey(unittest.TestCase):
504+
def test_schnorr(self):
505+
"""Test the Python Schnorr implementation."""
506+
byte_arrays = [generate_privkey() for _ in range(3)] + [v.to_bytes(32, 'big') for v in [0, SECP256K1_ORDER - 1, SECP256K1_ORDER, 2**256 - 1]]
507+
keys = {}
508+
for privkey in byte_arrays: # build array of key/pubkey pairs
509+
pubkey, _ = compute_xonly_pubkey(privkey)
510+
if pubkey is not None:
511+
keys[privkey] = pubkey
512+
for msg in byte_arrays: # test every combination of message, signing key, verification key
513+
for sign_privkey, sign_pubkey in keys.items():
514+
sig = sign_schnorr(sign_privkey, msg)
515+
for verify_privkey, verify_pubkey in keys.items():
516+
if verify_privkey == sign_privkey:
517+
self.assertTrue(verify_schnorr(verify_pubkey, sig, msg))
518+
sig = list(sig)
519+
sig[random.randrange(64)] ^= (1 << (random.randrange(8))) # damaging signature should break things
520+
sig = bytes(sig)
521+
self.assertFalse(verify_schnorr(verify_pubkey, sig, msg))
522+
523+
def test_schnorr_testvectors(self):
524+
"""Implement the BIP340 test vectors (read from bip340_test_vectors.csv)."""
525+
num_tests = 0
526+
with open(os.path.join(sys.path[0], 'test_framework', 'bip340_test_vectors.csv'), newline='', encoding='utf8') as csvfile:
527+
reader = csv.reader(csvfile)
528+
next(reader)
529+
for row in reader:
530+
(i_str, seckey_hex, pubkey_hex, aux_rand_hex, msg_hex, sig_hex, result_str, comment) = row
531+
i = int(i_str)
532+
pubkey = bytes.fromhex(pubkey_hex)
533+
msg = bytes.fromhex(msg_hex)
534+
sig = bytes.fromhex(sig_hex)
535+
result = result_str == 'TRUE'
536+
if seckey_hex != '':
537+
seckey = bytes.fromhex(seckey_hex)
538+
pubkey_actual = compute_xonly_pubkey(seckey)[0]
539+
self.assertEqual(pubkey.hex(), pubkey_actual.hex(), "BIP340 test vector %i (%s): pubkey mismatch" % (i, comment))
540+
aux_rand = bytes.fromhex(aux_rand_hex)
541+
try:
542+
sig_actual = sign_schnorr(seckey, msg, aux_rand)
543+
self.assertEqual(sig.hex(), sig_actual.hex(), "BIP340 test vector %i (%s): sig mismatch" % (i, comment))
544+
except RuntimeError as e:
545+
self.assertFalse("BIP340 test vector %i (%s): signing raised exception %s" % (i, comment, e))
546+
result_actual = verify_schnorr(pubkey, sig, msg)
547+
if result:
548+
self.assertEqual(result, result_actual, "BIP340 test vector %i (%s): verification failed" % (i, comment))
549+
else:
550+
self.assertEqual(result, result_actual, "BIP340 test vector %i (%s): verification succeeded unexpectedly" % (i, comment))
551+
num_tests += 1
552+
self.assertTrue(num_tests >= 15) # expect at least 15 test vectors

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
"address",
7171
"blocktools",
7272
"muhash",
73+
"key",
7374
"script",
7475
"segwit_addr",
7576
"util",

0 commit comments

Comments
 (0)