whitespace, cleanups, imports throughout [73 files changed]

This commit is contained in:
The MMGen Project 2023-03-27 10:48:21 +00:00
commit 78e882143c
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
73 changed files with 482 additions and 268 deletions

View file

@ -13,8 +13,10 @@ examples.halving-calculator.py: Demonstrate use of the MMGen asyncio/aiohttp JSO
"""
import time
from decimal import Decimal
from mmgen.common import *
import mmgen.opts as opts
from mmgen.opts import opt
from mmgen.util import async_run
opts.init({
'text': {

View file

@ -20,13 +20,14 @@
addrfile: Address and password file classes for the MMGen suite
"""
from .globalvars import g
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
from .key import PrivKey
from .addr import ViewKey,AddrListID,MMGenAddrType,MMGenPasswordType,is_addr_idx
from .addrlist import KeyList,AddrListData,dmsg_sc
from .addrlist import KeyList,AddrListData
class AddrFile(MMGenObject):
desc = 'addresses'
@ -57,12 +58,10 @@ class AddrFile(MMGenObject):
@property
def filename(self):
from .globalvars import g
return '{}{x}{}.{}'.format(
return '{}{}.{}'.format(
self.parent.id_str,
('.' + self.parent.proto.network) if self.parent.proto.testnet else '',
self.ext,
x = '-α' if g.debug_utf8 else '' )
self.ext )
def write(self,fn=None,ask_tty=True,ask_write_default_yes=False,binary=False,desc=None):
from .opts import opt
@ -97,7 +96,7 @@ class AddrFile(MMGenObject):
out.append('# Record this value to a secure location.\n')
lbl = self.make_label()
dmsg_sc('lbl',lbl[9:])
self.parent.dmsg_sc('lbl',lbl[9:])
out.append(f'{lbl} {{')
fs = ' {:<%s} {:<34}{}' % len(str(p.data[-1].idx))

View file

@ -20,17 +20,13 @@
addrlist: Address list classes for the MMGen suite
"""
from .globalvars import g
from .util import qmsg,qmsg_r,suf,make_chksum_N,Msg,die
from .objmethods import MMGenObject,Hilite,InitErrors
from .obj import MMGenListItem,ListItemAttr,MMGenDict,TwComment,WalletPassword
from .key import PrivKey
from .addr import MMGenID,MMGenAddrType,CoinAddr,AddrIdx,AddrListID,ViewKey
def dmsg_sc(desc,data):
from .globalvars import g
if g.debug_addrlist:
Msg(f'sc_debug_{desc}: {data}')
class AddrIdxList(tuple,InitErrors,MMGenObject):
max_len = 1000000
@ -135,7 +131,7 @@ class AddrListIDStr(str,Hilite):
('-'+mt,'')[mt in ('L','E')],
s )
dmsg_sc('id_str',ret[8:].split('[')[0])
addrlist.dmsg_sc('id_str',ret[8:].split('[')[0])
return str.__new__(cls,ret)
@ -154,7 +150,15 @@ class AddrList(MMGenObject): # Address info for a single seed ID
has_keys = False
chksum_rec_f = lambda foo,e: ( str(e.idx), e.addr )
def __init__(self,proto,
def dmsg_sc(self,desc,data):
Msg(f'sc_debug_{desc}: {data}')
def noop(self,desc,data):
pass
def __init__(
self,
proto,
addrfile = '',
al_id = '',
adata = [],
@ -166,14 +170,17 @@ class AddrList(MMGenObject): # Address info for a single seed ID
mmtype = None,
key_address_validity_check = None, # None=prompt user, True=check without prompt, False=skip check
skip_chksum = False,
add_p2pkh = False,
):
skip_chksum_msg = False,
add_p2pkh = False ):
self.ka_validity_chk = key_address_validity_check
self.add_p2pkh = add_p2pkh
self.proto = proto
do_chksum = False
if not g.debug_addrlist:
self.dmsg_sc = self.noop
if seed and addr_idxs: # data from seed + idxs
self.al_id = AddrListID( sid=seed.sid, mmtype=MMGenAddrType(proto, mmtype or proto.dfl_mmtype) )
src = 'gen'
@ -217,7 +224,8 @@ class AddrList(MMGenObject): # Address info for a single seed ID
if do_chksum and not skip_chksum:
self.chksum = AddrListChksum(self)
self.do_chksum_msg(record=src=='gen')
if not skip_chksum_msg:
self.do_chksum_msg(record=src=='gen')
def do_chksum_msg(self,record):
chk = 'Check this value against your records'
@ -229,7 +237,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
def generate(self,seed,addr_idxs):
seed = self.scramble_seed(seed.data)
dmsg_sc('seed',seed[:8].hex())
self.dmsg_sc('seed',seed[:8].hex())
mmtype = self.al_id.mmtype
@ -298,7 +306,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
def scramble_seed(self,seed):
is_btcfork = self.proto.base_coin == 'BTC'
if is_btcfork and self.al_id.mmtype == 'L' and not self.proto.testnet:
dmsg_sc('str','(none)')
self.dmsg_sc('str','(none)')
return seed
if self.proto.base_coin == 'ETH':
scramble_key = self.proto.coin.lower()
@ -307,7 +315,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
from .crypto import scramble_seed
if self.proto.testnet:
scramble_key += ':' + self.proto.network
dmsg_sc('str',scramble_key)
self.dmsg_sc('str',scramble_key)
return scramble_seed(seed,scramble_key.encode())
def idxs(self):

View file

@ -290,13 +290,13 @@ def add_user_random(
return rand_bytes
def get_hash_preset_from_user(
hash_preset = g.dfl_hash_preset,
old_preset = g.dfl_hash_preset,
data_desc = 'data',
prompt = None ):
prompt = prompt or (
f'Enter hash preset for {data_desc},\n' +
f'or hit ENTER to accept the default value ({hash_preset!r}): ' )
f'or hit ENTER to accept the default value ({old_preset!r}): ' )
from .ui import line_input
while True:
@ -307,7 +307,7 @@ def get_hash_preset_from_user(
else:
msg('Invalid input. Valid choices are {}'.format(', '.join(hash_presets)))
else:
return hash_preset
return old_preset
def get_new_passphrase(data_desc,hash_preset,passwd_file,pw_desc='passphrase'):
message = f"""

