From da5742f667ac015ac4cf11ced11c950761077e43 Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Sun, 12 Apr 2020 15:02:52 +0000 Subject: [PATCH] various cleanups throughout --- mmgen/globalvars.py | 2 +- mmgen/main_tool.py | 2 +- mmgen/main_txcreate.py | 5 +++-- mmgen/main_txdo.py | 5 +++-- mmgen/regtest.py | 3 ++- mmgen/tool.py | 4 ++-- mmgen/tx.py | 21 ++++++++++++--------- mmgen/util.py | 6 ++++-- scripts/traceback_run.py | 23 +++++++++++++---------- 9 files changed, 41 insertions(+), 30 deletions(-) diff --git a/mmgen/globalvars.py b/mmgen/globalvars.py index e5400629..3cea849f 100755 --- a/mmgen/globalvars.py +++ b/mmgen/globalvars.py @@ -171,7 +171,7 @@ class g(object): ('label','keep_label'), ('tx_id','info'), ('tx_id','terse_info'), - ('batch','rescan') # still incompatible as of Core 0.15.0 + ('batch','rescan'), # TODO: still incompatible? ) cfg_file_opts = ( 'color','debug','hash_preset','http_timeout','no_license','rpc_host','rpc_port', diff --git a/mmgen/main_tool.py b/mmgen/main_tool.py index f7ea9f49..2d792774 100755 --- a/mmgen/main_tool.py +++ b/mmgen/main_tool.py @@ -41,7 +41,7 @@ def make_cmd_help(): max_w = max(map(len,bc.user_commands)) fs = ' {{:{}}} - {{}}'.format(max_w) - for name,code in bc.user_commands.items(): + for name,code in sorted(bc.user_commands.items()): if code.__doc__: yield fs.format(name, pretty_format( diff --git a/mmgen/main_txcreate.py b/mmgen/main_txcreate.py index 014e25d1..8badc068 100755 --- a/mmgen/main_txcreate.py +++ b/mmgen/main_txcreate.py @@ -38,7 +38,7 @@ opts_data = { -d, --outdir= d Specify an alternate directory 'd' for output -D, --contract-data=D Path to hex-encoded contract data (ETH only) -E, --fee-estimate-mode=M Specify the network fee estimate mode. Choices: - {fe[1]}. Default: '{fe[1][0]}' + {fe_all}. Default: {fe_dfl!r} -f, --tx-fee= f Transaction fee, as a decimal {cu} amount or as {fu} (an integer followed by {fl}). See FEE SPECIFICATION below. If omitted, fee will be @@ -64,7 +64,8 @@ opts_data = { 'options': lambda s: s.format( fu=help_notes('rel_fee_desc'), fl=help_notes('fee_spec_letters'), - fe=g.autoset_opts['fee_estimate_mode'], + fe_all=fmt_list(g.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'), + fe_dfl=g.autoset_opts['fee_estimate_mode'].choices[0], cu=g.coin, g=g), 'notes': lambda s: s.format( diff --git a/mmgen/main_txdo.py b/mmgen/main_txdo.py index 71843259..cff07604 100755 --- a/mmgen/main_txdo.py +++ b/mmgen/main_txdo.py @@ -42,7 +42,7 @@ opts_data = { -D, --contract-data= D Path to hex-encoded contract data (ETH only) -e, --echo-passphrase Print passphrase to screen when typing it -E, --fee-estimate-mode=M Specify the network fee estimate mode. Choices: - {fe[1]}. Default: '{fe[1][0]}' + {fe_all}. Default: {fe_dfl!r} -f, --tx-fee= f Transaction fee, as a decimal {cu} amount or as {fu} (an integer followed by {fl}). See FEE SPECIFICATION below. If omitted, fee will be @@ -99,7 +99,8 @@ column below: fu=help_notes('rel_fee_desc'), fl=help_notes('fee_spec_letters'), ss=g.subseeds,ss_max=SubSeedIdxRange.max_idx, - fe=g.autoset_opts['fee_estimate_mode'], + fe_all=fmt_list(g.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'), + fe_dfl=g.autoset_opts['fee_estimate_mode'].choices[0], kg=g.key_generator, cu=g.coin), 'notes': lambda s: s.format( diff --git a/mmgen/regtest.py b/mmgen/regtest.py index 3d3fdc72..e8506906 100755 --- a/mmgen/regtest.py +++ b/mmgen/regtest.py @@ -179,12 +179,13 @@ class MMGenRegtest(MMGenObject): lines = reversed(get_log_tail(40_000).decode().splitlines()) + pat = re.compile(r'\bwallet\.dat\.([a-z]+)') for ss in ( 'BerkeleyEnvironment::Open', 'Wallet completed loading in', 'Using wallet wallet' ): for line in lines: if ss in line: - m = re.search(r'\bwallet\.dat\.([a-z]+)',line) + m = pat.search(line) if m and m.group(1) in self.users: return m.group(1) diff --git a/mmgen/tool.py b/mmgen/tool.py index 253dbf99..853d90a2 100755 --- a/mmgen/tool.py +++ b/mmgen/tool.py @@ -94,7 +94,7 @@ def _usage(cmd=None,exit_val=1): cls_info = bc.__doc__.strip().split('\n')[0] Msg(' {}{}\n'.format(cls_info[0].upper(),cls_info[1:])) max_w = max(map(len,bc.user_commands)) - for cmd in bc.user_commands: + for cmd in sorted(bc.user_commands): Msg(' {:{w}} {}'.format(cmd,_create_call_sig(cmd),w=max_w)) Msg('') Msg(m2) @@ -240,7 +240,7 @@ class MMGenToolCmdMeta(type): classes = {} methods = {} def __new__(mcls,name,bases,namespace): - methods = {k:v for k,v in namespace.items() if k[0] != '_' and callable(v)} + methods = {k:v for k,v in namespace.items() if k[0] != '_' and callable(v) and v.__doc__} if g.test_suite: if name in mcls.classes: raise ValueError(f'Class {name!r} already defined!') diff --git a/mmgen/tx.py b/mmgen/tx.py index 67301292..bfda37a8 100755 --- a/mmgen/tx.py +++ b/mmgen/tx.py @@ -588,18 +588,21 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam # given tx size and absolute fee or fee spec, return absolute fee # relative fee is N+ def process_fee_spec(self,tx_fee,tx_size,on_fail='throw'): - import re - units = {u[0]:u for u in g.proto.coin_amt.units} - pat = r'([1-9][0-9]*)({})'.format('|'.join(units.keys())) + if g.proto.coin_amt(tx_fee,on_fail='silent'): return g.proto.coin_amt(tx_fee) - elif re.match(pat,tx_fee): - return self.convert_fee_spec(tx_size,units,*re.match(pat,tx_fee).groups()) else: - if on_fail == 'return': - return False - elif on_fail == 'throw': - assert False, "'{}': invalid tx-fee argument".format(tx_fee) + import re + units = {u[0]:u for u in g.proto.coin_amt.units} + pat = re.compile(r'([1-9][0-9]*)({})'.format('|'.join(units))) + if pat.match(tx_fee): + amt,unit = pat.match(tx_fee).groups() + return self.convert_fee_spec(tx_size,units,amt,unit) + + if on_fail == 'return': + return False + elif on_fail == 'throw': + assert False, "'{}': invalid tx-fee argument".format(tx_fee) def get_usr_fee_interactive(self,tx_fee=None,desc='Starting'): abs_fee = None diff --git a/mmgen/util.py b/mmgen/util.py index cbc58be1..cfa6a56a 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -107,6 +107,8 @@ def fmt_list(l,fmt='dfl',indent=''): 'dfl': ("', '", "'", "'"), 'bare': (' ', '', '' ), 'no_quotes': (', ', '', '' ), + 'no_spc': ("','", "'", "'"), + 'min': (",", "'", "'"), 'col': ('\n'+indent, indent, '' ), }[fmt] return lq + sep.join(l) + rq @@ -390,8 +392,8 @@ def pretty_hexdump(data,gw=2,cols=8,line_nums=None): def decode_pretty_hexdump(data): from string import hexdigits - pat = r'^[{}]+:\s+'.format(hexdigits) - lines = [re.sub(pat,'',l) for l in data.splitlines()] + pat = re.compile(fr'^[{hexdigits}]+:\s+') + lines = [pat.sub('',line) for line in data.splitlines()] try: return bytes.fromhex(''.join((''.join(lines).split()))) except: diff --git a/scripts/traceback_run.py b/scripts/traceback_run.py index 5a3d5a71..6b0e6423 100755 --- a/scripts/traceback_run.py +++ b/scripts/traceback_run.py @@ -22,21 +22,24 @@ def traceback_run_init(): def traceback_run_process_exception(): import traceback,re - l = traceback.format_exception(*sys.exc_info()) # returns a list + lines = traceback.format_exception(*sys.exc_info()) # returns a list - for n in range(len(l)): - l[n] = re.sub('File ""','File "{}"'.format(traceback_run_execed_file),l[n],count=1) + pat = re.compile('File ""') + repl = f'File "{traceback_run_execed_file}"' + lines = [pat.sub(repl,line,count=1) for line in lines] + + exc = lines.pop() + if exc.startswith('SystemExit:'): + lines.pop() - exc = l.pop() - if exc[:11] == 'SystemExit:': l.pop() if False: # was: if os.getenv('MMGEN_DISABLE_COLOR'): - sys.stdout.write('{}{}'.format(''.join(l),exc)) + sys.stdout.write('{}{}'.format(''.join(lines),exc)) else: - def red(s): return '\033[31;1m{}\033[0m'.format(s) - def yellow(s): return '\033[33;1m{}\033[0m'.format(s) - sys.stdout.write('{}{}'.format(yellow(''.join(l)),red(exc))) + yellow = lambda s: f'\033[33;1m{s}\033[0m' + red = lambda s: f'\033[31;1m{s}\033[0m' + sys.stdout.write('{}{}'.format(yellow(''.join(lines)),red(exc))) - open(traceback_run_outfile,'w').write(''.join(l+[exc])) + open(traceback_run_outfile,'w').write(''.join(lines+[exc])) traceback_run_outfile = traceback_run_init() traceback_run_tstart = time.time()