Browse Source

Use Exception attributes: e.message, e.code

MMGen 6 years ago
parent
commit
7ebe50dc0b

+ 1 - 1
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

+ 1 - 1
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):

+ 2 - 2
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()

+ 3 - 3
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)

+ 2 - 2
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

+ 3 - 3
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

+ 1 - 1
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)

+ 17 - 17
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

+ 1 - 1
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

+ 2 - 2
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 ================== #
 

+ 1 - 1
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.

+ 1 - 1
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'):

+ 2 - 2
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'))
 

+ 7 - 10
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)

+ 1 - 1
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

+ 2 - 2
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()+':'

+ 2 - 2
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)