do_hashlib_scrypt(): cleanups

This commit is contained in:
The MMGen Project 2021-09-24 20:07:05 +00:00
commit 8559b9c668
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
4 changed files with 34 additions and 20 deletions

View file

@ -96,26 +96,39 @@ def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):
# Buflen arg is for brainwallets only, which use this function to generate
# the seed directly.
N,r,p = get_hash_params(hash_preset)
if isinstance(passwd,str): passwd = passwd.encode()
ps = get_hash_params(hash_preset)
if isinstance(passwd,str):
passwd = passwd.encode()
def do_hashlib_scrypt():
from hashlib import scrypt # Python >= v3.6
return scrypt(passwd,salt=salt,n=2**N,r=r,p=p,maxmem=0,dklen=buflen)
from hashlib import scrypt
return scrypt(
password = passwd,
salt = salt,
n = 2**ps.N,
r = ps.r,
p = ps.p,
maxmem = 0,
dklen = buflen )
def do_standalone_scrypt():
import scrypt
return scrypt.hash(passwd,salt,2**N,r,p,buflen=buflen)
return scrypt.hash(
password = passwd,
salt = salt,
N = 2**ps.N,
r = ps.r,
p = ps.p,
buflen = buflen )
if int(hash_preset) > 3:
msg_r('Hashing passphrase, please wait...')
# hashlib.scrypt doesn't support N > 14 (hash preset 3)
if N > 14 or g.force_standalone_scrypt_module:
ret = do_standalone_scrypt()
else:
try: ret = do_hashlib_scrypt()
except: ret = do_standalone_scrypt()
# hashlib.scrypt doesn't support N > 14 (hash preset > 3)
ret = (
do_standalone_scrypt() if ps.N > 14 or g.force_standalone_scrypt_module else
do_hashlib_scrypt() )
if int(hash_preset) > 3:
msg_r('\b'*34 + ' '*34 + '\b'*34)

View file

@ -282,14 +282,15 @@ class GlobalContext(Lockable):
# Scrypt params: 'id_num': [N, r, p] (N is an exponent of two)
# NB: hashlib.scrypt in Python (>=v3.6) supports max N value of 14. This means that
# for hash presets > 3 the standalone scrypt library must be used!
_hp = namedtuple('scrypt_preset',['N','r','p'])
hash_presets = {
'1': [12, 8, 1],
'2': [13, 8, 4],
'3': [14, 8, 8],
'4': [15, 8, 12],
'5': [16, 8, 16],
'6': [17, 8, 20],
'7': [18, 8, 24],
'1': _hp(12, 8, 1),
'2': _hp(13, 8, 4),
'3': _hp(14, 8, 8),
'4': _hp(15, 8, 12),
'5': _hp(16, 8, 16),
'6': _hp(17, 8, 20),
'7': _hp(18, 8, 24),
}
if os.getenv('MMGEN_TEST_SUITE'):

View file

@ -426,7 +426,7 @@ def strip_comments(lines):
def get_hash_params(hash_preset):
if hash_preset in g.hash_presets:
return g.hash_presets[hash_preset] # N,p,r,buflen
return g.hash_presets[hash_preset] # N,r,p
else: # Shouldn't be here
die(3,f"{hash_preset}: invalid 'hash_preset' value")

View file

@ -815,7 +815,7 @@ class MMGenWallet(WalletEnc):
if opt.hash_preset and opt.hash_preset != hp:
qmsg('Warning: ignoring user-requested hash preset {opt.hash_preset}')
hash_params = list(map(int,hpdata[1:]))
hash_params = tuple(map(int,hpdata[1:]))
if hash_params != get_hash_params(d.hash_preset):
msg(f"Hash parameters {' '.join(hash_params)!r} don't match hash preset {d.hash_preset!r}")