merge bitcoin#27538: remove modinv python util helper function

This commit is contained in:
Kittywhiskers Van Gogh 2023-04-27 18:08:20 +01:00 committed by pasta
parent 13c8dc535c
commit 3960c1bccf
No known key found for this signature in database
GPG Key ID: 52527BEDABE87984
3 changed files with 4 additions and 28 deletions

View File

@ -13,8 +13,6 @@ import random
import sys
import unittest
from .util import modinv
def TaggedHash(tag, data):
ss = hashlib.sha256(tag.encode('utf-8')).digest()
ss += ss
@ -77,7 +75,7 @@ class EllipticCurve:
x1, y1, z1 = p1
if z1 == 0:
return None
inv = modinv(z1, self.p)
inv = pow(z1, -1, self.p)
inv_2 = (inv**2) % self.p
inv_3 = (inv_2 * inv) % self.p
return ((inv_2 * x1) % self.p, (inv_3 * y1) % self.p, 1)
@ -318,7 +316,7 @@ class ECPubKey():
z = int.from_bytes(msg, 'big')
# Run verifier algorithm on r, s
w = modinv(s, SECP256K1_ORDER)
w = pow(s, -1, SECP256K1_ORDER)
u1 = z*w % SECP256K1_ORDER
u2 = r*w % SECP256K1_ORDER
R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, u1), (self.p, u2)]))
@ -383,7 +381,7 @@ class ECKey():
k = random.randrange(1, SECP256K1_ORDER)
R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, k)]))
r = R[0] % SECP256K1_ORDER
s = (modinv(k, SECP256K1_ORDER) * (z + self.secret * r)) % SECP256K1_ORDER
s = (pow(k, -1, SECP256K1_ORDER) * (z + self.secret * r)) % SECP256K1_ORDER
if low_s and s > SECP256K1_ORDER_HALF:
s = SECP256K1_ORDER - s
# Represent in DER format. The byte representations of r and s have

View File

@ -6,8 +6,6 @@
import hashlib
import unittest
from .util import modinv
def rot32(v, bits):
"""Rotate the 32-bit value v left by bits bits."""
bits %= 32 # Make sure the term below does not throw an exception
@ -88,7 +86,7 @@ class MuHash3072:
def digest(self):
"""Extract the final hash. Does not modify this object."""
val = (self.numerator * modinv(self.denominator, self.MODULUS)) % self.MODULUS
val = (self.numerator * pow(self.denominator, -1, self.MODULUS)) % self.MODULUS
bytes384 = val.to_bytes(384, 'little')
return hashlib.sha256(bytes384).digest()

View File

@ -16,7 +16,6 @@ import os
import shutil
import re
import time
import unittest
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
@ -597,22 +596,3 @@ def find_vout_for_address(node, txid, addr):
if any([addr == a for a in tx["vout"][i]["scriptPubKey"]["addresses"]]):
return i
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
def modinv(a, n):
"""Compute the modular inverse of a modulo n using the extended Euclidean
Algorithm. See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers.
"""
return pow(a, -1, n)
class TestFrameworkUtil(unittest.TestCase):
def test_modinv(self):
test_vectors = [
[7, 11],
[11, 29],
[90, 13],
[1891, 3797],
[6003722857, 77695236973],
]
for a, n in test_vectors:
self.assertEqual(modinv(a, n), pow(a, n-2, n))