new Lockable class; lock global vars after initialization (amended)

This commit is contained in:
The MMGen Project 2020-05-29 16:10:12 +00:00
commit 4c2410e0d6
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
25 changed files with 422 additions and 206 deletions

View file

@ -244,7 +244,7 @@ Actions: [q]uit view, [p]rint to file, pager [v]iew, [w]ide view,
'l':'a_lbl_add','D':'a_addr_delete','R':'a_balance_refresh' }
async def __ainit__(self,proto,*args,**kwargs):
if g.use_cached_balances:
if g.cached_balances:
self.hdr_fmt += '\n' + yellow('WARNING: Using cached balances. These may be out of date!')
await TwUnspentOutputs.__ainit__(self,proto,*args,**kwargs)

88
mmgen/base_obj.py Executable file
View file

@ -0,0 +1,88 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2020 The MMGen Project <mmgen@tuta.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
base_obj.py: base objects with no internal imports for the MMGen suite
"""
class AttrCtrl:
"""
After instance is locked, forbid setting any attribute if the attribute is not present
in either the class or instance dict.
If _use_class_attr is True, ensure that attribute's type matches that of the class
attribute, unless the class attribute is set to None, in which case no type checking
is performed.
"""
_lock = False
_use_class_attr = False
def lock(self):
self._lock = True
def __setattr__(self,name,value):
if self._lock:
def do_error(name,value,ref_val):
raise AttributeError(
f'{value!r}: invalid value for attribute {name!r}'
+ ' of {} object (must be of type {}, not {})'.format(
type(self).__name__,
type(ref_val).__name__,
type(value).__name__ ) )
if not hasattr(self,name):
raise AttributeError(f'{type(self).__name__} object has no attribute {name!r}')
ref_val = getattr(type(self),name) if self._use_class_attr else getattr(self,name)
if (ref_val is not None) and not isinstance(value,type(ref_val)):
do_error(name,value,ref_val)
return object.__setattr__(self,name,value)
def __delattr__(self,name,value):
raise AttributeError('attribute cannot be deleted')
class Lockable(AttrCtrl):
"""
After instance is locked, its attributes become read-only, with the following exceptions:
- if the attribute's name is in _set_ok, attr can be set once after locking, if unset
- if the attribute's name is in _reset_ok, read-only restrictions are bypassed and only
AttrCtrl checking is performed
To determine whether an attribute is set, it's matched against either None or the class attribute,
if _use_class_attr is True
"""
_set_ok = ()
_reset_ok = ()
def __setattr__(self,name,value):
if self._lock and hasattr(self,name):
if name not in (self._set_ok + self._reset_ok):
raise AttributeError(f'attribute {name!r} of {type(self).__name__} object is read-only')
elif name not in self._reset_ok:
#print(self.__dict__)
if not (
getattr(self,name) is None or
( self._use_class_attr and name not in self.__dict__ ) ):
raise AttributeError(
f'attribute {name!r} of {type(self).__name__} object is already set,'
+ ' and resetting is forbidden' )
# name is in (_set_ok + _reset_ok) -- allow name to be in both lists
return AttrCtrl.__setattr__(self,name,value)

View file

@ -216,14 +216,44 @@ def get_hash_preset_from_user(hp=g.dfl_hash_preset,desc='data'):
else:
return hp
_salt_len,_sha256_len,_nonce_len = 32,32,32
def get_new_passphrase(desc,passchg=False):
w = '{}passphrase for {}'.format(('','new ')[bool(passchg)], desc)
if opt.passwd_file:
pw = ' '.join(get_words_from_file(opt.passwd_file,w))
elif opt.echo_passphrase:
pw = ' '.join(get_words_from_user(f'Enter {w}: '))
else:
for i in range(g.passwd_max_tries):
pw = ' '.join(get_words_from_user(f'Enter {w}: '))
pw_chk = ' '.join(get_words_from_user('Repeat passphrase: '))
dmsg(f'Passphrases: [{pw}] [{pw_chk}]')
if pw == pw_chk:
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')
if pw == '':
qmsg('WARNING: Empty passphrase')
return pw
def get_passphrase(desc,passchg=False):
prompt ='Enter {}passphrase for {}: '.format(('','old ')[bool(passchg)],desc)
if opt.passwd_file:
pwfile_reuse_warning(opt.passwd_file)
return ' '.join(get_words_from_file(opt.passwd_file,'passphrase'))
else:
return ' '.join(get_words_from_user(prompt))
_salt_len,_sha256_len,_nonce_len = (32,32,32)
def mmgen_encrypt(data,desc='data',hash_preset=''):
salt = get_random(_salt_len)
iv = get_random(g.aesctr_iv_len)
nonce = get_random(_nonce_len)
hp = hash_preset or (
opt.hash_preset if 'hash_preset' in opt.set_by_user else get_hash_preset_from_user('3',desc))
hp = hash_preset or opt.hash_preset or get_hash_preset_from_user('3',desc)
m = ('user-requested','default')[hp=='3']
vmsg(f'Encrypting {desc}')
qmsg(f'Using {m} hash preset of {hp!r}')
@ -238,8 +268,7 @@ def mmgen_decrypt(data,desc='data',hash_preset=''):
salt = data[:_salt_len]
iv = data[_salt_len:dstart]
enc_d = data[dstart:]
hp = hash_preset or (
opt.hash_preset if 'hash_preset' in opt.set_by_user else get_hash_preset_from_user('3',desc))
hp = hash_preset or opt.hash_preset or get_hash_preset_from_user('3',desc)
m = ('user-requested','default')[hp=='3']
qmsg(f'Using {m} hash preset of {hp!r}')
passwd = get_passphrase(desc)

View file

@ -25,12 +25,14 @@ from decimal import Decimal
from collections import namedtuple
from .devtools import *
from .base_obj import Lockable
def die(exit_val,s=''):
if s:
sys.stderr.write(s+'\n')
sys.exit(exit_val)
class GlobalContext:
class GlobalContext(Lockable):
"""
Set global vars to default values
Globals are overridden in this order:
@ -38,6 +40,10 @@ class GlobalContext:
2 - environmental vars
3 - command line
"""
_set_ok = ('user_entropy','session')
_reset_ok = ('stdout','stderr','accept_defaults')
_use_class_attr = True
# Constants:
version = '0.12.099'
release_date = 'May 2020'
@ -63,12 +69,12 @@ class GlobalContext:
# Variables - these might be altered at runtime:
user_entropy = b''
hash_preset = '3'
dfl_hash_preset = '3'
dfl_seed_len = 256
usr_randchars = 30
tx_fee_adj = Decimal('1.0')
tx_confs = 3
seed_len = 256
# Constant vars - some of these might be overridden in opts.py, but they don't change thereafter
@ -97,7 +103,8 @@ class GlobalContext:
monero_wallet_rpc_password = ''
rpc_fail_on_command = ''
aiohttp_rpc_queue_len = 16
use_cached_balances = False
session = None
cached_balances = False
# regtest:
bob = False
@ -141,11 +148,12 @@ class GlobalContext:
daemon_data_dir = '' # set by user
# global var sets user opt:
global_sets_opt = ( 'minconf','seed_len','hash_preset','usr_randchars','debug',
'quiet','tx_confs','tx_fee_adj','key_generator' )
global_sets_opt = (
'minconf','usr_randchars','debug', 'quiet','tx_confs','tx_fee_adj','key_generator' )
# user opt sets global var:
opt_sets_global = ( 'use_internal_keccak_module','subseeds' )
opt_sets_global = (
'use_internal_keccak_module','subseeds','cached_balances' )
# 'long' opts - opt sets global var
common_opts = (
@ -160,7 +168,7 @@ class GlobalContext:
'quiet','verbose','debug','outdir','echo_passphrase','passwd_file','stdout',
'show_hash_presets','label','keep_passphrase','keep_hash_preset','yes',
'brain_params','b16','usr_randchars','coin','bob','alice','key_generator',
'hidden_incog_input_params','in_fmt'
'hidden_incog_input_params','in_fmt','hash_preset','seed_len',
)
incompatible_opts = (
('help','longhelp'),
@ -229,6 +237,10 @@ class GlobalContext:
if platform == 'win':
autoset_opts['rpc_backend'].choices.remove('aiohttp')
auto_typeset_opts = {
'seed_len': int,
}
min_screen_width = 80
minconf = 1
max_tx_file_size = 100000
@ -271,6 +283,9 @@ class GlobalContext:
short_disp_timeout = 0.1
if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):
stdin_tty = True
if prog_name == 'unit_tests.py':
_set_ok += ('debug_subseed',)
_reset_ok += ('force_standalone_scrypt_module','session')
if os.getenv('MMGEN_DEBUG_ALL'):
for name in env_opts:

View file

@ -65,9 +65,9 @@ opts_data = {
Options: {kgs} (default: {kg})
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths
with non-standard (< {g.dfl_seed_len}-bit) seed lengths
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-z, --show-hash-presets Show information on available hash presets
-P, --passwd-file= f Get wallet passphrase from file 'f'
-q, --quiet Produce quieter output; suppress some warnings

View file

@ -31,6 +31,8 @@ wallet_dir = '/dev/shm/autosign'
key_fn = 'autosign.key'
from .common import *
opts.UserOpts._set_ok += ('outdir','passwd_file')
prog_name = os.path.basename(sys.argv[0])
opts_data = {
'sets': [('stealth_led', True, 'led', True)],
@ -107,11 +109,22 @@ This command is currently available only on Linux-based platforms.
}
}
cmd_args = opts.init(opts_data,add_opts=['mmgen_keys_from_file','in_fmt'])
cmd_args = opts.init(
opts_data,
add_opts = ['mmgen_keys_from_file','hidden_incog_input_params'],
init_opts = {
'quiet': True,
'in_fmt': 'words',
'out_fmt': 'wallet',
'usr_randchars': 0,
'hash_preset': '1',
'label': 'Autosign Wallet',
})
exit_if_mswin('autosigning')
import mmgen.tx
from .wallet import Wallet
from .txsign import txsign
from .protocol import init_proto
from .rpc import rpc_init
@ -123,6 +136,7 @@ if opt.mountpoint:
mountpoint = opt.mountpoint
opt.outdir = tx_dir = os.path.join(mountpoint,'tx')
opt.passwd_file = os.path.join(tx_dir,key_fn)
async def check_daemons_running():
if opt.coin:
@ -220,15 +234,11 @@ async def sign():
return True
def decrypt_wallets():
opt.hash_preset = '1'
opt.set_by_user = ['hash_preset']
opt.passwd_file = os.path.join(tx_dir,key_fn)
from .wallet import Wallet
msg(f'Unlocking wallet{suf(wfs)} with key from {opt.passwd_file!r}')
fails = 0
for wf in wfs:
try:
Wallet(wf)
Wallet(wf,ignore_in_fmt=True)
except SystemExit as e:
if e.code != 0:
fails += 1
@ -335,18 +345,7 @@ def create_wallet_dir():
def setup():
remove_wallet_dir()
gen_key(no_unmount=True)
from .wallet import Wallet
opt.hidden_incog_input_params = None
opt.quiet = True
opt.in_fmt = 'words'
ss_in = Wallet()
opt.out_fmt = 'wallet'
opt.usr_randchars = 0
opt.hash_preset = '1'
opt.set_by_user = ['hash_preset']
opt.passwd_file = os.path.join(tx_dir,key_fn)
from .obj import MMGenWalletLabel
opt.label = MMGenWalletLabel('Autosign Wallet')
ss_out = Wallet(ss=ss_in)
ss_out.write_to_file(desc='autosign wallet',outdir=wallet_dir)

View file

@ -54,9 +54,9 @@ opts_data = {
generate passwords of half the default length.
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths
with non-standard (< {g.dfl_seed_len}-bit) seed lengths
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-z, --show-hash-presets Show information on available hash presets
-P, --passwd-file= f Get wallet passphrase from file 'f'
-q, --quiet Produce quieter output; suppress some warnings

View file

@ -48,7 +48,7 @@ opts_data = {
-L, --label= l Specify a label 'l' for output wallet
-M, --master-share=i Use a master share with index 'i' (min:{ms_min}, max:{ms_max})
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-z, --show-hash-presets Show information on available hash presets
-P, --passwd-file= f Get wallet passphrase from file 'f'
-q, --quiet Produce quieter output; suppress some warnings
@ -110,9 +110,6 @@ cmd_args = opts.init(opts_data)
if len(cmd_args) + bool(opt.hidden_incog_input_params) < 2:
opts.usage()
if opt.label:
opt.label = MMGenWalletLabel(opt.label,msg="Error in option '--label'")
if opt.master_share:
master_idx = MasterShareIdx(opt.master_share)
id_str = SeedSplitIDString(opt.id_str or 'default')

View file

@ -63,7 +63,7 @@ opts_data = {
--, --longhelp Print help message for long options (common options)
-k, --use-internal-keccak-module Force use of the internal keccak module
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-P, --passwd-file= f Get passphrase from file 'f'.
-q, --quiet Produce quieter output
-r, --usr-randchars=n Get 'n' characters of additional randomness from
@ -91,8 +91,6 @@ Type '{pn} help <command>' for help on a particular command
cmd_args = opts.init(opts_data,add_opts=['hidden_incog_input_params','in_fmt','use_old_ed25519'])
g.use_cached_balances = opt.cached_balances
if len(cmd_args) < 1:
opts.usage()

View file

@ -49,7 +49,7 @@ opts_data = {
-i, --in-fmt= f Input is from wallet format 'f' (see FMT CODES below)
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths.
with non-standard (< {g.dfl_seed_len}-bit) seed lengths.
-k, --keys-from-file=f Provide additional keys for non-{pnm} addresses
-K, --key-generator= m Use method 'm' for public key generation
Options: {kgs}
@ -63,7 +63,7 @@ opts_data = {
for the transaction's change output, if present)
-O, --old-incog-fmt Specify old-format incognito input
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-P, --passwd-file= f Get {pnm} wallet or {dn} passphrase from file 'f'
-q, --quiet Suppress warnings; overwrite files without prompting
-s, --send Sign and send the transaction (the default if seed

View file

@ -76,8 +76,6 @@ opts_data = {
cmd_args = opts.init(opts_data)
g.use_cached_balances = opt.cached_balances
async def main():
from .protocol import init_proto_from_opts

View file

@ -56,7 +56,7 @@ opts_data = {
outputs associated with each address will be included.
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths.
with non-standard (< {g.dfl_seed_len}-bit) seed lengths.
-k, --keys-from-file=f Provide additional keys for non-{pnm} addresses
-K, --key-generator= m Use method 'm' for public key generation
Options: {kgs}
@ -71,7 +71,7 @@ opts_data = {
mappings, so the user should record its checksum.
-O, --old-incog-fmt Specify old-format incognito input
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-P, --passwd-file= f Get {pnm} wallet passphrase from file 'f'
-r, --rbf Make transaction BIP 125 (replace-by-fee) replaceable
-q, --quiet Suppress warnings; overwrite files without prompting
@ -114,8 +114,6 @@ column below:
cmd_args = opts.init(opts_data)
g.use_cached_balances = opt.cached_balances
from .tx import *
from .txsign import *

View file

@ -45,9 +45,9 @@ opts_data = {
-O, --old-incog-fmt Specify old-format incognito input
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths.
with non-standard (< {g.dfl_seed_len}-bit) seed lengths.
-p, --hash-preset=p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-z, --show-hash-presets Show information on available hash presets
-k, --keys-from-file=f Provide additional keys for non-{pnm} addresses
-K, --key-generator=m Use method 'm' for public key generation

View file

@ -101,12 +101,12 @@ opts_data = {
-K, --keep-hash-preset Reuse hash preset of input wallet for output wallet
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
is required only for brainwallet and incognito inputs
with non-standard (< {g.seed_len}-bit) seed lengths.
with non-standard (< {g.dfl_seed_len}-bit) seed lengths.
-L, --label= l Specify a label 'l' for output wallet
-m, --keep-label Reuse label of input wallet for output wallet
-M, --master-share=i Use a master share with index 'i' (min:{ms_min}, max:{ms_max})
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
for password hashing (default: '{g.hash_preset}')
for password hashing (default: '{g.dfl_hash_preset}')
-z, --show-hash-presets Show information on available hash presets
-P, --passwd-file= f Get wallet passphrase from file 'f'
-q, --quiet Produce quieter output; suppress some warnings
@ -144,9 +144,6 @@ FMT CODES:
cmd_args = opts.init(opts_data,opt_filter=opt_filter)
if opt.label:
opt.label = MMGenWalletLabel(opt.label,msg="Error in option '--label'")
if invoked_as == 'subgen':
from .obj import SubSeedIdx
ss_idx = SubSeedIdx(cmd_args.pop())

View file

@ -21,13 +21,17 @@ opts.py: MMGen-specific options processing after generic processing by share.Op
"""
import sys,os,stat
class opt_cls(object):
pass
opt = opt_cls()
from .exception import UserOptError
from .globalvars import g
from .base_obj import Lockable
import mmgen.share.Opts
class UserOpts(Lockable):
_set_ok = ('usr_randchars',)
_reset_ok = ('quiet','verbose','yes')
opt = UserOpts()
from .util import *
def usage():
@ -228,7 +232,7 @@ opts_data_dfl = {
}
}
def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
def init(opts_data=None,add_opts=None,init_opts=None,opt_filter=None,parse_only=False):
if opts_data is None:
opts_data = opts_data_dfl
@ -238,6 +242,11 @@ def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
# po: (user_opts,cmd_args,opts,skipped_opts)
po = mmgen.share.Opts.parse_opts(opts_data,opt_filter=opt_filter,parse_only=parse_only)
if init_opts: # allow programs to preload user opts
for uopt,val in init_opts.items():
if uopt not in po.user_opts:
po.user_opts[uopt] = val
if parse_only:
return po
@ -248,7 +257,8 @@ def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
for o in set(
po.opts
+ po.skipped_opts
+ tuple(add_opts)
+ tuple(add_opts or [])
+ tuple(init_opts or [])
+ g.required_opts
+ g.common_opts ):
setattr(opt,o,po.user_opts[o] if o in po.user_opts else None)
@ -309,11 +319,9 @@ def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
# Set user opts from globals:
# - if opt is unset, set it to global value
# - if opt is set, convert its type to that of global value
opt.set_by_user = []
for k in g.global_sets_opt:
if hasattr(opt,k) and getattr(opt,k) != None:
setattr(opt,k,set_for_type(getattr(opt,k),getattr(g,k),'--'+k))
opt.set_by_user.append(k)
else:
setattr(opt,k,getattr(g,k))
@ -355,6 +363,8 @@ def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
# Check all opts against g.autoset_opts, setting if unset
check_and_set_autoset_opts()
set_auto_typeset_opts()
if opt.verbose:
opt.quiet = None
@ -370,6 +380,9 @@ def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
if k in opts_data:
del opts_data[k]
g.lock()
opt.lock()
return po.cmd_args
# DISABLED
@ -575,6 +588,13 @@ def check_usr_opts(usr_opts): # Raises an exception if any check fails
elif g.debug:
Msg('check_usr_opts(): No test for opt {!r}'.format(key))
def set_auto_typeset_opts():
for key,ref_type in g.auto_typeset_opts.items():
if hasattr(opt,key):
val = getattr(opt,key)
if val is not None: # typeset only if opt is set
setattr(opt,key,ref_type(val))
def check_and_set_autoset_opts(): # Raises exception if any check fails
def nocase_str(key,val,asd):

