Browse Source

pylint throughout (excluding tests) - f-strings

The MMGen Project 1 year ago
parent
commit
83ac0f860c

+ 2 - 2
mmgen/addr.py

@@ -129,13 +129,13 @@ class MMGenID(str,Hilite,InitErrors,MMGenObject):
 			ss = str(id_str).split(':')
 			assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
 			t = proto.addr_type((ss[1],proto.dfl_mmtype)[len(ss)==2])
-			me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
+			me = str.__new__(cls,f'{ss[0]}:{t}:{ss[-1]}')
 			me.sid = SeedID(sid=ss[0])
 			me.idx = AddrIdx(ss[-1])
 			me.mmtype = t
 			assert t in proto.mmtypes, f'{t}: invalid address type for {proto.cls_name}'
 			me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
-			me.sort_key = '{}:{}:{:0{w}}'.format(me.sid,me.mmtype,me.idx,w=me.idx.max_digits)
+			me.sort_key = f'{me.sid}:{me.mmtype}:{me.idx:0{me.idx.max_digits}}'
 			me.proto = proto
 			return me
 		except Exception as e:

+ 2 - 8
mmgen/altcoin.py

@@ -50,13 +50,7 @@ def test_equal(desc,a,b,*cdata):
 		msg(f'  {desc:20}: {a!r}')
 	if a != b:
 		raise ValueError(
-			'{}s for {} {} do not match:\n  CoinInfo: {}\n  {}: {}'.format(
-				desc.capitalize(),
-				coin.upper(),
-				network,
-				a,
-				b_desc,
-				b ))
+			f'{desc.capitalize()}s for {coin.upper()} {network} do not match:\n  CoinInfo: {a}\n  {b_desc}: {b}' )
 
 ce = namedtuple('CoinInfoEntry',
 	['name','symbol','wif_ver_num','p2pkh_info','p2sh_info','has_segwit','trust_level'])
@@ -785,7 +779,7 @@ if __name__ == '__main__':
 
 	opts_data = {
 		'text': {
-			'desc': f'Check altcoin data',
+			'desc': 'Check altcoin data',
 			'usage':'[opts]',
 			'options': '-q, --quiet    Be quieter\n-v, --verbose  Be more verbose'
 		}

+ 6 - 6
mmgen/bip39.py

@@ -84,7 +84,7 @@ class bip39(baseconv):
 			if w not in wl:
 				die( 'MnemonicError', f'word #{n+1} is not in the BIP39 word list' )
 
-		res = ''.join(['{:011b}'.format(wl.index(w)) for w in words])
+		res = ''.join(f'{wl.index(w):011b}' for w in words_arg)
 
 		for k,v in self.constants.items():
 			if len(words) == v.mn_len:
@@ -96,15 +96,15 @@ class bip39(baseconv):
 		seed_bin = res[:bitlen]
 		chk_bin = res[bitlen:]
 
-		seed_hex = '{:0{w}x}'.format(int(seed_bin,2),w=bitlen//4)
+		seed_hex = f'{int(seed_bin,2):0{bitlen//4}x}'
 		seed_bytes = bytes.fromhex(seed_hex)
 
 		chk_len = self.constants[bitlen].chk_len
 		chk_hex_chk = sha256(seed_bytes).hexdigest()
-		chk_bin_chk = '{:0{w}b}'.format(int(chk_hex_chk,16),w=256)[:chk_len]
+		chk_bin_chk = f'{int(chk_hex_chk,16):0256b}'[:chk_len]
 
 		if chk_bin != chk_bin_chk:
-			die( 'MnemonicError', 'invalid BIP39 seed phrase checksum' )
+			die( 'MnemonicError', f'invalid BIP39 seed phrase checksum ({chk_bin} != {chk_bin_chk})' )
 
 		return seed_hex
 
@@ -122,8 +122,8 @@ class bip39(baseconv):
 
 		chk_hex = sha256(seed_bytes).hexdigest()
 
-		seed_bin = '{:0{w}b}'.format(int(seed_hex,16),w=bitlen)
-		chk_bin = '{:0{w}b}'.format(int(chk_hex,16),w=256)[:c.chk_len]
+		seed_bin = f'{int(hexstr,16):0{bitlen}b}'
+		chk_bin  = f'{int(chk_hex,16):0256b}'
 
 		res = seed_bin + chk_bin
 

+ 3 - 3
mmgen/cfg.py

@@ -613,8 +613,8 @@ class Config(Lockable):
 					'{a!r}: invalid {b} (not {c}: {d})'.format(
 						a = val,
 						b = {
-							'cmdline': 'parameter for option --{}'.format(key.replace('_','-')),
-							'cfgfile': 'value for cfg file option {!r}'.format(key)
+							'cmdline': f'parameter for option --{key.replace("_","-")}',
+							'cfgfile': f'value for cfg file option {key!r}'
 						}[src],
 						c = desc,
 						d = fmt_list(data.choices) ))
@@ -860,7 +860,7 @@ def opt_postproc_debug(cfg):
 	from .util import Msg
 	Msg('\n    Configuration opts:')
 	for e in [d for d in dir(cfg) if d[:2] != '__']:
-		Msg('        {:<20}: {}'.format(e, getattr(cfg,e)))
+		Msg(f'        {e:<20}: {getattr(cfg,e)}')
 	Msg("    Configuration opts set to 'None':")
 	Msg('        {}\n'.format('\n        '.join(b)))
 	Msg('\n=== end opts.py debug ===\n')

+ 1 - 1
mmgen/crypto.py

@@ -326,7 +326,7 @@ class Crypto:
 				os_rand + int.to_bytes(urand['counter'],8,'big'),
 				'sha256' )
 
