util.py: relocate user-prompting functions to ui.py

This commit is contained in:
The MMGen Project 2022-10-17 18:37:22 +00:00
commit 1d8b908c7c
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
45 changed files with 300 additions and 229 deletions

View file

@ -20,14 +20,7 @@
addrfile.py: Address and password file classes for the MMGen suite
"""
from .util import (
msg,
qmsg,
qmsg_r,
die,
capfirst,
keypress_confirm,
)
from .util import msg,qmsg,qmsg_r,die,capfirst
from .protocol import init_proto
from .obj import MMGenObject,TwComment,WalletPassword,MMGenPWIDString
from .seed import SeedID,is_seed_id
@ -166,8 +159,8 @@ class AddrFile(MMGenObject):
ret.append(a)
if p.has_keys and p.ka_validity_chk != False:
from .opts import opt
if opt.yes or p.ka_validity_chk == True or keypress_confirm('Check key-to-address validity?'):
def verify_keys():
from .addrgen import KeyGenerator,AddrGenerator
kg = KeyGenerator(p.proto,p.al_id.mmtype.pubkey_type)
ag = AddrGenerator(p.proto,p.al_id.mmtype)
@ -178,6 +171,14 @@ class AddrFile(MMGenObject):
f'Key doesn’t match address!\n {e.sec.wif}\n {e.addr}')
qmsg(' - done')
from .opts import opt
if opt.yes or p.ka_validity_chk == True:
verify_keys()
else:
from .ui import keypress_confirm
if keypress_confirm('Check key-to-address validity?'):
verify_keys()
return ret
def parse_file(self,fn,buf=[],exit_on_error=True):

View file

@ -271,6 +271,8 @@ class CfgFileSampleUsr(CfgFileSample):
{' ' + fmt_list(bad,fmt='bare')}
"""
ymsg(fmt(m,indent=' ',strip_char='\t'))
from .ui import keypress_confirm,do_pager
while True:
if not keypress_confirm(self.details_confirm_prompt,no_nl=True):
return

View file

@ -34,8 +34,6 @@ from .util import (
qmsg,
fmt,
die,
line_input,
get_words_from_user,
make_chksum_8,
compare_chksums,
oneshot_warning,
@ -246,6 +244,7 @@ def _get_random_data_from_user(uchars,desc):
if g.debug:
msg(f'USER ENTROPY (user input + keystroke timings):\n{ret}')
from .ui import line_input
line_input('User random data successfully acquired. Press ENTER to continue: ')
return ret.encode()
@ -299,6 +298,7 @@ def get_hash_preset_from_user(
f'Enter hash preset for {data_desc},\n' +
f'or hit ENTER to accept the default value ({hash_preset!r}): ' )
from .ui import line_input
while True:
ret = line_input(prompt)
if ret:
@ -324,6 +324,7 @@ def get_new_passphrase(data_desc,hash_preset,passwd_file,pw_desc='passphrase'):
quiet = pwfile_reuse_warning(passwd_file).warning_shown ))
else:
qmsg('\n'+fmt(message,indent=' '))
from .ui import get_words_from_user
if opt.echo_passphrase:
pw = ' '.join(get_words_from_user(f'Enter {pw_desc} for {data_desc}: '))
else:
@ -352,6 +353,7 @@ def get_passphrase(data_desc,passwd_file,pw_desc='passphrase'):
desc = f'{pw_desc} for {data_desc}',
quiet = pwfile_reuse_warning(passwd_file).warning_shown ))
else:
from .ui import get_words_from_user
return ' '.join(get_words_from_user(f'Enter {pw_desc} for {data_desc}: '))
mmenc_salt_len = 32

View file