View file

@ -163,7 +163,7 @@ class MMGenObjectMethods: # mixin class for MMGenObject
if isList(e) or isDict(e):
out.append('{:>{l}}{:<10} {:16}'.format( '', k, f'<{type(e).__name__}>', l=(lvl*8)+4 ))
do_list(out,e,lvl=lvl,is_dict=isDict(e))
elif hasattr(e,'pfmt') and type(e) != type:
elif hasattr(e,'pfmt') and callable(e.pfmt) and type(e) != type:
out.append('{:>{l}}{:10} {}'.format(
'',
k,

View file

@ -20,11 +20,8 @@
filename: File and MMGenFile classes and methods for the MMGen suite
"""
import sys,os
from .obj import *
import os
from .util import die,get_extension
from .seed import *
class File:
@ -46,6 +43,7 @@ class File:
import stat
if stat.S_ISBLK(st.st_mode):
mode = (os.O_RDONLY,os.O_RDWR)[bool(write)]
from .globalvars import g
if g.platform == 'win':
mode |= os.O_BINARY
try:

View file

@ -114,7 +114,7 @@ def check_outfile(f,blkdev_ok=False):
def check_outdir(f):
return _check_file_type_and_access(f,'output directory')
def get_seed_file(cmd_args,nargs,invoked_as=None):
def get_seed_file(wallets,nargs,invoked_as=None):
from .opts import opt
from .filename import find_file_in_dir
@ -125,19 +125,19 @@ def get_seed_file(cmd_args,nargs,invoked_as=None):
wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
import mmgen.opts as opts
if len(cmd_args) + (wd_from_opt or bool(wf)) < nargs:
if len(wallets) + (wd_from_opt or bool(wf)) < nargs:
if not wf:
msg('No default wallet found, and no other seed source was specified')
opts.usage()
elif len(cmd_args) > nargs:
elif len(wallets) > nargs:
opts.usage()
elif len(cmd_args) == nargs and wf and invoked_as != 'gen':
elif len(wallets) == nargs and wf and invoked_as != 'gen':
qmsg('Warning: overriding default wallet with user-supplied wallet')
if cmd_args or wf:
check_infile(cmd_args[0] if cmd_args else wf)
if wallets or wf:
check_infile(wallets[0] if wallets else wf)
return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
return wallets[0] if wallets else (wf,None)[wd_from_opt]
def _open_or_die(filename,mode,silent=False):
try:
@ -149,18 +149,21 @@ def _open_or_die(filename,mode,silent=False):
('reading' if 'r' in mode else 'writing')
))
def write_data_to_file( outfile,data,desc='data',
ask_write=False,
ask_write_prompt='',
ask_write_default_yes=True,
ask_overwrite=True,
ask_tty=True,
no_tty=False,
quiet=False,
binary=False,
ignore_opt_outdir=False,
check_data=False,
cmp_data=None):
def write_data_to_file(
outfile,
data,
desc = 'data',
ask_write = False,
ask_write_prompt = '',
ask_write_default_yes = True,
ask_overwrite = True,
ask_tty = True,
no_tty = False,
quiet = False,
binary = False,
ignore_opt_outdir = False,
check_data = False,
cmp_data = None):
from .opts import opt
@ -220,8 +223,9 @@ def write_data_to_file( outfile,data,desc='data',
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):
if not keypress_confirm(
ask_write_prompt,
default_yes = ask_write_default_yes ):
die(1,f'{capfirst(desc)} not saved')
hush = False
@ -282,7 +286,13 @@ def get_words_from_file(infile,desc,quiet=False):
return words
def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False,quiet=False):
def get_data_from_file(
infile,
desc = 'data',
dash = False,
silent = False,
binary = False,
quiet = False ):
from .opts import opt
if not (opt.quiet or silent or quiet):
@ -314,7 +324,13 @@ def _mmgen_decrypt_file_maybe(fn,desc='data',quiet=False,silent=False):
d = mmgen_decrypt_retry(d,desc)
return d
def get_lines_from_file(fn,desc='data',trim_comments=False,quiet=False,silent=False):
def get_lines_from_file(
fn,
desc = 'data',
trim_comments = False,
quiet = False,
silent = False ):
dec = _mmgen_decrypt_file_maybe(fn,desc=desc,quiet=quiet,silent=silent)
ret = dec.decode().splitlines()
if trim_comments:

View file

@ -169,7 +169,7 @@ class GlobalConfig(Lockable):
# user opt sets global var:
opt_sets_global = ( 'cached_balances', )
# 'long' opt sets global var (subset of common_opts_data):
# 'long' opts (subset of common_opts_data):
common_opts = (
'accept_defaults',
'aiohttp_rpc_queue_len',
@ -196,6 +196,7 @@ class GlobalConfig(Lockable):
# opts not in common_opts but required to be set during opts initialization
init_opts = ('show_hash_presets','yes','verbose')
incompatible_opts = (
('help','longhelp'),
('bob','alice','carol'),
@ -203,6 +204,7 @@ class GlobalConfig(Lockable):
('tx_id','info'),
('tx_id','terse_info'),
)
cfg_file_opts = (
'autochg_ignore_labels',
'color',
@ -269,7 +271,6 @@ class GlobalConfig(Lockable):
'MMGEN_FORCE_256_COLOR',
'MMGEN_HOLD_PROTECT_DISABLE',
'MMGEN_QUIET',
'MMGEN_MIN_URANDCHARS',
'MMGEN_NO_LICENSE',
'MMGEN_RPC_HOST',
'MMGEN_RPC_FAIL_ON_COMMAND',
@ -290,12 +291,11 @@ class GlobalConfig(Lockable):
'comment_file',
'contract_data',
)
# Auto-typechecked and auto-set opts. These have no corresponding value in g.
# First value in list is the default
ov = namedtuple('autoset_opt_info',['type','choices'])
# Auto-typechecked and auto-set opts - first value in list is the default
_ov = namedtuple('autoset_opt_info',['type','choices'])
autoset_opts = {
'fee_estimate_mode': ov('nocase_pfx', ['conservative','economical']),
'rpc_backend': ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
'fee_estimate_mode': _ov('nocase_pfx', ['conservative','economical']),
'rpc_backend': _ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
}
if platform == 'win':
_skip_type_check = ('stdout','stderr')
@ -319,6 +319,7 @@ class GlobalConfig(Lockable):
force_standalone_scrypt_module = False
if os.getenv('MMGEN_TEST_SUITE'):
min_urandchars = 3
err_disp_timeout = 0.1
short_disp_timeout = 0.1
if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):

View file

@ -20,8 +20,9 @@
help: help notes for MMGen suite commands
"""
from .globalvars import g
def help_notes_func(proto,opt,k):
from .globalvars import g
def fee_spec_letters(use_quotes=False):
cu = proto.coin_amt.units

View file

@ -20,9 +20,10 @@
led: Control the LED on a single-board computer
"""
import sys,time
from mmgen.common import *
import threading
import os,threading
from collections import namedtuple
from .util import msg,msg_r,fmt,die
class LEDControl:

View file

@ -21,7 +21,9 @@ mmgen-addrgen: Generate a series or range of addresses from an MMGen
deterministic wallet
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .addr import MMGenAddrType
from .addrfile import AddrFile
from .wallet import Wallet
@ -126,15 +128,13 @@ FMT CODES:
cmd_args = opts.init(opts_data,opt_filter=opt_filter)
errmsg = f'{opt.type!r}: invalid parameter for --type option'
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
addr_type = MMGenAddrType(
proto = proto,
id_str = opt.type or proto.dfl_mmtype,
errmsg = errmsg )
errmsg = f'{opt.type!r}: invalid parameter for --type option' )
if len(cmd_args) < 1:
opts.usage()

View file

@ -22,7 +22,10 @@ mmgen-addrimport: Import addresses into a MMGen coin daemon tracking wallet
from collections import namedtuple
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import msg,qmsg,suf,die,fmt,async_run
from .addrlist import AddrList,KeyAddrList
from .tw.shared import TwLabel
@ -181,7 +184,8 @@ async def main():
del twctl
cmd_args = opts.init(opts_data)
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
import asyncio
async_run(main())

View file

@ -25,7 +25,11 @@ from subprocess import run,PIPE,DEVNULL
from collections import namedtuple
from stat import *
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import msg,msg_r,vmsg,qmsg,ymsg,rmsg,gmsg,bmsg,die,suf,fmt_list,async_run,exit_if_mswin
from .color import yellow,red,orange
mountpoint = '/mnt/tx'
tx_dir = '/mnt/tx/tx'
@ -38,8 +42,6 @@ mn_fmts = {
}
mn_fmt_dfl = 'mmgen'
opts.UserOpts._set_ok += ('outdir','passwd_file')
opts_data = {
'sets': [('stealth_led', True, 'led', True)],
'text': {
@ -131,6 +133,8 @@ cmd_args = opts.init(
'label': 'Autosign Wallet',
})
type(opt)._set_ok += ('outdir','passwd_file')
exit_if_mswin('autosigning')
if opt.mnemonic_fmt:

View file

@ -12,9 +12,20 @@
mmgen-msg: Message signing operations for the MMGen suite
"""
import sys
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .base_obj import AsyncInit
from .common import *
from .msg import *
from .util import msg,suf,async_run,stdout_or_pager
from .msg import (
NewMsg,
CompletedMsg,
UnsignedMsg,
SignedMsg,
SignedOnlineMsg,
ExportedMsgSigs,
)
class MsgOps:
ops = ('create','sign','verify')

View file

@ -21,7 +21,9 @@ mmgen-passgen: Generate a series or range of passwords from an MMGen
deterministic wallet
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .addrlist import AddrIdxList
from .passwdlist import PasswordList
from .wallet import Wallet
@ -177,5 +179,6 @@ if keypress_confirm('Encrypt password list?'):
af.write(binary=True,desc='encrypted password list')
else:
if g.test_suite_popen_spawn and g.platform == 'win':
import time
time.sleep(0.1)
af.write(desc='password list')

View file

@ -21,7 +21,9 @@ mmgen-regtest: Coin daemon regression test mode setup and operations for the MMG
suite
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .util import die,async_run
opts_data = {
'sets': [('yes', True, 'quiet', True)],

View file

@ -21,7 +21,11 @@ mmgen-seedjoin: Regenerate an MMGen deterministic wallet from seed shares
created by 'mmgen-seedsplit'
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import msg,msg_r,qmsg,die
from .color import yellow
from .obj import MMGenWalletLabel
from .seed import Seed
from .seedsplit import SeedSplitIDString,MasterShareIdx,SeedShareMasterJoining

View file

@ -21,8 +21,11 @@ mmgen-tool: Perform various MMGen- and cryptocoin-related operations.
Part of the MMGen suite
"""
import os,importlib
from .common import *
import sys,os,importlib
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import msg,Msg,die,capfirst,suf,async_run
opts_data = {
'text': {
@ -301,8 +304,6 @@ def process_result(ret,pager=False,print_result=False):
pager instead of returning it.
"""
from .util import Msg,die
def triage_result(o):
if print_result:
if pager:

View file

@ -21,7 +21,11 @@ mmgen-txbump: Increase the fee on a replaceable (replace-by-fee) MMGen
transaction, and optionally sign and send it
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import msg,msg_r,qmsg,die,async_run
from .color import green
from .wallet import Wallet
opts_data = {
@ -106,8 +110,8 @@ tx_file = cmd_args.pop(0)
from .fileutil import check_infile
check_infile(tx_file)
from .tx import *
from .tx.sign import *
from .tx import CompletedTX,BumpTX,UnsignedTX,OnlineSignedTX
from .tx.sign import txsign,get_seed_files,get_keyaddrlist,get_keylist
seed_files = get_seed_files(opt,cmd_args) if (cmd_args or opt.send) else None
@ -116,8 +120,6 @@ do_license_msg()
silent = opt.yes and opt.fee != None and opt.output_to_reduce != None
from .tx import CompletedTX,BumpTX,UnsignedTX,OnlineSignedTX
async def main():
orig_tx = await CompletedTX(filename=tx_file)

View file

@ -21,7 +21,10 @@ mmgen-txcreate: Create a cryptocoin transaction with MMGen- and/or non-MMGen
inputs and outputs
"""
from .common import *
import mmgen.opts as opts
from .globalvars import g
from .opts import opt
from .util import fmt_list,async_run
opts_data = {
'sets': [('yes', True, 'quiet', True)],

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