minor fixes and cleanups

This commit is contained in:
The MMGen Project 2022-01-15 14:00:11 +00:00
commit 7cb44abd78
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
11 changed files with 50 additions and 40 deletions

View file

@ -20,13 +20,11 @@
addr.py: Address generation/display routines for the MMGen suite
"""
from hashlib import sha256,sha512
from .common import *
from .objmethods import MMGenObject
from .obj import *
from .baseconv import *
from .protocol import hash160
from .key import PrivKey,PubKey
from string import ascii_letters,digits
from collections import namedtuple
from .objmethods import Hilite,InitErrors,MMGenObject
from .obj import ImmutableAttr,MMGenIdx,HexStr,get_obj
from .seed import SeedID
ati = namedtuple('addrtype_info',
@ -59,6 +57,7 @@ class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
if isinstance(id_str,cls):
return id_str
try:
id_str = id_str.replace('-','_')
for k,v in cls.mmtypes.items():
if id_str in (k,v.name):
if id_str == v.name:
@ -180,6 +179,12 @@ class MoneroViewKey(HexStr):
class ZcashViewKey(CoinAddr):
hex_width = 128
from .opts import opt
from .util import qmsg
from .protocol import hash160
from .key import PrivKey,PubKey
from .baseconv import baseconv
class AddrGenerator(MMGenObject):
def __new__(cls,proto,addr_type):

View file

@ -36,9 +36,7 @@ altcoin.py - Coin constants for Bitcoin-derived altcoins
# NBT: 150/191 c/u, 25/('B'), 26/('B')
import sys
def msg(s):
sys.stderr.write(s+'\n')
from mmgen.util import msg
def test_equal(desc,a,b,*cdata):
if type(a) == int:
@ -599,14 +597,13 @@ class CoinInfo(object):
trust_override = {'BTC':3,'BCH':3,'LTC':3,'DASH':1,'EMC':2}
@classmethod
def get_test_support(cls,coin,addr_type,network,tool=None,verbose=False):
def get_test_support(cls,coin,addr_type,network,toolname=None,verbose=False):
"""
If requested tool supports coin/addr_type/network triplet, return tool name.
If 'tool' is None, return tool that supports coin/addr_type/network triplet.
Return None on failure.
"""
tool_arg = tool
all_tools = [tool] if tool else list(cls.external_tests[network].keys())
all_tools = [toolname] if toolname else list(cls.external_tests[network].keys())
coin = coin.upper()
for tool in all_tools:
@ -616,11 +613,11 @@ class CoinInfo(object):
if verbose:
m1 = 'Requested tool {t!r} does not support coin {c} on network {n}'
m2 = 'No test tool found for coin {c} on network {n}'
msg((m1 if tool_arg else m2).format(t=tool,c=coin,n=network))
msg((m1 if toolname else m2).format(t=tool,c=coin,n=network))
return None
if addr_type == 'zcash_z':
if tool_arg in (None,'zcash-mini'):
if toolname in (None,'zcash-mini'):
return 'zcash-mini'
else:
if verbose:
@ -638,7 +635,7 @@ class CoinInfo(object):
msg(f'Tool {tool!r} blacklisted for coin {coin}, addr_type {addr_type!r}')
return None
if tool_arg: # skip whitelists
if toolname: # skip whitelists
return tool
if addr_type in ('segwit','bech32'):
@ -649,7 +646,7 @@ class CoinInfo(object):
if verbose:
m1 = 'Requested tool {t!r} does not support coin {c}, addr_type {a!r}, on network {n}'
m2 = 'No test tool found supporting coin {c}, addr_type {a!r}, on network {n}'
msg((m1 if tool_arg else m2).format(t=tool,c=coin,n=network,a=addr_type))
msg((m1 if toolname else m2).format(t=tool,c=coin,n=network,a=addr_type))
return None
return tool

View file

@ -119,7 +119,6 @@ FMT CODES:
seed_lens=', '.join(map(str,g.seed_lens)),
g=g,pnm=g.proj_name,
dpf=PasswordList.dfl_pw_fmt,
kgs=' '.join([f'{n}:{k}' for n,k in enumerate(g.key_generators,1)])
),
'notes': lambda help_notes,s: s.format(
o=opts,g=g,i58=pwi['b58'],i32=pwi['b32'],i39=pwi['bip39'],

View file

@ -59,21 +59,21 @@ opts_data = {
'desc': f'Perform various {g.proj_name}- and cryptocoin-related operations',
'usage': '[opts] <command> <command args>',
'options': """
-d, --outdir= d Specify an alternate directory 'd' for output
-h, --help Print this help message
--, --longhelp Print help message for long options (common options)
-d, --outdir= d Specify an alternate directory 'd' for output
-h, --help Print this help message
--, --longhelp Print help message for long options (common options)
-k, --use-internal-keccak-module Force use of the internal keccak module
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.dfl_hash_preset}')
-P, --passwd-file= f Get passphrase from file 'f'.
-q, --quiet Produce quieter output
-r, --usr-randchars=n Get 'n' characters of additional randomness from
user (min={g.min_urandchars}, max={g.max_urandchars})
-t, --type=t Specify address type (valid options: 'legacy',
'compressed', 'segwit', 'bech32', 'zcash_z')
-v, --verbose Produce more verbose output
-X, --cached-balances Use cached balances (Ethereum only)
-y, --yes Answer 'yes' to prompts, suppress non-essential output
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.dfl_hash_preset}')
-P, --passwd-file= f Get passphrase from file 'f'.
-q, --quiet Produce quieter output
-r, --usr-randchars=n Get 'n' characters of additional randomness from
user (min={g.min_urandchars}, max={g.max_urandchars})
-t, --type=t Specify address type (valid options: 'legacy',
'compressed', 'segwit', 'bech32', 'zcash_z')
-v, --verbose Produce more verbose output
-X, --cached-balances Use cached balances (Ethereum only)
-y, --yes Answer 'yes' to prompts, suppress non-essential output
""",
'notes': """