@ -29,13 +29,11 @@ from .util import (
qmsg,
dmsg,
die,
confirm_or_raise,
get_extension,
is_utf8,
capfirst,
make_full_path,
strip_comments,
keypress_confirm,
)
def check_or_create_dir(path):
@ -181,6 +179,7 @@ def write_data_to_file( outfile,data,desc='data',
if no_tty:
die(2,f'Printing {desc} to screen is not allowed')
if (ask_tty and not opt.quiet) or binary:
from .ui import confirm_or_raise
confirm_or_raise(
message = '',
action = f'output {desc} to screen' )
@ -193,6 +192,7 @@ def write_data_to_file( outfile,data,desc='data',
if no_tty:
die(2,f'Writing {desc} to pipe is not allowed')
if ask_tty and not opt.quiet:
from .ui import confirm_or_raise
confirm_or_raise(
message = '',
action = f'output {desc} to pipe' )
@ -219,12 +219,14 @@ def write_data_to_file( outfile,data,desc='data',
if ask_write:
if not ask_write_prompt:
ask_write_prompt = f'Save {desc}?'
from .ui import keypress_confirm
if not keypress_confirm(ask_write_prompt,
default_yes=ask_write_default_yes):
die(1,f'{capfirst(desc)} not saved')
hush = False
if os.path.lexists(outfile) and ask_overwrite:
from .ui import confirm_or_raise
confirm_or_raise(
message = '',
action = f'File {outfile!r} already exists\nOverwrite?' )

View file

@ -148,6 +148,7 @@ idxs = mmgen.addrlist.AddrIdxList( fmt_str=cmd_args.pop() )
from .fileutil import get_seed_file
sf = get_seed_file(cmd_args,1)
from .ui import do_license_msg
do_license_msg()
ss = Wallet(sf)
@ -170,6 +171,7 @@ af.format()
if al.gen_addrs and opt.print_checksum:
Die(0,al.checksum)
from .ui import keypress_confirm
if al.gen_keys and keypress_confirm('Encrypt key list?'):
af.encrypt()
af.write(

View file

@ -120,6 +120,7 @@ def check_opts(tw):
rescan = False
if rescan and not opt.quiet:
from .ui import keypress_confirm
if not keypress_confirm(
'\n{}\n\nContinue?'.format(addrimport_msgs['rescan']),
default_yes = True ):

View file

@ -154,6 +154,7 @@ PasswordList(
pw_fmt = pw_fmt,
chk_params_only = True )
from .ui import do_license_msg
do_license_msg()
ss = Wallet(sf)
@ -170,6 +171,7 @@ af = al.get_file()
af.format()
from .ui import keypress_confirm
if keypress_confirm('Encrypt password list?'):
af.encrypt()
af.write(binary=True,desc='encrypted password list')

View file

@ -119,10 +119,12 @@ if opt.id_str and not opt.master_share:
die(1,'--id-str option meaningless in context of non-master-share join')
from .fileutil import check_infile
from .wallet import check_wallet_extension
for arg in cmd_args:
check_wallet_extension(arg)
check_infile(arg)
from .ui import do_license_msg
do_license_msg()
qmsg('Input files:\n {}\n'.format('\n '.join(cmd_args)))

View file

@ -294,15 +294,24 @@ def process_args(cmd,cmd_args,cls):
return ( args, kwargs )
def process_result(ret,pager=False,print_result=False):
from .util import Msg,die
"""
Convert result to something suitable for output to screen and return it.
If result is bytes and not convertible to utf8, output as binary using os.write().
If 'print_result' is True, send the converted result directly to screen or
pager instead of returning it.
"""
from .util import Msg,die
def triage_result(o):
return o if not print_result else do_pager(o) if pager else Msg(o)
if print_result:
if pager:
from .ui import do_pager
do_pager(o)
else:
Msg(o)
else:
return o
if ret == True:
return True
@ -316,8 +325,7 @@ def process_result(ret,pager=False,print_result=False):
return triage_result('\n'.join([r.decode() if isinstance(r,bytes) else r for r in ret]))
elif isinstance(ret,bytes):
try:
o = ret.decode()
return o if not print_result else do_pager(o) if pager else Msg(o)
return triage_result(ret.decode())
except:
# don't add NL to binary data if it can't be converted to utf8
if print_result:

View file

@ -111,6 +111,7 @@ from .tx.sign import *
seed_files = get_seed_files(opt,cmd_args) if (cmd_args or opt.send) else None
from .ui import do_license_msg
do_license_msg()
silent = opt.yes and opt.tx_fee != None and opt.output_to_reduce != None

View file

@ -48,6 +48,7 @@ else:
opts.usage()
if not opt.status:
from .ui import do_license_msg
do_license_msg()
async def main():

View file

@ -106,6 +106,7 @@ for i in infiles:
check_infile(i)
if not opt.info and not opt.terse_info:
from .ui import do_license_msg
do_license_msg(immed=True)
from .tx.sign import *

View file

@ -176,6 +176,7 @@ if cmd_args:
sf = get_seed_file(cmd_args,nargs,invoked_as=invoked_as)
if invoked_as != 'chk':
from .ui import do_license_msg
do_license_msg()
if invoked_as == 'gen':
@ -242,6 +243,7 @@ if invoked_as == 'passchg':
return old_fn
if ss_in.infile.dirname == g.data_dir:
from .ui import confirm_or_raise
confirm_or_raise(
message = yellow('Confirmation of default wallet update'),
action = 'update the default wallet',
@ -252,18 +254,21 @@ if invoked_as == 'passchg':
else:
old_wallet = rename_old_wallet_maybe(silent=False)
ss_out.write_to_file()
from .ui import keypress_confirm
if keypress_confirm(f'Securely delete old wallet {old_wallet!r}?'):
secure_delete( old_wallet )
elif invoked_as == 'gen' and not opt.outdir and not opt.stdout:
from .filename import find_file_in_dir
if (
not find_file_in_dir( get_wallet_cls('mmgen'), g.data_dir )
and keypress_confirm(
'Make this wallet your default and move it to the data directory?',
default_yes = True ) ):
ss_out.write_to_file(outdir=g.data_dir)
else:
if find_file_in_dir( get_wallet_cls('mmgen'), g.data_dir ):
ss_out.write_to_file()
else:
from .ui import keypress_confirm
if keypress_confirm(
'Make this wallet your default and move it to the data directory?',
default_yes = True ):
ss_out.write_to_file(outdir=g.data_dir)
else:
ss_out.write_to_file()
else:
ss_out.write_to_file()

View file

@ -78,7 +78,7 @@ def print_help(po,opts_data,opt_filter):
opts_data['text']['long_options'] = d
remove_unneeded_long_opts()
from .util import do_pager
from .ui import do_pager
do_pager(
mmgen.share.Opts.make_help(
proto,

View file

@ -22,7 +22,7 @@ passwdlist.py: Password list class for the MMGen suite
from collections import namedtuple
from .util import ymsg,is_int,keypress_confirm,die
from .util import ymsg,is_int,die
from .obj import ImmutableAttr,ListItemAttr,MMGenPWIDString,TwComment
from .key import PrivKey
from .addr import MMGenPasswordType,AddrIdx,AddrListID
@ -184,6 +184,7 @@ class PasswordList(AddrList):
).format(good_pw_len) )
if pf in ('bip39','hex') and pw_bytes < seed.byte_len:
from .ui import keypress_confirm
if not keypress_confirm(
f'WARNING: requested {self.pw_info[pf].desc} length has less entropy ' +
'than underlying seed!\nIs this what you want?',

View file

@ -30,6 +30,7 @@ def create_data_dir(data_dir):
try: os.stat(os.path.join(data_dir,'regtest'))
except: pass
else:
from ...ui import keypress_confirm
if keypress_confirm(
f'Delete your existing MMGen regtest setup at {data_dir!r} and create a new one?'):
shutil.rmtree(data_dir)

View file

@ -19,7 +19,7 @@ from .base import Base,TokenBase
from ....opts import opt
from ....obj import Int,ETHNonce,MMGenTxID,Str,HexStr
from ....amt import ETHAmt
from ....util import msg,line_input,is_int,is_hex_str,make_chksum_6
from ....util import msg,is_int,is_hex_str,make_chksum_6
from ....tw.ctl import TrackingWallet
from ....addr import is_mmgen_id,is_coin_addr
from ..contract import Token
@ -88,6 +88,7 @@ class New(Base,TxBase.New):
self.process_cmd_arg(a,ad_f,ad_w)
def select_unspent(self,unspent):
from ....ui import line_input
while True:
reply = line_input('Enter an account to spend from: ').strip()
if reply:

View file

@ -302,7 +302,7 @@ def warn_trustlevel(coinsym):
Are you sure you want to continue?
"""
from .util import qmsg,fmt,keypress_confirm
from .util import qmsg,fmt
from .color import red,yellow,green
warning = fmt(m).strip().format(
@ -319,6 +319,7 @@ def warn_trustlevel(coinsym):
qmsg(warning)
return
from .ui import keypress_confirm
if not keypress_confirm(warning,default_yes=True):
import sys
sys.exit(0)

View file

@ -152,7 +152,7 @@ class tool_cmd(tool_cmd_base):
def extract_key_from_geth_wallet( self, wallet_file:str, check_addr=True ):
"decrypt the encrypted private key in a Geth keystore wallet, returning the decrypted key"
from ..util import line_input
from ..ui import line_input
from ..opts import opt
from ..proto.eth.misc import extract_key_from_geth_keystore_wallet
passwd = line_input( 'Enter passphrase: ', echo=opt.echo_passphrase ).strip().encode()

View file

@ -184,7 +184,7 @@ def gen_tool_cmd_usage(mod,cmdname):
def usage(cmdname=None,exit_val=1):
from ..util import Msg,die,do_pager
from ..util import Msg,die
if cmdname:
for mod,cmdlist in main_tool.mods.items():
@ -194,6 +194,7 @@ def usage(cmdname=None,exit_val=1):
else:
die(1,f'{cmdname!r}: no such tool command')
else:
from ..ui import do_pager
do_pager('\n'.join(gen_tool_usage()))
import sys

Some files were not shown because too many files have changed in this diff Show more