From 7ebe50dc0b0511f3105092d0d0e2313277a7538e Mon Sep 17 00:00:00 2001 From: MMGen Date: Tue, 16 Oct 2018 15:39:33 +0000 Subject: [PATCH] Use Exception attributes: e.message, e.code --- mmgen/addr.py | 2 +- mmgen/altcoins/eth/obj.py | 2 +- mmgen/altcoins/eth/tx.py | 4 ++-- mmgen/main.py | 6 +++--- mmgen/main_addrimport.py | 4 ++-- mmgen/main_autosign.py | 6 +++--- mmgen/main_wallet.py | 2 +- mmgen/obj.py | 34 +++++++++++++++++----------------- mmgen/rpc.py | 2 +- mmgen/tool.py | 4 ++-- mmgen/tw.py | 2 +- mmgen/tx.py | 2 +- mmgen/util.py | 4 ++-- scripts/traceback.py | 17 +++++++---------- test/gentest.py | 2 +- test/objtest.py | 4 ++-- test/test.py | 4 ++-- 17 files changed, 49 insertions(+), 52 deletions(-) diff --git a/mmgen/addr.py b/mmgen/addr.py index 5fdc25c4..bca63aa3 100755 --- a/mmgen/addr.py +++ b/mmgen/addr.py @@ -708,7 +708,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file data = self.parse_file_body(lines[1:-1]) assert issubclass(type(data),list),'Invalid file body data' except Exception as e: - m = 'Invalid address list file ({})'.format(e[0]) + m = u'Invalid address list file ({})'.format(e.message) if exit_on_error: die(3,m) msg(msg) return False diff --git a/mmgen/altcoins/eth/obj.py b/mmgen/altcoins/eth/obj.py index ce8c5fa2..8d7b6484 100755 --- a/mmgen/altcoins/eth/obj.py +++ b/mmgen/altcoins/eth/obj.py @@ -56,7 +56,7 @@ class ETHNonce(int,Hilite,InitErrors): # WIP return me except Exception as e: m = "{!r}: value cannot be converted to ETH nonce ({})" - return cls.init_fail(m.format(n,e[0]),on_fail) + return cls.init_fail(m.format(n,e.message),on_fail) @classmethod def colorize(cls,s,color=True): diff --git a/mmgen/altcoins/eth/tx.py b/mmgen/altcoins/eth/tx.py index 66248742..c79abd3f 100755 --- a/mmgen/altcoins/eth/tx.py +++ b/mmgen/altcoins/eth/tx.py @@ -299,7 +299,7 @@ class EthereumMMGenTX(MMGenTX): self.token_addr = TokenAddr(etx.creates.encode('hex')) except Exception as e: m = "{!r}: transaction signing failed!" - msg(m.format(e[0])) + msg(m.format(e.message)) return False return self.check_sigs() @@ -461,7 +461,7 @@ class EthereumTokenMMGenTX(EthereumMMGenTX): msg('OK') except Exception as e: m = "{!r}: transaction signing failed!" - msg(m.format(e[0])) + msg(m.format(e.message)) return False return self.check_sigs() diff --git a/mmgen/main.py b/mmgen/main.py index d2791aa2..743b1d5d 100755 --- a/mmgen/main.py +++ b/mmgen/main.py @@ -55,9 +55,9 @@ def launch(what): if os.getenv('MMGEN_TRACEBACK'): raise else: - try: m = u'{}'.format(e[0]) + try: m = u'{}'.format(e.message) except: - try: m = u'{!r}'.format(e[0]) - except: m = u'{!r}'.format(e) + try: m = e.message.decode('utf8') + except: m = repr(e.message) from mmgen.util import ydie ydie(2,u'\nERROR: ' + m) diff --git a/mmgen/main_addrimport.py b/mmgen/main_addrimport.py index 84dc573d..7a5e5a88 100755 --- a/mmgen/main_addrimport.py +++ b/mmgen/main_addrimport.py @@ -108,7 +108,7 @@ try: except UnrecognizedTokenSymbolError as e: m1 = "Note: when importing addresses for a new token, the token must be specified" m2 = "by address, not symbol." - die(1,'{}\n{}\n{}'.format(e[0],m1,m2)) + die(1,'{}\n{}\n{}'.format(e.message,m1,m2)) if opt.rescan and not 'rescan' in tw.caps: msg("'--rescan' ignored: not supported by {}".format(type(tw).__name__)) @@ -125,7 +125,7 @@ def import_address(addr,label,rescan): try: tw.import_address(addr,label,rescan) except Exception as e: global err_msg - err_msg = e + err_msg = e.message w_n_of_m = len(str(al.num_addrs)) * 2 + 2 w_mmid = 1 if opt.addrlist or opt.address else len(str(max(al.idxs()))) + 13 diff --git a/mmgen/main_autosign.py b/mmgen/main_autosign.py index b4627ac0..dc76e5ce 100755 --- a/mmgen/main_autosign.py +++ b/mmgen/main_autosign.py @@ -127,7 +127,7 @@ def check_daemons_running(): rpc_init(reinit=True) g.rpch.getbalance() except SystemExit as e: - if e[0] != 0: + if e.code != 0: fs = '{} daemon not running or not listening on port {}' ydie(1,fs.format(coin,g.proto.rpc_port)) @@ -194,7 +194,7 @@ def sign_tx_file(txfile): tx.write_to_file(ask_write=False) return True except Exception as e: - msg('An error occurred: {}'.format(e)) + msg(u'An error occurred: {}'.format(e.message)) return False except: return False @@ -235,7 +235,7 @@ def decrypt_wallets(): try: SeedSource(wf) except SystemExit as e: - if e[0] != 0: + if e.code != 0: fails += 1 return False if fails else True diff --git a/mmgen/main_wallet.py b/mmgen/main_wallet.py index f0b23540..5b35e68d 100755 --- a/mmgen/main_wallet.py +++ b/mmgen/main_wallet.py @@ -164,7 +164,7 @@ else: m = 'Make this wallet your default and move it to the data directory?' assert keypress_confirm(m,default_yes=True),'dw' except Exception as e: - if e[0] != 'dw': raise + if e.message != 'dw': raise ss_out.write_to_file() else: ss_out.write_to_file(outdir=g.data_dir) diff --git a/mmgen/obj.py b/mmgen/obj.py index 5384cdc5..b84fa7bf 100755 --- a/mmgen/obj.py +++ b/mmgen/obj.py @@ -272,7 +272,7 @@ class AddrIdx(int,InitErrors): return me except Exception as e: m = "{!r}: value cannot be converted to address index ({})" - return cls.init_fail(m.format(num,e[0]),on_fail) + return cls.init_fail(m.format(num,e.message),on_fail) class AddrIdxList(list,InitErrors,MMGenObject): max_len = 1000000 @@ -302,7 +302,7 @@ class AddrIdxList(list,InitErrors,MMGenObject): raise ValueError,"{!r}: invalid range".format(i) except Exception as e: m = "{!r}: value cannot be converted to AddrIdxList ({})" - return type(self).init_fail(m.format(idx_list or fmt_str,e[0]),on_fail) + return type(self).init_fail(m.format(idx_list or fmt_str,e.message),on_fail) class UnknownCoinAmt(Decimal): pass @@ -336,7 +336,7 @@ class BTCAmt(Decimal,Hilite,InitErrors): return me except Exception as e: m = "{!r}: value cannot be converted to {} ({})" - return cls.init_fail(m.format(num,cls.__name__,e[0]),on_fail) + return cls.init_fail(m.format(num,cls.__name__,e.message),on_fail) def toSatoshi(self): return int(Decimal(self) / self.satoshi) @@ -418,7 +418,7 @@ class CoinAddr(str,Hilite,InitErrors,MMGenObject): return me except Exception as e: m = "{!r}: value cannot be converted to {} address ({})" - return cls.init_fail(m.format(s,g.proto.__name__,e[0]),on_fail) + return cls.init_fail(m.format(s,g.proto.__name__,e.message),on_fail) @classmethod def fmtc(cls,s,**kwargs): @@ -487,7 +487,7 @@ class SeedID(str,Hilite,InitErrors): raise ValueError,'no arguments provided' except Exception as e: m = "{!r}: value cannot be converted to SeedID ({})" - return cls.init_fail(m.format(seed or sid,e[0]),on_fail) + return cls.init_fail(m.format(seed or sid,e.message),on_fail) class MMGenID(str,Hilite,InitErrors,MMGenObject): color = 'orange' @@ -510,7 +510,7 @@ class MMGenID(str,Hilite,InitErrors,MMGenObject): return me except Exception as e: m = "{}\n{!r}: value cannot be converted to MMGenID" - return cls.init_fail(m.format(e[0],s),on_fail) + return cls.init_fail(m.format(e.message,s),on_fail) class TwMMGenID(str,Hilite,InitErrors,MMGenObject): color = 'orange' @@ -533,7 +533,7 @@ class TwMMGenID(str,Hilite,InitErrors,MMGenObject): ret,sort_key,idtype = str(s),'z_'+s,'non-mmgen' except Exception as f: m = "{}\nValue is {}\n{!r}: value cannot be converted to TwMMGenID" - return cls.init_fail(m.format(e[0],f[0],s),on_fail) + return cls.init_fail(m.format(e.message,f.message,s),on_fail) me = str.__new__(cls,ret) me.obj = ret @@ -556,7 +556,7 @@ class TwLabel(unicode,InitErrors,MMGenObject): return me except Exception as e: m = u"{}\n{!r}: value cannot be converted to TwLabel" - return cls.init_fail(m.format(e[0],s),on_fail) + return cls.init_fail(m.format(e.message,s),on_fail) class HexStr(str,Hilite,InitErrors): color = 'red' @@ -572,7 +572,7 @@ class HexStr(str,Hilite,InitErrors): return str.__new__(cls,s) except Exception as e: m = "{!r}: value cannot be converted to {} (value is {})" - return cls.init_fail(m.format(s,cls.__name__,e[0]),on_fail) + return cls.init_fail(m.format(s,cls.__name__,e.message),on_fail) class Str(str,Hilite): pass class Int(int,Hilite): pass @@ -590,7 +590,7 @@ class HexStrWithWidth(HexStr): return ret except Exception as e: m = "{}\n{!r}: value cannot be converted to {}" - return cls.init_fail(m.format(e[0],s,cls.__name__),on_fail) + return cls.init_fail(m.format(e.message,s,cls.__name__),on_fail) class MMGenTxID(HexStrWithWidth): color,width,hexcase = 'red',6,'upper' class MoneroViewKey(HexStrWithWidth): color,width,hexcase = 'cyan',64,'lower' @@ -609,7 +609,7 @@ class WifKey(str,Hilite,InitErrors): g.proto.wif2hex(s) # raises exception on error return str.__new__(cls,s) except Exception as e: - m = '{!r}: invalid value for WIF key ({})'.format(s,e[0]) + m = '{!r}: invalid value for WIF key ({})'.format(s,e.message) return cls.init_fail(m,on_fail) class PubKey(HexStr,MMGenObject): # TODO: add some real checks @@ -620,7 +620,7 @@ class PubKey(HexStr,MMGenObject): # TODO: add some real checks me.compressed = compressed return me except Exception as e: - m = '{!r}: invalid value for pubkey ({})'.format(s,e[0]) + m = '{!r}: invalid value for pubkey ({})'.format(s,e.message) return cls.init_fail(m,on_fail) class PrivKey(str,Hilite,InitErrors,MMGenObject): @@ -652,7 +652,7 @@ class PrivKey(str,Hilite,InitErrors,MMGenObject): return me except Exception as e: fs = "Value {!r} cannot be converted to {} WIF key ({})" - return cls.init_fail(fs.format(wif,g.coin,e[0]),on_fail) + return cls.init_fail(fs.format(wif,g.coin,e.message),on_fail) try: assert s and type(compressed) == bool and pubkey_type,'Incorrect args for PrivKey()' @@ -668,7 +668,7 @@ class PrivKey(str,Hilite,InitErrors,MMGenObject): return me except Exception as e: fs = "Key={!r}\nCompressed={}\nValue pair cannot be converted to PrivKey\n({})" - return cls.init_fail(fs.format(s,compressed,e),on_fail) + return cls.init_fail(fs.format(s,compressed,e.message),on_fail) class AddrListID(str,Hilite,InitErrors,MMGenObject): @@ -686,7 +686,7 @@ class AddrListID(str,Hilite,InitErrors,MMGenObject): me.mmtype = mmtype return me except Exception as e: - m = "Cannot create AddrListID ({})".format(e[0]) + m = "Cannot create AddrListID ({})".format(e.message) return cls.init_fail(m,on_fail) class MMGenLabel(unicode,Hilite,InitErrors): @@ -721,7 +721,7 @@ class MMGenLabel(unicode,Hilite,InitErrors): return unicode.__new__(cls,s) except Exception as e: m = u"{!r}: value cannot be converted to {} ({})" - return cls.init_fail(m.format(s,cls.__name__,e),on_fail) + return cls.init_fail(m.format(s,cls.__name__,e.message),on_fail) class MMGenWalletLabel(MMGenLabel): max_len = 48 @@ -813,7 +813,7 @@ class MMGenAddrType(str,Hilite,InitErrors,MMGenObject): raise ValueError,'not found' except Exception as e: m = '{}{!r}: invalid value for {} ({})'.format( - ('{!r}\n'.format(errmsg) if errmsg else ''),s,cls.__name__,e[0]) + ('{!r}\n'.format(errmsg) if errmsg else ''),s,cls.__name__,e.message) return cls.init_fail(m,on_fail) @classmethod diff --git a/mmgen/rpc.py b/mmgen/rpc.py index 9165d85b..7508872b 100755 --- a/mmgen/rpc.py +++ b/mmgen/rpc.py @@ -129,7 +129,7 @@ class CoinDaemonRPCConnection(object): hc.request('POST','/',json.dumps(p,cls=MyJSONEncoder),http_hdr) except Exception as e: m = '{}\nUnable to connect to {} at {}:{}' - return do_fail(None,2,m.format(e,g.proto.daemon_name,self.host,self.port)) + return do_fail(None,2,m.format(e.message,g.proto.daemon_name,self.host,self.port)) try: r = hc.getresponse() # returns HTTPResponse instance diff --git a/mmgen/tool.py b/mmgen/tool.py index 7444740d..f6641e4c 100755 --- a/mmgen/tool.py +++ b/mmgen/tool.py @@ -639,9 +639,9 @@ def monero_wallet_ops(infile,op,blockheight=None,addrs=None): rdie(2,'\nEnd of file\n') except Exception as e: try: - die(1,'Error: {}'.format(e[0])) + die(1,'Error: {}'.format(e.message)) except: - rdie(1,'Error: {!r}'.format(e)) + rdie(1,'Error: {!r}'.format(e.message)) # ================ RPC commands ================== # diff --git a/mmgen/tw.py b/mmgen/tw.py index 2c6f89aa..b0271ded 100755 --- a/mmgen/tw.py +++ b/mmgen/tw.py @@ -546,7 +546,7 @@ class TrackingWallet(MMGenObject): assert coinaddr,u"{pn} address '{ma}' not found in tracking wallet" assert self.is_in_wallet(coinaddr),u"Address '{ca}' not found in tracking wallet" except Exception as e: - msg(e[0].format(pn=g.proj_name,ma=mmaddr,ca=coinaddr)) + msg(e.message.format(pn=g.proj_name,ma=mmaddr,ca=coinaddr)) return False # Allow for the possibility that BTC addr of MMGen addr was entered. diff --git a/mmgen/tx.py b/mmgen/tx.py index b5bcdff0..2f6f4e49 100755 --- a/mmgen/tx.py +++ b/mmgen/tx.py @@ -1205,7 +1205,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam desc = 'outputs data' self.outputs = eval_io_data(outputs_data,'outputs') except Exception as e: - die(2,'Invalid {} in transaction file: {}'.format(desc,e[0])) + die(2,'Invalid {} in transaction file: {}'.format(desc,e.message)) # test doesn't work for Ethereum: test and mainnet addrs have same format if not self.chain and not self.inputs[0].addr.is_for_chain('testnet'): diff --git a/mmgen/util.py b/mmgen/util.py index c9df9534..cf1b56fa 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -867,7 +867,7 @@ def rpc_init_bitcoind(): assert conn.getblockhash(fork[0]) == fork[1], ( 'Bad block hash at fork block {}. Is this the {} chain?'.format(fork[0],fork[2].upper())) except Exception as e: - die(2,"{}\n'{c}' requested, but this is not the {c} chain!".format(e,c=g.coin)) + die(2,"{}\n'{c}' requested, but this is not the {c} chain!".format(e.message,c=g.coin)) def check_chaintype_mismatch(): try: @@ -875,7 +875,7 @@ def rpc_init_bitcoind(): if g.testnet: assert g.chain != 'mainnet','--testnet option selected, but chain is mainnet' if not g.testnet: assert g.chain == 'mainnet','mainnet selected, but chain is not mainnet' except Exception as e: - die(1,'{}\nChain is {}!'.format(e,g.chain)) + die(1,'{}\nChain is {}!'.format(e.message,g.chain)) cfg = get_daemon_cfg_options(('rpcuser','rpcpassword')) diff --git a/scripts/traceback.py b/scripts/traceback.py index 1b1a18d5..e0c28269 100755 --- a/scripts/traceback.py +++ b/scripts/traceback.py @@ -8,8 +8,8 @@ os.environ['MMGEN_TRACEBACK'] = '1' tb_source = open(sys.argv[1]) tb_file = os.path.join(os.environ['PWD'],'my.err') -def process_exception(es): - l = traceback.format_exception(*es) +def process_exception(): + l = traceback.format_exception(*sys.exc_info()) l_save = l[:] exc = l.pop() if exc[:11] == 'SystemExit:': l.pop() @@ -22,13 +22,10 @@ def process_exception(es): try: sys.argv.pop(0) exec tb_source -except SystemExit: -# pass - e = sys.exc_info() - if int(str(e[1])) != 0: - process_exception(e) - sys.exit(int(str(e[1]))) +except SystemExit as e: + if e.code != 0: + process_exception() + sys.exit(e.code) except: - e = sys.exc_info() - process_exception(e) + process_exception() sys.exit(1) diff --git a/test/gentest.py b/test/gentest.py index a73c247e..db4ff65b 100755 --- a/test/gentest.py +++ b/test/gentest.py @@ -274,7 +274,7 @@ else: assert 1 <= b <= len(g.key_generators),'{}: invalid key generator'.format(b) assert a != b,'Key generators are the same!' except Exception as e: - die(1,'{}\n{}: invalid generator argument'.format(e[0],cmd_args[0])) + die(1,'{}\n{}: invalid generator argument'.format(e.message,cmd_args[0])) from mmgen.addr import KeyGenerator,AddrGenerator from mmgen.obj import PrivKey diff --git a/test/objtest.py b/test/objtest.py index 92630629..d6b419d7 100755 --- a/test/objtest.py +++ b/test/objtest.py @@ -90,10 +90,10 @@ def run_test(test,arg,input_data): if input_data == 'good': raise ValueError,'Error on good input data' if opt.verbose: - msg('exitval: {}'.format(e[0])) + msg('exitval: {}'.format(e.code)) except UserWarning as e: msg('==> {!r}'.format(ret)) - die(2,red('{}'.format(e[0]))) + die(2,red('{}'.format(e.message))) r32,r24,r16,r17,r18 = os.urandom(32),os.urandom(24),os.urandom(16),os.urandom(17),os.urandom(18) tw_pfx = g.proto.base_coin.lower()+':' diff --git a/test/test.py b/test/test.py index 64c96166..6cb93b14 100755 --- a/test/test.py +++ b/test/test.py @@ -104,12 +104,12 @@ if not any(e in ('--skip-deps','--resume','-S','-r') for e in sys.argv+shortopts try: subprocess.call('rm -rf {}/{}*'.format(d,pfx),shell=True) except Exception as e: - die(2,'Unable to delete directory tree {}/{}* ({})'.format(d,pfx,e)) + die(2,'Unable to delete directory tree {}/{}* ({})'.format(d,pfx,e.message)) try: import tempfile shm_dir = unicode(tempfile.mkdtemp('',pfx,d)) except Exception as e: - die(2,'Unable to create temporary directory in {} ({})'.format(d,e)) + die(2,'Unable to create temporary directory in {} ({})'.format(d,e.message)) for tdir in (data_dir,trash_dir): dd = os.path.join(shm_dir,os.path.basename(tdir)) os.mkdir(dd,0755)