-			msg('Encrypting random data {} with ephemeral key #{}'.format( desc, urand['counter'] ))
+			msg(f'Encrypting random data {desc} with ephemeral key #{urand["counter"]}')
 
 			return self.encrypt_data( data=rand_bytes, key=key, desc=desc, verify=False, silent=True )
 		else:

+ 2 - 2
mmgen/daemon.py

@@ -427,8 +427,8 @@ class CoinDaemon(Daemon):
 			self.private_port = getattr(self.private_ports,self.network)
 
 		# bind_port == self.private_port or self.rpc_port
-		self.pidfile = '{}/{}-{}-daemon-{}.pid'.format(self.logdir,self.id,self.network,self.bind_port)
-		self.logfile = '{}/{}-{}-daemon-{}.log'.format(self.logdir,self.id,self.network,self.bind_port)
+		self.pidfile = f'{self.logdir}/{self.id}-{self.network}-daemon-{self.bind_port}.pid'
+		self.logfile = f'{self.logdir}/{self.id}-{self.network}-daemon-{self.bind_port}.log'
 
 		self.init_subclass()
 

+ 1 - 1
mmgen/keygen.py

@@ -82,7 +82,7 @@ def _check_backend(cfg,backend,pubkey_type,desc='keygen backend'):
 	if not (1 <= int(backend) <= len(backends)):
 		die(1,
 			f'{backend}: {desc} out of range\n' +
-			f'Configured backends: ' +
+			'Configured backends: ' +
 			' '.join( f'{n}:{k}' for n,k in enumerate(backends,1) )
 		)
 

+ 2 - 2
mmgen/msg.py

@@ -168,7 +168,7 @@ class coin_msg:
 					yield 'Signatures:'
 					for n,(k,v) in enumerate(self.sigs.items()):
 						yield ''
-						yield '{:>3}) {}'.format(n+1,k)
+						yield f'{n+1:>3}) {k}'
 						for res in gen_entry(v):
 							yield res
 
@@ -238,7 +238,7 @@ class coin_msg:
 						message = self.data['message'],
 						msghash_type = self.data['msghash_type'] )
 
-					mmid = '{}:{}:{}'.format( al_in.sid, al_in.mmtype, e.idx )
+					mmid = f'{al_in.sid}:{al_in.mmtype}:{e.idx}'
 					data = {
 						'addr': e.addr,
 						'sig': sig,

+ 1 - 3
mmgen/passwdlist.py

@@ -123,9 +123,7 @@ class PasswordList(AddrList):
 			self.pw_fmt_disp = pw_fmt
 		if self.pw_fmt not in self.pw_info:
 			die( 'InvalidPasswdFormat',
-				'{!r}: invalid password format.  Valid formats: {}'.format(
-					self.pw_fmt,
-					', '.join(self.pw_info) ))
+				f'{self.pw_fmt!r}: invalid password format.  Valid formats: {", ".join(self.pw_info)}' )
 
 	def chk_pw_len(self,passwd=None):
 		if passwd is None:

+ 1 - 1
mmgen/proto/btc/misc.py

@@ -54,7 +54,7 @@ async def scantxoutset(cfg,rpc,descriptor_list):
 		ret = await task1
 		await task2
 	else:
-		msg_r(f'Scanning UTXO set, this could take several minutes...')
+		msg_r('Scanning UTXO set, this could take several minutes...')
 		ret = await do_scan()
 		msg('done')
 

+ 2 - 2
mmgen/proto/btc/tx/new.py

@@ -26,7 +26,7 @@ class New(Base,TxBase.New):
 	def relay_fee(self):
 		kb_fee = self.proto.coin_amt(self.rpc.cached['networkinfo']['relayfee'])
 		ret = kb_fee * self.estimate_size() / 1024
-		self.cfg._util.vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=self.coin))
+		self.cfg._util.vmsg(f'Relay fee: {kb_fee} {self.coin}/kB, for transaction: {ret} {self.coin}')
 		return ret
 
 	async def get_rel_fee_from_network(self):
@@ -133,7 +133,7 @@ class New(Base,TxBase.New):
 			msg(f'Setting nLockTime to {self.strfmt_locktime(locktime)}!')
 			assert isinstance(locktime,int), 'locktime value not an integer'
 			self.locktime = locktime
-			ret = ret[:-8] + bytes.fromhex('{:08x}'.format(locktime))[::-1].hex()
+			ret = ret[:-8] + bytes.fromhex(f'{locktime:08x}')[::-1].hex()
 
 		# TxID is set only once!
 		self.txid = MMGenTxID(make_chksum_6(bytes.fromhex(ret)).upper())

+ 1 - 1
mmgen/proto/eth/daemon.py

@@ -78,7 +78,7 @@ class openethereum_daemon(ethereum_daemon):
 			[f'--port={self.p2p_port}', self.p2p_port],
 			[f'--base-path={self.datadir}', self.non_dfl_datadir],
 			[f'--chain={self.proto.chain_name}', self.network!='regtest'],
-			[f'--config=dev', self.network=='regtest'], # no presets for mainnet or testnet
+			['--config=dev', self.network=='regtest'], # no presets for mainnet or testnet
 			['--mode=offline', self.test_suite or self.network=='regtest'],
 			[f'--log-file={self.logfile}', self.non_dfl_datadir],
 			['daemon', ld],

+ 1 - 1
mmgen/proto/xmr/daemon.py

