CoinProtocol: use capitalized 'name' attr; related cleanups, fixes

This commit is contained in:
The MMGen Project 2020-05-16 10:04:03 +00:00
commit 94e3b1c0b0
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
14 changed files with 51 additions and 41 deletions

View file

@ -440,7 +440,7 @@ class CoinInfo(object):
msg('Verifying {} {}'.format(coin.upper(),network))
if coin != 'bch': # TODO
test_equal('coin name',e.name,proto.name.capitalize(),*cdata)
test_equal('coin name',e.name,proto.name,*cdata)
if e.trust_level != -1:
test_equal('Trust level',e.trust_level,CoinProtocol.coins[coin].trust_level,*cdata)

View file

@ -308,7 +308,10 @@ class EthereumMMGenTX(MMGenTX):
if not self.disable_fee_check and (fee > g.proto.max_tx_fee):
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
fee,g.proto.name.capitalize(),g.proto.max_tx_fee,g.coin))
fee,
g.proto.name,
g.proto.max_tx_fee,
g.proto.coin ))
await self.get_status()
@ -500,9 +503,12 @@ class EthereumTokenMMGenTxForSigning(EthereumTokenMMGenTX,EthereumMMGenTxForSign
if g.token.upper() == self.dcoin:
g.token = d['token_addr']
elif g.token != d['token_addr']:
m1 = "'{p}': invalid --token parameter for {t} {n} token transaction file\n"
m2 = "Please use '--token={t}'"
die(1,(m1+m2).format(p=g.token,t=self.dcoin,n=capfirst(g.proto.name)))
die(1,"""
{p!r}: invalid --token parameter for {t} {n} token transaction file\nPlease use '--token={t}'
""").strip().format(
p = g.token,
t = self.dcoin,
n = g.proto.name )
def parse_txfile_hex_data(self):
d = EthereumMMGenTxForSigning.parse_txfile_hex_data(self)

View file

@ -200,7 +200,7 @@ addresses of the form <seed ID>:<index>.
To send the value of all inputs (minus TX fee) to a single output, specify
one address with no amount on the command line.
""".format(g=g,pnm=g.proj_name,pnu=g.proto.name.capitalize()),
""".format(g=g,pnm=g.proj_name,pnu=g.proto.name),
'fee': """
FEE SPECIFICATION: Transaction fees, both on the command line and at the
interactive prompt, may be specified as either absolute {c} amounts, using
@ -232,7 +232,7 @@ must also be supplied on the command line if the data can't be found in the
default wallet.
""".format( dn=g.proto.daemon_name,
pnm=g.proj_name,
pnu=g.proto.name.capitalize(),
pnu=g.proto.name,
pnl=g.proj_name.lower())
}[k] + ('' if g.debug_utf8 else '')

View file

@ -554,12 +554,12 @@ class TokenAddr(CoinAddr):
class ViewKey(object):
def __new__(cls,s,on_fail='die'):
if g.proto.name == 'zcash':
if g.proto.name == 'Zcash':
return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
elif g.proto.name == 'monero':
elif g.proto.name == 'Monero':
return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
else:
raise ValueError('{}: protocol does not support view keys'.format(g.proto.name.capitalize()))
raise ValueError(f'{g.proto.name}: protocol does not support view keys')
class ZcashViewKey(CoinAddr): hex_width = 128

View file

