f-strings, whitespace (program files) [43 files patched]

This commit is contained in:
The MMGen Project 2021-09-29 21:17:56 +00:00
commit 2872d4b683
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
43 changed files with 614 additions and 525 deletions

View file

@ -347,7 +347,11 @@ class AddrListIDStr(str,Hilite):
else:
bc = (addrlist.proto.base_coin,addrlist.proto.coin)[addrlist.proto.base_coin=='ETH']
mt = addrlist.al_id.mmtype
ret = '{}{}{}[{}]'.format(addrlist.al_id.sid,('-'+bc,'')[bc=='BTC'],('-'+mt,'')[mt in ('L','E')],s)
ret = '{}{}{}[{}]'.format(
addrlist.al_id.sid,
('-'+bc,'')[bc == 'BTC'],
('-'+mt,'')[mt in ('L','E')],
s )
dmsg_sc('id_str',ret[8:].split('[')[0])
@ -355,7 +359,7 @@ class AddrListIDStr(str,Hilite):
class AddrList(MMGenObject): # Address info for a single seed ID
msgs = {
'file_header': """
'file_header': """
# {pnm} address file
#
# This file is editable.
@ -364,13 +368,13 @@ class AddrList(MMGenObject): # Address info for a single seed ID
# address, and it will be appended to the tracking wallet label upon import.
# The label may contain any printable ASCII symbol.
""".strip().format(n=TwComment.max_screen_width,pnm=pnm),
'record_chksum': """
'record_chksum': """
Record this checksum: it will be used to verify the address file in the future
""".strip(),
'check_chksum': 'Check this value against your records',
'removed_dup_keys': """
'check_chksum': 'Check this value against your records',
'removed_dup_keys': f"""
Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
""".strip().format(pnm=pnm)
""".strip(),
}
entry_type = AddrListEntry
main_attr = 'addr'
@ -431,7 +435,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
elif al_id or adata:
die(3,'Must specify both al_id and adata')
else:
die(3,'Incorrect arguments for {}'.format(type(self).__name__))
die(3,f'Incorrect arguments for {type(self).__name__}')
# al_id,adata now set
self.data = adata
@ -446,8 +450,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
if do_chksum:
self.chksum = AddrListChksum(self)
qmsg('Checksum for {} data {}: {}'.format(
self.data_desc,self.id_str.hl(),self.chksum.hl()))
qmsg(f'Checksum for {self.data_desc} data {self.id_str.hl()}: {self.chksum.hl()}')
qmsg(self.msgs[('check_chksum','record_chksum')[src=='gen']])
def update_msgs(self):
@ -482,7 +485,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
pos += 1
if not g.debug:
qmsg_r('\rGenerating {} #{} ({} of {})'.format(self.gen_desc,num,pos,t_addrs))
qmsg_r(f'\rGenerating {self.gen_desc} #{num} ({pos} of {t_addrs})')
e = le(proto=self.proto,idx=num)
@ -503,14 +506,19 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
if type(self) == PasswordList:
e.passwd = str(self.make_passwd(e.sec)) # TODO - own type
dmsg('Key {:>03}: {}'.format(pos,e.passwd))
dmsg(f'Key {pos:>03}: {e.passwd}')
out.append(e)
if g.debug_addrlist:
Msg('generate():\n{}'.format(e.pfmt()))
Msg(f'generate():\n{e.pfmt()}')
qmsg('\r{}: {} {}{} generated{}'.format(
self.al_id.hl(),t_addrs,self.gen_desc,suf(t_addrs,self.gen_desc_pl),' '*15))
self.al_id.hl(),
t_addrs,
self.gen_desc,
suf(t_addrs,self.gen_desc_pl),
' ' * 15 ))
return out
def check_format(self,addr):
@ -546,7 +554,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
return [e.idx for e in self.data]
def addrs(self):
return ['{}:{}'.format(self.al_id.sid,e.idx) for e in self.data]
return [f'{self.al_id.sid}:{e.idx}' for e in self.data]
def addrpairs(self):
return [(e.idx,e.addr) for e in self.data]
@ -612,11 +620,11 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
ag = AddrGenerator(self.proto,at)
d = self.data
for n,e in enumerate(d,1):
qmsg_r('\rGenerating addresses from keylist: {}/{}'.format(n,len(d)))
qmsg_r(f'\rGenerating addresses from keylist: {n}/{len(d)}')
e.addr = ag.to_addr(kg.to_pubhex(e.sec))
if g.debug_addrlist:
Msg('generate_addrs_from_keys():\n{}'.format(e.pfmt()))
qmsg('\rGenerated addresses from keylist: {}/{} '.format(n,len(d)))
Msg(f'generate_addrs_from_keys():\n{e.pfmt()}')
qmsg(f'\rGenerated addresses from keylist: {n}/{len(d)} ')
def make_label(self):
bc,mt = self.proto.base_coin,self.al_id.mmtype
@ -630,30 +638,29 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
out = [self.msgs['file_header']+'\n']
if self.chksum:
out.append('# {} data checksum for {}: {}'.format(
capfirst(self.data_desc),self.id_str,self.chksum))
out.append(f'# {capfirst(self.data_desc)} data checksum for {self.id_str}: {self.chksum}')
out.append('# Record this value to a secure location.\n')
lbl = self.make_label()
dmsg_sc('lbl',lbl[9:])
out.append('{} {{'.format(lbl))
out.append(f'{lbl} {{')
fs = ' {:<%s} {:<34}{}' % len(str(self.data[-1].idx))
for e in self.data:
c = ' '+e.label if add_comments and e.label else ''
if type(self) == KeyList:
out.append(fs.format(e.idx,'{}: {}'.format(self.al_id.mmtype.wif_label,e.sec.wif),c))
out.append(fs.format( e.idx, f'{self.al_id.mmtype.wif_label}: {e.sec.wif}', c ))
elif type(self) == PasswordList:
out.append(fs.format(e.idx,e.passwd,c))
else: # First line with idx
out.append(fs.format(e.idx,e.addr,c))
if self.has_keys:
if opt.b16:
out.append(fs.format('', 'orig_hex: '+e.sec.orig_hex,c))
out.append(fs.format('','{}: {}'.format(self.al_id.mmtype.wif_label,e.sec.wif),c))
out.append(fs.format( '', f'orig_hex: {e.sec.orig_hex}', c ))
out.append(fs.format( '', f'{self.al_id.mmtype.wif_label}: {e.sec.wif}', c ))
for k in ('viewkey','wallet_passwd'):
v = getattr(e,k)
if v: out.append(fs.format('','{}: {}'.format(k,v),c))
if v: out.append(fs.format( '', f'{k}: {v}', c ))
out.append('}')
self.fmt_data = '\n'.join([l.rstrip() for l in out]) + '\n'
@ -682,14 +689,14 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
if self.has_keys: # order: wif,(orig_hex),viewkey,wallet_passwd
d = self.get_line(lines)
assert d[0] == self.al_id.mmtype.wif_label+':',iifs.format(d[0],self.al_id.mmtype.wif_label)
assert d[0] == self.al_id.mmtype.wif_label+':', iifs.format(d[0],self.al_id.mmtype.wif_label)
a.sec = PrivKey(proto=self.proto,wif=d[1])
for k,dtype,add_proto in (
('viewkey',ViewKey,True),
('wallet_passwd',WalletPassword,False) ):
if k in self.al_id.mmtype.extra_attrs:
d = self.get_line(lines)
assert d[0] == k+':',iifs.format(d[0],k)
assert d[0] == k+':', iifs.format(d[0],k)
setattr(a,k,dtype( *((self.proto,d[1]) if add_proto else (d[1],)) ) )
ret.append(a)
@ -700,9 +707,9 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
ag = AddrGenerator(self.proto,self.al_id.mmtype)
llen = len(ret)
for n,e in enumerate(ret):
qmsg_r('\rVerifying keys {}/{}'.format(n+1,llen))
qmsg_r(f'\rVerifying keys {n+1}/{llen}')
assert e.addr == ag.to_addr(kg.to_pubhex(e.sec)),(
"Key doesn't match address!\n {}\n {}".format(e.sec.wif,e.addr))
f'Key doesn’t match address!\n {e.sec.wif}\n {e.addr}')
qmsg(' - done')
return ret
@ -934,9 +941,9 @@ Record this checksum: it will be used to verify the password file in the future
self.fmt_data = ''
self.chksum = AddrListChksum(self)
fs = '{}-{}-{}-{}[{{}}]'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt_disp,self.pw_len)
fs = f'{self.al_id.sid}-{self.pw_id_str}-{self.pw_fmt_disp}-{self.pw_len}[{{}}]'
self.id_str = AddrListIDStr(self,fs)
qmsg('Checksum for {} data {}: {}'.format(self.data_desc,self.id_str.hl(),self.chksum.hl()))
qmsg(f'Checksum for {self.data_desc} data {self.id_str.hl()}: {self.chksum.hl()}')
qmsg(self.msgs[('record_chksum','check_chksum')[bool(infile)]])
def set_pw_fmt(self,pw_fmt):
@ -964,11 +971,11 @@ Record this checksum: it will be used to verify the password file in the future
d = self.pw_info[self.pw_fmt]
if d.valid_lens:
if pw_len not in d.valid_lens:
die(2,fs.format(l=pw_len,b=d.desc,c='not one of ',m=d.valid_lens,pw=passwd))
die(2, fs.format( l=pw_len, b=d.desc, c='not one of ', m=d.valid_lens, pw=passwd ))
elif pw_len > d.max_len:
die(2,fs.format(l=pw_len,b=d.desc,c='>',m=d.max_len,pw=passwd))
die(2, fs.format( l=pw_len, b=d.desc, c='>', m=d.max_len, pw=passwd ))
elif pw_len < d.min_len:
die(2,fs.format(l=pw_len,b=d.desc,c='<',m=d.min_len,pw=passwd))
die(2, fs.format( l=pw_len, b=d.desc, c='<', m=d.min_len, pw=passwd ))
def set_pw_len(self,pw_len):
d = self.pw_info[self.pw_fmt]
@ -978,7 +985,7 @@ Record this checksum: it will be used to verify the password file in the future
return
if not is_int(pw_len):
die(2,"'{}': invalid user-requested password length (not an integer)".format(pw_len,d.desc))
die(2,f'{pw_len!r}: invalid user-requested password length (not an integer)')
self.pw_len = int(pw_len)
self.chk_pw_len()
@ -996,24 +1003,27 @@ Record this checksum: it will be used to verify the password file in the future
try:
good_pw_len = baseconv.seedlen_map['xmrseed'][seed.byte_len]
except:
die(1,'{}: unsupported seed length for Monero new-style mnemonic'.format(seed.byte_len*8))
die(1,f'{seed.byte_len*8}: unsupported seed length for Monero new-style mnemonic')
elif pf in ('b32','b58'):
pw_int = (32 if pf == 'b32' else 58) ** self.pw_len
pw_bytes = pw_int.bit_length() // 8
good_pw_len = len(baseconv.frombytes(b'\xff'*seed.byte_len,wl_id=pf))
else:
raise NotImplementedError('{!r}: unknown password format'.format(pf))
raise NotImplementedError(f'{pf!r}: unknown password format')
if pw_bytes > seed.byte_len:
m1 = 'Cannot generate passwords with more entropy than underlying seed! ({} bits)'
m2 = ( 'Re-run the command with --passwd-len={}' if pf in ('bip39','hex') else
'Re-run the command, specifying a password length of {} or less' )
die(1,(m1+'\n'+m2).format(len(seed.data) * 8,good_pw_len))
die(1,
'Cannot generate passwords with more entropy than underlying seed! ({} bits)\n'.format(
len(seed.data) * 8 ) + (
'Re-run the command with --passwd-len={}' if pf in ('bip39','hex') else
'Re-run the command, specifying a password length of {} or less'
).format(good_pw_len) )
if pf in ('bip39','hex') and pw_bytes < seed.byte_len:
m1 = 'WARNING: requested {} length has less entropy than underlying seed!'
m2 = 'Is this what you want?'
if not keypress_confirm((m1+'\n'+m2).format(self.pw_info[pf].desc),default_yes=True):
if not keypress_confirm(
f'WARNING: requested {self.pw_info[pf].desc} length has less entropy ' +
'than underlying seed!\nIs this what you want?',
default_yes = True ):
die(1,'Exiting at user request')
def make_passwd(self,hex_sec):
@ -1038,22 +1048,22 @@ Record this checksum: it will be used to verify the password file in the future
def check_format(self,pw):
if not self.pw_info[self.pw_fmt].chk_func(pw):
raise ValueError('Password is not valid {} data'.format(self.pw_info[self.pw_fmt].desc))
raise ValueError(f'Password is not valid {self.pw_info[self.pw_fmt].desc} data')
pwlen = len(pw.split()) if self.pw_fmt in ('bip39','xmrseed') else len(pw)
if pwlen != self.pw_len:
raise ValueError('Password has incorrect length ({} != {})'.format(pwlen,self.pw_len))
raise ValueError(f'Password has incorrect length ({pwlen} != {self.pw_len})')
return True
def scramble_seed(self,seed):
# Changing either pw_fmt or pw_len will cause a different, unrelated
# set of passwords to be generated: this is what we want.
# NB: In original implementation, pw_id_str was 'baseN', not 'bN'
scramble_key = '{}:{}:{}'.format(self.pw_fmt,self.pw_len,self.pw_id_str)
scramble_key = f'{self.pw_fmt}:{self.pw_len}:{self.pw_id_str}'
if self.hex2bip39:
from .bip39 import bip39
pwlen = bip39.nwords2seedlen(self.pw_len,in_hex=True)
scramble_key = '{}:{}:{}'.format('hex',pwlen,self.pw_id_str)
scramble_key = f'hex:{pwlen}:{self.pw_id_str}'
from .crypto import scramble_seed
dmsg_sc('str',scramble_key)
@ -1064,11 +1074,11 @@ Record this checksum: it will be used to verify the password file in the future
if self.pw_fmt in ('bip39','xmrseed'):
ret = lines.pop(0).split(None,self.pw_len+1)
if len(ret) > self.pw_len+1:
m1 = 'extraneous text {!r} found after password'.format(ret[self.pw_len+1])
m1 = f'extraneous text {ret[self.pw_len+1]!r} found after password'
m2 = '[bare comments not allowed in BIP39 password files]'
m = m1+' '+m2
elif len(ret) < self.pw_len+1:
m = 'invalid password length {}'.format(len(ret)-1)
m = f'invalid password length {len(ret)-1}'
else:
return (ret[0],' '.join(ret[1:self.pw_len+1]),'')
raise ValueError(m)
@ -1077,16 +1087,16 @@ Record this checksum: it will be used to verify the password file in the future
return ret if len(ret) == 3 else ret + ['']
def make_label(self):
return '{} {} {}:{}'.format(self.al_id.sid,self.pw_id_str,self.pw_fmt_disp,self.pw_len)
return f'{self.al_id.sid} {self.pw_id_str} {self.pw_fmt_disp}:{self.pw_len}'
class AddrData(MMGenObject):
msgs = {
'too_many_acct_addresses': """
'too_many_acct_addresses': f"""
ERROR: More than one address found for account: '{{}}'.
Your 'wallet.dat' file appears to have been altered by a non-{pnm} program.
Please restore your tracking wallet from a backup or create a new one and
re-import your addresses.
""".strip().format(pnm=pnm)
""".strip()
}
def __new__(cls,proto,*args,**kwargs):
@ -1121,7 +1131,7 @@ re-import your addresses.
self.al_ids[addrlist.al_id] = addrlist
return True
else:
raise TypeError('Error: object {!r} is not of type AddrList'.format(addrlist))
raise TypeError(f'Error: object {addrlist!r} is not of type AddrList')
def make_reverse_dict(self,coinaddrs):
d = MMGenDict()
@ -1169,6 +1179,6 @@ class TwAddrData(AddrData,metaclass=AsyncInit):
out[al_id].append(AddrListEntry(self.proto,idx=obj.idx,addr=addr_array[0],label=l.comment))
i += 1
vmsg('{n} {pnm} addresses found, {m} accounts total'.format(n=i,pnm=pnm,m=len(twd)))
vmsg(f'{i} {pnm} addresses found, {len(twd)} accounts total')
for al_id in out:
self.add(AddrList(self.proto,al_id=al_id,adata=AddrListData(sorted(out[al_id],key=lambda a: a.idx))))