View file

@ -554,7 +554,6 @@ def init_proto(coin=None,testnet=False,regtest=False,network=None,network_id=Non
tokensym = tokensym )
def init_proto_from_opts():
from .opts import opt
return init_proto(
coin = g.coin,
testnet = g.testnet,

View file

@ -32,7 +32,7 @@ class SeedBase(MMGenObject):
def __init__(self,seed_bin=None):
if not seed_bin:
# Truncate random data for smaller seed lengths
seed_bin = sha256(get_random(1033)).digest()[:opt.seed_len//8]
seed_bin = sha256(get_random(1033)).digest()[:(opt.seed_len or g.dfl_seed_len)//8]
elif len(seed_bin)*8 not in g.seed_lens:
die(3,'{}: invalid seed length'.format(len(seed_bin)))
@ -58,6 +58,7 @@ class SeedBase(MMGenObject):
class SubSeedList(MMGenObject):
have_short = True
nonce_start = 0
debug_last_share_sid_len = 3
def __init__(self,parent_seed):
self.member_type = SubSeed
@ -134,7 +135,7 @@ class SubSeedList(MMGenObject):
m2 = 'collision with parent Seed ID {},'.format(sid)
else:
if debug_last_share:
sl = g.debug_last_share_sid_len
sl = self.debug_last_share_sid_len
colliding_idx = [d[:sl] for d in self.data[slen].keys].index(sid[:sl]) + 1
sid = sid[:sl]
else:
@ -285,7 +286,7 @@ class SeedShareList(SubSeedList):
def last_share_debug(last_share):
if not debug_last_share:
return False
sid_len = g.debug_last_share_sid_len
sid_len = self.debug_last_share_sid_len
lsid = last_share.sid[:sid_len]
psid = parent_seed.sid[:sid_len]
ssids = [d[:sid_len] for d in self.data['long'].keys]

View file

@ -269,9 +269,10 @@ class MMGenToolCmdMeta(type):
class MMGenToolCmds(metaclass=MMGenToolCmdMeta):
def __init__(self,proto=None):
def __init__(self,proto=None,mmtype=None):
from .protocol import init_proto_from_opts
self.proto = proto or init_proto_from_opts()
self.mmtype = mmtype or getattr(opt,'type',None) or self.proto.dfl_mmtype
if g.token:
self.proto.tokensym = g.token.upper()
@ -279,7 +280,7 @@ class MMGenToolCmds(metaclass=MMGenToolCmdMeta):
global at,kg,ag
at = MMGenAddrType(
proto = self.proto,
id_str = getattr(opt,'type',None) or self.proto.dfl_mmtype )
id_str = self.mmtype )
if arg != 'at':
kg = KeyGenerator(self.proto,at)
ag = AddrGenerator(self.proto,at)
@ -460,7 +461,7 @@ class MMGenToolCmdCoin(MMGenToolCmds):
def wif2redeem_script(self,wifkey:'sstr'): # new
"convert a WIF private key to a Segwit P2SH-P2WPKH redeem script"
assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
assert self.mmtype == 'segwit','This command is meaningful only for --type=segwit'
self.init_generators()
privhex = PrivKey(
self.proto,
@ -469,7 +470,7 @@ class MMGenToolCmdCoin(MMGenToolCmds):
def wif2segwit_pair(self,wifkey:'sstr'):
"generate both a Segwit P2SH-P2WPKH redeem script and address from WIF"
assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
assert self.mmtype == 'segwit','This command is meaningful only for --type=segwit'
self.init_generators()
pubhex = kg.to_pubhex(PrivKey(
self.proto,
@ -495,26 +496,26 @@ class MMGenToolCmdCoin(MMGenToolCmds):
def pubhex2addr(self,pubkeyhex:'sstr'):
"convert a hex pubkey to an address"
if opt.type == 'segwit':
if self.mmtype == 'segwit':
return self.proto.pubhex2segwitaddr(pubkeyhex)
else:
return self.pubhash2addr(hash160(pubkeyhex))
def pubhex2redeem_script(self,pubkeyhex:'sstr'): # new
"convert a hex pubkey to a Segwit P2SH-P2WPKH redeem script"
assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
assert self.mmtype == 'segwit','This command is meaningful only for --type=segwit'
return self.proto.pubhex2redeem_script(pubkeyhex)
def redeem_script2addr(self,redeem_scripthex:'sstr'): # new
"convert a Segwit P2SH-P2WPKH redeem script to an address"
assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
assert self.mmtype == 'segwit','This command is meaningful only for --type=segwit'
assert redeem_scripthex[:4] == '0014','{!r}: invalid redeem script'.format(redeem_scripthex)
assert len(redeem_scripthex) == 44,'{} bytes: invalid redeem script length'.format(len(redeem_scripthex)//2)
return self.pubhash2addr(hash160(redeem_scripthex))
def pubhash2addr(self,pubhashhex:'sstr'):
"convert public key hash to address"
if opt.type == 'bech32':
if self.mmtype == 'bech32':
return self.proto.pubhash2bech32addr(pubhashhex)
else:
self.init_generators('at')
@ -1108,7 +1109,7 @@ class MMGenToolCmdMonero(MMGenToolCmds):
return True
async def process_wallets(op):
opt.accept_defaults = opt.accept_defaults or op.accept_defaults
g.accept_defaults = g.accept_defaults or op.accept_defaults
from .protocol import init_proto
proto = init_proto('xmr',network='mainnet')
from .addr import AddrList
@ -1223,8 +1224,7 @@ class tool_api(
super().__init__()
if not hasattr(opt,'version'):
opts.init()
opt.use_old_ed25519 = None
opt.type = None
self.mmtype = self.proto.dfl_mmtype
def init_coin(self,coinsym,network):
"""
@ -1277,11 +1277,11 @@ class tool_api(
@property
def addrtype(self):
"""The currently configured address type (is assignable)"""
return opt.type
return self.mmtype
@addrtype.setter
def addrtype(self,val):
opt.type = val
self.mmtype = val
@property
def usr_randchars(self):

View file

@ -801,7 +801,7 @@ class TrackingWallet(MMGenObject,metaclass=aInitMeta):
def get_cached_balance(self,addr,session_cache,data_root):
if addr in session_cache:
return self.proto.coin_amt(session_cache[addr])
if not g.use_cached_balances:
if not g.cached_balances:
return None
if addr in data_root and 'balance' in data_root[addr]:
return self.proto.coin_amt(data_root[addr]['balance'])

View file

@ -505,27 +505,6 @@ def get_seed_file(cmd_args,nargs,invoked_as=None):
return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
def get_new_passphrase(desc,passchg=False):
w = '{}passphrase for {}'.format(('','new ')[bool(passchg)], desc)
if opt.passwd_file:
pw = ' '.join(get_words_from_file(opt.passwd_file,w))
elif opt.echo_passphrase:
pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
else:
for i in range(g.passwd_max_tries):
pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
pw2 = ' '.join(get_words_from_user('Repeat passphrase: '))
dmsg('Passphrases: [{}] [{}]'.format(pw,pw2))
if pw == pw2:
vmsg('Passphrases match'); break
else: msg('Passphrases do not match. Try again.')
else:
die(2,'User failed to duplicate passphrase in {} attempts'.format(g.passwd_max_tries))
if pw == '': qmsg('WARNING: Empty passphrase')
return pw
def confirm_or_raise(message,q,expect='YES',exit_msg='Exiting at user request'):
m = message.strip()
if m: msg(m)
@ -701,20 +680,14 @@ def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False,q
return data
def pwfile_reuse_warning():
if 'passwd_file_used' in globals():
qmsg("Reusing passphrase from file '{}' at user request".format(opt.passwd_file))
return True
globals()['passwd_file_used'] = True
return False
passwd_files_used = {}
def get_mmgen_passphrase(desc,passchg=False):
prompt ='Enter {}passphrase for {}: '.format(('','old ')[bool(passchg)],desc)
if opt.passwd_file:
pwfile_reuse_warning()
return ' '.join(get_words_from_file(opt.passwd_file,'passphrase'))
else:
return ' '.join(get_words_from_user(prompt))
def pwfile_reuse_warning(passwd_file):
if passwd_file in passwd_files_used:
qmsg(f'Reusing passphrase from file {passwd_file!r} at user request')
return True
passwd_files_used[passwd_file] = True
return False
def my_raw_input(prompt,echo=True,insert_txt='',use_readline=True):
@ -760,7 +733,7 @@ def keypress_confirm(prompt,default_yes=False,verbose=False,no_nl=False,complete
p = prompt if complete_prompt else '{} {}: '.format(prompt,q)
nl = ('\n','\r{}\r'.format(' '*len(p)))[no_nl]
if opt.accept_defaults:
if g.accept_defaults:
msg(p)
return default_yes

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