@ -104,11 +104,11 @@ def override_globals_from_cfg_file(ucfg):
try:
val = dict([val.split(':')])
except:
raise CfgFileParseError('Parse error in file {!r}, line {}'.format(ucfg.fn,d.lineno))
raise CfgFileParseError(f'Parse error in file {ucfg.fn!r}, line {d.lineno}')
val_conv = set_for_type(val,refval,attr,src=ucfg.fn)
setattr(cls,attr,val_conv)
else:
die(2,'{!r}: unrecognized option in {!r}, line {}'.format(d.name,ucfg.fn,d.lineno))
raise CfgFileParseError(f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}')
def override_globals_and_set_opts_from_env(opt):
for name in g.env_opts:
@ -126,16 +126,6 @@ def override_globals_and_set_opts_from_env(opt):
else:
raise ValueError(f'Name {gname} not present in globals or opts')
def common_opts_code(s):
from .protocol import CoinProtocol
return s.format(
pnm = g.proj_name,
pn = g.proto.name,
dn = g.proto.daemon_name,
cu_dfl = g.coin,
cu_all = ' '.join(CoinProtocol.coins)
)
def show_common_opts_diff():
def common_opts_data_to_list():
@ -188,7 +178,11 @@ common_opts_data = {
--, --bob Switch to user "Bob" in MMGen regtest setup
--, --alice Switch to user "Alice" in MMGen regtest setup
""",
'code': common_opts_code
'code': lambda s: s.format(
pnm = g.proj_name,
dn = g.proto.daemon_name,
cu_dfl = g.coin,
)
}
opts_data_dfl = {

View file

@ -90,7 +90,7 @@ class CoinProtocol(MMGenObject):
def __init__(self,coin,name,network):
self.coin = coin.upper()
self.dcoin = self.coin # display coin - for Ethereum, is set to ERC20 token name
self.name = name[0].lower() + name[1:]
self.name = name
self.network = network
self.testnet = network in ('testnet','regtest')
self.regtest = network == 'regtest'
@ -244,7 +244,7 @@ class CoinProtocol(MMGenObject):
bech32_hrp = 'bcrt'
class BitcoinCash(Bitcoin):
is_fork_of = 'bitcoin'
is_fork_of = 'Bitcoin'
# TODO: assumes MSWin user installs in custom dir 'Bitcoin_ABC'
daemon_name = 'bitcoind-abc'
daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Bitcoin_ABC') if g.platform == 'win' \
@ -273,7 +273,7 @@ class CoinProtocol(MMGenObject):
pass
class B2X(Bitcoin):
is_fork_of = 'bitcoin'
is_fork_of = 'Bitcoin'
daemon_name = 'bitcoind-2x'
daemon_data_dir = os.path.join(os.getenv('APPDATA'),'Bitcoin_2X') if g.platform == 'win' \
else os.path.join(g.home_dir,'.bitcoin-2x')

View file

@ -152,8 +152,9 @@ class MMGenRegtest(MMGenObject):
err = cp.stderr.decode()
if err:
if "couldn't connect to server" in err:
rdie(1,'Error stopping the {} daemon:\n{}'.format(g.proto.name.capitalize(),err))
msg(err)
rdie(1,f'Error stopping the {g.proto.name} daemon:\n{err}')
else:
msg(err)
def current_user_unix(self,quiet=False):
cmd = ['pgrep','-af','{}.*--rpcport={}.*'.format(g.proto.daemon_name,self.d.rpc_port)]

View file

@ -33,18 +33,18 @@ rpc_credentials_msg = '\n'+fmt("""
A) If daemon is local and running as same user as you:
- no credentials required, or matching rpcuser/rpcpassword and
rpc_user/rpc_password values in {base_name}.conf and mmgen.cfg
rpc_user/rpc_password values in {cf_name}.conf and mmgen.cfg
B) If daemon is running remotely or as different user:
- matching credentials in {base_name}.conf and mmgen.cfg as described above
- matching credentials in {cf_name}.conf and mmgen.cfg as described above
The --rpc-user/--rpc-password options may be supplied on the MMGen command line.
They override the corresponding values in mmgen.cfg. Set them to an empty string
to use cookie authentication with a local server when the options are set
in mmgen.cfg.
For better security, rpcauth should be used in {base_name}.conf instead of
For better security, rpcauth should be used in {cf_name}.conf instead of
rpcuser/rpcpassword.
""",strip_char='\t')
@ -241,8 +241,8 @@ class RPCClient(MMGenObject):
return
die(1,rpc_credentials_msg.format(
proto_name = capfirst(self.proto.name),
base_name = self.proto.is_fork_of or self.proto.name,
proto_name = self.proto.name,
cf_name = (self.proto.is_fork_of or self.proto.name).lower(),
))
# positional params are passed to the daemon, kwargs to the backend

View file

@ -628,7 +628,7 @@ class TrackingWallet(MMGenObject,metaclass=aInitMeta):
print_stack_trace('TW INIT {!r} {!r}'.format(mode,self))
self.mode = mode
self.desc = self.base_desc = '{} tracking wallet'.format(capfirst(g.proto.name))
self.desc = self.base_desc = f'{g.proto.name} tracking wallet'
if self.use_tw_file:
self.init_from_wallet_file()

View file

@ -900,7 +900,10 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
if self.get_fee_from_tx() > g.proto.max_tx_fee:
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
self.get_fee_from_tx(),g.proto.name.capitalize(),g.proto.max_tx_fee,g.coin))
self.get_fee_from_tx(),
g.proto.name,
g.proto.max_tx_fee,
g.proto.coin ))
await self.get_status()
@ -1171,7 +1174,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
if len(tx_data) == 6:
assert len(tx_data[-1]) == 64,'invalid coin TxID length'
desc = '{} TxID'.format(g.proto.name.capitalize())
desc = f'{g.proto.name} TxID'
self.coin_txid = CoinTxID(tx_data.pop(-1),on_fail='raise')
if len(tx_data) == 5:

View file

@ -822,7 +822,9 @@ def do_license_msg(immed=False):
def get_coin_daemon_cfg_fn():
# Use dirname() to remove 'bob' or 'alice' component
cfg_dir = os.path.dirname(g.data_dir) if g.proto.regtest else g.proto.daemon_data_dir
return os.path.join(cfg_dir,g.proto.name+'.conf' )
return os.path.join(
cfg_dir,
(g.proto.is_fork_of or g.proto.name).lower() + '.conf' )
def get_coin_daemon_cfg_options(req_keys):

View file

@ -126,7 +126,7 @@ class TestSuiteCfg(TestSuiteBase):
if old_set:
t.expect('unrecognized option')
t.req_exit_val = 2
t.req_exit_val = 1
if args == ['parse_test']:
t.expect('parsed chunks: 29')

View file

@ -333,8 +333,12 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
from mmgen.addr import AddrGenerator,KeyGenerator
rand_coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator('std').to_pubhex(privkey))
of = joinpath(self.cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
write_data_to_file(of, privkey.wif+'\n','compressed {} key'.format(g.proto.name),
quiet=True,ignore_opt_outdir=True)
write_data_to_file(
outfile = of,
data = privkey.wif + '\n',
desc = f'compressed {g.proto.name} key',
quiet = True,
ignore_opt_outdir = True )
out.append(self._create_fake_unspent_entry(rand_coinaddr,non_mmgen=True,segwit=False))
return out

View file

@ -117,7 +117,7 @@ cfg = {
}
}
ref_subdir = '' if g.proto.base_coin == 'BTC' else g.proto.name
ref_subdir = '' if g.proto.base_coin == 'BTC' else g.proto.name.lower()
altcoin_pfx = '' if g.proto.base_coin == 'BTC' else '-'+g.proto.base_coin
tn_ext = ('','.testnet')[g.proto.testnet]