View file

@ -202,7 +202,7 @@ class PasswordList(AddrList):
bytes_preproc = init_proto('xmr').preprocess_key(
bytes.fromhex(hex_sec[:pw_len_hex]),
None )
return ' '.join(baseconv.frombytes(bytes_preproc,wl_id='xmrseed'))
return ' '.join( baseconv.frombytes( bytes_preproc, wl_id='xmrseed' ) )
else:
# take least significant part
return baseconv.fromhex(

View file

@ -92,6 +92,7 @@ class CoinProtocol(MMGenObject):
def __init__(self,coin,name,network,tokensym=None):
self.coin = coin.upper()
self.coin_id = self.coin
self.name = name
self.network = network
self.tokensym = tokensym
@ -456,6 +457,11 @@ class CoinProtocol(MMGenObject):
dfl_mmtype = 'L'
avg_bdi = 75
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
from .opts import opt
self.coin_id = 'ZEC-Z' if getattr(opt,'type',None) in ('zcash_z','Z') else 'ZEC-T'
def get_addr_len(self,addr_fmt):
return (20,64)[addr_fmt in ('zcash_z','viewkey')]
@ -470,7 +476,7 @@ class CoinProtocol(MMGenObject):
if hash_len == 40:
return super().pubhash2addr(pubkey_hash,p2sh)
elif hash_len == 128:
raise NotImplementedError('Zcash z-addresses have no pubkey hash')
raise NotImplementedError('Zcash z-addresses do not support pubhash2addr()')
else:
raise ValueError(f'{hash_len}: incorrect pubkey_hash length')

View file

@ -107,7 +107,7 @@ def get_tw_label(proto,s):
except BadTwComment:
raise
except Exception as e:
print(e)
# print(e)
return None
class TwUnspentOutputs(MMGenObject,metaclass=AsyncInit):

View file

@ -584,7 +584,7 @@ class MoneroWalletOps:
'restore_deterministic_wallet',
filename = os.path.basename(fn),
password = d.wallet_passwd,
seed = baseconv.fromhex(d.sec,'xmrseed',tostr=True),
seed = baseconv.fromhex(d.sec.wif,'xmrseed',tostr=True),
restore_height = uopt.restore_height,
language = 'English' )

View file

@ -242,7 +242,7 @@ def find_or_check_tool(proto,addr_type,toolname):
addr_type.name,
proto.network,
verbose = not opt.quiet,
tool = toolname if toolname != 'ext' else None )
toolname = toolname if toolname != 'ext' else None )
if tool and toolname in ext_progs and toolname != tool:
sys.exit(3)
if tool == None:

View file

@ -36,6 +36,7 @@ from mmgen.seedsplit import *
from mmgen.addr import *
from mmgen.addrlist import *
from mmgen.addrdata import *
from mmgen.tw import *
from mmgen.amt import *
from mmgen.key import *
from mmgen.rpc import IPPort

View file

@ -383,7 +383,7 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
from mmgen.addr import KeyGenerator,AddrGenerator
rand_coinaddr = AddrGenerator(
self.proto,
'compressed'
('legacy','compressed')[non_mmgen_input_compressed]
).to_addr(KeyGenerator(self.proto,'std').to_pubhex(privkey))
of = joinpath(self.cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
write_data_to_file(
@ -420,8 +420,10 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
from mmgen.key import PrivKey
privkey = PrivKey(self.proto,getrand(32),compressed=True,pubkey_type='std')
t = ('compressed','segwit')['S' in self.proto.mmtypes]
from mmgen.addr import AddrGenerator,KeyGenerator
rand_coinaddr = AddrGenerator(self.proto,t).to_addr(KeyGenerator(self.proto,'std').to_pubhex(privkey))
from mmgen.addr import KeyGenerator,AddrGenerator
rand_coinaddr = AddrGenerator(self.proto,t).to_addr(
KeyGenerator(self.proto,'std').to_pubhex(privkey)
)
# total of two outputs must be < 10 BTC (<1000 LTC)
mods = {'btc':(6,4),'bch':(6,4),'ltc':(600,400)}[self.proto.coin.lower()]