Config API, Part I

This patch eliminates the global configuration variables `opt` and `g`, making
all functions and class instances locally configurable.  Configuration data is
passed to functions and constructors via the `cfg` parameter and made available
to methods in `self.cfg`.

Local configuration free from dependence on the command line will enable the
creation of multiple, independently configured instances of MMGen’s data
objects within a single process.

Potential applications include testing (tracking wallets configured to interact
with spawned processes, for example) and the use of MMGen as a library for
other projects.

This patch completes most of the work required to enable the API.  The full
implementation will appear in a forthcoming commit.
This commit is contained in:
The MMGen Project 2023-03-28 18:14:37 +00:00
commit c7adb56e38
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
197 changed files with 2218 additions and 2078 deletions

View file

@ -15,10 +15,9 @@ examples.halving-calculator.py: Demonstrate use of the MMGen asyncio/aiohttp JSO
import time
import mmgen.opts as opts
from mmgen.opts import opt
from mmgen.util import async_run
opts.init({
cfg = opts.init({
'text': {
'desc': 'Estimate date of next block subsidy halving',
'usage':'[opts]',
@ -55,16 +54,15 @@ def time_diff_warning(t_diff):
async def main():
from mmgen.protocol import init_proto_from_opts
proto = init_proto_from_opts(need_amt=True)
proto = cfg._proto
from mmgen.rpc import rpc_init
c = await rpc_init(proto)
c = await rpc_init(cfg,proto)
tip = await c.call('getblockcount')
assert tip > 1, 'block tip must be > 1'
remaining = proto.halving_interval - tip % proto.halving_interval
sample_size = int(opt.sample_size) if opt.sample_size else min(tip-1,max(remaining,144))
sample_size = int(cfg.sample_size) if cfg.sample_size else min(tip-1,max(remaining,144))
# aiohttp backend will perform these two calls concurrently:
cur,old = await c.gathered_call('getblockstats',((tip,),(tip - sample_size,)))

View file

@ -20,7 +20,8 @@
addrdata: MMGen AddrData and related classes
"""
from .util import vmsg,fmt,die
from .globalvars import gc
from .util import fmt,die
from .base_obj import AsyncInit
from .obj import MMGenObject,MMGenDict,get_obj
from .addr import MMGenID,AddrListID
@ -68,16 +69,16 @@ class AddrData(MMGenObject):
class TwAddrData(AddrData,metaclass=AsyncInit):
def __new__(cls,proto,*args,**kwargs):
def __new__(cls,cfg,proto,*args,**kwargs):
return MMGenObject.__new__(proto.base_proto_subclass(cls,'addrdata'))
async def __init__(self,proto,twctl=None):
async def __init__(self,cfg,proto,twctl=None):
from .rpc import rpc_init
from .tw.shared import TwLabel
from .globalvars import gc
from .seed import SeedID
self.cfg = cfg
self.proto = proto
self.rpc = await rpc_init(proto)
self.rpc = await rpc_init(cfg,proto)
self.al_ids = {}
twd = await self.get_tw_data(twctl)
out,i = {},0
@ -96,10 +97,11 @@ class TwAddrData(AddrData,metaclass=AsyncInit):
out[al_id].append(AddrListEntry(self.proto,idx=obj.idx,addr=addr_array[0],comment=l.comment))
i += 1
vmsg(f'{i} {gc.proj_name} addresses found, {len(twd)} accounts total')
self.cfg._util.vmsg(f'{i} {gc.proj_name} addresses found, {len(twd)} accounts total')
for al_id in out:
self.add(AddrList(
self.cfg,
self.proto,
al_id = al_id,
adata = AddrListData(sorted( out[al_id], key=lambda a: a.idx ))

View file

@ -20,8 +20,8 @@
addrfile: Address and password file classes for the MMGen suite
"""
from .globalvars import g
from .util import msg,qmsg,qmsg_r,die,capfirst
from .globalvars import gc
from .util import msg,die,capfirst
from .protocol import init_proto
from .obj import MMGenObject,TwComment,WalletPassword,MMGenPWIDString
from .seed import SeedID,is_seed_id
@ -44,13 +44,13 @@ class AddrFile(MMGenObject):
"""
def __init__(self,parent):
self.parent = parent
self.cfg = parent.cfg
self.infile = None
def encrypt(self):
from .crypto import Crypto
self.fmt_data = Crypto().mmgen_encrypt(
self.fmt_data = Crypto(self.cfg).mmgen_encrypt(
data = self.fmt_data.encode(),
desc = f'new {self.parent.desc} list' )
self.ext += f'.{Crypto.mmenc_ext}'
@ -63,13 +63,13 @@ class AddrFile(MMGenObject):
self.ext )
def write(self,fn=None,ask_tty=True,ask_write_default_yes=False,binary=False,desc=None):
from .opts import opt
from .fileutil import write_data_to_file
write_data_to_file(
self.cfg,
fn or self.filename,
self.fmt_data,
desc or self.desc,
ask_tty = self.parent.has_keys and not opt.quiet,
ask_tty = self.parent.has_keys and not self.cfg.quiet,
binary = binary )
def make_label(self):
@ -87,8 +87,7 @@ class AddrFile(MMGenObject):
self.file_header_mn.format(p.pw_fmt.upper())
if p.gen_passwds and p.pw_fmt in ('bip39','xmrseed') else
self.file_header ).strip()
from .globalvars import gc
out = [fh.format(pnm=gc.proj_name,n=TwComment.max_screen_width) + '\n']
out = [fh.format( pnm=gc.proj_name, n=TwComment.max_screen_width ) + '\n']
if p.chksum:
out.append(f'# {capfirst(p.desc)} data checksum for {p.id_str}: {p.chksum}')
@ -108,8 +107,7 @@ class AddrFile(MMGenObject):
else: # First line with idx
out.append(fs.format(e.idx,e.addr,c))
if p.has_keys:
from .opts import opt
if opt.b16:
if self.cfg.b16:
out.append(fs.format( '', f'orig_hex: {e.sec.orig_bytes.hex()}', c ))
out.append(fs.format( '', f'{p.al_id.mmtype.wif_label}: {e.sec.wif}', c ))
for k in ('viewkey','wallet_passwd'):
@ -160,21 +158,21 @@ class AddrFile(MMGenObject):
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)
kg = KeyGenerator( self.cfg, p.proto, p.al_id.mmtype.pubkey_type )
ag = AddrGenerator( self.cfg, p.proto, p.al_id.mmtype )
llen = len(ret)
qmsg_r = p.cfg._util.qmsg_r
for n,e in enumerate(ret):
qmsg_r(f'\rVerifying keys {n+1}/{llen}')
assert e.addr == ag.to_addr(kg.gen_data(e.sec)),(
f'Key doesn’t match address!\n {e.sec.wif}\n {e.addr}')
qmsg(' - done')
p.cfg._util.qmsg(' - done')
from .opts import opt
if opt.yes or p.ka_validity_chk == True:
if self.cfg.yes or p.ka_validity_chk == True:
verify_keys()
else:
from .ui import keypress_confirm
if keypress_confirm('Check key-to-address validity?'):
if keypress_confirm( p.cfg, 'Check key-to-address validity?' ):
verify_keys()
return ret
@ -216,7 +214,7 @@ class AddrFile(MMGenObject):
else: # only component is coin
coin,mmtype_key = ( lbl, None )
proto = init_proto(coin=coin,network=network)
proto = init_proto( p.cfg, coin=coin, network=network )
if mmtype_key == None:
mmtype_key = proto.mmtypes[0]
@ -224,8 +222,9 @@ class AddrFile(MMGenObject):
return ( proto, proto.addr_type(mmtype_key) )
p = self.parent
from .fileutil import get_lines_from_file
lines = get_lines_from_file(fn,p.desc+' data',trim_comments=True)
lines = get_lines_from_file( p.cfg, fn, p.desc+' data', trim_comments=True )
try:
assert len(lines) >= 3, f'Too few lines in address file ({len(lines)})'
@ -246,12 +245,12 @@ class AddrFile(MMGenObject):
modname,funcname = p.pw_info[p.pw_fmt].chk_func.split('.')
import importlib
p.chk_func = getattr(importlib.import_module('mmgen.'+modname),funcname)
proto = init_proto('btc') # FIXME: dummy protocol
proto = init_proto( p.cfg, 'btc' ) # FIXME: dummy protocol
mmtype = MMGenPasswordType(proto,'P')
elif len(ls) == 1:
proto,mmtype = parse_addrfile_label(ls[0])
elif len(ls) == 0:
proto = init_proto('btc')
proto = init_proto( p.cfg, 'btc' )
mmtype = proto.addr_type('L')
else:
raise ValueError(f'{lines[0]}: Invalid first line for {p.gen_desc} file {fn!r}')

View file

@ -36,7 +36,7 @@ class addr_generator:
class base:
def __init__(self,proto,addr_type):
def __init__(self,cfg,proto,addr_type):
self.proto = proto
self.pubkey_type = addr_type.pubkey_type
self.compressed = addr_type.compressed
@ -44,12 +44,12 @@ class addr_generator:
class keccak(base):
def __init__(self,proto,addr_type):
super().__init__(proto,addr_type)
def __init__(self,cfg,proto,addr_type):
super().__init__(cfg,proto,addr_type)
from .util2 import get_keccak
self.keccak_256 = get_keccak()
self.keccak_256 = get_keccak(cfg)
def AddrGenerator(proto,addr_type):
def AddrGenerator(cfg,proto,addr_type):
"""
factory function returning an address generator for the specified address type
"""
@ -76,4 +76,4 @@ def AddrGenerator(proto,addr_type):
import importlib
return getattr(
importlib.import_module(f'mmgen.proto.{package_map[addr_type.name]}.addrgen'),
addr_type.name )(proto,addr_type)
addr_type.name )(cfg,proto,addr_type)

View file

@ -20,8 +20,7 @@
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 .util import suf,make_chksum_N,Msg,die
from .objmethods import MMGenObject,Hilite,InitErrors
from .obj import MMGenListItem,ListItemAttr,MMGenDict,TwComment,WalletPassword
from .key import PrivKey
@ -158,6 +157,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
def __init__(
self,
cfg,
proto,
addrfile = '',
al_id = '',
@ -173,12 +173,13 @@ class AddrList(MMGenObject): # Address info for a single seed ID
skip_chksum_msg = False,
add_p2pkh = False ):
self.cfg = cfg
self.ka_validity_chk = key_address_validity_check
self.add_p2pkh = add_p2pkh
self.proto = proto
do_chksum = False
if not g.debug_addrlist:
if not cfg.debug_addrlist:
self.dmsg_sc = self.noop
if seed and addr_idxs: # data from seed + idxs
@ -230,7 +231,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
def do_chksum_msg(self,record):
chk = 'Check this value against your records'
rec = f'Record this checksum: it will be used to verify the {self.desc} file in the future'
qmsg(
self.cfg._util.qmsg(
f'Checksum for {self.desc} data {self.id_str.hl()}: {self.chksum.hl()}\n' +
(chk,rec)[record] )
@ -246,23 +247,23 @@ class AddrList(MMGenObject): # Address info for a single seed ID
if self.gen_addrs:
from .addrgen import KeyGenerator,AddrGenerator
kg = KeyGenerator( self.proto, mmtype.pubkey_type )
ag = AddrGenerator( self.proto, mmtype )
kg = KeyGenerator( self.cfg, self.proto, mmtype.pubkey_type )
ag = AddrGenerator( self.cfg, self.proto, mmtype )
if self.add_p2pkh:
ag2 = AddrGenerator( self.proto, 'compressed' )
ag2 = AddrGenerator( self.cfg, self.proto, 'compressed' )
from .globalvars import g
from .derive import derive_coin_privkey_bytes
t_addrs = len(addr_idxs)
le = self.entry_type
out = AddrListData()
CR = '\n' if g.debug_addrlist else '\r'
CR = '\n' if self.cfg.debug_addrlist else '\r'
for pk_bytes in derive_coin_privkey_bytes(seed,addr_idxs):
if not g.debug:
qmsg_r(f'{CR}Generating {self.gen_desc} #{pk_bytes.idx} ({pk_bytes.pos} of {t_addrs})')
if not self.cfg.debug:
self.cfg._util.qmsg_r(
f'{CR}Generating {self.gen_desc} #{pk_bytes.idx} ({pk_bytes.pos} of {t_addrs})' )
e = le( proto=self.proto, idx=pk_bytes.idx )
@ -286,7 +287,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
out.append(e)
qmsg('{}{}: {} {}{} generated{}'.format(
self.cfg._util.qmsg('{}{}: {} {}{} generated{}'.format(
CR,
self.al_id.hl(),
t_addrs,
@ -316,7 +317,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
if self.proto.testnet:
scramble_key += ':' + self.proto.network
self.dmsg_sc('str',scramble_key)
return Crypto().scramble_seed(seed,scramble_key.encode())
return Crypto(self.cfg).scramble_seed(seed,scramble_key.encode())
def idxs(self):
return [e.idx for e in self.data]
@ -371,8 +372,8 @@ class AddrList(MMGenObject): # Address info for a single seed ID
def gen_addr(pk,t):
at = self.proto.addr_type(t)
from .addrgen import KeyGenerator,AddrGenerator
kg = KeyGenerator(self.proto,at.pubkey_type)
ag = AddrGenerator(self.proto,at)
kg = KeyGenerator( self.cfg, self.proto, at.pubkey_type )
ag = AddrGenerator( self.cfg, self.proto, at )
return ag.to_addr(kg.gen_data(pk))
compressed_types = set(self.proto.mmtypes) - {'L','E'}

View file

@ -434,14 +434,14 @@ class CoinInfo(object):
test_equal('P2SH leading symbol',vn_info[1],ret,*cdata)
@classmethod
def verify_core_coin_data(cls,quiet=False,verbose=False):
def verify_core_coin_data(cls,cfg,quiet=False,verbose=False):
from .protocol import CoinProtocol,init_proto
for network in ('mainnet','testnet'):
for coin in gc.core_coins:
e = cls.get_entry(coin,network)
if e:
proto = init_proto(coin,testnet=network=='testnet')
proto = init_proto( cfg, coin, network=network )
cdata = (network,coin,e,type(proto).__name__,verbose)
if not quiet:
msg(f'Verifying {coin.upper()} {network}')
@ -791,11 +791,11 @@ if __name__ == '__main__':
}
}
from mmgen.opts import init,opt
init( opts_data )
from mmgen.opts import init
cfg = init( opts_data, need_amt=False )
msg('Checking CoinInfo WIF/P2PKH/P2SH version numbers and trust levels against protocol.py')
CoinInfo.verify_core_coin_data( quiet=opt.quiet, verbose=opt.verbose )
CoinInfo.verify_core_coin_data( cfg, cfg.quiet, cfg.verbose )
msg('Checking CoinInfo address leading symbols')
CoinInfo.verify_leading_symbols( quiet=opt.quiet, verbose=opt.verbose )
CoinInfo.verify_leading_symbols( cfg.quiet, cfg.verbose )

View file

@ -100,14 +100,13 @@ class baseconv(object):
from hashlib import sha256
return sha256( ' '.join(self.digits).encode() ).hexdigest()[:8]
def check_wordlist(self):
def check_wordlist(self,cfg):
wl = self.digits
from .util import qmsg,compare_chksums
ret = f'Wordlist: {self.wl_id}\nLength: {len(wl)} words'
new_chksum = self.get_wordlist_chksum()
compare_chksums( new_chksum, 'generated', self.wl_chksum, 'saved', die_on_fail=True )
cfg._util.compare_chksums( new_chksum, 'generated', self.wl_chksum, 'saved', die_on_fail=True )
if tuple(sorted(wl)) == wl:
return ret + '\nList is sorted'

View file

@ -23,11 +23,10 @@ cfgfile: API for the MMGen runtime configuration file and related files
import os,re
from collections import namedtuple
from .globalvars import g,gc
from .util import msg,ymsg,suf,fmt,fmt_list,oneshot_warning,strip_comment,capfirst
def mmgen_cfg_file(id_str):
return cfg_file.get_cls_by_id(id_str)()
def mmgen_cfg_file(cfg,id_str):
return cfg_file.get_cls_by_id(id_str)(cfg)
class cfg_file:
cur_ver = 2
@ -53,7 +52,7 @@ class cfg_file:
def copy_system_data(self,fn):
assert self.write_ok, f'writing to file {fn!r} not allowed!'
src = mmgen_cfg_file('sys')
src = mmgen_cfg_file(self.cfg,'sys')
if src.data:
data = src.data + src.make_metadata() if self.write_metadata else src.data
try:
@ -169,8 +168,9 @@ class CfgFileUsr(cfg_file):
warn_missing = False
write_ok = True
def __init__(self):
self.fn = os.path.join(g.data_dir_root,self.fn_base)
def __init__(self,cfg):
self.cfg = cfg
self.fn = os.path.join(cfg.data_dir_root,self.fn_base)
self.data = self.get_data(self.fn)
if not self.data:
self.copy_system_data(self.fn)
@ -179,14 +179,16 @@ class CfgFileSampleSys(cfg_file_sample):
desc = 'system sample configuration file'
test_fn_subdir = 'usr.local.share'
def __init__(self):
if g.test_suite_cfgtest:
self.fn = os.path.join(g.data_dir_root,self.test_fn_subdir,self.fn_base)
def __init__(self,cfg):
self.cfg = cfg
if self.cfg.test_suite_cfgtest:
self.fn = os.path.join(cfg.data_dir_root,self.test_fn_subdir,self.fn_base)
with open(self.fn) as fp:
self.data = fp.read().splitlines()
else:
# self.fn is used for error msgs only, so file need not exist on filesystem
self.fn = os.path.join(os.path.dirname(__file__),'data',self.fn_base)
from .globalvars import gc
self.data = gc.get_mmgen_data_file(self.fn_base).splitlines()
def make_metadata(self):
@ -202,11 +204,12 @@ class CfgFileSampleUsr(cfg_file_sample):
out_of_date_fs = 'File {!r} is out of date - replacing'
altered_by_user_fs = 'File {!r} was altered by user - replacing'
def __init__(self):
self.fn = os.path.join(g.data_dir_root,f'{self.fn_base}.sample')
def __init__(self,cfg):
self.cfg = cfg
self.fn = os.path.join(cfg.data_dir_root,f'{self.fn_base}.sample')
self.data = self.get_data(self.fn)
src = mmgen_cfg_file('sys')
src = mmgen_cfg_file(cfg,'sys')
if not src.data:
return
@ -255,7 +258,7 @@ class CfgFileSampleUsr(cfg_file_sample):
opts = fmt_list([i.name for i in data],fmt='bare')
msg(f' The following option{suf(data,verb="has")} been {desc}:\n {opts}\n')
if desc == 'removed' and data:
uc = mmgen_cfg_file('usr')
uc = mmgen_cfg_file(self.cfg,'usr')
usr_names = [i.name for i in uc.get_lines()]
rm_names = [i.name for i in data]
bad = sorted(set(usr_names).intersection(rm_names))
@ -269,7 +272,7 @@ class CfgFileSampleUsr(cfg_file_sample):
from .ui import keypress_confirm,do_pager
while True:
if not keypress_confirm(self.details_confirm_prompt,no_nl=True):
if not keypress_confirm( self.cfg, self.details_confirm_prompt, no_nl=True ):
return
def get_details():

View file

@ -23,5 +23,4 @@ common: Common imports for all MMGen scripts
import sys,os
from .globalvars import *
import mmgen.opts as opts
from .opts import opt
from .util import *

View file

@ -23,23 +23,16 @@ crypto: Random number, password hashing and symmetric encryption routines for th
import os
from collections import namedtuple
from .globalvars import g,gc
from .opts import opt
from .globalvars import gc
from .util import (
msg,
msg_r,
dmsg,
vmsg,
vmsg_r,
qmsg,
fmt,
die,
make_chksum_8,
compare_chksums,
oneshot_warning,
)
class Crypto:
mmenc_ext = 'mmenc'
@ -72,6 +65,10 @@ class Crypto:
def __init__(self,fn):
oneshot_warning.__init__(self,div=fn,fmt_args=[fn],reverse=True)
def __init__(self,cfg):
self.cfg = cfg
self.util = cfg._util
def get_hash_params(self,hash_preset):
if hash_preset in self.hash_presets:
return self.hash_presets[hash_preset] # N,r,p
@ -87,7 +84,7 @@ class Crypto:
def scramble_seed(self,seed,scramble_key):
import hmac
step1 = hmac.digest(seed,scramble_key,'sha256')
if g.debug:
if self.cfg.debug:
msg(f'Seed: {seed.hex()!r}\nScramble key: {scramble_key}\nScrambled seed: {step1.hex()}\n')
return self.sha256_rounds(step1)
@ -95,56 +92,56 @@ class Crypto:
return self.encrypt_data(data,key,desc=desc)
def decrypt_seed(self,enc_seed,key,seed_id,key_id):
vmsg_r('Checking key...')
self.util.vmsg_r('Checking key...')
chk1 = make_chksum_8(key)
if key_id:
if not compare_chksums(key_id,'key ID',chk1,'computed'):
if not self.util.compare_chksums(key_id,'key ID',chk1,'computed'):
msg('Incorrect passphrase or hash preset')
return False
dec_seed = self.decrypt_data(enc_seed,key,desc='seed')
chk2 = make_chksum_8(dec_seed)
if seed_id:
if compare_chksums(seed_id,'Seed ID',chk2,'decrypted seed'):
qmsg('Passphrase is OK')
if self.util.compare_chksums(seed_id,'Seed ID',chk2,'decrypted seed'):
self.util.qmsg('Passphrase is OK')
else:
if not opt.debug:
if not self.cfg.debug:
msg_r('Checking key ID...')
if compare_chksums(key_id,'key ID',chk1,'computed'):
if self.util.compare_chksums(key_id,'key ID',chk1,'computed'):
msg('Key ID is correct but decryption of seed failed')
else:
msg('Incorrect passphrase or hash preset')
vmsg('')
self.util.vmsg('')
return False
dmsg(f'Decrypted seed: {dec_seed.hex()}')
self.util.dmsg(f'Decrypted seed: {dec_seed.hex()}')
return dec_seed
def encrypt_data(self,data,key,iv=aesctr_dfl_iv,desc='data',verify=True,silent=False):
from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
from cryptography.hazmat.backends import default_backend
if not silent:
vmsg(f'Encrypting {desc}')
self.util.vmsg(f'Encrypting {desc}')
c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
encryptor = c.encryptor()
enc_data = encryptor.update(data) + encryptor.finalize()
if verify:
vmsg_r(f'Performing a test decryption of the {desc}...')
self.util.vmsg_r(f'Performing a test decryption of the {desc}...')
c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
encryptor = c.encryptor()
dec_data = encryptor.update(enc_data) + encryptor.finalize()
if dec_data != data:
die(2,f'ERROR.\nDecrypted {desc} doesn’t match original {desc}')
if not silent:
vmsg('done')
self.util.vmsg('done')
return enc_data
def decrypt_data(self,enc_data,key,iv=aesctr_dfl_iv,desc='data'):
from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
from cryptography.hazmat.backends import default_backend
vmsg_r(f'Decrypting {desc} with key...')
self.util.vmsg_r(f'Decrypting {desc} with key...')
c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
encryptor = c.encryptor()
return encryptor.update(enc_data) + encryptor.finalize()
@ -184,7 +181,7 @@ class Crypto:
# hashlib.scrypt doesn't support N > 14 (hash preset > 3)
ret = (
do_standalone_scrypt() if ps.N > 14 or g.force_standalone_scrypt_module else
do_standalone_scrypt() if ps.N > 14 or self.cfg.force_standalone_scrypt_module else
do_hashlib_scrypt() )
if int(hash_preset) > 3:
@ -193,17 +190,17 @@ class Crypto:
return ret
def make_key(self,passwd,salt,hash_preset,desc='encryption key',from_what='passphrase',verbose=False):
if opt.verbose or verbose:
if self.cfg.verbose or verbose:
msg_r(f"Generating {desc}{' from ' + from_what if from_what else ''}...")
key = self.scrypt_hash_passphrase(passwd,salt,hash_preset)
if opt.verbose or verbose: msg('done')
dmsg(f'Key: {key.hex()}')
if self.cfg.verbose or verbose: msg('done')
self.util.dmsg(f'Key: {key.hex()}')
return key
def _get_random_data_from_user(self,uchars=None,desc='data'):
if uchars is None:
uchars = opt.usr_randchars
uchars = self.cfg.usr_randchars
info1 = f"""
Now we're going to gather some additional input from the keyboard to further
@ -225,7 +222,7 @@ class Crypto:
on the screen.
"""
msg(f'Enter {uchars} random symbols' if opt.quiet else
msg(f'Enter {uchars} random symbols' if self.cfg.quiet else
'\n' + fmt(info1,indent=' ') +
'\n' + fmt(info2) )
@ -238,7 +235,7 @@ class Crypto:
key_data += get_char_raw(f'\rYou may begin typing. {uchars-i} symbols left: ')
time_data.append(time.time())
msg_r( '\r' if opt.quiet else f'\rThank you. That’s enough.{" "*18}\n\n' )
msg_r( '\r' if self.cfg.quiet else f'\rThank you. That’s enough.{" "*18}\n\n' )
time_data = [f'{t:.22f}'.rstrip('0') for t in time_data]
@ -249,11 +246,11 @@ class Crypto:
ret = key_data + '\n' + '\n'.join(time_data)
if g.debug:
if self.cfg.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: ' )
line_input( self.cfg, 'User random data successfully acquired. Press ENTER to continue: ' )
return ret.encode()
@ -274,7 +271,7 @@ class Crypto:
assert type(rand_bytes) == bytes, 'add_user_random_chk1'
if opt.usr_randchars:
if self.cfg.usr_randchars:
if not urand['data']:
from hashlib import sha256
@ -310,7 +307,7 @@ class Crypto:
from .ui import line_input
while True:
ret = line_input( prompt )
ret = line_input( self.cfg, prompt )
if ret:
if ret in self.hash_presets:
return ret
@ -329,29 +326,30 @@ class Crypto:
if passwd_file:
from .fileutil import get_words_from_file
pw = ' '.join(get_words_from_file(
cfg = self.cfg,
infile = passwd_file,
desc = f'{pw_desc} for {data_desc}',
quiet = self.pwfile_reuse_warning(passwd_file).warning_shown ))
else:
qmsg('\n'+fmt(message,indent=' '))
self.util.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}: ' ))
if self.cfg.echo_passphrase:
pw = ' '.join(get_words_from_user( self.cfg, f'Enter {pw_desc} for {data_desc}: ' ))
else:
for i in range(gc.passwd_max_tries):
pw = ' '.join(get_words_from_user( f'Enter {pw_desc} for {data_desc}: ' ))
pw_chk = ' '.join(get_words_from_user( f'Repeat {pw_desc}: ' ))
dmsg(f'Passphrases: [{pw}] [{pw_chk}]')
pw = ' '.join(get_words_from_user( self.cfg, f'Enter {pw_desc} for {data_desc}: ' ))
pw_chk = ' '.join(get_words_from_user( self.cfg, f'Repeat {pw_desc}: ' ))
self.util.dmsg(f'Passphrases: [{pw}] [{pw_chk}]')
if pw == pw_chk:
vmsg('Passphrases match')
self.util.vmsg('Passphrases match')
break
else:
msg('Passphrases do not match. Try again.')
else:
die(2,f'User failed to duplicate passphrase in {g.passwd_max_tries} attempts')
die(2,f'User failed to duplicate passphrase in {gc.passwd_max_tries} attempts')
if pw == '':
qmsg('WARNING: Empty passphrase')
self.util.qmsg('WARNING: Empty passphrase')
return pw
@ -359,48 +357,49 @@ class Crypto:
if passwd_file:
from .fileutil import get_words_from_file
return ' '.join(get_words_from_file(
cfg = self.cfg,
infile = passwd_file,
desc = f'{pw_desc} for {data_desc}',
quiet = self.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}: ' ))
return ' '.join(get_words_from_user( self.cfg, f'Enter {pw_desc} for {data_desc}: ' ))
def mmgen_encrypt(self,data,desc='data',hash_preset=None):
salt = self.get_random(self.mmenc_salt_len)
iv = self.get_random(self.aesctr_iv_len)
nonce = self.get_random(self.mmenc_nonce_len)
hp = hash_preset or opt.hash_preset or self.get_hash_preset_from_user(data_desc=desc)
hp = hash_preset or self.cfg.hash_preset or self.get_hash_preset_from_user(data_desc=desc)
m = ('user-requested','default')[hp=='3']
vmsg(f'Encrypting {desc}')
qmsg(f'Using {m} hash preset of {hp!r}')
self.util.vmsg(f'Encrypting {desc}')
self.util.qmsg(f'Using {m} hash preset of {hp!r}')
passwd = self.get_new_passphrase(
data_desc = desc,
hash_preset = hp,
passwd_file = opt.passwd_file )
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 )
return salt+iv+enc_d
def mmgen_decrypt(self,data,desc='data',hash_preset=None):
vmsg(f'Preparing to decrypt {desc}')
self.util.vmsg(f'Preparing to decrypt {desc}')
dstart = self.mmenc_salt_len + self.aesctr_iv_len
salt = data[:self.mmenc_salt_len]
iv = data[self.mmenc_salt_len:dstart]
enc_d = data[dstart:]
hp = hash_preset or opt.hash_preset or self.get_hash_preset_from_user(data_desc=desc)
hp = hash_preset or self.cfg.hash_preset or self.get_hash_preset_from_user(data_desc=desc)
m = ('user-requested','default')[hp=='3']
qmsg(f'Using {m} hash preset of {hp!r}')
self.util.qmsg(f'Using {m} hash preset of {hp!r}')
passwd = self.get_passphrase(
data_desc = desc,
passwd_file = opt.passwd_file )
passwd_file = self.cfg.passwd_file )
key = self.make_key(passwd,salt,hp)
dec_d = self.decrypt_data( enc_d, key, iv, desc )
sha256_len = 32
from hashlib import sha256
if dec_d[:sha256_len] == sha256(dec_d[sha256_len:]).digest():
vmsg('OK')
self.util.vmsg('OK')
return dec_d[sha256_len+self.mmenc_nonce_len:]
else:
msg('Incorrect passphrase or hash preset')

View file

@ -24,7 +24,7 @@ import os,time,importlib
from subprocess import run,PIPE,CompletedProcess
from collections import namedtuple
from .globalvars import g,gc
from .globalvars import gc
from .color import set_vt100
from .util import msg,Msg_r,ymsg,die,remove_dups,oneshot_warning
from .flags import *
@ -49,8 +49,9 @@ class Daemon(Lockable):
avail_flags = () # like opts, but can be set or unset after instantiation
_reset_ok = ('debug','wait','pids')
def __init__(self,opts=None,flags=None):
def __init__(self,cfg,opts=None,flags=None):
self.cfg = cfg
self.platform = gc.platform
if self.platform == 'win':
self.use_pidfile = False
@ -237,8 +238,8 @@ class RPCDaemon(Daemon):
avail_opts = ('no_daemonize',)
def __init__(self):
super().__init__()
def __init__(self,cfg):
super().__init__(cfg)
self.desc = '{} {} {}RPC daemon'.format(
self.rpc_type,
getattr(self.proto.network_names,self.proto.network),
@ -280,13 +281,13 @@ class CoinDaemon(Daemon):
message = 'blacklisted daemon: {!r}'
@classmethod
def get_daemon_ids(cls,coin):
def get_daemon_ids(cls,cfg,coin):
ret = cls.coins[coin].daemon_ids
if 'erigon' in ret and not g.enable_erigon:
if 'erigon' in ret and not cfg.enable_erigon:
ret.remove('erigon')
if g.blacklisted_daemons:
blacklist = g.blacklisted_daemons.split()
if cfg.blacklisted_daemons:
blacklist = cfg.blacklisted_daemons.split()
def gen():
for daemon_id in ret:
if daemon_id in blacklist:
@ -297,21 +298,21 @@ class CoinDaemon(Daemon):
return ret
@classmethod
def get_daemon(cls,coin,daemon_id,proto=None):
def get_daemon(cls,cfg,coin,daemon_id,proto=None):
if not proto:
from .protocol import init_proto
proto = init_proto(coin)
proto = init_proto( cfg, coin )
return getattr(
importlib.import_module(f'mmgen.proto.{proto.base_proto_coin.lower()}.daemon'),
daemon_id+'_daemon' )
@classmethod
def get_network_ids(cls):
def get_network_ids(cls,cfg):
from .protocol import CoinProtocol
def gen():
for coin in cls.coins:
for daemon_id in cls.get_daemon_ids(coin):
for network in cls.get_daemon(coin,daemon_id).networks:
for daemon_id in cls.get_daemon_ids(cfg,coin):
for network in cls.get_daemon( cfg, coin, daemon_id ).networks:
yield CoinProtocol.Base.create_network_id(coin,network)
return remove_dups(list(gen()),quiet=True)
@ -329,6 +330,7 @@ class CoinDaemon(Daemon):
return ( res[0] if len(res) == 1 else [s for s in res if 'ersion' in s][0] ).strip()
def __new__(cls,
cfg,
network_id = None,
proto = None,
opts = None,
@ -349,19 +351,19 @@ class CoinDaemon(Daemon):
else:
network_id = network_id.lower()
from .protocol import CoinProtocol,init_proto
proto = init_proto(network_id=network_id)
proto = init_proto( cfg, network_id=network_id )
coin,network = CoinProtocol.Base.parse_network_id(network_id)
coin = coin.upper()
daemon_ids = cls.get_daemon_ids(coin)
daemon_ids = cls.get_daemon_ids(cfg,coin)
if not daemon_ids:
die(1,f'No configured daemons for coin {coin}!')
daemon_id = daemon_id or g.daemon_id or daemon_ids[0]
daemon_id = daemon_id or cfg.daemon_id or daemon_ids[0]
if daemon_id not in daemon_ids:
die(1,f'{daemon_id!r}: invalid daemon_id - valid choices: {fmt_list(daemon_ids)}')
me = Daemon.__new__(cls.get_daemon( None, daemon_id, proto=proto ))
me = Daemon.__new__(cls.get_daemon( cfg, None, daemon_id, proto=proto ))
assert network in me.networks, f'{network!r}: unsupported network for daemon {daemon_id}'
me.network_id = network_id
@ -373,6 +375,7 @@ class CoinDaemon(Daemon):
return me
def __init__(self,
cfg,
network_id = None,
proto = None,
opts = None,
@ -385,7 +388,7 @@ class CoinDaemon(Daemon):
self.test_suite = test_suite
super().__init__(opts=opts,flags=flags)
super().__init__(cfg=cfg,opts=opts,flags=flags)
self._set_ok += ('shared_args','usr_coind_args')
self.shared_args = []
@ -400,8 +403,8 @@ class CoinDaemon(Daemon):
'test suite ' if test_suite else '' )
# user-set values take precedence
self.datadir = os.path.abspath(datadir or g.daemon_data_dir or self.init_datadir())
self.non_dfl_datadir = bool(datadir or g.daemon_data_dir or test_suite or self.network == 'regtest')
self.datadir = os.path.abspath(datadir or cfg.daemon_data_dir or self.init_datadir())
self.non_dfl_datadir = bool(datadir or cfg.daemon_data_dir or test_suite or self.network == 'regtest')
# init_datadir() may have already initialized logdir
self.logdir = os.path.abspath(getattr(self,'logdir',self.datadir))
@ -409,7 +412,7 @@ class CoinDaemon(Daemon):
ps_adj = (port_shift or 0) + (self.test_suite_port_shift if test_suite else 0)
# user-set values take precedence
self.rpc_port = (g.rpc_port or 0) + (port_shift or 0) if g.rpc_port else ps_adj + self.get_rpc_port()
self.rpc_port = (cfg.rpc_port or 0) + (port_shift or 0) if cfg.rpc_port else ps_adj + self.get_rpc_port()
self.p2p_port = (
p2p_port or (
self.get_p2p_port() + ps_adj if self.get_p2p_port() and (test_suite or ps_adj) else None

View file

@ -1 +1 @@
13.3.dev41
13.3.dev42

View file

@ -22,12 +22,10 @@ fileutil: Routines that read, write, execute or stat files
import sys,os
from .globalvars import g,gc
from .globalvars import gc
from .color import set_vt100
from .util import (
msg,
qmsg,
dmsg,
die,
get_extension,
is_utf8,
@ -114,15 +112,16 @@ def check_outfile(f,blkdev_ok=False):
def check_outdir(f):
return _check_file_type_and_access(f,'output directory')
def get_seed_file(wallets,nargs,invoked_as=None):
def get_seed_file(cfg,nargs,wallets=None,invoked_as=None):
wallets = wallets or cfg._args
from .opts import opt
from .filename import find_file_in_dir
from .wallet.mmgen import wallet
wf = find_file_in_dir(wallet,g.data_dir)
wf = find_file_in_dir(wallet,cfg.data_dir)
wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
wd_from_opt = bool(cfg.hidden_incog_input_params or cfg.in_fmt) # have wallet data from opt?
import mmgen.opts as opts
if len(wallets) + (wd_from_opt or bool(wf)) < nargs:
@ -132,7 +131,7 @@ def get_seed_file(wallets,nargs,invoked_as=None):
elif len(wallets) > nargs:
opts.usage()
elif len(wallets) == nargs and wf and invoked_as != 'gen':
qmsg('Warning: overriding default wallet with user-supplied wallet')
cfg._util.qmsg('Warning: overriding default wallet with user-supplied wallet')
if wallets or wf:
check_infile(wallets[0] if wallets else wf)
@ -150,6 +149,7 @@ def _open_or_die(filename,mode,silent=False):
))
def write_data_to_file(
cfg,
outfile,
data,
desc = 'data',
@ -165,25 +165,24 @@ def write_data_to_file(
check_data = False,
cmp_data = None):
from .opts import opt
if quiet:
ask_tty = ask_overwrite = False
if opt.quiet:
if cfg.quiet:
ask_overwrite = False
if ask_write_default_yes == False or ask_write_prompt:
ask_write = True
def do_stdout():
qmsg('Output to STDOUT requested')
if g.stdin_tty:
cfg._util.qmsg('Output to STDOUT requested')
if cfg.stdin_tty:
if no_tty:
die(2,f'Printing {desc} to screen is not allowed')
if (ask_tty and not opt.quiet) or binary:
if (ask_tty and not cfg.quiet) or binary:
from .ui import confirm_or_raise
confirm_or_raise(
cfg,
message = '',
action = f'output {desc} to screen' )
else:
@ -194,9 +193,10 @@ def write_data_to_file(
if of[:5] == 'pipe:':
if no_tty:
die(2,f'Writing {desc} to pipe is not allowed')
if ask_tty and not opt.quiet:
if ask_tty and not cfg.quiet:
from .ui import confirm_or_raise
confirm_or_raise(
cfg,
message = '',
action = f'output {desc} to pipe' )
msg('')
@ -216,14 +216,15 @@ def write_data_to_file(
os.write(1,data if isinstance(data,bytes) else data.encode())
def do_file(outfile,ask_write_prompt):
if opt.outdir and not ignore_opt_outdir and not os.path.isabs(outfile):
outfile = make_full_path(opt.outdir,outfile)
if cfg.outdir and not ignore_opt_outdir and not os.path.isabs(outfile):
outfile = make_full_path(cfg.outdir,outfile)
if ask_write:
if not ask_write_prompt:
ask_write_prompt = f'Save {desc}?'
from .ui import keypress_confirm
if not keypress_confirm(
cfg,
ask_write_prompt,
default_yes = ask_write_default_yes ):
die(1,f'{capfirst(desc)} not saved')
@ -232,6 +233,7 @@ def write_data_to_file(
if os.path.lexists(outfile) and ask_overwrite:
from .ui import confirm_or_raise
confirm_or_raise(
cfg,
message = '',
action = f'File {outfile!r} already exists\nOverwrite?' )
msg(f'Overwriting file {outfile!r}')
@ -262,17 +264,17 @@ def write_data_to_file(
return True
if opt.stdout or outfile in ('','-'):
if cfg.stdout or outfile in ('','-'):
do_stdout()
elif sys.stdin.isatty() and not sys.stdout.isatty():
do_stdout()
else:
do_file(outfile,ask_write_prompt)
def get_words_from_file(infile,desc,quiet=False):
def get_words_from_file(cfg,infile,desc,quiet=False):
if not quiet:
qmsg(f'Getting {desc} from file {infile!r}')
cfg._util.qmsg(f'Getting {desc} from file {infile!r}')
with _open_or_die(infile, 'rb') as fp:
data = fp.read()
@ -282,11 +284,12 @@ def get_words_from_file(infile,desc,quiet=False):
except:
die(1,f'{capfirst(desc)} data must be UTF-8 encoded.')
dmsg('Sanitized input: [{}]'.format(' '.join(words)))
cfg._util.dmsg('Sanitized input: [{}]'.format(' '.join(words)))
return words
def get_data_from_file(
cfg,
infile,
desc = 'data',
dash = False,
@ -294,26 +297,26 @@ def get_data_from_file(
binary = False,
quiet = False ):
from .opts import opt
if not (opt.quiet or silent or quiet):
qmsg(f'Getting {desc} from file {infile!r}')
if not (cfg.quiet or silent or quiet):
cfg._util.qmsg(f'Getting {desc} from file {infile!r}')
with _open_or_die(
(0 if dash and infile == '-' else infile),
'rb',
silent=silent) as fp:
data = fp.read(g.max_input_size+1)
data = fp.read(cfg.max_input_size+1)
if not binary:
data = data.decode()
if len(data) == g.max_input_size + 1:
if len(data) == cfg.max_input_size + 1:
die( 'MaxInputSizeExceeded',
f'Too much input data! Max input data size: {f.max_input_size} bytes' )
return data
def get_lines_from_file(
cfg,
fn,
desc = 'data',
trim_comments = False,
@ -321,17 +324,17 @@ def get_lines_from_file(
silent = False ):
def decrypt_file_maybe():
data = get_data_from_file( fn, desc=desc, binary=True, quiet=quiet, silent=silent )
data = get_data_from_file( cfg, fn, desc=desc, binary=True, quiet=quiet, silent=silent )
from .crypto import Crypto
have_enc_ext = get_extension(fn) == Crypto.mmenc_ext
if have_enc_ext or not is_utf8(data):
m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
qmsg(f'{m} {desc} {fn!r}')
data = Crypto().mmgen_decrypt_retry(data,desc)
cfg._util.qmsg(f'{m} {desc} {fn!r}')
data = Crypto(cfg).mmgen_decrypt_retry(data,desc)
return data
lines = decrypt_file_maybe().decode().splitlines()
if trim_comments:
lines = strip_comments(lines)
dmsg(f'Got {len(lines)} lines from file {fn!r}')
cfg._util.dmsg(f'Got {len(lines)} lines from file {fn!r}')
return lines

View file

@ -104,7 +104,7 @@ class GlobalVars:
gv = GlobalVars()
class GlobalConfig(Lockable):
class Config(Lockable):
"""
These values are configurable - RHS values are defaults
Globals are overridden with the following precedence:
@ -113,12 +113,13 @@ class GlobalConfig(Lockable):
3 - config file
"""
_autolock = False
_set_ok = ()
_reset_ok = ('accept_defaults',)
_set_ok = ('usr_randchars','_proto')
_reset_ok = ('accept_defaults','quiet','verbose','yes')
_use_class_attr = True
_default_to_none = True
# general
coin = ''
coin = 'BTC'
token = ''
outdir = ''
passwd_file = ''
@ -189,7 +190,7 @@ class GlobalConfig(Lockable):
bob = False
alice = False
carol = False
regtest_user = None
regtest_user = ''
# test suite:
bogus_send = False
@ -216,20 +217,6 @@ class GlobalConfig(Lockable):
_proto = None
pager = False
# global var sets user opt:
global_sets_opt = (
'autochg_ignore_labels',
'debug',
'minconf',
'quiet',
'fee_estimate_confs',
'fee_adjust',
'use_internal_keccak_module',
'usr_randchars' )
# user opt sets global var:
opt_sets_global = ( 'cached_balances', )
# 'long' opts (subset of common_opts_data):
common_opts = (
'accept_defaults',
@ -415,5 +402,3 @@ class GlobalConfig(Lockable):
'mainnet': (self.data_dir_root,),
}[self.network] ))
return self._data_dir
g = GlobalConfig()

View file

@ -22,7 +22,7 @@ help: help notes for MMGen suite commands
from .globalvars import gc
def help_notes_func(proto,opt,k):
def help_notes_func(proto,cfg,k):
def fee_spec_letters(use_quotes=False):
cu = proto.coin_amt.units
@ -36,7 +36,7 @@ def help_notes_func(proto,opt,k):
def coind_exec():
from .daemon import CoinDaemon
return (
CoinDaemon(proto.coin).exec_fn if proto.coin in CoinDaemon.coins else 'bitcoind' )
CoinDaemon(cfg,proto.coin).exec_fn if proto.coin in CoinDaemon.coins else 'bitcoind' )
class help_notes:
@ -92,7 +92,7 @@ def help_notes_func(proto,opt,k):
from .keygen import get_backends
from .addr import MMGenAddrType
backends = get_backends(
MMGenAddrType(proto,opt.type or proto.dfl_mmtype).pubkey_type
MMGenAddrType(proto,cfg.type or proto.dfl_mmtype).pubkey_type
)
return ' '.join( f'{n}:{k}{" [default]" if n==1 else ""}' for n,k in enumerate(backends,1) )
@ -102,11 +102,11 @@ def help_notes_func(proto,opt,k):
def coin_daemon_network_ids():
from .daemon import CoinDaemon
from .util import fmt_list
return fmt_list(CoinDaemon.get_network_ids(),fmt='bare')
return fmt_list(CoinDaemon.get_network_ids(cfg),fmt='bare')
def rel_fee_desc():
from .tx import BaseTX
return BaseTX(proto=proto).rel_fee_desc
return BaseTX(cfg=cfg,proto=proto).rel_fee_desc
def fee_spec_letters():
return fee_spec_letters()
@ -121,7 +121,7 @@ be specified as either absolute {c} amounts, using a plain decimal number, or
as {r}, using an integer followed by '{l}', for {u}.
""".format(
c = proto.coin,
r = BaseTX(proto=proto).rel_fee_desc,
r = BaseTX(cfg=cfg,proto=proto).rel_fee_desc,
l = fee_spec_letters(use_quotes=True),
u = fee_spec_names() )
@ -147,7 +147,7 @@ seed, the same seed length and hash preset parameters must always be used.
mmtype = 'S' if 'segwit' in proto.caps else 'C'
from .tool.coin import tool_cmd
t = tool_cmd(mmtype=mmtype)
t = tool_cmd(cfg,mmtype=mmtype)
sample_addr = t.privhex2addr('bead'*16)
return f"""

View file

@ -71,9 +71,9 @@ def get_pubkey_type_cls(pubkey_type):
importlib.import_module(f'mmgen.proto.{backend_data[pubkey_type]["package"]}.keygen'),
'backend' )
def _check_backend(backend,pubkey_type,desc='keygen backend'):
def _check_backend(cfg,backend,pubkey_type,desc='keygen backend'):
from .util import is_int,qmsg,die
from .util import is_int,die
assert is_int(backend), f'illegal value for {desc} (must be an integer)'
@ -86,21 +86,22 @@ def _check_backend(backend,pubkey_type,desc='keygen backend'):
' '.join( f'{n}:{k}' for n,k in enumerate(backends,1) )
)
qmsg(f'Using backend {backends[int(backend)-1]!r} for public key generation')
cfg._util.qmsg(f'Using backend {backends[int(backend)-1]!r} for public key generation')
return True
def check_backend(proto,backend,addr_type):
def check_backend(cfg,proto,backend,addr_type):
from .addr import MMGenAddrType
pubkey_type = MMGenAddrType(proto,addr_type or proto.dfl_mmtype).pubkey_type
return _check_backend(
cfg,
backend,
pubkey_type,
desc = '--keygen-backend parameter' )
def KeyGenerator(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
"""
@ -108,11 +109,10 @@ def KeyGenerator(proto,pubkey_type,backend=None,silent=False):
pubkey_type_cls = get_pubkey_type_cls(pubkey_type)
from .opts import opt
backend = backend or opt.keygen_backend
backend = backend or cfg.keygen_backend
if backend:
_check_backend(backend,pubkey_type)
_check_backend( cfg, backend, pubkey_type )
backend_id = backend_data[pubkey_type]['backends'][int(backend) - 1 if backend else 0]
@ -121,4 +121,4 @@ def KeyGenerator(proto,pubkey_type,backend=None,silent=False):
backend_id.replace('-','_')
).test_avail(silent=silent)
return getattr(pubkey_type_cls,backend_clsname)()
return getattr(pubkey_type_cls,backend_clsname)(cfg)

View file

@ -22,8 +22,7 @@ mmgen-addrgen: Generate a series or range of addresses from an MMGen
"""
import mmgen.opts as opts
from .globalvars import g,gc
from .opts import opt
from .globalvars import gc
from .addr import MMGenAddrType
from .addrfile import AddrFile
from .wallet import Wallet
@ -74,7 +73,7 @@ opts_data = {
-P, --passwd-file= f Get wallet passphrase from file 'f'
-q, --quiet Produce quieter output; suppress some warnings
-r, --usr-randchars=n Get 'n' characters of additional randomness from user
(min={g.min_urandchars}, max={g.max_urandchars}, default={g.usr_randchars})
(min={cfg.min_urandchars}, max={cfg.max_urandchars}, default={cfg.usr_randchars})
-S, --stdout Print {what} to stdout
-t, --type=t Choose address type. Options: see ADDRESS TYPES below
(default: {dmat})
@ -106,14 +105,14 @@ FMT CODES:
"""
},
'code': {
'options': lambda proto,help_notes,s: s.format(
'options': lambda proto,help_notes,cfg,s: s.format(
dmat=help_notes('dfl_mmtype'),
kgs=help_notes('keygen_backends'),
coin_id=help_notes('coin_id'),
dsl=help_notes('dfl_seed_len'),
pnm=gc.proj_name,
what=gen_what,
g=g,
cfg=cfg,
gc=gc,
),
'notes': lambda help_notes,s: s.format(
@ -127,39 +126,39 @@ FMT CODES:
}
}
cmd_args = opts.init(opts_data,opt_filter=opt_filter)
cfg = opts.init(opts_data,opt_filter=opt_filter,need_amt=False)
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
proto = cfg._proto
addr_type = MMGenAddrType(
proto = proto,
id_str = opt.type or proto.dfl_mmtype,
errmsg = f'{opt.type!r}: invalid parameter for --type option' )
id_str = cfg.type or proto.dfl_mmtype,
errmsg = f'{cfg.type!r}: invalid parameter for --type option' )
if len(cmd_args) < 1:
if len(cfg._args) < 1:
opts.usage()
if opt.keygen_backend:
if cfg.keygen_backend:
from .keygen import check_backend
check_backend( proto, opt.keygen_backend, opt.type )
check_backend( cfg, proto, cfg.keygen_backend, cfg.type )
idxs = mmgen.addrlist.AddrIdxList( fmt_str=cmd_args.pop() )
idxs = mmgen.addrlist.AddrIdxList( fmt_str=cfg._args.pop() )
from .fileutil import get_seed_file
sf = get_seed_file(cmd_args,1)
sf = get_seed_file(cfg,1)
from .ui import do_license_msg
do_license_msg()
do_license_msg(cfg)
ss = Wallet(sf)
ss = Wallet(cfg,sf)
ss_seed = ss.seed if opt.subwallet is None else ss.seed.subseed(opt.subwallet,print_msg=True)
ss_seed = ss.seed if cfg.subwallet is None else ss.seed.subseed(cfg.subwallet,print_msg=True)
if opt.no_addresses:
if cfg.no_addresses:
gen_clsname = 'KeyList'
al = getattr( mmgen.addrlist, gen_clsname )(
cfg = cfg,
proto = proto,
seed = ss_seed,
addr_idxs = idxs,
@ -169,11 +168,11 @@ af = al.get_file()
af.format()
if al.gen_addrs and opt.print_checksum:
if al.gen_addrs and cfg.print_checksum:
Die(0,al.checksum)
from .ui import keypress_confirm
if al.gen_keys and keypress_confirm('Encrypt key list?'):
if al.gen_keys and keypress_confirm( cfg, 'Encrypt key list?' ):
af.encrypt()
af.write(
binary = True,

View file

@ -24,8 +24,7 @@ from collections import namedtuple
import mmgen.opts as opts
from .globalvars import gc
from .opts import opt
from .util import msg,qmsg,suf,die,fmt,async_run
from .util import msg,suf,die,fmt,async_run
from .addrlist import AddrList,KeyAddrList
from .tw.shared import TwLabel
@ -87,7 +86,7 @@ addrimport_msgs = {
def parse_cmd_args(rpc,cmd_args):
def import_mmgen_list(infile):
al = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](proto,infile)
al = (AddrList,KeyAddrList)[bool(cfg.keyaddr_file)](cfg,proto,infile)
if al.al_id.mmtype in ('S','B'):
if not rpc.info('segwit_is_active'):
die(2,'Segwit is not active on this chain. Cannot import Segwit addresses')
@ -97,17 +96,19 @@ def parse_cmd_args(rpc,cmd_args):
infile = cmd_args[0]
from .fileutil import check_infile,get_lines_from_file
check_infile(infile)
if opt.addrlist:
if cfg.addrlist:
al = AddrList(
proto = proto,
cfg = cfg,
proto = proto,
addrlist = get_lines_from_file(
cfg,
infile,
f'non-{gc.proj_name} addresses',
trim_comments = True ) )
else:
al = import_mmgen_list(infile)
elif len(cmd_args) == 0 and opt.address:
al = AddrList(proto=proto,addrlist=[opt.address])
elif len(cmd_args) == 0 and cfg.address:
al = AddrList( cfg, proto=proto, addrlist=[cfg.address] )
infile = 'command line'
else:
die(1,addrimport_msgs['bad_args'])
@ -115,16 +116,17 @@ def parse_cmd_args(rpc,cmd_args):
return al,infile
def check_opts(twctl):
batch = bool(opt.batch)
rescan = bool(opt.rescan)
batch = bool(cfg.batch)
rescan = bool(cfg.rescan)
if rescan and not 'rescan' in twctl.caps:
msg(f"‘--rescan’ ignored: not supported by {type(twctl).__name__}")
rescan = False
if rescan and not opt.quiet:
if rescan and not cfg.quiet:
from .ui import keypress_confirm
if not keypress_confirm(
cfg,
'\n{}\n\nContinue?'.format(addrimport_msgs['rescan']),
default_yes = True ):
die(1,'Exiting at user request')
@ -137,32 +139,33 @@ def check_opts(twctl):
async def main():
from .tw.ctl import TwCtl
if opt.token_addr:
if cfg.token_addr:
proto.tokensym = 'foo' # hack to trigger 'Token' in proto.base_proto_subclass()
twctl = await TwCtl(
cfg = cfg,
proto = proto,
token_addr = opt.token_addr,
token_addr = cfg.token_addr,
mode = 'i' )
if opt.token or opt.token_addr:
if cfg.token or cfg.token_addr:
msg(f'Importing for token {twctl.token.hl()} ({twctl.token.hlc(proto.tokensym)})')
from .rpc import rpc_init
twctl.rpc = await rpc_init(proto)
twctl.rpc = await rpc_init(cfg,proto)
for k,v in addrimport_msgs.items():
addrimport_msgs[k] = fmt(v,indent=' ',strip_char='\t').rstrip()
al,infile = parse_cmd_args(twctl.rpc,cmd_args)
al,infile = parse_cmd_args(twctl.rpc,cfg._args)
qmsg(
cfg._util.qmsg(
f'OK. {al.num_addrs} addresses'
+ (f' from Seed ID {al.al_id.sid}' if hasattr(al.al_id,'sid') else '') )
msg(
f'Importing {len(al.data)} address{suf(al.data,"es")} from {infile}'
+ (' (batch mode)' if opt.batch else '') )
+ (' (batch mode)' if cfg.batch else '') )
batch,rescan = check_opts(twctl)
@ -183,9 +186,8 @@ async def main():
del twctl
cmd_args = opts.init(opts_data)
cfg = opts.init(opts_data,need_amt=False)
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
proto = cfg._proto
async_run(main())

View file

@ -26,9 +26,7 @@ from collections import namedtuple
from stat 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 .util import msg,msg_r,ymsg,rmsg,gmsg,bmsg,die,suf,fmt_list,async_run,exit_if_mswin
from .color import yellow,red,orange
mountpoint = '/mnt/tx'
@ -122,7 +120,7 @@ This command is currently available only on Linux-based platforms.
}
}
cmd_args = opts.init(
cfg = opts.init(
opts_data,
add_opts = ['outdir','passwd_file'], # in _set_ok, so must be set
init_opts = {
@ -133,14 +131,16 @@ cmd_args = opts.init(
'label': 'Autosign Wallet',
})
type(opt)._set_ok += ('outdir','passwd_file')
cmd_args = cfg._args
type(cfg)._set_ok += ('outdir','passwd_file')
exit_if_mswin('autosigning')
if opt.mnemonic_fmt:
if opt.mnemonic_fmt not in mn_fmts:
if cfg.mnemonic_fmt:
if cfg.mnemonic_fmt not in mn_fmts:
die(1,'{!r}: invalid mnemonic format (must be one of: {})'.format(
opt.mnemonic_fmt,
cfg.mnemonic_fmt,
fmt_list(mn_fmts,fmt='no_spc') ))
from .wallet import Wallet
@ -149,32 +149,32 @@ from .tx.sign import txsign
from .protocol import init_proto
from .rpc import rpc_init
if opt.mountpoint:
mountpoint = opt.mountpoint
if cfg.mountpoint:
mountpoint = cfg.mountpoint
keyfile = os.path.join(mountpoint,'autosign.key')
msg_dir = os.path.join(mountpoint,'msg')
tx_dir = os.path.join(mountpoint,'tx')
opt.outdir = tx_dir
opt.passwd_file = keyfile
cfg.outdir = tx_dir
cfg.passwd_file = keyfile
async def check_daemons_running():
if opt.coin:
if cfg.coin != type(cfg).coin:
die(1,'--coin option not supported with this command. Use --coins instead')
if opt.coins:
coins = opt.coins.upper().split(',')
if cfg.coins:
coins = cfg.coins.upper().split(',')
else:
ymsg('Warning: no coins specified, defaulting to BTC')
coins = ['BTC']
for coin in coins:
proto = init_proto( coin, testnet=g.network=='testnet', need_amt=True )
proto = init_proto( cfg, coin, testnet=cfg.network=='testnet', need_amt=True )
if proto.sign_mode == 'daemon':
vmsg(f'Checking {coin} daemon')
cfg._util.vmsg(f'Checking {coin} daemon')
from .exception import SocketError
try:
await rpc_init(proto)
await rpc_init(cfg,proto)
except SocketError as e:
die(2,f'{coin} daemon not running or not listening on port {proto.rpc_port}')
@ -213,10 +213,10 @@ def do_umount():
async def sign_object(d,fn):
try:
if d.desc == 'transaction':
tx1 = UnsignedTX(filename=fn)
tx1 = UnsignedTX(cfg=cfg,filename=fn)
if tx1.proto.sign_mode == 'daemon':
tx1.rpc = await rpc_init(tx1.proto)
tx2 = await txsign(tx1,wfs[:],None,None)
tx1.rpc = await rpc_init(cfg,tx1.proto)
tx2 = await txsign(cfg,tx1,wfs[:],None,None)
if tx2:
tx2.file.write(ask_write=False)
return tx2
@ -224,9 +224,9 @@ async def sign_object(d,fn):
return False
elif d.desc == 'message file':
from .msg import UnsignedMsg,SignedMsg
m = UnsignedMsg(infile=fn)
m = UnsignedMsg(cfg,infile=fn)
await m.sign(wallet_files=wfs[:])
m = SignedMsg(data=m.__dict__)
m = SignedMsg(cfg,data=m.__dict__)
m.write_to_file(
outdir = os.path.abspath(msg_dir),
ask_overwrite = False )
@ -259,12 +259,12 @@ async def sign(target):
ok.append(ret)
else:
bad.append(fn)
qmsg('')
cfg._util.qmsg('')
await asyncio.sleep(0.3)
msg(f'{len(ok)} {d.desc}{suf(ok)} signed')
if bad:
rmsg(f'{len(bad)} {d.desc}{suf(bad)} failed to {d.fail_desc}')
if ok and not opt.no_summary:
if ok and not cfg.no_summary:
print_summary(d,ok)
if bad:
msg('')
@ -285,11 +285,11 @@ async def sign(target):
return True
def decrypt_wallets():
msg(f'Unlocking wallet{suf(wfs)} with key from {opt.passwd_file!r}')
msg(f'Unlocking wallet{suf(wfs)} with key from {cfg.passwd_file!r}')
fails = 0
for wf in wfs:
try:
Wallet(wf,ignore_in_fmt=True)
Wallet(cfg,wf,ignore_in_fmt=True)
except SystemExit as e:
if e.code != 0:
fails += 1
@ -304,7 +304,7 @@ def print_summary(d,signed_objects):
gmsg(' ' + os.path.join(msg_dir,m.signed_filename) )
return
if opt.full_summary:
if cfg.full_summary:
bmsg('\nAutosign summary:\n')
def gen():
for tx in signed_objects:
@ -340,23 +340,23 @@ def print_summary(d,signed_objects):
msg('No non-MMGen outputs')
async def do_sign():
if not opt.stealth_led:
if not cfg.stealth_led:
led.set('busy')
do_mount()
key_ok = decrypt_wallets()
if key_ok:
if opt.stealth_led:
if cfg.stealth_led:
led.set('busy')
ret1 = await sign('tx')
ret2 = await sign('msg') if have_msg_dir else True
ret = ret1 and ret2
do_umount()
led.set(('standby','off','error')[(not ret)*2 or bool(opt.stealth_led)])
led.set(('standby','off','error')[(not ret)*2 or bool(cfg.stealth_led)])
return ret
else:
msg('Password is incorrect!')
do_umount()
if not opt.stealth_led:
if not cfg.stealth_led:
led.set('error')
return False
@ -366,7 +366,7 @@ def wipe_existing_key():
else:
from .fileutil import shred_file
msg(f'\nShredding existing key {keyfile!r}')
shred_file( keyfile, verbose=opt.verbose )
shred_file( keyfile, verbose=cfg.verbose )
def create_key():
kdata = os.urandom(32).hex()
@ -404,12 +404,12 @@ def create_wallet_dir():
def setup():
remove_wallet_dir()
gen_key(no_unmount=True)
ss_in = Wallet(in_fmt=mn_fmts[opt.mnemonic_fmt or mn_fmt_dfl])
ss_out = Wallet(ss=ss_in)
ss_in = Wallet(cfg,in_fmt=mn_fmts[cfg.mnemonic_fmt or mn_fmt_dfl])
ss_out = Wallet(cfg,ss=ss_in)
ss_out.write_to_file(desc='autosign wallet',outdir=wallet_dir)
def get_insert_status():
if opt.no_insert_check:
if cfg.no_insert_check:
return True
try: os.stat(os.path.join('/dev/disk/by-label',part_label))
except: return False
@ -417,7 +417,7 @@ def get_insert_status():
async def do_loop():
n,prev_status = 0,False
if not opt.stealth_led:
if not cfg.stealth_led:
led.set('standby')
while True:
status = get_insert_status()
@ -459,7 +459,7 @@ signal.signal(signal.SIGINT,handler)
from .led import LEDControl
led = LEDControl(
enabled = opt.led,
enabled = cfg.led,
simulate = os.getenv('MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE') )
led.set('off')

View file

@ -14,10 +14,8 @@ 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 .util import msg,suf,async_run,stdout_or_pager
from .util import msg,suf,async_run
from .msg import (
NewMsg,
CompletedMsg,
@ -33,30 +31,29 @@ class MsgOps:
class create:
def __init__(self,msg,addr_specs):
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
NewMsg(
coin = proto.coin,
network = proto.network,
cfg = cfg,
coin = cfg._proto.coin,
network = cfg._proto.network,
message = msg,
addrlists = addr_specs,
msghash_type = opt.msghash_type
msghash_type = cfg.msghash_type
).write_to_file( ask_overwrite=False )
class sign(metaclass=AsyncInit):
async def __init__(self,msgfile,wallet_files):
m = UnsignedMsg( infile=msgfile )
m = UnsignedMsg( cfg, infile=msgfile )
if not wallet_files:
from .filename import find_file_in_dir
from .wallet import get_wallet_cls
wallet_files = [find_file_in_dir( get_wallet_cls('mmgen'), g.data_dir )]
wallet_files = [find_file_in_dir( get_wallet_cls('mmgen'), cfg.data_dir )]
await m.sign(wallet_files)
m = SignedMsg( data=m.__dict__ )
m = SignedMsg( cfg, data=m.__dict__ )
m.write_to_file( ask_overwrite=False )
@ -67,18 +64,18 @@ class MsgOps:
async def __init__(self,msgfile,addr=None):
try:
m = SignedOnlineMsg( infile=msgfile )
m = SignedOnlineMsg( cfg, infile=msgfile )
except:
m = ExportedMsgSigs( infile=msgfile )
m = ExportedMsgSigs( cfg, infile=msgfile )
nSigs = await m.verify(addr)
summary = f'{nSigs} signature{suf(nSigs)} verified'
if opt.quiet:
if cfg.quiet:
msg(summary)
else:
stdout_or_pager(m.format(addr) + '\n\n' + summary + '\n')
cfg._util.stdout_or_pager(m.format(addr) + '\n\n' + summary + '\n')
if m.data.get('failed_sids'):
sys.exit(1)
@ -89,8 +86,9 @@ class MsgOps:
from .fileutil import write_data_to_file
write_data_to_file(
cfg = cfg,
outfile = 'signatures.json',
data = SignedOnlineMsg( infile=msgfile ).get_json_for_export( addr ),
data = SignedOnlineMsg( cfg, infile=msgfile ).get_json_for_export( addr ),
desc = 'signature data' )
opts_data = {
@ -205,14 +203,16 @@ $ mmgen-msg verify signatures.json
}
}
cmd_args = opts.init(opts_data)
cfg = opts.init(opts_data,need_amt=False)
cmd_args = cfg._args
if len(cmd_args) < 2:
opts.usage()
op = cmd_args.pop(0)
if opt.msghash_type and op != 'create':
if cfg.msghash_type and op != 'create':
die(1,'--msghash-type option may only be used with the "create" command')
async def main():

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