Skip to content

Commit bc51a13

Browse files
elichaijnewbery
authored andcommitted
make ECKey operations generic over bytes/int
1 parent 033ec30 commit bc51a13

File tree

1 file changed

+14
-8
lines changed
  • test/functional/test_framework

1 file changed

+14
-8
lines changed

test/functional/test_framework/key.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ def modsqrt(a, p):
6565
return sqrt
6666
return None
6767

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+
6877
class EllipticCurve:
6978
def __init__(self, p, a, b):
7079
"""Initialize elliptic curve y^2 = x^3 + a*x + b over GF(p)."""
@@ -384,8 +393,7 @@ def __sub__(self, other):
384393

385394
def tweak_add(self, tweak):
386395
assert(self.valid)
387-
assert(len(tweak) == 32)
388-
t = int.from_bytes(tweak, 'big')
396+
t = int_or_bytes(tweak)
389397
if t >= SECP256K1_ORDER:
390398
return None
391399
tweaked = SECP256K1.affine(SECP256K1.mul([(self.p, 1), (SECP256K1_G, t)]))
@@ -400,7 +408,6 @@ def tweak_add(self, tweak):
400408
def mul(self, data):
401409
"""Multiplies ECPubKey point with scalar data."""
402410
assert self.valid
403-
assert len(data) == 32
404411
other = ECKey()
405412
other.set(data, True)
406413
return self * other
@@ -412,9 +419,9 @@ def __init__(self):
412419
self.valid = False
413420

414421
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+
418425
self.valid = (secret > 0 and secret < SECP256K1_ORDER)
419426
if self.valid:
420427
self.secret = secret
@@ -556,8 +563,7 @@ def sign_schnorr(self, msg, nonce=None):
556563
def tweak_add(self, tweak):
557564
"""Return a tweaked version of this private key."""
558565
assert(self.valid)
559-
assert(len(tweak) == 32)
560-
t = int.from_bytes(tweak, 'big')
566+
t = int_or_bytes(tweak)
561567
if t >= SECP256K1_ORDER:
562568
return None
563569
tweaked = (self.secret + t) % SECP256K1_ORDER

0 commit comments

Comments
 (0)