Browse Source

cleanups, whitespace

The MMGen Project 2 months ago
parent
commit
15e01df145

+ 9 - 7
mmgen/addrfile.py

@@ -82,13 +82,15 @@ class AddrFile(MMGenObject):
 			outdir        = outdir)
 
 	def make_label(self):
-		p = self.parent
-		bc,mt = p.proto.base_coin,p.al_id.mmtype
-		l_coin = [] if bc == 'BTC' else [p.proto.coin] if bc == 'ETH' else [bc]
-		l_type = [] if mt == 'E' or (mt == 'L' and not p.proto.testnet) else [mt.name.upper()]
-		l_tn   = [] if not p.proto.testnet else [p.proto.network.upper()]
-		lbl_p2 = ':'.join(l_coin+l_type+l_tn)
-		return p.al_id.sid + ('',' ')[bool(lbl_p2)] + lbl_p2
+		proto = self.parent.proto
+		coin = proto.coin
+		mmtype = self.parent.al_id.mmtype
+		lbl_p2 = ':'.join(
+			([] if coin in ('BTC', 'BCH') else [coin])
+			+ ([] if mmtype == 'E' or (mmtype == 'L' and not proto.testnet) else [mmtype.name.upper()])
+			+ ([proto.network.upper()] if proto.testnet else [])
+		)
+		return self.parent.al_id.sid + (' ' if lbl_p2 else '') + lbl_p2
 
 	def format(self,add_comments=False):
 		p = self.parent

+ 6 - 5
mmgen/addrlist.py

@@ -121,13 +121,14 @@ class AddrListIDStr(HiliteStr):
 		if fmt_str:
 			ret = fmt_str.format(s)
 		else:
-			bc = (addrlist.proto.base_coin,addrlist.proto.coin)[addrlist.proto.base_coin=='ETH']
-			mt = addrlist.al_id.mmtype
+			proto = addrlist.proto
+			coin = 'BTC' if proto.coin == 'BCH' else proto.coin
+			mmtype = addrlist.al_id.mmtype
 			ret = '{}{}{}[{}]'.format(
 				addrlist.al_id.sid,
-				('-'+bc,'')[bc == 'BTC'],
-				('-'+mt,'')[mt in ('L','E')],
-				s )
+				(f'-{coin}', '')[coin == 'BTC'],
+				(f'-{mmtype}', '')[mmtype in ('L','E')],
+				s)
 
 		addrlist.dmsg_sc('id_str',ret[8:].split('[')[0])
 

+ 2 - 2
mmgen/cfg.py

@@ -528,10 +528,10 @@ class Config(Lockable):
 		self._lock()
 
 		if need_proto:
-			from .protocol import warn_trustlevel,init_proto_from_cfg
-			warn_trustlevel(self)
+			from .protocol import init_proto_from_cfg, warn_trustlevel
 			# requires the default-to-none behavior, so do after the lock:
 			self._proto = init_proto_from_cfg(self,need_amt=need_amt)
+			warn_trustlevel(self) # do this after initializing proto
 
 		if self._opts and not do_post_init:
 			self._opts.init_bottom(self)

+ 1 - 1
mmgen/opts.py

