@@ -65,6 +65,15 @@ def modsqrt(a, p):
65
65
return sqrt
66
66
return None
67
67
68
+ def int_or_bytes (s ):
69
+ "Convert 32-bytes to int while accepting also int and returning it as is."
70
+ if isinstance (s , bytes ):
71
+ assert (len (s ) == 32 )
72
+ s = int .from_bytes (s , 'big' )
73
+ elif not isinstance (s , int ):
74
+ raise TypeError
75
+ return s
76
+
68
77
class EllipticCurve :
69
78
def __init__ (self , p , a , b ):
70
79
"""Initialize elliptic curve y^2 = x^3 + a*x + b over GF(p)."""
@@ -384,8 +393,7 @@ def __sub__(self, other):
384
393
385
394
def tweak_add (self , tweak ):
386
395
assert (self .valid )
387
- assert (len (tweak ) == 32 )
388
- t = int .from_bytes (tweak , 'big' )
396
+ t = int_or_bytes (tweak )
389
397
if t >= SECP256K1_ORDER :
390
398
return None
391
399
tweaked = SECP256K1 .affine (SECP256K1 .mul ([(self .p , 1 ), (SECP256K1_G , t )]))
@@ -400,7 +408,6 @@ def tweak_add(self, tweak):
400
408
def mul (self , data ):
401
409
"""Multiplies ECPubKey point with scalar data."""
402
410
assert self .valid
403
- assert len (data ) == 32
404
411
other = ECKey ()
405
412
other .set (data , True )
406
413
return self * other
@@ -412,9 +419,9 @@ def __init__(self):
412
419
self .valid = False
413
420
414
421
def set (self , secret , compressed ):
415
- """Construct a private key object with given 32-byte secret and compressed flag."""
416
- assert ( len ( secret ) == 32 )
417
- secret = int . from_bytes ( secret , 'big' )
422
+ """Construct a private key object from either 32-bytes or an int secret and a compressed flag."""
423
+ secret = int_or_bytes ( secret )
424
+
418
425
self .valid = (secret > 0 and secret < SECP256K1_ORDER )
419
426
if self .valid :
420
427
self .secret = secret
@@ -556,8 +563,7 @@ def sign_schnorr(self, msg, nonce=None):
556
563
def tweak_add (self , tweak ):
557
564
"""Return a tweaked version of this private key."""
558
565
assert (self .valid )
559
- assert (len (tweak ) == 32 )
560
- t = int .from_bytes (tweak , 'big' )
566
+ t = int_or_bytes (tweak )
561
567
if t >= SECP256K1_ORDER :
562
568
return None
563
569
tweaked = (self .secret + t ) % SECP256K1_ORDER
0 commit comments