Browse Source

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

The MMGen Project 4 years ago
parent
commit
94e3b1c0b0
14 changed files with 51 additions and 41 deletions
  1. 1 1
      mmgen/altcoin.py
  2. 10 4
      mmgen/altcoins/eth/tx.py
  3. 2 2
      mmgen/common.py
  4. 3 3
      mmgen/obj.py
  5. 7 13
      mmgen/opts.py
  6. 3 3
      mmgen/protocol.py
  7. 3 2
      mmgen/regtest.py
  8. 5 5
      mmgen/rpc.py
  9. 1 1
      mmgen/tw.py
  10. 5 2
      mmgen/tx.py
  11. 3 1
      mmgen/util.py
  12. 1 1
      test/test_py_d/ts_cfg.py
  13. 6 2
      test/test_py_d/ts_main.py
  14. 1 1
      test/tooltest.py

+ 1 - 1
mmgen/altcoin.py

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

+ 10 - 4
mmgen/altcoins/eth/tx.py

@@ -308,7 +308,10 @@ class EthereumMMGenTX(MMGenTX):
 
 
 		if not self.disable_fee_check and (fee > g.proto.max_tx_fee):
 		if not self.disable_fee_check and (fee > g.proto.max_tx_fee):
 			die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
 			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()
 		await self.get_status()
 
 
@@ -500,9 +503,12 @@ class EthereumTokenMMGenTxForSigning(EthereumTokenMMGenTX,EthereumMMGenTxForSign
 		if g.token.upper() == self.dcoin:
 		if g.token.upper() == self.dcoin:
 			g.token = d['token_addr']
 			g.token = d['token_addr']
 		elif 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):
 	def parse_txfile_hex_data(self):
 		d = EthereumMMGenTxForSigning.parse_txfile_hex_data(self)
 		d = EthereumMMGenTxForSigning.parse_txfile_hex_data(self)

+ 2 - 2
mmgen/common.py

@@ -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
 To send the value of all inputs (minus TX fee) to a single output, specify
 one address with no amount on the command line.
 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': """
 FEE SPECIFICATION: Transaction fees, both on the command line and at the
 FEE SPECIFICATION: Transaction fees, both on the command line and at the
 interactive prompt, may be specified as either absolute {c} amounts, using
 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.
 default wallet.
 """.format( dn=g.proto.daemon_name,
 """.format( dn=g.proto.daemon_name,
 			pnm=g.proj_name,
 			pnm=g.proj_name,
-			pnu=g.proto.name.capitalize(),
+			pnu=g.proto.name,
 			pnl=g.proj_name.lower())
 			pnl=g.proj_name.lower())
 	}[k] + ('-α' if g.debug_utf8 else '')
 	}[k] + ('-α' if g.debug_utf8 else '')
 
 

+ 3 - 3
mmgen/obj.py

@@ -554,12 +554,12 @@ class TokenAddr(CoinAddr):
 
 
 class ViewKey(object):
 class ViewKey(object):
 	def __new__(cls,s,on_fail='die'):
 	def __new__(cls,s,on_fail='die'):
-		if g.proto.name == 'zcash':
+		if g.proto.name == 'Zcash':
 			return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
 			return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
-		elif g.proto.name == 'monero':
+		elif g.proto.name == 'Monero':
 			return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
 			return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
 		else:
 		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
 class ZcashViewKey(CoinAddr): hex_width = 128
 
 

+ 7 - 13
mmgen/opts.py

@@ -104,11 +104,11 @@ def override_globals_from_cfg_file(ucfg):
 				try:
 				try:
 					val = dict([val.split(':')])
 					val = dict([val.split(':')])
 				except:
 				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)
 			val_conv = set_for_type(val,refval,attr,src=ucfg.fn)
 			setattr(cls,attr,val_conv)
 			setattr(cls,attr,val_conv)
 		else:
 		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):
 def override_globals_and_set_opts_from_env(opt):
 	for name in g.env_opts:
 	for name in g.env_opts:
@@ -126,16 +126,6 @@ def override_globals_and_set_opts_from_env(opt):
 			else:
 			else:
 				raise ValueError(f'Name {gname} not present in globals or opts')
 				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 show_common_opts_diff():
 
 
 	def common_opts_data_to_list():
 	def common_opts_data_to_list():
