keyword-only parameters throughout

This commit is contained in:
The MMGen Project 2025-03-15 18:24:52 +00:00
commit 89ad0fd29b
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
101 changed files with 314 additions and 269 deletions

View file

@ -182,14 +182,14 @@ class CoinAddr(HiliteStr, InitErrors, MMGenObject):
# reimplement some HiliteStr methods:
@classmethod
def fmtc(cls, s, width, color=False):
def fmtc(cls, s, width, *, color=False):
return super().fmtc(s=s[:width-2]+'..' if len(s) > width else s, width=width, color=color)
def fmt(self, view_pref, width, color=False):
def fmt(self, view_pref, width, *, color=False):
s = self.views[view_pref]
return super().fmtc(f'{s[:width-2]}..' if len(s) > width else s, width=width, color=color)
def hl(self, view_pref, color=True):
def hl(self, view_pref, *, color=True):
return getattr(color_mod, self.color)(self.views[view_pref]) if color else self.views[view_pref]
def is_coin_addr(proto, s):

View file

@ -66,6 +66,7 @@ class AddrFile(MMGenObject):
def write(
self,
fn = None,
*,
binary = False,
desc = None,
ask_overwrite = True,
@ -92,7 +93,7 @@ class AddrFile(MMGenObject):
)
return self.parent.al_id.sid + (' ' if lbl_p2 else '') + lbl_p2
def format(self, add_comments=False):
def format(self, *, add_comments=False):
p = self.parent
if p.gen_passwds and p.pw_fmt in ('bip39', 'xmrseed'):
desc_pfx = f'{p.pw_fmt.upper()} '
@ -200,7 +201,7 @@ class AddrFile(MMGenObject):
return ret
def parse_file(self, fn, buf=[], exit_on_error=True):
def parse_file(self, fn, *, buf=[], exit_on_error=True):
def parse_addrfile_label(lbl):
"""
@ -249,7 +250,7 @@ class AddrFile(MMGenObject):
p = self.parent
from .fileutil import get_lines_from_file
lines = get_lines_from_file(p.cfg, fn, p.desc+' data', trim_comments=True)
lines = get_lines_from_file(p.cfg, fn, desc=f'{p.desc} data', trim_comments=True)
try:
assert len(lines) >= 3, f'Too few lines in address file ({len(lines)})'

View file

@ -159,6 +159,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
self,
cfg,
proto,
*,
infile = '',
al_id = '',
adata = [],

View file

@ -267,7 +267,7 @@ class CoinInfo:
return None
return cls.coin_constants[network][idx]
def make_proto(e, testnet=False):
def make_proto(e, *, testnet=False):
proto = ('X_' if e.name[0] in '0123456789' else '') + e.name + ('Testnet' if testnet else '')
@ -297,7 +297,7 @@ def make_proto(e, testnet=False):
)
)
def init_genonly_altcoins(usr_coin=None, testnet=False):
def init_genonly_altcoins(usr_coin=None, *, testnet=False):
"""
Initialize altcoin protocol class or classes for current network.
If usr_coin is a core coin, initialization is skipped.

View file

