various cleanups throughout

This commit is contained in:
The MMGen Project 2020-04-12 15:02:52 +00:00
commit da5742f667
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
9 changed files with 41 additions and 30 deletions

View file

@ -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',

View file

@ -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(

View file

@ -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(

View file

@ -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(

View file

@ -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)

View file

@ -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!')

View file

@ -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+<first letter of unit name>
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

View file

@ -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:

View file

@ -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 "<string>"','File "{}"'.format(traceback_run_execed_file),l[n],count=1)
pat = re.compile('File "<string>"')
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()