@@ -188,7 +178,11 @@ common_opts_data = {
 --, --bob                  Switch to user "Bob" in MMGen regtest setup
 --, --bob                  Switch to user "Bob" in MMGen regtest setup
 --, --alice                Switch to user "Alice" 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 = {
 opts_data_dfl = {

+ 3 - 3
mmgen/protocol.py

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

+ 3 - 2
mmgen/regtest.py

@@ -152,8 +152,9 @@ class MMGenRegtest(MMGenObject):
 			err = cp.stderr.decode()
 			err = cp.stderr.decode()
 			if err:
 			if err:
 				if "couldn't connect to server" in 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):
 	def current_user_unix(self,quiet=False):
 		cmd = ['pgrep','-af','{}.*--rpcport={}.*'.format(g.proto.daemon_name,self.d.rpc_port)]
 		cmd = ['pgrep','-af','{}.*--rpcport={}.*'.format(g.proto.daemon_name,self.d.rpc_port)]

+ 5 - 5
mmgen/rpc.py

@@ -33,18 +33,18 @@ rpc_credentials_msg = '\n'+fmt("""
 	A) If daemon is local and running as same user as you:
 	A) If daemon is local and running as same user as you:
 
 
 	   - no credentials required, or matching rpcuser/rpcpassword and
 	   - 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:
 	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.
 	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
 	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
 	to use cookie authentication with a local server when the options are set
 	in mmgen.cfg.
 	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.
 	rpcuser/rpcpassword.
 
 
 """,strip_char='\t')
 """,strip_char='\t')
@@ -241,8 +241,8 @@ class RPCClient(MMGenObject):
 				return
 				return
 
 
 		die(1,rpc_credentials_msg.format(
 		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
 	# positional params are passed to the daemon, kwargs to the backend

+ 1 - 1
mmgen/tw.py

@@ -628,7 +628,7 @@ class TrackingWallet(MMGenObject,metaclass=aInitMeta):
 			print_stack_trace('TW INIT {!r} {!r}'.format(mode,self))
 			print_stack_trace('TW INIT {!r} {!r}'.format(mode,self))
 
 
 		self.mode = mode
 		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:
 		if self.use_tw_file:
 			self.init_from_wallet_file()
 			self.init_from_wallet_file()

+ 5 - 2
mmgen/tx.py

@@ -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:
 		if self.get_fee_from_tx() > g.proto.max_tx_fee:
 			die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
 			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()
 		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:
 			if len(tx_data) == 6:
 				assert len(tx_data[-1]) == 64,'invalid coin TxID length'
 				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')
 				self.coin_txid = CoinTxID(tx_data.pop(-1),on_fail='raise')
 
 
 			if len(tx_data) == 5:
 			if len(tx_data) == 5:

+ 3 - 1
mmgen/util.py

@@ -822,7 +822,9 @@ def do_license_msg(immed=False):
 def get_coin_daemon_cfg_fn():
 def get_coin_daemon_cfg_fn():
 	# Use dirname() to remove 'bob' or 'alice' component
 	# 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
 	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):
 def get_coin_daemon_cfg_options(req_keys):
 
 

+ 1 - 1
test/test_py_d/ts_cfg.py

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

+ 6 - 2
test/test_py_d/ts_main.py

@@ -333,8 +333,12 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
 			from mmgen.addr import AddrGenerator,KeyGenerator
 			from mmgen.addr import AddrGenerator,KeyGenerator
 			rand_coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator('std').to_pubhex(privkey))
 			rand_coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator('std').to_pubhex(privkey))
 			of = joinpath(self.cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
 			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))
 			out.append(self._create_fake_unspent_entry(rand_coinaddr,non_mmgen=True,segwit=False))
 
 
 		return out
 		return out

+ 1 - 1
test/tooltest.py

@@ -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
 altcoin_pfx = '' if g.proto.base_coin == 'BTC' else '-'+g.proto.base_coin
 tn_ext = ('','.testnet')[g.proto.testnet]
 tn_ext = ('','.testnet')[g.proto.testnet]