@ -40,7 +40,7 @@ class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
max_amt = None # coin supply if known, otherwise None
units = () # defined unit names, e.g. ('satoshi',...)
def __new__(cls, num, from_unit=None, from_decimal=False):
def __new__(cls, num, *, from_unit=None, from_decimal=False):
if isinstance(num, CoinAmt):
raise TypeError(f'CoinAmt: {num} is instance of {cls.__name__}')
@ -71,7 +71,7 @@ class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
def fmtc(cls, *args, **kwargs):
cls.method_not_implemented()
def fmt(self, color=False, iwidth=1, prec=None): # iwidth: width of the integer part
def fmt(self, *, color=False, iwidth=1, prec=None): # iwidth: width of the integer part
prec = prec or self.max_prec
if '.' in (s := str(self)):
a, b = s.split('.', 1)
@ -83,11 +83,11 @@ class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
s.rjust(iwidth).ljust(iwidth+prec+1),
color = color)
def hl(self, color=True):
def hl(self, *, color=True):
return self.colorize(str(self), color=color)
# fancy highlighting with coin unit, enclosure, formatting
def hl2(self, color=True, unit=False, fs='{}', encl=''):
def hl2(self, *, color=True, unit=False, fs='{}', encl=''):
res = fs.format(self)
return (
encl[:-1]
@ -156,7 +156,7 @@ class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
def __mod__(self, *args, **kwargs):
self.method_not_implemented()
def is_coin_amt(proto, num, from_unit=None, from_decimal=False):
def is_coin_amt(proto, num, *, from_unit=None, from_decimal=False):
assert proto.coin_amt, 'proto.coin_amt is None! Did you call init_proto() with ‘need_amt’?'
return get_obj(proto.coin_amt, num=num, from_unit=from_unit, from_decimal=from_decimal, silent=True, return_bool=True)

View file

@ -33,12 +33,12 @@ def SwapMgr(*args, **kwargs):
class SwapMgrBase:
def __init__(self, cfg, ignore_zram=False):
def __init__(self, cfg, *, ignore_zram=False):
self.cfg = cfg
self.ignore_zram = ignore_zram
self.desc = 'disk swap' if ignore_zram else 'swap'
def enable(self, quiet=False):
def enable(self, *, quiet=False):
ret = self.do_enable()
if not quiet:
self.cfg._util.qmsg(
@ -47,7 +47,7 @@ class SwapMgrBase:
f'Could not enable {self.desc}')
return ret
def disable(self, quiet=False):
def disable(self, *, quiet=False):
self.cfg._util.qmsg_r(f'Attempting to disable {self.desc}...')
ret = self.do_disable()
self.cfg._util.qmsg('success')
@ -189,7 +189,7 @@ class Signable:
b = ' {}\n'.format('\n '.join(self.gen_bad_list(sorted(bad_files, key=lambda f: f.name))))
))
def die_wrong_num_txs(self, tx_type, msg=None, desc=None, show_dir=False):
def die_wrong_num_txs(self, tx_type, *, msg=None, desc=None, show_dir=False):
num_txs = len(getattr(self, tx_type))
die('AutosignTXError', "{m}{a} {b} transaction{c} {d} {e}!".format(
m = msg + '\n' if msg else '',
@ -581,7 +581,7 @@ class Autosign:
return self._wallet_files
def do_mount(self, silent=False, verbose=False):
def do_mount(self, *, silent=False, verbose=False):
def check_or_create(dirname):
path = getattr(self, dirname)
@ -615,7 +615,7 @@ class Autosign:
for dirname in self.dirs:
check_or_create(dirname)
def do_umount(self, silent=False, verbose=False):
def do_umount(self, *, silent=False, verbose=False):
if self.mountpoint.is_mount():
run(['sync'], check=True)
if not silent:
@ -630,7 +630,7 @@ class Autosign:
fails = 0
for wf in self.wallet_files:
try:
Wallet(self.cfg, wf, ignore_in_fmt=True, passwd_file=str(self.keyfile))
Wallet(self.cfg, fn=wf, ignore_in_fmt=True, passwd_file=str(self.keyfile))
except SystemExit as e:
if e.code != 0:
fails += 1
@ -710,7 +710,7 @@ class Autosign:
die(2, 'Unable to write ' + desc)
msg('Wrote ' + desc)
def gen_key(self, no_unmount=False):
def gen_key(self, *, no_unmount=False):
if not self.device_inserted:
die(1, 'Removable device not present!')
self.do_mount()
@ -776,7 +776,7 @@ class Autosign:
cfg = self.cfg,
prompt = f"Default wallet '{wf}' found.\nUse default wallet for autosigning?",
default_yes = True):
ss_in = Wallet(Config(), wf)
ss_in = Wallet(Config(), fn=wf)
else:
ss_in = Wallet(self.cfg, in_fmt=self.mn_fmts[self.cfg.mnemonic_fmt or self.dfl_mn_fmt])
ss_out = Wallet(self.cfg, ss=ss_in, passwd_file=str(self.keyfile))

View file

@ -129,11 +129,11 @@ class baseconv:
else:
die('BaseConversionPadError', f"{pad!r}: illegal value for 'pad' (must be None, 'seed' or int)")
def tohex(self, words_arg, pad=None):
def tohex(self, words_arg, *, pad=None):
"convert string or list data of instance base to a hexadecimal string"
return self.tobytes(words_arg, pad//2 if type(pad) is int else pad).hex()
return self.tobytes(words_arg, pad=pad//2 if type(pad) is int else pad).hex()
def tobytes(self, words_arg, pad=None):
def tobytes(self, words_arg, *, pad=None):
"convert string or list data of instance base to byte string"
words = words_arg if isinstance(words_arg, (list, tuple)) else tuple(words_arg.strip())
@ -163,7 +163,7 @@ class baseconv:
bl = ret.bit_length()
return ret.to_bytes(max(pad_val, bl//8+bool(bl%8)), 'big')
def fromhex(self, hexstr, pad=None, tostr=False):
def fromhex(self, hexstr, *, pad=None, tostr=False):
"convert a hexadecimal string to a list or string data of instance base"
from .util import is_hex_str
@ -172,9 +172,9 @@ class baseconv:
('seed data' if pad == 'seed' else f'{hexstr!r}:') +
' not a hexadecimal string')
return self.frombytes(bytes.fromhex(hexstr), pad, tostr)
return self.frombytes(bytes.fromhex(hexstr), pad=pad, tostr=tostr)
def frombytes(self, bytestr, pad=None, tostr=False):
def frombytes(self, bytestr, *, pad=None, tostr=False):
"convert byte string to list or string data of instance base"
if not bytestr:

View file

@ -54,14 +54,14 @@ class bip39(baseconv):
self.wl_id = 'bip39'
@classmethod
def nwords2seedlen(cls, nwords, in_bytes=False, in_hex=False):
def nwords2seedlen(cls, nwords, *, in_bytes=False, in_hex=False):
for k, v in cls.constants.items():
if v.mn_len == nwords:
return k//8 if in_bytes else k//4 if in_hex else k
die('MnemonicError', f'{nwords!r}: invalid word length for BIP39 mnemonic')
@classmethod
def seedlen2nwords(cls, seed_len, in_bytes=False, in_hex=False):
def seedlen2nwords(cls, seed_len, *, in_bytes=False, in_hex=False):
seed_bits = seed_len * 8 if in_bytes else seed_len * 4 if in_hex else seed_len
try:
return cls.constants[seed_bits].mn_len
@ -105,11 +105,11 @@ class bip39(baseconv):
return seed_bytes
def fromhex(self, hexstr, pad=None, tostr=False):
def fromhex(self, hexstr, *, pad=None, tostr=False):
assert is_hex_str(hexstr), 'seed data not a hexadecimal string'
return self.frombytes(bytes.fromhex(hexstr), pad=pad, tostr=tostr)
def frombytes(self, seed_bytes, pad=None, tostr=False):
def frombytes(self, seed_bytes, *, pad=None, tostr=False):
assert tostr is False, "'tostr' must be False for 'bip39'"
assert pad in (None, 'seed'), f"{pad}: invalid 'pad' argument (must be None or 'seed')"

View file

@ -185,6 +185,7 @@ class MasterNode(Lockable):
def init_cfg(
self,
coin = None,
*,
network = None,
addr_type = None,
from_path = False,
@ -204,11 +205,11 @@ class MasterNode(Lockable):
new._lock()
return new
def to_coin_type(self, coin=None, network=None, addr_type=None):
return self.init_cfg(coin, network, addr_type).to_coin_type()
def to_coin_type(self, *, coin=None, network=None, addr_type=None):
return self.init_cfg(coin, network=network, addr_type=addr_type).to_coin_type()
def to_chain(self, idx, coin=None, network=None, addr_type=None, hardened=False, public=False):
return self.init_cfg(coin, network, addr_type).to_chain(
def to_chain(self, idx, *, coin=None, network=None, addr_type=None, hardened=False, public=False):
return self.init_cfg(coin, network=network, addr_type=addr_type).to_chain(
idx = idx,
hardened = hardened,
public = public)
@ -294,7 +295,7 @@ class BipHDNode(Lockable):
def xprv(self):
return self.key_extended(public=False, as_str=True)
def key_extended(self, public, as_str=False):
def key_extended(self, public, *, as_str=False):
if self.public and not public:
raise ValueError('cannot create extended private key for public node!')
ret = b58chk_encode(
@ -363,6 +364,7 @@ class BipHDNode(Lockable):
base_cfg,
seed,
path_str,
*,
coin = None,
addr_type = None,
no_path_checks = False):
@ -441,7 +443,7 @@ class BipHDNodeMaster(BipHDNode):
# purpose coin_type
return self.derive_private().derive_private()
def to_chain(self, idx, hardened=False, public=False):
def to_chain(self, idx, *, hardened=False, public=False):
# purpose coin_type account #0 chain
return self.derive_private().derive_private().derive_private(idx=0).derive(
idx = idx,
@ -475,7 +477,7 @@ class BipHDNodeCoinType(BipHDNode):
f'chain index {chain_idx} for coin {cfg.base_cfg.coin!r}')
return (chain_idx, type(self).hardened)
def to_chain(self, idx, hardened=False, public=False):
def to_chain(self, idx, *, hardened=False, public=False):
# account #0 chain
return self.derive_private(idx=0).derive(
idx = idx,

View file

@ -438,6 +438,7 @@ class Config(Lockable):
def __init__(
self,
cfg = None,
*,
opts_data = None,
init_opts = None,
parse_only = False,
@ -845,7 +846,7 @@ def check_opts(cfg): # Raises exception if any check fails
if hasattr(cfg, key2):
val2 = getattr(cfg, key2)
from .wallet import get_wallet_data
wd = get_wallet_data('incog_hidden')
wd = get_wallet_data(wtype='incog_hidden')
if val2 and val2 not in wd.fmt_codes:
die('UserOptError', f'Option conflict:\n {fmt_opt(name)}, with\n {fmt_opt(key2)}={val2}')
@ -929,7 +930,7 @@ def opt_postproc_debug(cfg):
Msg(' {}\n'.format('\n '.join(none_opts)))
Msg('\n=== end opts.py debug ===\n')
def conv_type(name, val, refval, src, invert_bool=False):
def conv_type(name, val, refval, *, src, invert_bool=False):
def do_fail():
desc = {

View file

@ -90,7 +90,7 @@ class Crypto:
return self.sha256_rounds(step1)
def encrypt_seed(self, data, key, desc='seed'):
return self.encrypt_data(data, key, desc=desc)
return self.encrypt_data(data, key=key, desc=desc)
def decrypt_seed(self, enc_seed, key, seed_id, key_id):
self.util.vmsg_r('Checking key...')
@ -121,6 +121,7 @@ class Crypto:
def encrypt_data(
self,
data,
*,
key,
iv = aesctr_dfl_iv,
desc = 'data',
@ -214,6 +215,7 @@ class Crypto:
passwd,
salt,
hash_preset,
*,
desc = 'encryption key',
from_what = 'passphrase',
verbose = False):
@ -407,7 +409,7 @@ class Crypto:
passwd_file = self.cfg.passwd_file)
key = self.make_key(passwd, salt, hp)
from hashlib import sha256
enc_d = self.encrypt_data(sha256(nonce+data).digest() + nonce + data, key, iv, desc=desc)
enc_d = self.encrypt_data(sha256(nonce+data).digest() + nonce + data, key=key, iv=iv, desc=desc)
return salt+iv+enc_d
def mmgen_decrypt(self, data, desc='data', hash_preset=None):

View file

@ -91,7 +91,7 @@ class Daemon(Lockable):
print(cp)
return cp
def run_cmd(self, cmd, silent=False, is_daemon=False, check_retcode=False):
def run_cmd(self, cmd, *, silent=False, is_daemon=False, check_retcode=False):
if self.debug:
msg('\n\n')
@ -181,7 +181,7 @@ class Daemon(Lockable):
def pre_start(self):
pass
def start(self, quiet=False, silent=False):
def start(self, *, quiet=False, silent=False):
if self.state == 'ready':
if not (quiet or silent):
msg(self.state_msg(extra_text='already'))
@ -200,7 +200,7 @@ class Daemon(Lockable):
return ret
def stop(self, quiet=False, silent=False):
def stop(self, *, quiet=False, silent=False):
if self.state == 'ready':
if not silent:
msg(f'Stopping {self.desc} on port {self.bind_port}')
@ -221,7 +221,7 @@ class Daemon(Lockable):
msg(f'{self.desc} on port {self.bind_port} not running')
return True
def restart(self, silent=False):
def restart(self, *, silent=False):
self.stop(silent=silent)
return self.start(silent=silent)
@ -339,6 +339,7 @@ class CoinDaemon(Daemon):
def __new__(cls,
cfg,
*,
network_id = None,
proto = None,
opts = None,
@ -384,6 +385,7 @@ class CoinDaemon(Daemon):
def __init__(self,
cfg,
*,
network_id = None,
proto = None,
opts = None,

View file

@ -131,7 +131,7 @@ class MMGenObjectMethods: # mixin class for MMGenObject
def isScalar(obj):
return isinstance(obj, scalars)
def do_list(out, e, lvl=0, is_dict=False):
def do_list(out, e, *, lvl=0, is_dict=False):
out.append('\n')
for i in e:
el = i if not is_dict else e[i]

View file

@ -25,7 +25,7 @@ from .util import die, get_extension
class File:
def __init__(self, fn, write=False):
def __init__(self, fn, *, write=False):
self.name = fn
self.dirname = os.path.dirname(fn)
@ -66,21 +66,21 @@ class File:
class FileList(list):
def __init__(self, fns, write=False):
def __init__(self, fns, *, write=False):
list.__init__(
self,
[File(fn, write) for fn in fns])
[File(fn, write=write) for fn in fns])
def names(self):
return [f.name for f in self]
def sort_by_age(self, key='mtime', reverse=False):
def sort_by_age(self, *, key='mtime', reverse=False):
assert key in ('atime', 'ctime', 'mtime'), f'{key!r}: invalid sort key'
self.sort(key=lambda a: getattr(a, key), reverse=reverse)
class MMGenFile(File):
def __init__(self, fn, base_class=None, subclass=None, proto=None, write=False):
def __init__(self, fn, *, base_class=None, subclass=None, proto=None, write=False):
"""
'base_class' - a base class with an 'ext_to_cls' method
'subclass' - a subclass with an 'ext' attribute
@ -91,7 +91,7 @@ class MMGenFile(File):
attribute to True.
"""
super().__init__(fn, write)
super().__init__(fn, write=write)
assert (subclass or base_class) and not (subclass and base_class), 'MMGenFile chk1'
@ -107,12 +107,12 @@ class MMGenFile(File):
class MMGenFileList(FileList):
def __init__(self, fns, base_class, proto=None, write=False):
def __init__(self, fns, base_class, *, proto=None, write=False):
list.__init__(
self,
[MMGenFile(fn, base_class=base_class, proto=proto, write=write) for fn in fns])
def find_files_in_dir(subclass, fdir, no_dups=False):
def find_files_in_dir(subclass, fdir, *, no_dups=False):
assert isinstance(subclass, type), f'{subclass}: not a class'

View file

@ -57,7 +57,7 @@ def check_binary(args):
die(2, f'{args[0]!r} binary missing, not in path, or not executable')
set_vt100()
def shred_file(fn, verbose=False):
def shred_file(fn, *, verbose=False):
check_binary(['shred', '--version'])
from subprocess import run
run(
@ -67,7 +67,7 @@ def shred_file(fn, verbose=False):
check=True)
set_vt100()
def _check_file_type_and_access(fname, ftype, blkdev_ok=False):
def _check_file_type_and_access(fname, ftype, *, blkdev_ok=False):
import stat
@ -103,16 +103,16 @@ def _check_file_type_and_access(fname, ftype, blkdev_ok=False):
return True
def check_infile(f, blkdev_ok=False):
def check_infile(f, *, blkdev_ok=False):
return _check_file_type_and_access(f, 'input file', blkdev_ok=blkdev_ok)
def check_outfile(f, blkdev_ok=False):
def check_outfile(f, *, blkdev_ok=False):
return _check_file_type_and_access(f, 'output file', blkdev_ok=blkdev_ok)
def check_outdir(f):
return _check_file_type_and_access(f, 'output directory')
def get_seed_file(cfg, nargs, wallets=None, invoked_as=None):
def get_seed_file(cfg, *, nargs, wallets=None, invoked_as=None):
wallets = wallets or cfg._args
@ -137,7 +137,7 @@ def get_seed_file(cfg, nargs, wallets=None, invoked_as=None):
return str(wallets[0]) if wallets else (wf, None)[wd_from_opt] # could be a Path instance
def _open_or_die(filename, mode, silent=False):
def _open_or_die(filename, mode, *, silent=False):
try:
return open(filename, mode)
except:
@ -152,6 +152,7 @@ def write_data_to_file(
cfg,
outfile,
data,
*,
desc = 'data',
ask_write = False,
ask_write_prompt = '',
@ -279,7 +280,7 @@ def write_data_to_file(
else:
do_file(outfile, ask_write_prompt)
def get_words_from_file(cfg, infile, desc, quiet=False):
def get_words_from_file(cfg, infile, *, desc, quiet=False):
if not quiet:
cfg._util.qmsg(f'Getting {desc} from file ‘{infile}’')
@ -299,6 +300,7 @@ def get_words_from_file(cfg, infile, desc, quiet=False):
def get_data_from_file(
cfg,
infile,
*,
desc = 'data',
dash = False,
silent = False,
@ -326,6 +328,7 @@ def get_data_from_file(
def get_lines_from_file(
cfg,
fn,
*,
desc = 'data',
trim_comments = False,
quiet = False,

View file

@ -30,7 +30,7 @@ class help_notes:
def account_info_desc(self):
return 'unspent outputs' if self.proto.base_proto == 'Bitcoin' else 'account info'
def fee_spec_letters(self, use_quotes=False):
def fee_spec_letters(self, *, use_quotes=False):
cu = self.proto.coin_amt.units
sep, conj = ((',', ' or '), ("','", "' or '"))[use_quotes]
return sep.join(u[0] for u in cu[:-1]) + ('', conj)[len(cu)>1] + cu[-1][0]

View file

@ -19,7 +19,7 @@ from ..daemon import CoinDaemon
def help(proto, cfg):
def coind_exec():
return CoinDaemon(cfg, proto.coin).exec_fn if proto.coin in CoinDaemon.coins else 'bitcoind'
return CoinDaemon(cfg, network_id=proto.coin).exec_fn if proto.coin in CoinDaemon.coins else 'bitcoind'
return """
Transactions may contain both {pnm} or non-{pnm} input addresses.

View file

@ -51,7 +51,7 @@ class keygen_base:
return None
@classmethod
def get_clsname(cls, cfg, silent=False):
def get_clsname(cls, cfg, *, silent=False):
return cls.__name__
backend_data = {
@ -104,7 +104,7 @@ def check_backend(cfg, proto, backend, addr_type):
return _check_backend(cfg, backend, pubkey_type, desc='--keygen-backend parameter')
def KeyGenerator(cfg, proto, pubkey_type, backend=None, silent=False):
def KeyGenerator(cfg, proto, pubkey_type, *, backend=None, silent=False):
"""
factory function returning a key generator backend for the specified pubkey type
"""

View file

@ -71,7 +71,7 @@ class LEDControl:
trigger = '/tmp/led_trigger'),
}
def __init__(self, enabled, simulate=False, debug=False):
def __init__(self, *, enabled, simulate=False, debug=False):
self.enabled = enabled
self.debug = debug or simulate

View file

@ -141,12 +141,12 @@ if cfg.keygen_backend:
idxs = addrlist.AddrIdxList(fmt_str=cfg._args.pop())
from .fileutil import get_seed_file
sf = get_seed_file(cfg, 1)
sf = get_seed_file(cfg, nargs=1)
from .ui import do_license_msg
do_license_msg(cfg)
ss = Wallet(cfg, sf)
ss = Wallet(cfg, fn=sf)
ss_seed = ss.seed if cfg.subwallet is None else ss.seed.subseed(cfg.subwallet, print_msg=True)

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