@@ -54,7 +54,7 @@ class monero_daemon(CoinDaemon):
 			daemon = self )
 
 		self.shared_args = list_gen(
-			[f'--no-zmq'],
+			['--no-zmq'],
 			[f'--p2p-bind-port={self.p2p_port}', self.p2p_port],
 			[f'--rpc-bind-port={self.rpc_port}'],
 			['--stagenet', self.network == 'testnet'],

+ 1 - 3
mmgen/protocol.py

@@ -170,9 +170,7 @@ class CoinProtocol(MMGenObject):
 			"""
 			magic module loading and class selection
 			"""
-			modpath = 'mmgen.proto.{}.{}'.format(
-				self.base_proto_coin.lower(),
-				modname )
+			modpath = f'mmgen.proto.{self.base_proto_coin.lower()}.{modname}'
 
 			clsname = (
 				self.mod_clsname

+ 2 - 5
mmgen/rpc.py

@@ -41,7 +41,7 @@ def dmsg_rpc(fs,data=None,is_json=False):
 def dmsg_rpc_backend(host_url,host_path,payload):
 	msg(
 		f'\n    RPC URL: {host_url}{host_path}' +
-		f'\n    RPC PAYLOAD data (httplib) ==>' +
+		'\n    RPC PAYLOAD data (httplib) ==>' +
 		f'\n{pp_fmt(payload)}\n' )
 
 def noop(*args,**kwargs):
@@ -179,10 +179,7 @@ class RPCBackends:
 				auth_str = f'{caller.auth.user}:{caller.auth.passwd}'
 				auth_str_b64 = 'Basic ' + base64.b64encode(auth_str.encode()).decode()
 				self.http_hdrs.update({ 'Host': self.host, 'Authorization': auth_str_b64 })
-				dmsg_rpc('    RPC AUTHORIZATION data ==> raw: [{}]\n{:>31}enc: [{}]\n'.format(
-					auth_str,
-					'',
-					auth_str_b64 ))
+				dmsg_rpc(f'    RPC AUTHORIZATION data ==> raw: [{auth_str}]\n{"":>31}enc: [{auth_str_b64}]\n')
 
 		async def run(self,payload,timeout,host_path):
 			dmsg_rpc_backend(self.host_url,host_path,payload)

+ 1 - 1
mmgen/tw/addresses.py

@@ -231,7 +231,7 @@ class TwAddresses(TwView):
 			# Hack, but OK for the foreseeable future:
 			('{:>012}'.format(1_000_000_000 - d.confs) if d.confs else '_'),
 			d.twmmid.sort_key),
-		'amt': lambda d: '{}_{}'.format(d.al_id,d.amt),
+		'amt': lambda d: f'{d.al_id}_{d.amt}',
 		'twmmid': lambda d: d.twmmid.sort_key,
 	}
 

+ 1 - 1
mmgen/tw/bal.py

@@ -83,7 +83,7 @@ class TwGetBalance(MMGenObject,metaclass=AsyncInit):
 
 				net_desc = self.proto.coin + ' ' + self.proto.network.upper()
 				if net_desc != 'BTC MAINNET':
-					yield 'Network: {}'.format(green(net_desc))
+					yield f'Network: {green(net_desc)}'
 
 				yield '{lbl:{w}} {cols}'.format(
 					lbl = 'Wallet',

+ 1 - 3
mmgen/tw/ctl.py

@@ -82,9 +82,7 @@ class TwCtl(MMGenObject,metaclass=AsyncInit):
 
 		if self.data['coin'] != self.proto.coin: # TODO remove?
 			die( 'WalletFileError',
-				'Tracking wallet coin ({}) does not match current coin ({})!'.format(
-					self.data['coin'],
-					self.proto.coin ))
+				f'Tracking wallet coin ({self.data["coin"]}) does not match current coin ({self.proto.coin})!')
 
 		self.conv_types(self.data[self.data_key])
 		self.cur_balances = {} # cache balances to prevent repeated lookups per program invocation

+ 2 - 2
mmgen/tw/json.py

@@ -111,7 +111,7 @@ class TwJSON:
 					if ignore_checksum:
 						ymsg(f'Warning: ignoring incorrect checksum {chksum}')
 					else:
-						die(3,'File checksum incorrect! ({} != {})'.format(chksum,d['checksum']))
+						die(3,f'File checksum incorrect! ({chksum} != {d["checksum"]})')
 
 			def verify_data(d):
 				check_network(d['data'])
@@ -214,5 +214,5 @@ class TwJSON:
 						'data': data
 					},
 					pretty = pretty ),
-				desc    = f'tracking wallet JSON data',
+				desc    = 'tracking wallet JSON data',
 				ask_overwrite = not force_overwrite )

+ 1 - 1
mmgen/tw/view.py