@@ -42,7 +42,7 @@ long_opts_data = {
 --, --accept-defaults      Accept defaults at all prompts
 --, --coin=c               Choose coin unit. Default: BTC. Current choice: {cu_dfl}
 --, --token=t              Specify an ERC20 token by address or symbol
---, --color=0|1            Disable or enable color output (enabled by default)
+--, --color=0|1            Disable or enable color output (default: 1)
 --, --columns=N            Force N columns of output with certain commands
 --, --scroll               Use the curses-like scrolling interface for
                          tracking wallet views

+ 1 - 1
mmgen/proto/bch/params.py

@@ -12,7 +12,7 @@
 proto.bch.params: Bitcoin Cash protocol
 """
 
-from ..btc.params import mainnet,_finfo
+from ..btc.params import mainnet, _finfo
 
 class mainnet(mainnet):
 	is_fork_of      = 'Bitcoin'

+ 6 - 7
mmgen/proto/btc/tw/addresses.py

@@ -21,13 +21,12 @@ from .rpc import BitcoinTwRPC
 class BitcoinTwAddresses(TwAddresses,BitcoinTwRPC):
 
 	has_age = True
-	prompt_fs = """
-Sort options: [a]mt, [A]ge, [M]mgen addr, [r]everse
-Column options: toggle [D]ays/date/confs/block
-Filters: show [E]mpty addrs, [u]sed addrs, all [L]abels
-View/Print: pager [v]iew, [w]ide pager view, [p]rint{s}
-Actions: [q]uit menu, r[e]draw, add [l]abel:
-"""
+	prompt_fs_in = [
+		'Sort options: [a]mt, [A]ge, [M]mgen addr, [r]everse',
+		'Column options: toggle [D]ays/date/confs/block',
+		'Filters: show [E]mpty addrs, [u]sed addrs, all [L]abels',
+		'View/Print: pager [v]iew, [w]ide pager view, [p]rint{s}',
+		'Actions: [q]uit menu, r[e]draw, add [l]abel:']
 	key_mappings = {
 		'a':'s_amt',
 		'A':'s_age',

+ 1 - 1
mmgen/proto/btc/tw/ctl.py

@@ -68,7 +68,7 @@ class BitcoinTwCtl(TwCtl):
 		endless = stop is None
 		CR = '\n' if self.cfg.test_suite else '\r'
 
-		if not ( start >= 0 and (stop if stop is not None else start) >= start ):
+		if not (start >= 0 and (stop if stop is not None else start) >= start):
 			die(1,f'{start} {stop}: invalid range')
 
 		async def do_scan(chunks,tip):

+ 6 - 7
mmgen/proto/btc/tw/prune.py

@@ -17,13 +17,12 @@ from .addresses import BitcoinTwAddresses
 
 class BitcoinTwAddressesPrune(BitcoinTwAddresses,TwAddressesPrune):
 
-	prompt_fs = """
-Sort options: [a]mt, [A]ge, [M]mgen addr, [r]everse
-Column options: toggle [D]ays/date/confs/block
-Filters: show [E]mpty addrs, [U]sed addrs, all [L]abels
-View/Actions: pager [v]iew, [w]ide view, r[e]draw{s}
-Pruning: [q]uit pruning, [p]rune, [u]nprune, [c]lear prune list:
-"""
+	prompt_fs_in = [
+		'Sort options: [a]mt, [A]ge, [M]mgen addr, [r]everse',
+		'Column options: toggle [D]ays/date/confs/block',
+		'Filters: show [E]mpty addrs, [U]sed addrs, all [L]abels',
+		'View/Actions: pager [v]iew, [w]ide view, r[e]draw{s}',
+		'Pruning: [q]uit pruning, [p]rune, [u]nprune, [c]lear prune list:']
 	key_mappings = {
 		'a':'s_amt',
 		'A':'s_age',

+ 5 - 6
mmgen/proto/btc/tw/txhistory.py

@@ -235,12 +235,11 @@ class BitcoinTwTxHistory(TwTxHistory,BitcoinTwRPC):
 	desc = 'transaction history'
 	item_desc = 'transaction'
 	no_data_errmsg = 'No transactions in tracking wallet!'
-	prompt_fs = """
-Sort options: [t]xid, [a]mt, total a[m]t, [A]ge, block[n]um, [r]everse
-Column options: toggle [D]ays/date/confs/block, tx[i]d, [T]otal amt
-View/Print: pager [v]iew, full pager [V]iew, [p]rint, full [P]rint{s}
-Filters/Actions: show [u]nconfirmed, [q]uit menu, r[e]draw:
-"""
+	prompt_fs_in = [
+		'Sort options: [t]xid, [a]mt, total a[m]t, [A]ge, block[n]um, [r]everse',
+		'Column options: toggle [D]ays/date/confs/block, tx[i]d, [T]otal amt',
+		'View/Print: pager [v]iew, full pager [V]iew, [p]rint, full [P]rint{s}',
+		'Filters/Actions: show [u]nconfirmed, [q]uit menu, r[e]draw:']
 	key_mappings = {
 		'A':'s_age',
 		'n':'s_blockheight',

+ 5 - 6
mmgen/proto/btc/tw/unspent.py

@@ -28,12 +28,11 @@ class BitcoinTwUnspentOutputs(TwUnspentOutputs):
 	item_desc = 'unspent output'
 	no_data_errmsg = 'No unspent outputs in tracking wallet!'
 	dump_fn_pfx = 'listunspent'
-	prompt_fs = """
-Sort options: [t]xid, [a]mount, [A]ge, a[d]dr, [M]mgen addr, [r]everse
-Column options: toggle [D]ays/date/confs/block, gr[o]up, show [m]mgen addr
-View options: pager [v]iew, [w]ide pager view{s}
-Actions: [q]uit menu, [p]rint, r[e]draw, add [l]abel:
-"""
+	prompt_fs_in = [
+		'Sort options: [t]xid, [a]mount, [A]ge, a[d]dr, [M]mgen addr, [r]everse',
+		'Column options: toggle [D]ays/date/confs/block, gr[o]up, show [m]mgen addr',
+		'View options: pager [v]iew, [w]ide pager view{s}',
+		'Actions: [q]uit menu, [p]rint, r[e]draw, add [l]abel:']
 	key_mappings = {
 		't':'s_txid',
 		'a':'s_amt',

+ 5 - 6
mmgen/proto/eth/tw/addresses.py

@@ -19,12 +19,11 @@ from .rpc import EthereumTwRPC
 class EthereumTwAddresses(TwAddresses,EthereumTwView,EthereumTwRPC):
 
 	has_age = False
-	prompt_fs = """
-Sort options: [a]mt, [M]mgen addr, [r]everse
-Filters: show [E]mpty addrs, show all [L]abels
-View/Print: pager [v]iew, [w]ide pager view, [p]rint{s}
-Actions: [q]uit menu, r[e]draw, [D]elete addr, add [l]abel:
-"""
+	prompt_fs_in = [
+		'Sort options: [a]mt, [M]mgen addr, [r]everse',
+		'Filters: show [E]mpty addrs, show all [L]abels',
+		'View/Print: pager [v]iew, [w]ide pager view, [p]rint{s}',
+		'Actions: [q]uit menu, r[e]draw, [D]elete addr, add [l]abel:']
 	key_mappings = {
 		'a':'s_amt',
 		'M':'s_twmmid',

+ 5 - 6
mmgen/proto/eth/tw/unspent.py

@@ -45,12 +45,11 @@ class EthereumTwUnspentOutputs(EthereumTwView,TwUnspentOutputs):
 	desc    = 'account balances'
 	item_desc = 'account'
 	dump_fn_pfx = 'balances'
-	prompt_fs = """
-Sort options: [a]mount, a[d]dr, [M]mgen addr, [r]everse
-Display options: show [m]mgen addr, r[e]draw screen
-View/Print: pager [v]iew, [w]ide pager view, [p]rint to file{s}
-Actions: [q]uit menu, [D]elete addr, add [l]abel, [R]efresh balance:
-"""
+	prompt_fs_in = [
+		'Sort options: [a]mount, a[d]dr, [M]mgen addr, [r]everse',
+		'Display options: show [m]mgen addr, r[e]draw screen',
+		'View/Print: pager [v]iew, [w]ide pager view, [p]rint to file{s}',
+		'Actions: [q]uit menu, [D]elete addr, add [l]abel, [R]efresh balance:']
 	key_mappings = {
 		'a':'s_amt',
 		'd':'s_addr',

+ 10 - 7
mmgen/proto/eth/tx/info.py

@@ -13,10 +13,9 @@ proto.eth.tx.info: Ethereum transaction info class
 """
 
 from ....tx.info import TxInfo
-from ....util import fmt,pp_fmt
-from ....color import pink,yellow,blue
+from ....util import fmt, pp_fmt
+from ....color import pink, yellow, blue
 from ....addr import MMGenID
-from ....obj import Str
 
 class TxInfo(TxInfo):
 	txinfo_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) Sig={s} Locktime={l}\n'