View file

@ -36,7 +36,9 @@ altcoin.py - Coin constants for Bitcoin-derived altcoins
# NBT: 150/191 c/u, 25/('B'), 26/('B')
import sys
def msg(s): sys.stderr.write(s+'\n')
def msg(s):
sys.stderr.write(s+'\n')
def test_equal(desc,a,b,*cdata):
if type(a) == int:
@ -44,11 +46,16 @@ def test_equal(desc,a,b,*cdata):
b = hex(b)
(network,coin,e,b_desc,verbose) = cdata
if verbose:
m = ' {:20}: {!r}'
msg(m.format(desc,a))
msg(f' {desc:20}: {a!r}')
if a != b:
m = '{}s for {} {} do not match:\n CoinInfo: {}\n {}: {}'
raise ValueError(m.format(desc.capitalize(),coin.upper(),network,a,b_desc,b))
raise ValueError(
'{}s for {} {} do not match:\n CoinInfo: {}\n {}: {}'.format(
desc.capitalize(),
coin.upper(),
network,
a,
b_desc,
b ))
from collections import namedtuple
ce = namedtuple('CoinInfoEntry',
@ -415,7 +422,7 @@ class CoinInfo(object):
cdata = (network,coin,e,'Computed value',verbose)
if not quiet:
msg('{} {}'.format(coin,network))
msg(f'{coin} {network}')
vn_info = e.p2pkh_info
ret = cls.find_addr_leading_symbol(vn_info[0])
@ -437,7 +444,7 @@ class CoinInfo(object):
proto = init_proto(coin,testnet=network=='testnet')
cdata = (network,coin,e,type(proto).__name__,verbose)
if not quiet:
msg('Verifying {} {}'.format(coin.upper(),network))
msg(f'Verifying {coin.upper()} {network}')
if coin != 'bch': # TODO
test_equal('coin name',e.name,proto.name,*cdata)
@ -490,9 +497,9 @@ class CoinInfo(object):
e[k] = list(e[k])
e[k][0] = myhex(e[k][0])
s1 = cls.find_addr_leading_symbol(int(e[k][0][2:],16))
m = 'Fixing leading address letter for coin {} ({!r} --> {})'.format(e['symbol'],e[k][1],s1)
m = f'Fixing leading address letter for coin {e["symbol"]} ({e[k][1]!r} --> {s1})'
if e[k][1] != '?':
assert s1 == e[k][1],'First letters do not match! {}'.format(m)
assert s1 == e[k][1], f'First letters do not match! {m}'
else:
msg(m)
e[k][1] = s1
@ -501,7 +508,7 @@ class CoinInfo(object):
old_sym = None
for sym in sorted([e.symbol for e in data]):
if sym == old_sym:
msg("'{}': duplicate coin symbol in data!".format(sym))
msg(f'{sym!r}: duplicate coin symbol in data!')
sys.exit(2)
old_sym = sym
@ -528,20 +535,20 @@ class CoinInfo(object):
if sym in tt:
src = tt[sym]
if src != trust:
msg("Updating trust for coin '{}': {} -> {}".format(sym,trust,src))
msg(f'Updating trust for coin {sym!r}: {trust} -> {src}')
e['trust_level'] = src
else:
if trust != 0:
msg("Downgrading trust for coin '{}': {} -> {}".format(sym,trust,0))
msg(f'Downgrading trust for coin {sym!r}: {trust} -> 0')
e['trust_level'] = 0
if sym in cls.cross_checks:
if int(e['trust_level']) == 0 and len(cls.cross_checks[sym]) > 1:
msg("Upgrading trust for coin '{}': {} -> {}".format(sym,e['trust_level'],1))
msg(f'Upgrading trust for coin {sym!r}: {e["trust_level"]} -> 1')
e['trust_level'] = 1
print(fs.format(*e.values()))
msg('Processed {} entries'.format(len(data)))
msg(f'Processed {len(data)} entries')
@classmethod
def find_addr_leading_symbol(cls,ver_num,verbose=False):
@ -569,17 +576,17 @@ class CoinInfo(object):
def print_symbols(cls,include_names=False,reverse=False):
for e in cls.coin_constants['mainnet']:
if reverse:
print('{:6} {}'.format(e.symbol,e.name))
print(f'{e.symbol:6} {e.name}')
else:
name_w = max(len(e.name) for e in cls.coin_constants['mainnet'])
print(('{:{}} '.format(e.name,name_w) if include_names else '') + e.symbol)
print((f'{e.name:{name_w}} ' if include_names else '') + e.symbol)
@classmethod
def create_trust_table(cls):
tt = {}
mn = cls.external_tests['mainnet']
for ext_prog in mn:
assert len(set(mn[ext_prog])) == len(mn[ext_prog]),"Duplicate entry in '{}'!".format(ext_prog)
assert len(set(mn[ext_prog])) == len(mn[ext_prog]), f'Duplicate entry in {ext_prog!r}!'
for coin in mn[ext_prog]:
if coin in tt:
tt[coin] += 1
@ -609,8 +616,7 @@ class CoinInfo(object):
if verbose:
m1 = 'Requested tool {t!r} does not support coin {c} on network {n}'
m2 = 'No test tool found for coin {c} on network {n}'
m = m1 if tool_arg else m2
msg(m.format(t=tool,c=coin,n=network))
msg((m1 if tool_arg else m2).format(t=tool,c=coin,n=network))
return None
if addr_type == 'zcash_z':
@ -618,8 +624,7 @@ class CoinInfo(object):
return 'zcash-mini'
else:
if verbose:
m = "Address type {a!r} supported only by tool 'zcash-mini'"
msg(m.format(a=addr_type))
msg(f"Address type {addr_type!r} supported only by tool 'zcash-mini'")
return None
try:
@ -630,8 +635,7 @@ class CoinInfo(object):
pass
else:
if verbose:
m = 'Tool {t!r} blacklisted for coin {c}, addr_type {a!r}'
msg(m.format(t=tool,c=coin,a=addr_type))
msg(f'Tool {tool!r} blacklisted for coin {coin}, addr_type {addr_type!r}')
return None
if tool_arg: # skip whitelists
@ -645,8 +649,7 @@ class CoinInfo(object):
if verbose:
m1 = 'Requested tool {t!r} does not support coin {c}, addr_type {a!r}, on network {n}'
m2 = 'No test tool found supporting coin {c}, addr_type {a!r}, on network {n}'
m = m1 if tool_arg else m2
msg(m.format(t=tool,c=coin,n=network,a=addr_type))
msg((m1 if tool_arg else m2).format(t=tool,c=coin,n=network,a=addr_type))
return None
return tool

View file

@ -51,7 +51,9 @@ class TokenBase(MMGenObject): # ERC20
async def do_call(self,method_sig,method_args='',toUnit=False):
data = create_method_id(method_sig) + method_args
if g.debug:
msg('ETH_CALL {}: {}'.format(method_sig,'\n '.join(parse_abi(data))))
msg('ETH_CALL {}: {}'.format(
method_sig,
'\n '.join(parse_abi(data)) ))
ret = await self.rpc.call('eth_call',{ 'to': '0x'+self.addr, 'data': '0x'+data },'pending')
if self.proto.network == 'regtest' and g.daemon_id == 'erigon': # ERIGON
import asyncio
@ -79,19 +81,19 @@ class TokenBase(MMGenObject): # ERC20
assert ret[:2] == '0x'
return int(ret,16)
except:
msg("RPC call to decimals() failed (returned '{}')".format(ret))
msg(f'RPC call to decimals() failed (returned {ret!r})')
return None
async def get_total_supply(self):
return await self.do_call('totalSupply()',toUnit=True)
async def info(self):
fs = '{:15}{}\n' * 5
return fs.format('token address:', self.addr,
'token symbol:', await self.get_symbol(),
'token name:', await self.get_name(),
'decimals:', self.decimals,
'total supply:', await self.get_total_supply())
return ('{:15}{}\n' * 5).format(
'token address:', self.addr,
'token symbol:', await self.get_symbol(),
'token name:', await self.get_name(),
'decimals:', self.decimals,
'total supply:', await self.get_total_supply() )
async def code(self):
return (await self.rpc.call('eth_getCode','0x'+self.addr))[2:]
@ -99,7 +101,7 @@ class TokenBase(MMGenObject): # ERC20
def create_data(self,to_addr,amt,method_sig='transfer(address,uint256)',from_addr=None):
from_arg = from_addr.rjust(64,'0') if from_addr else ''
to_arg = to_addr.rjust(64,'0')
amt_arg = '{:064x}'.format(int(amt / self.base_unit))
amt_arg = '{:064x}'.format( int(amt / self.base_unit) )
return create_method_id(method_sig) + from_arg + to_arg + amt_arg
def make_tx_in( self,from_addr,to_addr,amt,start_gas,gasPrice,nonce,
@ -128,7 +130,8 @@ class TokenBase(MMGenObject): # ERC20
if g.debug:
msg('TOKEN DATA:')
pp_msg(tx.to_dict())
msg('PARSED ABI DATA:\n {}'.format('\n '.join(parse_abi(tx.data.hex()))))
msg('PARSED ABI DATA:\n {}'.format(
'\n '.join(parse_abi(tx.data.hex())) ))
return hex_tx,coin_txid
# The following are used for token deployment only:

View file

@ -43,7 +43,7 @@ class EthereumTrackingWallet(TrackingWallet):
upgraded = False
if not 'accounts' in self.data or not 'coin' in self.data:
ymsg('Upgrading {} (v1->v2: accounts field added)'.format(self.desc))
ymsg(f'Upgrading {self.desc} (v1->v2: accounts field added)')
if not 'accounts' in self.data:
self.data = {}
import json
@ -66,13 +66,13 @@ class EthereumTrackingWallet(TrackingWallet):
upgraded = True
if self.data['tokens'] and not have_token_params_fields():
ymsg('Upgrading {} (v2->v3: token params fields added)'.format(self.desc))
ymsg(f'Upgrading {self.desc} (v2->v3: token params fields added)')
add_token_params_fields()
upgraded = True
if upgraded:
self.force_write()
msg('{} upgraded successfully!'.format(self.desc))
msg(f'{self.desc} upgraded successfully!')
async def rpc_get_balance(self,addr):
return ETHAmt(int(await self.rpc.call('eth_getBalance','0x'+addr,'latest'),16),'wei')

View file

@ -46,7 +46,7 @@ class EthereumMMGenTX:
# given absolute fee in ETH, return gas price in Gwei using tx_gas
def fee_abs2rel(self,abs_fee,to_unit='Gwei'):
ret = ETHAmt(int(abs_fee.toWei() // self.tx_gas.toWei()),'wei')
dmsg('fee_abs2rel() ==> {} ETH'.format(ret))
dmsg(f'fee_abs2rel() ==> {ret} ETH')
return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
def get_hex_locktime(self):
@ -54,7 +54,7 @@ class EthereumMMGenTX:
# given rel fee (gasPrice) in wei, return absolute fee using tx_gas (not in MMGenTX)
def fee_gasPrice2abs(self,rel_fee):
assert isinstance(rel_fee,int),"'{}': incorrect type for fee estimate (not an integer)".format(rel_fee)
assert isinstance(rel_fee,int), f'{rel_fee!r}: incorrect type for fee estimate (not an integer)'
return ETHAmt(rel_fee * self.tx_gas.toWei(),'wei')
def is_replaceable(self):
@ -114,7 +114,7 @@ class EthereumMMGenTX:
assert len(self.inputs) == 1,'Transaction has more than one input!'
o_num = len(self.outputs)
o_ok = 0 if self.usr_contract_data else 1
assert o_num == o_ok,'Transaction has {} output{} (should have {})'.format(o_num,suf(o_num),o_ok)
assert o_num == o_ok, f'Transaction has {o_num} output{suf(o_num)} (should have {o_ok})'
await self.make_txobj()
odict = { k: str(v) for k,v in self.txobj.items() if k != 'token_to' }
self.hex = json.dumps(odict)
@ -147,7 +147,7 @@ class EthereumMMGenTX:
elif int(reply) < 1:
msg('Account number must be >= 1')
elif int(reply) > len(unspent):
msg('Account number must be <= {}'.format(len(unspent)))
msg(f'Account number must be <= {len(unspent)}')
else:
return [int(reply)]
@ -175,7 +175,7 @@ class EthereumMMGenTX:
def fee_est2abs(self,rel_fee,fe_type=None):
ret = self.fee_gasPrice2abs(rel_fee) * opt.tx_fee_adj
if opt.verbose:
msg('Estimated fee: {} ETH'.format(ret))
msg(f'Estimated fee: {ret} ETH')
return ret
def convert_and_check_fee(self,tx_fee,desc='Missing description'):
@ -183,8 +183,11 @@ class EthereumMMGenTX:
if abs_fee == False:
return False
elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
m = '{} {c}: {} fee too large (maximum fee: {} {c})'
msg(m.format(abs_fee.hl(),desc,self.proto.max_tx_fee.hl(),c=self.proto.coin))
msg('{} {c}: {} fee too large (maximum fee: {} {c})'.format(
abs_fee.hl(),
desc,
self.proto.max_tx_fee.hl(),
c = self.proto.coin ))
return False
else:
return abs_fee
@ -211,12 +214,12 @@ class EthereumMMGenTX:
raise UserAddressNotInWallet(m.format(i))
ret.append(i)
else:
die(1,"'{}': not an MMGen ID or coin address".format(i))
die(1,f'{i!r}: not an MMGen ID or coin address')
return ret
def final_inputs_ok_msg(self,funds_left):
chg = '0' if (self.outputs and self.outputs[0].is_chg) else funds_left
return "Transaction leaves {} {} in the sender's account".format(
return 'Transaction leaves {} {} in the sender’s account'.format(
ETHAmt(chg).hl(),
self.proto.coin
)
@ -426,10 +429,10 @@ class EthereumMMGenTX:
if self.txobj['data']:
cd = capfirst(self.contract_desc)
if r.exec_status == 0:
msg('{} failed to execute!'.format(cd))
msg(f'{cd} failed to execute!')
else:
msg('{} successfully executed with status {}'.format(cd,r.exec_status))
die(0,'Transaction has {} confirmation{}'.format(r.confs,suf(r.confs)))
msg(f'{cd} successfully executed with status {r.exec_status}')
die(0,f'Transaction has {r.confs} confirmation{suf(r.confs)}')
die(1,'Transaction is neither in mempool nor blockchain!')
async def send(self,prompt_user=True,exit_on_fail=False):
@ -458,7 +461,7 @@ class EthereumMMGenTX:
ret = False
if ret == False:
msg(red('Send of MMGen transaction {} failed'.format(self.txid)))
msg(red(f'Send of MMGen transaction {self.txid} failed'))
if exit_on_fail:
sys.exit(1)
return False
@ -553,9 +556,9 @@ class EthereumTokenMMGenTX:
def format_view_body(self,*args,**kwargs):
return 'Token: {d} {c}\n{r}'.format(
d=self.txobj['token_addr'].hl(),
c=blue('(' + self.proto.dcoin + ')'),
r=super().format_view_body(*args,**kwargs))
d = self.txobj['token_addr'].hl(),
c = blue('(' + self.proto.dcoin + ')'),
r = super().format_view_body(*args,**kwargs ))
class Unsigned(Completed,EthereumMMGenTX.Unsigned):
desc = 'unsigned transaction'

View file

@ -85,7 +85,7 @@ class baseconv(object):
from .mn_tirosh import words
cls.digits[mn_id] = words[:cls.mn_base]
else:
raise ValueError('{}: unrecognized mnemonic ID'.format(mn_id))
raise ValueError(f'{mn_id}: unrecognized mnemonic ID')
@classmethod
def get_wordlist(cls,wl_id):
@ -101,7 +101,7 @@ class baseconv(object):
def check_wordlists(cls):
for k,v in list(cls.wl_chksums.items()):
res = cls.get_wordlist_chksum(k)
assert res == v,'{}: checksum mismatch for {} (should be {})'.format(res,k,v)
assert res == v,f'{res}: checksum mismatch for {k} (should be {v})'
return True
@classmethod
@ -110,7 +110,7 @@ class baseconv(object):
wl = cls.digits[wl_id]
from .util import qmsg,compare_chksums
ret = 'Wordlist: {}\nLength: {} words'.format(wl_id,len(wl))
ret = f'Wordlist: {wl_id}\nLength: {len(wl)} words'
new_chksum = cls.get_wordlist_chksum(wl_id)
a,b = 'generated','saved'
@ -136,8 +136,7 @@ class baseconv(object):
elif pad == 'seed':
return seed_pad_func()
else:
m = "{!r}: illegal value for 'pad' (must be None,'seed' or int)"
raise BaseConversionPadError(m.format(pad))
raise BaseConversionPadError(f"{pad!r}: illegal value for 'pad' (must be None,'seed' or int)")
@staticmethod
def monero_mn_checksum(words):
@ -161,14 +160,14 @@ class baseconv(object):
desc = cls.desc[wl_id][0]
if len(words) == 0:
raise BaseConversionError('empty {} data'.format(desc))
raise BaseConversionError(f'empty {desc} data')
def get_seed_pad():
assert wl_id in cls.seedlen_map_rev,'seed padding not supported for base {!r}'.format(wl_id)
assert wl_id in cls.seedlen_map_rev,f'seed padding not supported for base {wl_id!r}'
d = cls.seedlen_map_rev[wl_id]
if not len(words) in d:
m = '{}: invalid length for seed-padded {} data in base conversion'
raise BaseConversionError(m.format(len(words),desc))
raise BaseConversionError(
f'{len(words)}: invalid length for seed-padded {desc} data in base conversion' )
return d[len(words)]
pad_val = max(cls.get_pad(pad,get_seed_pad),1)
@ -176,12 +175,13 @@ class baseconv(object):
base = len(wl)
if not set(words) <= set(wl):
m = ('{w!r}:','seed data')[pad=='seed'] + ' not in {d} format'
raise BaseConversionError(m.format(w=words_arg,d=desc))
raise BaseConversionError(
( 'seed data' if pad == 'seed' else f'{words_arg!r}:' ) +
f' not in {desc} format' )
if wl_id == 'xmrseed':
if len(words) not in cls.seedlen_map_rev['xmrseed']:
die(2,'{}: invalid length for Monero mnemonic'.format(len(words)))
die(2,f'{len(words)}: invalid length for Monero mnemonic')
z = cls.monero_mn_checksum(words[:-1])
assert z == words[-1],'invalid Monero mnemonic checksum'
@ -204,8 +204,9 @@ class baseconv(object):
from .util import is_hex_str
if not is_hex_str(hexstr):
m = ('{h!r}:','seed data')[pad=='seed'] + ' not a hexadecimal string'
raise HexadecimalStringError(m.format(h=hexstr))
raise HexadecimalStringError(
( 'seed data' if pad == 'seed' else f'{hexstr!r}:' ) +
' not a hexadecimal string' )
return cls.frombytes(bytes.fromhex(hexstr),wl_id,pad,tostr)
@ -220,11 +221,11 @@ class baseconv(object):
raise BaseConversionError('empty data not allowed in base conversion')
def get_seed_pad():
assert wl_id in cls.seedlen_map,'seed padding not supported for base {!r}'.format(wl_id)
assert wl_id in cls.seedlen_map, f'seed padding not supported for base {wl_id!r}'
d = cls.seedlen_map[wl_id]
if not len(bytestr) in d:
m = '{}: invalid byte length for seed data in seed-padded base conversion'
raise SeedLengthError(m.format(len(bytestr)))
raise SeedLengthError(
f'{len(bytestr)}: invalid byte length for seed data in seed-padded base conversion' )
return d[len(bytestr)]
pad = max(cls.get_pad(pad,get_seed_pad),1)
@ -233,7 +234,7 @@ class baseconv(object):
if wl_id == 'xmrseed':
if len(bytestr) not in cls.seedlen_map['xmrseed']:
die(2,'{}: invalid seed byte length for Monero mnemonic'.format(len(bytestr)))
die(2, f'{len(bytestr)}: invalid seed byte length for Monero mnemonic')
def num2base_monero(num):
w1 = num % base

View file

@ -2099,7 +2099,7 @@ zoo
for k,v in cls.constants.items():
if v[1] == nwords:
return int(k)//8 if in_bytes else int(k)//4 if in_hex else int(k)
raise MnemonicError('{!r}: invalid word length for BIP39 mnemonic'.format(nwords))
raise MnemonicError(f'{nwords!r}: invalid word length for BIP39 mnemonic')
@classmethod
def seedlen2nwords(cls,seed_len,in_bytes=False,in_hex=False):
@ -2107,7 +2107,7 @@ zoo
try:
return cls.constants[str(seed_bits)][1]
except:
raise ValueError('{!r}: invalid seed length for BIP39 mnemonic'.format(seed_bits))
raise ValueError(f'{seed_bits!r}: invalid seed length for BIP39 mnemonic')
@classmethod
def tohex(cls,words,wl_id,pad=None):
@ -2118,7 +2118,7 @@ zoo
for n,w in enumerate(words):
if w not in wl:
raise MnemonicError('word #{} is not in the BIP39 word list'.format(n+1))
raise MnemonicError(f'word #{n+1} is not in the BIP39 word list')
res = ''.join(['{:011b}'.format(wl.index(w)) for w in words])
@ -2127,10 +2127,10 @@ zoo
bitlen = int(k)
break
else:
raise MnemonicError('{}: invalid BIP39 seed phrase length'.format(len(words)))
raise MnemonicError(f'{len(words)}: invalid BIP39 seed phrase length')
if pad != None:
assert pad * 4 == bitlen, '{}: invalid pad length'.format(pad)
assert pad * 4 == bitlen, f'{pad}: invalid pad length'
seed_bin = res[:bitlen]
chk_bin = res[bitlen:]
@ -2157,11 +2157,11 @@ zoo
seed_bytes = bytes.fromhex(seed_hex)
bitlen = len(seed_bytes) * 8
assert str(bitlen) in cls.constants,'{}: invalid seed bit length'.format(bitlen)
assert str(bitlen) in cls.constants, f'{bitlen}: invalid seed bit length'
chk_len,mn_len = cls.constants[str(bitlen)]
if pad != None:
assert mn_len == pad, '{}: invalid pad length'.format(pad)
assert mn_len == pad, f'{pad}: invalid pad length'
chk_hex = sha256(seed_bytes).hexdigest()

View file

@ -56,7 +56,7 @@ class CfgFile(object):
self.data = ''
def copy_data(self):
assert self.write_ok, 'writing to file {!r} not allowed!'.format(self.fn)
assert self.write_ok, f'writing to file {self.fn!r} not allowed!'
src = cfg_file('sys')
if src.data:
data = src.data + src.make_metadata() if self.write_metadata else src.data
@ -64,7 +64,7 @@ class CfgFile(object):
open(self.fn,'w').write('\n'.join(data)+'\n')
os.chmod(self.fn,0o600)
except:
die(2,'ERROR: unable to write to {!r}'.format(self.fn))
die(2,f'ERROR: unable to write to {self.fn!r}')
def parse_value(self,value,refval):
if isinstance(refval,dict):
@ -89,7 +89,7 @@ class CfgFile(object):
if m:
yield self.line_data(m[1],m[3],lineno,None)
else:
raise CfgFileParseError('Parse error in file {!r}, line {}'.format(self.fn,lineno))
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
return gen_lines()
@classmethod
@ -105,7 +105,7 @@ class CfgFileSample(CfgFile):
@classmethod
def cls_make_metadata(cls,data):
return ['# Version {} {}'.format(cls.cur_ver,cls.compute_chksum(data))]
return [f'# Version {cls.cur_ver} {cls.compute_chksum(data)}']
@staticmethod
def compute_chksum(data):
@ -131,7 +131,7 @@ class CfgFileSample(CfgFile):
if m:
return self.line_data(m[2],m[4],lineno,chunk)
else:
raise CfgFileParseError('Parse error in file {!r}, line {}'.format(self.fn,lineno))
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
def gen_chunks(lines):
hdr = True
@ -159,7 +159,7 @@ class CfgFileSample(CfgFile):
chunk.append(line)
last_nonblank = lineno
else:
raise CfgFileParseError('Parse error in file {!r}, line {}'.format(self.fn,lineno))
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
if chunk:
yield process_chunk(chunk,last_nonblank)
@ -201,7 +201,7 @@ class CfgFileSampleSys(CfgFileSample):
self.data = files('mmgen').joinpath('data',self.fn_base).read_text().splitlines()
def make_metadata(self):
return ['# Version {} {}'.format(self.cur_ver,self.computed_chksum)]
return [f'# Version {self.cur_ver} {self.computed_chksum}']
class CfgFileSampleUsr(CfgFileSample):
desc = 'sample configuration file'
@ -260,25 +260,23 @@ class CfgFileSampleUsr(CfgFileSample):
def show_changes(self,diff):
ymsg('Warning: configuration file options have changed!\n')
m1 = ' The following option{} been {}:\n {}\n'
m2 = """
The following removed option{} set in {!r}
and must be deleted or commented out:
{}
"""
for desc in ('added','removed'):
data = diff[desc]
if data:
opts = fmt_list([i.name for i in data],fmt='bare')
msg(m1.format(suf(data,verb='has'),desc,opts))
msg(f' The following option{suf(data,verb="has")} been {desc}:\n {opts}\n')
if desc == 'removed' and data:
uc = cfg_file('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))
if bad:
ymsg(fmt(m2,' ').format(suf(bad,verb='is'),uc.fn,' '+fmt_list(bad,fmt='bare')))
m = f"""
The following removed option{suf(bad,verb='is')} set in {uc.fn!r}
and must be deleted or commented out:
{' ' + fmt_list(bad,fmt='bare')}
"""
ymsg(fmt(m,indent=' ',strip_char='\t'))
while True:
if not keypress_confirm(self.details_confirm_prompt,no_nl=True):
return
@ -288,9 +286,9 @@ class CfgFileSampleUsr(CfgFileSample):
sep,sep2 = ('\n ','\n\n ')
if data:
yield (
'{} section{}:'.format(capfirst(desc),suf(data))
f'{capfirst(desc)} section{suf(data)}:'
+ sep2
+ sep2.join(['{}'.format(sep.join(v.chunk)) for v in data])
+ sep2.join([f'{sep.join(v.chunk)}' for v in data])
)
do_pager(

View file

@ -34,8 +34,7 @@ def scramble_seed(seed,scramble_key):
import hmac
step1 = hmac.new(seed,scramble_key,sha256).digest()
if g.debug:
fs = 'Seed: {!r}\nScramble key: {}\nScrambled seed: {}\n'
msg(fs.format(seed.hex(),scramble_key,step1.hex()))
msg(f'Seed: {seed.hex()!r}\nScramble key: {scramble_key}\nScrambled seed: {step1.hex()}\n')
return sha256_rounds(step1,g.scramble_hash_rounds)
def encrypt_seed(seed,key):
@ -64,30 +63,30 @@ def decrypt_seed(enc_seed,key,seed_id,key_id):
vmsg('')
return False
# else:
# qmsg('Generated IDs (Seed/Key): {}/{}'.format(chk2,chk1))
# qmsg(f'Generated IDs (Seed/Key): {chk2}/{chk1}')
dmsg('Decrypted seed: {}'.format(dec_seed.hex()))
dmsg(f'Decrypted seed: {dec_seed.hex()}')
return dec_seed
def encrypt_data(data,key,iv=g.aesctr_dfl_iv,desc='data',verify=True):
vmsg('Encrypting {}'.format(desc))
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('Performing a test decryption of the {}...'.format(desc))
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,"ERROR.\nDecrypted {s} doesn't match original {s}".format(s=desc))
die(2,f'ERROR.\nDecrypted {desc} doesn’t match original {desc}')
vmsg('done')
return enc_data
def decrypt_data(enc_data,key,iv=g.aesctr_dfl_iv,desc='data'):
vmsg_r('Decrypting {} with key...'.format(desc))
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()
@ -136,12 +135,11 @@ def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):
return ret
def make_key(passwd,salt,hash_preset,desc='encryption key',from_what='passphrase',verbose=False):
if from_what: desc += ' from '
if opt.verbose or verbose:
msg_r('Generating {}{}...'.format(desc,from_what))
msg_r(f"Generating {desc}{' from ' + from_what if from_what else ''}...")
key = scrypt_hash_passphrase(passwd,salt,hash_preset)
if opt.verbose or verbose: msg('done')
dmsg('Key: {}'.format(key.hex()))
dmsg(f'Key: {key.hex()}')
return key
def _get_random_data_from_user(uchars,desc):
@ -166,9 +164,8 @@ def _get_random_data_from_user(uchars,desc):
"""
msg(f'Enter {uchars} random symbols' if opt.quiet else
'\n{}\n{}'.format( fmt(info1,indent=' '), fmt(info2) ))
prompt = 'You may begin typing. {} symbols left: '
'\n' + fmt(info1,indent=' ') +
'\n' + fmt(info2) )
import time
from .term import get_char_raw
@ -176,12 +173,12 @@ def _get_random_data_from_user(uchars,desc):
time_data = []
for i in range(uchars):
key_data += get_char_raw('\r'+prompt.format(uchars-i))
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 opt.quiet else f'\rThank you. That’s enough.{" "*18}\n\n' )
time_data = ['{:.22f}'.format(t).rstrip('0') for t in time_data]
time_data = [f'{t:.22f}'.rstrip('0') for t in time_data]
avg_prec = sum(len(t.split('.')[1]) for t in time_data) // len(time_data)
@ -217,21 +214,21 @@ def add_user_random(rand_bytes,desc):
return rand_bytes
def get_hash_preset_from_user(hp=g.dfl_hash_preset,desc='data'):
prompt = f'Enter hash preset for {desc},\nor hit ENTER to accept the default value ({hp!r}): '
while True:
ret = my_raw_input(prompt)
ret = my_raw_input(
f'Enter hash preset for {desc},\n' +
f'or hit ENTER to accept the default value ({hp!r}): ' )
if ret:
if ret in g.hash_presets:
return ret
else:
msg('Invalid input. Valid choices are {}'.format(', '.join(g.hash_presets)))
msg(f'Invalid input. Valid choices are {", ".join(g.hash_presets)}')
continue
else:
return hp
def get_new_passphrase(desc,passchg=False):
pw_desc = '{}passphrase for {}'.format(('','new ')[bool(passchg)], desc)
pw_desc = f"{'new ' if passchg else ''}passphrase for {desc}"
if opt.passwd_file:
pw = ' '.join(get_words_from_file(opt.passwd_file,pw_desc))
elif opt.echo_passphrase:
@ -253,7 +250,7 @@ def get_new_passphrase(desc,passchg=False):
return pw
def get_passphrase(desc,passchg=False):
pw_desc ='{}passphrase for {}'.format(('','old ')[bool(passchg)],desc)
pw_desc = f"{'old ' if passchg else ''}passphrase for {desc}"
if opt.passwd_file:
pwfile_reuse_warning(opt.passwd_file)
return ' '.join(get_words_from_file(opt.passwd_file,pw_desc))

View file

@ -88,7 +88,7 @@ class Daemon(Lockable):
msg(f'Starting {self.desc} on port {self.bind_port}')
if self.debug:
msg('\nExecuting: {}'.format(' '.join(cmd)))
msg(f'\nExecuting: {" ".join(cmd)}')
if self.use_threads and is_daemon and not self.opt.no_daemonize:
ret = self.exec_cmd_thread(cmd)
@ -445,7 +445,7 @@ class CoinDaemon(Daemon):
os.makedirs(self.datadir,exist_ok=True)
if self.cfg_file and not self.flag.keep_cfg_file:
open('{}/{}'.format(self.datadir,self.cfg_file),'w').write(self.cfg_file_hdr)
open(f'{self.datadir}/{self.cfg_file}','w').write(self.cfg_file_hdr)
if self.use_pidfile and os.path.exists(self.pidfile):
# Parity overwrites the data in the existing pidfile without zeroing it first, leading

View file

@ -64,24 +64,27 @@ if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN
if is_dict:
out.append('{s}{:<{l}}'.format(i,s=' '*(4*lvl+8),l=10,l2=8*(lvl+1)+8))
if hasattr(el,'pfmt'):
out.append('{:>{l}}{}'.format('',el.pfmt(
lvl=lvl+1,id_list=id_list+[id(self)]),l=(lvl+1)*8))
out.append('{:>{l}}{}'.format(
'',
el.pfmt( lvl=lvl+1, id_list=id_list+[id(self)] ),
l = (lvl+1)*8 ))
elif isinstance(el,scalars):
if isList(e):
out.append('{:>{l}}{:16}\n'.format('',repr(el),l=lvl*8))
out.append( '{:>{l}}{!r:16}\n'.format( '', el, l=lvl*8 ))
else:
out.append(' {}'.format(repr(el)))
out.append(f' {el!r}')
elif isList(el) or isDict(el):
indent = 1 if is_dict else lvl*8+4
out.append('{:>{l}}{:16}'.format('','<'+type(el).__name__+'>',l=indent))
out.append('{:>{l}}{:16}'.format( '', f'<{type(el).__name__}>', l=indent ))
if isList(el) and isinstance(el[0],scalars):
out.append('\n')
do_list(out,el,lvl=lvl+1,is_dict=isDict(el))
else:
out.append('{:>{l}}{:16} {}\n'.format(
'','<'+type(el).__name__+'>',repr(el),l=(lvl*8)+8))
out.append('{:>{l}}{:16} {!r}\n'.format( '', f'<{type(el).__name__}>', el, l=(lvl*8)+8 ))
out.append('\n')
if not e: out.append('{}\n'.format(repr(e)))
if not e:
out.append(f'{e!r}\n')
def isDict(obj):
return isinstance(obj,dict)
@ -90,7 +93,8 @@ if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN
def isScalar(obj):
return isinstance(obj,scalars)
out = ['<{}>{}\n'.format(type(self).__name__,' '+repr(self) if isScalar(self) else '')]
out = [f'<{type(self).__name__}>{" "+repr(self) if isScalar(self) else ""}\n']
if id(self) in id_list:
return out[-1].rstrip() + ' [RECURSION]\n'
if isList(self) or isDict(self):
@ -99,14 +103,21 @@ if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN
for k in self.__dict__:
e = getattr(self,k)
if isList(e) or isDict(e):
out.append('{:>{l}}{:<10} {:16}'.format('',k,'<'+type(e).__name__+'>',l=(lvl*8)+4))
out.append('{:>{l}}{:<10} {:16}'.format( '', k, f'<{type(e).__name__}>', l=(lvl*8)+4 ))
do_list(out,e,lvl=lvl,is_dict=isDict(e))
elif hasattr(e,'pfmt') and type(e) != type:
out.append('{:>{l}}{:10} {}'.format(
'',k,e.pfmt(lvl=lvl+1,id_list=id_list+[id(self)]),l=(lvl*8)+4))
'',
k,
e.pfmt( lvl=lvl+1, id_list=id_list+[id(self)] ),
l = (lvl*8)+4 ))
else:
out.append('{:>{l}}{:<10} {:16} {}\n'.format(
'',k,'<'+type(e).__name__+'>',repr(e),l=(lvl*8)+4))
'',
k,
f'<{type(e).__name__}>',
repr(e),
l=(lvl*8)+4 ))
import re
return re.sub('\n+','\n',''.join(out))
@ -123,11 +134,11 @@ if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN
attr = o.__dict__[attrname]
break
else:
rdie(3,'unable to find descriptor {}.{}'.format(cls.__name__,attrname))
rdie(3,f'unable to find descriptor {cls.__name__}.{attrname}')
if type(attr).__name__ == 'ImmutableAttr':
if attrname not in self.__dict__:
fs = 'attribute {!r} of {} has not been initialized in constructor!'
rdie(3,fs.format(attrname,cls.__name__))
rdie(3,
f'attribute {attrname!r} of {cls.__name__} has not been initialized in constructor!')
def print_diff(a,b,from_file='',to_file='',from_json=True):
if from_json:
@ -136,7 +147,8 @@ if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN
else:
a = a.split('\n')
b = b.split('\n')
sys.stderr.write(' DIFF:\n {}\n'.format('\n '.join(unified_diff(a,b,from_file,to_file))))
sys.stderr.write(' DIFF:\n {}\n'.format(
'\n '.join(unified_diff(a,b,from_file,to_file)) ))
def get_ndiff(a,b):
a = a.split('\n')

View file

@ -47,20 +47,19 @@ class Filename(MMGenObject):
self.ftype = ftype
# elif: # other MMGen file types
else:
die(3,"'{}': not a recognized file type for Wallet".format(ftype))
die(3,f'{ftype!r}: not a recognized file type for Wallet')
else:
die(3,"'{}': not a class".format(ftype))
die(3,f'{ftype!r}: not a class')
else:
# TODO: other file types
self.ftype = Wallet.ext_to_type(self.ext)
if not self.ftype:
m = "'{}': not a recognized Wallet file extension".format(self.ext)
raise BadFileExtension(m)
raise BadFileExtension(f'{self.ext!r}: not a recognized Wallet file extension')
try:
st = os.stat(fn)
except:
raise FileNotFound('{!r}: file not found'.format(fn))
raise FileNotFound(f'{fn!r}: file not found')
import stat
if stat.S_ISBLK(st.st_mode):
@ -70,7 +69,7 @@ class Filename(MMGenObject):
fd = os.open(fn, mode)
except OSError as e:
if e.errno == 13:
die(2,"'{}': permission denied".format(fn))
die(2,f'{fn!r}: permission denied')
# if e.errno != 17: raise
else:
self.size = os.lseek(fd, 0, os.SEEK_END)
@ -92,25 +91,27 @@ class MMGenFileList(list,MMGenObject):
def sort_by_age(self,key='mtime',reverse=False):
if key not in ('atime','ctime','mtime'):
die(1,"'{}': illegal sort key".format(key))
die(1,f'{key!r}: illegal sort key')
self.sort(key=lambda a: getattr(a,key),reverse=reverse)
def find_files_in_dir(ftype,fdir,no_dups=False):
if not isinstance(ftype,type):
die(3,"'{}': is of type {} (not a subclass of type 'type')".format(ftype,type(ftype)))
die(3,f"{ftype!r}: is of type {type(ftype)} (not a subclass of type 'type')")
from .wallet import Wallet
if not issubclass(ftype,Wallet):
die(3,"'{}': not a recognized file type".format(ftype))
die(3,f'{ftype!r}: not a recognized file type')
try: dirlist = os.listdir(fdir)
except: die(3,"ERROR: unable to read directory '{}'".format(fdir))
try:
dirlist = os.listdir(fdir)
except:
die(3,f'ERROR: unable to read directory {fdir!r}')
matches = [l for l in dirlist if l[-len(ftype.ext)-1:]=='.'+ftype.ext]
if no_dups:
if len(matches) > 1:
die(1,"ERROR: more than one {} file in directory '{}'".format(ftype.__name__,fdir))
die(1,f'ERROR: more than one {ftype.__name__} file in directory {fdir!r}')
return os.path.join(fdir,matches[0]) if len(matches) else None
else:
return [os.path.join(fdir,m) for m in matches]

View file

@ -22,11 +22,11 @@ license.py: Copyright notice and text of GPLv3
from .globalvars import g
warning = """
{pnm} Copyright (C) {g.Cdates} by {g.author} {g.email}. This
warning = f"""
{g.proj_name} Copyright (C) {g.Cdates} by {g.author} {g.email}. This
program comes with ABSOLUTELY NO WARRANTY. This is free software, and
you are welcome to redistribute it under certain conditions.
""".format(g=g,pnm=g.proj_name)
"""
conditions = """
TERMS AND CONDITIONS

View file

@ -127,7 +127,7 @@ FMT CODES:
cmd_args = opts.init(opts_data,add_opts=['b16'],opt_filter=opt_filter)
errmsg = "'{}': invalid parameter for --type option".format(opt.type)
errmsg = f'{opt.type!r}: invalid parameter for --type option'
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()

View file

@ -38,10 +38,10 @@ WARNING: If any of the addresses you're importing is already in the blockchain,
has a balance and is not in your tracking wallet, you must exit the program now
and rerun it using the '--rescan' option.
""".strip(),
'bad_args': """
You must specify an {pnm} address file, a single address with the '--address'
option, or a list of non-{pnm} addresses with the '--addrlist' option
""".strip().format(pnm=g.proj_name)
'bad_args': f"""
You must specify an {g.proj_name} address file, a single address with the '--address'
option, or a list of non-{g.proj_name} addresses with the '--addrlist' option
""".strip()
}[k]
# In batch mode, daemon just rescans each address separately anyway, so make
@ -49,7 +49,7 @@ option, or a list of non-{pnm} addresses with the '--addrlist' option
opts_data = {
'text': {
'desc': """Import addresses into an {} tracking wallet""".format(g.proj_name),
'desc': f'Import addresses into an {g.proj_name} tracking wallet',
'usage':'[opts] [mmgen address file]',
'options': """
-h, --help Print this help message
@ -87,7 +87,7 @@ def parse_cmd_args(rpc,cmd_args):
if opt.addrlist:
al = AddrList(
proto = proto,
addrlist = get_lines_from_file(infile,'non-{pnm} addresses'.format(pnm=g.proj_name),
addrlist = get_lines_from_file(infile,f'non-{g.proj_name} addresses',
trim_comments = True) )
else:
al = import_mmgen_list(infile)
@ -104,14 +104,14 @@ def check_opts(tw):
rescan = bool(opt.rescan)
if rescan and not 'rescan' in tw.caps:
msg("'--rescan' ignored: not supported by {}".format(type(tw).__name__))
msg(f"'--rescan' ignored: not supported by {type(tw).__name__}")
rescan = False
if rescan and not opt.quiet:
confirm_or_raise(ai_msgs('rescan'),'continue',expect='YES')
if batch and not 'batch' in tw.caps:
msg("'--batch' ignored: not supported by {}".format(type(tw).__name__))
msg(f"'--batch' ignored: not supported by {type(tw).__name__}")
batch = False
return batch,rescan
@ -124,7 +124,9 @@ async def import_addr(tw,addr,label,rescan,msg_fmt,msg_args):
while True:
if task.done():
break
msg_r(('\r{} '+msg_fmt).format(secs_to_hms(int(time.time()-start)),*msg_args))
msg_r(('\r{} '+msg_fmt).format(
secs_to_hms(int(time.time()-start)),
*msg_args ))
await asyncio.sleep(0.5)
await task
msg('\nOK')
@ -132,7 +134,7 @@ async def import_addr(tw,addr,label,rescan,msg_fmt,msg_args):
await task
qmsg(msg_fmt.format(*msg_args) + ' - OK')
except Exception as e:
die(2,'\nImport of address {!r} failed: {!r}'.format(addr,e.args[0]))
die(2,f'\nImport of address {addr!r} failed: {e.args[0]!r}')
def make_args_list(tw,al,batch,rescan):
@ -142,10 +144,10 @@ def make_args_list(tw,al,batch,rescan):
for num,e in enumerate(al.data,1):
if e.idx:
label = '{}:{}'.format(al.al_id,e.idx) + (' ' + e.label if e.label else '')
label = f'{al.al_id}:{e.idx}' + (' ' + e.label if e.label else '')
add_msg = label
else:
label = '{}:{}'.format(proto.base_coin.lower(),e.addr)
label = f'{proto.base_coin.lower()}:{e.addr}'
add_msg = 'non-'+g.proj_name
if batch:

View file

@ -44,15 +44,15 @@ opts_data = {
'text': {
'desc': 'Auto-sign MMGen transactions',
'usage':'[opts] [command]',
'options': """
'options': f"""
-h, --help Print this help message
--, --longhelp Print help message for long options (common options)
-c, --coins=c Coins to sign for (comma-separated list)
-I, --no-insert-check Don’t check for device insertion
-l, --led Use status LED to signal standby, busy and error
-m, --mountpoint=M Specify an alternate mountpoint 'M' (default: '{mp}')
-m, --mountpoint=M Specify an alternate mountpoint 'M' (default: '{mountpoint}')
-M, --mnemonic-fmt=F During setup, prompt for mnemonic seed phrase of format
'F' (choices: {mc}; default: '{md}')
'F' (choices: {fmt_list(mn_fmts,fmt='no_spc')}; default: {mn_fmt_dfl!r})
-n, --no-summary Don’t print a transaction summary
-s, --stealth-led Stealth LED mode - signal busy and error only, and only
after successful authorization.
@ -61,16 +61,12 @@ opts_data = {
will not be printed.
-q, --quiet Produce quieter output
-v, --verbose Produce more verbose output
""".format(
md = mn_fmt_dfl,
mc = fmt_list(mn_fmts,fmt='no_spc'),
mp = mountpoint
),
'notes': """
""",
'notes': f"""
COMMANDS
gen_key - generate the wallet encryption key and copy it to '{td}'
gen_key - generate the wallet encryption key and copy it to '{tx_dir}'
setup - generate the wallet encryption key and wallet
wait - start in loop mode: wait-mount-sign-unmount-wait
@ -91,13 +87,13 @@ ready for device insertion or removal.
The removable device must have a partition labeled MMGEN_TX and a user-
writable directory '/tx', where unsigned MMGen transactions are placed.
On the signing machine the mount point '{mp}' must exist and /etc/fstab
On the signing machine the mount point '{mountpoint}' must exist and /etc/fstab
must contain the following entry:
LABEL='MMGEN_TX' /mnt/tx auto noauto,user 0 0
Transactions are signed with a wallet on the signing machine (in the directory
'{wd}') encrypted with a 64-character hexadecimal password on the
'{wallet_dir}') encrypted with a 64-character hexadecimal password on the
removable device.
The password and wallet can be created in one operation by invoking the
@ -108,7 +104,7 @@ Alternatively, the password and wallet can be created separately by first
invoking the command with 'gen_key' and then creating and encrypting the
wallet using the -P (--passwd-file) option:
$ mmgen-walletconv -r0 -q -iwords -d{wd} -p1 -P{td}/{kf} -Llabel
$ mmgen-walletconv -r0 -q -iwords -d{wallet_dir} -p1 -P{tx_dir}/{key_fn} -Llabel
Note that the hash preset must be '1'. Multiple wallets are permissible.
@ -116,7 +112,7 @@ For good security, it's advisable to re-generate a new wallet and key for
each signing session.
This command is currently available only on Linux-based platforms.
""".format(pnm=prog_name,wd=wallet_dir,td=tx_dir,kf=key_fn,mp=mountpoint)
"""
}
}

View file

@ -33,10 +33,10 @@ pwi_fs = '{:8} {:1} {:26} {:<7} {:<7} {}'
opts_data = {
'sets': [('print_checksum',True,'quiet',True)],
'text': {
'desc': """
Generate a range or list of passwords from an {pnm} wallet,
'desc': f"""
Generate a range or list of passwords from an {g.proj_name} wallet,
mnemonic, seed or brainwallet for the given ID string
""".format(pnm=g.proj_name),
""",
'usage':'[opts] [seed source] <ID string> <index list or range(s)>',
'options': """
-h, --help Print this help message
@ -118,7 +118,7 @@ FMT CODES:
seed_lens=', '.join(map(str,g.seed_lens)),
g=g,pnm=g.proj_name,
dpf=PasswordList.dfl_pw_fmt,
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)])
kgs=' '.join([f'{n}:{k}' for n,k in enumerate(g.key_generators,1)])
),
'notes': lambda help_notes,s: s.format(
o=opts,g=g,i58=pwi['b58'],i32=pwi['b32'],i39=pwi['bip39'],

View file

@ -26,7 +26,7 @@ from .common import *
opts_data = {
'sets': [('yes', True, 'quiet', True)],
'text': {
'desc': 'Coin daemon regression test mode setup and operations for the {} suite'.format(g.proj_name),
'desc': f'Coin daemon regression test mode setup and operations for the {g.proj_name} suite',
'usage': '[opts] <command>',
'options': """
-h, --help Print this help message
@ -77,7 +77,7 @@ def check_num_args():
if not cmd_args:
opts.usage()
elif cmd_args[0] not in MMGenRegtest.usr_cmds:
die(1,'{!r}: invalid command'.format(cmd_args[0]))
die(1,f'{cmd_args[0]!r}: invalid command')
elif cmd_args[0] not in ('cli','balances'):
check_num_args()

View file

@ -102,7 +102,7 @@ def print_shares_info():
len(shares) )
si = 1
for n,s in enumerate(shares[si:],si+1):
out += '{:3}: {}\n'.format(n,s.sid)
out += f'{n:3}: {s.sid}\n'
qmsg(out)
cmd_args = opts.init(opts_data)
@ -139,6 +139,6 @@ msg_r('Joining {n}-of-{n} XOR split...'.format(n=len(shares)))
seed_out = Seed.join_shares([share1]+shares[1:])
msg('OK\nJoined Seed ID: {}'.format(seed_out.sid.hl()))
msg(f'OK\nJoined Seed ID: {seed_out.sid.hl()}')
Wallet(seed=seed_out).write_to_file()

View file

@ -29,10 +29,10 @@ from .common import *
opts_data = {
'text': {
'desc': """
Split funds in a {pnm} wallet after a chain fork using a
'desc': f"""
Split funds in an {g.proj_name} wallet after a chain fork using a
timelocked transaction
""".format(pnm=g.proj_name),
""",
'usage':'[opts] [output addr1] [output addr2]',
'options': """
-h, --help Print this help message
@ -51,10 +51,10 @@ opts_data = {
-L, --locktime= t Lock time (block height or unix seconds)
(default: {bh})
""",
'notes': """\n
'notes': f"""\n
This command creates two transactions: one (with the timelock) to be broadcast
on the long chain and one on the short chain after a replayable chain fork.
Only {pnm} addresses may be spent to.
Only {g.proj_name} addresses may be spent to.
The command must be run on the longest chain. The user is reponsible for
ensuring that the current chain is the longest. The other chain is specified
@ -77,7 +77,7 @@ attacks on the majority chain or reorg attacks on the minority chain if the
minority chain is ahead of the timelock. If the reorg'd minority chain is
behind the timelock, protection is contingent on getting the non-timelocked
transaction reconfirmed before the timelock expires. Use at your own risk.
""".format(pnm=g.proj_name)
"""
},
'code': {
'options': lambda proto,s: s.format(
@ -96,11 +96,10 @@ die(1,'This command is disabled')
# the following code is broken:
opt.other_coin = opt.other_coin.upper() if opt.other_coin else proto.forks[-1][2].upper()
if opt.other_coin.lower() not in [e[2] for e in proto.forks if e[3] == True]:
die(1,"'{}': not a replayable fork of {} chain".format(opt.other_coin,proto.coin))
die(1,f'{opt.other_coin!r}: not a replayable fork of {proto.coin} chain')
if len(cmd_args) != 2:
fs = 'This command requires exactly two {} addresses as arguments'
die(1,fs.format(g.proj_name))
die(1,f'This command requires exactly two {g.proj_name} addresses as arguments')
from .obj import MMGenID
try:
@ -109,7 +108,7 @@ except:
die(1,'Command line arguments must be valid MMGen IDs')
if mmids[0] == mmids[1]:
die(2,'Both transactions have the same output! ({})'.format(mmids[0]))
die(2,f'Both transactions have the same output! ({mmids[0]})')
from .tx import MMGenSplitTX
from .protocol import init_proto
@ -124,7 +123,7 @@ tx1 = MMGenSplitTX()
opt.no_blank = True
async def main():
gmsg("Creating timelocked transaction for long chain ({})".format(proto.coin))
gmsg(f'Creating timelocked transaction for long chain ({proto.coin})')
locktime = int(opt.locktime)
if not locktime:
rpc = rpc_init(proto)
@ -134,7 +133,7 @@ async def main():
tx1.format()
tx1.create_fn()
gmsg("\nCreating transaction for short chain ({})".format(opt.other_coin))
gmsg(f'\nCreating transaction for short chain ({opt.other_coin})')
proto = init_proto(opt.other_coin)

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