@@ -397,7 +397,7 @@ class TwView(MMGenObject,metaclass=AsyncInit):
 				yield '{} (sort order: {}){}'.format(
 					self.hdr_lbl.upper(),
 					Blue(sort_info),
-					' ' * (self.cols - len('{} (sort order: {})'.format(self.hdr_lbl,sort_info))) )
+					' ' * (self.cols - len(f'{self.hdr_lbl} (sort order: {sort_info})')) )
 
 				if self.filters:
 					yield 'Filters: {}{}'.format(

+ 1 - 1
mmgen/tx/__init__.py

@@ -17,7 +17,7 @@ from ..objmethods import MMGenObject
 def _base_proto_subclass(clsname,modname,proto):
 	if proto:
 		clsname = ('Token' if proto.tokensym else '') + clsname
-		modname = 'mmgen.proto.{}.tx.{}'.format( proto.base_proto_coin.lower(), modname )
+		modname = f'mmgen.proto.{proto.base_proto_coin.lower()}.tx.{modname}'
 	else:
 		modname = 'mmgen.tx.base'
 	import importlib

+ 3 - 3
mmgen/tx/file.py

@@ -43,7 +43,7 @@ class MMGenTxFile(MMGenObject):
 					ymsg('Warning: transaction data appears to be in old format')
 				import re
 				d = literal_eval(re.sub(r"[A-Za-z]+?\(('.+?')\)",r'\1',raw_data))
-			assert type(d) == list, f'{desc} data not a list!'
+			assert isinstance(d,list), f'{desc} data not a list!'
 			if not (desc == 'outputs' and tx.proto.base_coin == 'ETH'): # ETH txs can have no outputs
 				assert len(d), f'no {desc}!'
 			for e in d:
@@ -72,7 +72,7 @@ class MMGenTxFile(MMGenObject):
 
 			if len(tx_data) == 6:
 				assert len(tx_data[-1]) == 64,'invalid coin TxID length'
-				desc = f'coin TxID'
+				desc = 'coin TxID'
 				tx.coin_txid = CoinTxID(tx_data.pop(-1))
 
 			if len(tx_data) == 5:
@@ -146,7 +146,7 @@ class MMGenTxFile(MMGenObject):
 			if tx.is_replaceable():
 				yield ',{}'.format(tx.fee_abs2rel(tx.fee,to_unit=tx.fn_fee_unit))
 			if tx.get_serialized_locktime():
-				yield ',tl={}'.format(tx.get_serialized_locktime())
+				yield f',tl={tx.get_serialized_locktime()}'
 			yield ']'
 			if tx.proto.testnet:
 				yield '.' + tx.proto.network

+ 1 - 1
mmgen/tx/new.py

@@ -284,7 +284,7 @@ class New(Base):
 			if not keypress_confirm(
 					self.cfg,
 					'{a} {b} {c}\n{d}'.format(
-						a = yellow(f'Requested change address'),
+						a = yellow('Requested change address'),
 						b = (chg.mmid or chg.addr).hl(),
 						c = yellow('is already used!'),
 						d = yellow('Address reuse harms your privacy and security. Continue anyway? (y/N): ')

+ 1 - 3
mmgen/wallet/mmhex.py

@@ -26,9 +26,7 @@ class wallet(wallet):
 		h = self.seed.hexdata
 		self.ssdata.chksum = make_chksum_6(h)
 		self.ssdata.hexseed = h
-		self.fmt_data = '{} {}\n'.format(
-			self.ssdata.chksum,
-			split_into_cols(4,h) )
+		self.fmt_data = f'{self.ssdata.chksum} {split_into_cols(4,h)}\n'
 
 	def _deformat(self):
 		desc = self.desc

+ 12 - 16
mmgen/xmrwallet.py

@@ -289,7 +289,7 @@ class MoneroMMGenTX:
 			fn = '{a}-XMR[{b!s}]{c}.{d}'.format(
 				a = self.file_id,
 				b = self.data.amount,
-				c = (lambda s: '' if s == 'mainnet' else f'.{s}')(self.data.network),
+				c = '' if self.data.network == 'mainnet' else f'.{self.data.network}',
 				d = self.ext
 			)
 
@@ -1153,7 +1153,7 @@ class MoneroWalletOps:
 					restore_height = restore_height,
 					language       = 'English' )
 
-			pp_msg(ret) if self.cfg.debug else msg('  Address: {}'.format( ret['address'] ))
+			pp_msg(ret) if self.cfg.debug else msg(f'  Address: {ret["address"]}')
 			return True
 
 	class create_offline(create):
@@ -1186,7 +1186,7 @@ class MoneroWalletOps:
 
 		def check_uopts(self):
 			if self.cfg.restore_height is not None:
-				die(1,f'--restore-height must be unset when running the ‘restore’ command')
+				die(1,'--restore-height must be unset when running the ‘restore’ command')
 
 		async def process_wallet(self,d,fn,last):
 
@@ -1239,7 +1239,7 @@ class MoneroWalletOps:
 			def check_restored_data():
 				restored_data = h.get_accts(print=False)[1]
 				if restored_data != data:
-					rmsg(f'Restored data does not match original dump!  Dumping bad data.')
+					rmsg('Restored data does not match original dump!  Dumping bad data.')
 					MoneroWalletDumpFile.New(
 						parent    = self,
 						wallet_fn = fn,
@@ -1336,9 +1336,7 @@ class MoneroWalletOps:
 			self.accts_data[fn.name] = { 'accts': a, 'addrs': b }
 
 			msg(f'  Wallet height: {wallet_height}')
-			msg('  Sync time: {:02}:{:02}'.format(
-				t_elapsed // 60,
-				t_elapsed % 60 ))
+			msg(f'  Sync time: {t_elapsed//60:02}:{t_elapsed%60:02}')
 
 			if not last:
 				self.c.call('close_wallet')
@@ -1405,9 +1403,7 @@ class MoneroWalletOps:
 						try:
 							res = self.kal.entry(idx)
 						except:
-							die(1,'Supplied key-address file does not contain address {}:{}'.format(
-								self.kal.al_id.sid,
-								idx ))
+							die(1,f'Supplied key-address file does not contain address {self.kal.al_id.sid}:{idx}')
 						else:
 							setattr(self,k,res)
 							yield res
@@ -1565,7 +1561,7 @@ class MoneroWalletOps:
 			if self.account == None:
 				acct,addr = h.create_acct(label=label)
 			else:
-				msg_r('\n    Account index: {}'.format( pink(str(self.account)) ))
+				msg_r(f'\n    Account index: {pink(str(self.account))}')
 				addr = h.create_new_addr(self.account,label=label)
 
 			accts_data = h.get_accts()[0]
@@ -1766,7 +1762,7 @@ class MoneroWalletOps:
 
 		def check_uopts(self):
 			if not self.cfg.autosign:
-				die(1,f'--autosign is required for this operation')
+				die(1,'--autosign is required for this operation')
 
 		def get_tx(self):
 			asi = get_autosign_obj(self.cfg,'xmr')
@@ -1803,7 +1799,7 @@ class MoneroWalletOps:
 			h.open_wallet('source')
 
 			if self.cfg.rescan_blockchain:
-				gmsg_r(f'\n  Rescanning blockchain...')
+				gmsg_r('\n  Rescanning blockchain...')
 				self.c.call('rescan_blockchain')
 				gmsg('done')
 
@@ -1842,7 +1838,7 @@ class MoneroWalletOps:
 				'import_outputs',
 				outputs_data_hex = m.data.outputs_data_hex )
 			idata = res['num_imported']
-			bmsg('\n  {} output{} imported'.format( idata, suf(idata) ))
+			bmsg(f'\n  {idata} output{suf(idata)} imported')
 			data = m.data._asdict()
 			data.update(self.c.call('export_key_images', all=True))
 			m = MoneroWalletOutputsFile.SignedNew(
@@ -1850,7 +1846,7 @@ class MoneroWalletOps:
 				wallet_fn = m.get_wallet_fn(fn),
 				data      = data )
 			idata = m.data.signed_key_images or []
-			bmsg('  {} key image{} signed'.format( len(idata), suf(idata) ))
+			bmsg(f'  {len(idata)} key image{suf(idata)} signed')
 			return m
 
 	class import_key_images(wallet):
@@ -1872,7 +1868,7 @@ class MoneroWalletOps:
 			self.head_msg(d.idx,h.fn)
 			m = MoneroWalletOutputsFile.Signed( parent=self, fn=keyimage_fn )
 			data = m.data.signed_key_images or []
-			bmsg('\n  {} signed key image{} to import'.format( len(data), suf(data) ))
+			bmsg(f'\n  {len(data)} signed key image{suf(data)} to import')
 			if data:
 				res = self.c.call( 'import_key_images', signed_key_images=data )
 				bmsg(f'  Success: {res}')