@@ -27,7 +26,7 @@ class TxInfo(TxInfo):
 		Remaining balance: {C} {d}
 		TX fee:            {a} {c}{r}
 	""")
-	fmt_keys = ('from','to','amt','nonce')
+	to_addr_key = 'to'
 
 	def format_body(self, blockcount, nonmm_str, max_mmwid, enl, terse, sort):
 		tx = self.tx
@@ -47,9 +46,13 @@ class TxInfo(TxInfo):
 		""".strip().replace('\t','')
 		t = tx.txobj
 		td = t['data']
+		to_addr = t[self.to_addr_key]
 		return fs.format(
-			*((t[k] if t[k] != '' else Str('None')).hl() for k in self.fmt_keys),
-			d      = '{}... ({} bytes)'.format(td[:40],len(td)//2) if len(td) else Str('None'),
+			f      = t['from'].hl(),
+			t      = to_addr.hl() if to_addr else blue('None'),
+			a      = t['amt'].hl(),
+			n      = t['nonce'].hl(),
+			d      = '{}... ({} bytes)'.format(td[:40],len(td)//2) if len(td) else blue('None'),
 			c      = tx.proto.dcoin if len(tx.outputs) else '',
 			g      = yellow(str(t['gasPrice'].to_unit('Gwei',show_decimal=True))),
 			G      = yellow(str(t['startGas'].to_unit('Kwei'))),
@@ -72,7 +75,7 @@ class TxInfo(TxInfo):
 			return ''
 
 class TokenTxInfo(TxInfo):
-	fmt_keys = ('from','token_to','amt','nonce')
+	to_addr_key = 'token_to'
 
 	def format_rel_fee(self):
 		return ''

+ 6 - 6
mmgen/proto/eth/tx/new.py

@@ -15,12 +15,12 @@ proto.eth.tx.new: Ethereum new transaction class
 import json
 
 from ....tx import new as TxBase
-from ....obj import Int,ETHNonce,MMGenTxID,Str,HexStr
-from ....util import msg,is_int,is_hex_str,make_chksum_6,suf,die
+from ....obj import Int, ETHNonce, MMGenTxID, HexStr
+from ....util import msg, is_int, is_hex_str, make_chksum_6, suf, die
 from ....tw.ctl import TwCtl
-from ....addr import is_mmgen_id,is_coin_addr
+from ....addr import is_mmgen_id, is_coin_addr
 from ..contract import Token
-from .base import Base,TokenBase
+from .base import Base, TokenBase
 
 class New(Base,TxBase.New):
 	desc = 'transaction'
@@ -51,7 +51,7 @@ class New(Base,TxBase.New):
 	async def make_txobj(self): # called by create_serialized()
 		self.txobj = {
 			'from': self.inputs[0].addr,
-			'to':   self.outputs[0].addr if self.outputs else Str(''),
+			'to':   self.outputs[0].addr if self.outputs else None,
 			'amt':  self.outputs[0].amt if self.outputs else self.proto.coin_amt('0'),
 			'gasPrice': self.fee_abs2rel(self.usr_fee,to_unit='eth'),
 			'startGas': self.start_gas,
@@ -69,7 +69,7 @@ class New(Base,TxBase.New):
 		o_ok = 0 if self.usr_contract_data else 1
 		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' }
+		odict = {k:v if v is None else str(v) for k,v in self.txobj.items() if k != 'token_to'}
 		self.serialized = json.dumps(odict)
 		self.update_txid()
 

+ 4 - 4
mmgen/proto/eth/tx/signed.py

@@ -13,9 +13,9 @@ proto.eth.tx.signed: Ethereum signed transaction class
 """
 
 from ....tx import signed as TxBase
-from ....obj import Str,CoinTxID,ETHNonce,HexStr
-from ....addr import CoinAddr,TokenAddr
-from .completed import Completed,TokenCompleted
+from ....obj import CoinTxID, ETHNonce, HexStr
+from ....addr import CoinAddr, TokenAddr
+from .completed import Completed, TokenCompleted
 
 class Signed(Completed,TxBase.Signed):
 
@@ -32,7 +32,7 @@ class Signed(Completed,TxBase.Signed):
 		o = {
 			'from':     CoinAddr(self.proto,d['sender']),
 			# NB: for token, 'to' is token address
-			'to':       CoinAddr(self.proto,d['to']) if d['to'] else Str(''),
+			'to':       CoinAddr(self.proto,d['to']) if d['to'] else None,
 			'amt':      self.proto.coin_amt(d['value'],'wei'),
 			'gasPrice': self.proto.coin_amt(d['gasprice'],'wei'),
 			'startGas': self.proto.coin_amt(d['startgas'],'wei'),

+ 6 - 6
mmgen/proto/eth/tx/unsigned.py

@@ -15,11 +15,11 @@ proto.eth.tx.unsigned: Ethereum unsigned transaction class
 import json
 
 from ....tx import unsigned as TxBase
-from ....util import msg,msg_r
-from ....obj import Str,CoinTxID,ETHNonce,Int,HexStr
-from ....addr import CoinAddr,TokenAddr
+from ....util import msg, msg_r
+from ....obj import CoinTxID, ETHNonce, Int, HexStr
+from ....addr import CoinAddr, TokenAddr
 from ..contract import Token
-from .completed import Completed,TokenCompleted
+from .completed import Completed, TokenCompleted
 
 class Unsigned(Completed,TxBase.Unsigned):
 	desc = 'unsigned transaction'
@@ -29,7 +29,7 @@ class Unsigned(Completed,TxBase.Unsigned):
 		o = {
 			'from':     CoinAddr(self.proto,d['from']),
 			# NB: for token, 'to' is sendto address
-			'to':       CoinAddr(self.proto,d['to']) if d['to'] else Str(''),
+			'to':       CoinAddr(self.proto,d['to']) if d['to'] else None,
 			'amt':      self.proto.coin_amt(d['amt']),
 			'gasPrice': self.proto.coin_amt(d['gasPrice']),
 			'startGas': self.proto.coin_amt(d['startGas']),
@@ -43,7 +43,7 @@ class Unsigned(Completed,TxBase.Unsigned):
 	async def do_sign(self,wif):
 		o = self.txobj
 		o_conv = {
-			'to':       bytes.fromhex(o['to']),
+			'to':       bytes.fromhex(o['to'] or ''),
 			'startgas': o['startGas'].toWei(),
 			'gasprice': o['gasPrice'].toWei(),
 			'value':    o['amt'].toWei() if o['amt'] else 0,

+ 2 - 3
mmgen/term.py

@@ -295,9 +295,8 @@ def init_term(cfg,noecho=False):
 
 	term.init(noecho=noecho)
 
-	from . import term as self
-	for var in ('get_char','get_char_raw','kb_hold_protect','get_terminal_size'):
-		setattr( self, var, getattr(term,var) )
+	for var in ('get_char', 'get_char_raw', 'kb_hold_protect', 'get_terminal_size'):
+		globals()[var] = getattr(term, var)
 
 	term.cfg = cfg # setting the _class_ attribute
 

+ 3 - 3
mmgen/tw/ctl.py

@@ -278,9 +278,9 @@ class TwCtl(MMGenObject,metaclass=AsyncInit):
 
 		if await self.set_label(res.coinaddr,lbl):
 			if not silent:
-				desc = '{} address {} in tracking wallet'.format(
-					res.twmmid.type.replace('mmgen','MMGen'),
-					res.twmmid.addr.hl() )
+				desc = '{t} address {a} in tracking wallet'.format(
+					t = res.twmmid.type.replace('mmgen','MMGen'),
+					a = res.twmmid.addr.hl())
 				msg(
 					'Added label {} to {}'.format(comment.hl2(encl='‘’'),desc) if comment else
 					'Removed label from {}'.format(desc) )

+ 1 - 0
mmgen/tw/view.py

@@ -194,6 +194,7 @@ class TwView(MMGenObject,metaclass=AsyncInit):
 			from .ctl import TwCtl
 			self.twctl = await TwCtl(cfg,proto,mode='w')
 		self.amt_keys = {'amt':'iwidth','amt2':'iwidth2'} if self.has_amt2 else {'amt':'iwidth'}
+		self.prompt_fs = '\n'.join(self.prompt_fs_in)
 
 	@property
 	def age_w(self):

+ 1 - 1
test/unit_tests_d/ut_bip_hd.py

@@ -316,6 +316,7 @@ class unit_tests:
 			if coin not in BipHDConfig.supported_coins:
 				vmsg(gray(fs.format(coin.upper(), (addr_type or ''), '[not supported yet]')))
 				continue
+			vmsg(fs.format(coin.upper(), (addr_type or 'auto'), addr_chk))
 			node = m.to_chain(idx=0,coin=coin,addr_type=addr_type).derive_private(0)
 			xpub_parsed = node.key_extended(public=True)
 			xprv_parsed = node.key_extended(public=False)
@@ -332,7 +333,6 @@ class unit_tests:
 			if proto.base_proto == 'Ethereum':
 				addr = proto.checksummed_addr(node.address)
 				addr_from_wif = proto.checksummed_addr(addr_from_wif)
-			vmsg(fs.format(coin.upper(), (addr_type or 'auto'), addr))
 			assert addr == addr_chk, f'{addr} != {addr_chk}'
 			assert addr == addr_from_wif, f'{addr} != {addr_from_wif}'