Browse Source

handle environmental vars consistently

MMGen 6 years ago
parent
commit
27355e0b27
7 changed files with 35 additions and 27 deletions
  1. 4 6
      mmgen/altcoins/eth/tx.py
  2. 16 5
      mmgen/globalvars.py
  3. 2 1
      mmgen/obj.py
  4. 5 5
      mmgen/opts.py
  5. 1 1
      mmgen/rpc.py
  6. 2 2
      mmgen/term.py
  7. 5 7
      mmgen/tx.py

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

@@ -311,7 +311,7 @@ class EthereumMMGenTX(MMGenTX):
 			msg('OK')
 			return True
 		except Exception as e:
-			if os.getenv('MMGEN_TRACEBACK'):
+			if g.traceback:
 				import traceback
 				ymsg('\n'+''.join(traceback.format_exception(*sys.exc_info())))
 			m = "{!r}: transaction signing failed!"
@@ -352,8 +352,6 @@ class EthereumMMGenTX(MMGenTX):
 
 		self.check_correct_chain(on_fail='die')
 
-		bogus_send = os.getenv('MMGEN_BOGUS_SEND')
-
 		fee = self.fee_rel2abs(self.txobj['gasPrice'].toWei())
 
 		if not self.disable_fee_check and fee > g.proto.max_tx_fee:
@@ -364,7 +362,7 @@ class EthereumMMGenTX(MMGenTX):
 
 		if prompt_user: self.confirm_send()
 
-		ret = None if bogus_send else g.rpch.eth_sendRawTransaction('0x'+self.hex,on_fail='return')
+		ret = None if g.bogus_send else g.rpch.eth_sendRawTransaction('0x'+self.hex,on_fail='return')
 
 		from mmgen.rpc import rpc_error,rpc_errmsg
 		if rpc_error(ret):
@@ -373,8 +371,8 @@ class EthereumMMGenTX(MMGenTX):
 			if exit_on_fail: sys.exit(1)
 			return False
 		else:
-			m = 'BOGUS transaction NOT sent: {}' if bogus_send else 'Transaction sent: {}'
-			if not bogus_send:
+			m = 'BOGUS transaction NOT sent: {}' if g.bogus_send else 'Transaction sent: {}'
+			if not g.bogus_send:
 				assert ret == '0x'+self.coin_txid,'txid mismatch (after sending)'
 			self.desc = 'sent transaction'
 			msg(m.format(self.coin_txid.hl()))

+ 16 - 5
mmgen/globalvars.py

@@ -30,8 +30,6 @@ import sys,os
 
 class g(object):
 
-	skip_segwit_active_check = bool(os.getenv('MMGEN_TEST_SUITE'))
-
 	def die(ev=0,s=''):
 		if s: sys.stderr.write(s+'\n')
 		sys.exit(ev)
@@ -88,6 +86,7 @@ class g(object):
 	rpc_port             = 0
 	rpc_user             = ''
 	rpc_password         = ''
+	rpc_fail_on_command  = ''
 	rpch                 = None # global RPC handle
 
 	bob                  = False
@@ -95,7 +94,10 @@ class g(object):
 
 	# test suite:
 	bogus_wallet_data    = ''
+	bogus_send           = False
 	debug_utf8           = False
+	traceback            = False
+	test_suite           = False
 
 	for k in ('win','linux'):
 		if sys.platform[:len(k)] == k:
@@ -142,22 +144,31 @@ class g(object):
 		'eth_mainnet_chain_name','eth_testnet_chain_name',
 		'max_tx_file_size','max_input_size'
 	)
+	# Supported environmental vars
+	# The corresponding vars (lowercase, minus 'mmgen_') must be initialized in g
+	# 'DISABLE_' env vars disable the corresponding var in g
 	env_opts = (
+		'MMGEN_DEBUG_ALL', # special: there is no g.debug_all var
+
+		'MMGEN_TEST_SUITE',
 		'MMGEN_BOGUS_WALLET_DATA',
-		'MMGEN_DEBUG_ALL',
+		'MMGEN_BOGUS_SEND',
 		'MMGEN_DEBUG',
 		'MMGEN_DEBUG_OPTS',
 		'MMGEN_DEBUG_RPC',
 		'MMGEN_DEBUG_ADDRLIST',
 		'MMGEN_DEBUG_UTF8',
 		'MMGEN_QUIET',
-		'MMGEN_DISABLE_COLOR',
 		'MMGEN_FORCE_256_COLOR',
 		'MMGEN_MIN_URANDCHARS',
 		'MMGEN_NO_LICENSE',
 		'MMGEN_RPC_HOST',
+		'MMGEN_RPC_FAIL_ON_COMMAND',
 		'MMGEN_TESTNET',
-		'MMGEN_REGTEST'
+		'MMGEN_REGTEST',
+		'MMGEN_TRACEBACK',
+
+		'MMGEN_DISABLE_COLOR',
 	)
 
 	min_screen_width = 80

+ 2 - 1
mmgen/obj.py

@@ -122,7 +122,8 @@ class InitErrors(object):
 
 	@staticmethod
 	def init_fail(m,on_fail):
-		if os.getenv('MMGEN_TRACEBACK'): on_fail == 'raise'
+		from mmgen.globalvars import g
+		if g.traceback: on_fail == 'raise'
 		from mmgen.util import die,msg
 		if   on_fail == 'silent': return None # TODO: return False instead?
 		elif on_fail == 'raise':  raise ValueError(m)

+ 5 - 5
mmgen/opts.py

@@ -161,11 +161,11 @@ def override_from_env():
 	from mmgen.util import set_for_type
 	for name in g.env_opts:
 		if name == 'MMGEN_DEBUG_ALL': continue
-		idx,invert_bool = ((6,False),(14,True))[name[:14]=='MMGEN_DISABLE_']
+		disable = name[:14] == 'MMGEN_DISABLE_'
 		val = os.getenv(name) # os.getenv() returns None if env var is unset
-		if val: # exclude empty string values too
-			gname = name[idx:].lower()
-			setattr(g,gname,set_for_type(val,getattr(g,gname),name,invert_bool))
+		if val: # exclude empty string values; string value of '0' or 'false' sets variable to False
+			gname = name[(6,14)[disable]:].lower()
+			setattr(g,gname,set_for_type(val,getattr(g,gname),name,disable))
 
 def warn_altcoins(trust_level):
 	if trust_level == None: return
@@ -176,7 +176,7 @@ responsibility for any loss of funds you may incur.
 This coin's {pn} testing status: {}
 Are you sure you want to continue?
 """.strip().format(g.coin,tl[trust_level],pn=g.proj_name)
-	if os.getenv('MMGEN_TEST_SUITE'):
+	if g.test_suite:
 		msg(m); return
 	if not keypress_confirm(m,default_yes=True):
 		sys.exit(0)

+ 1 - 1
mmgen/rpc.py

@@ -80,7 +80,7 @@ class CoinDaemonRPCConnection(object):
 	# With on_fail='return', returns 'rpcfail',(resp_object,(die_args))
 	def request(self,cmd,*args,**kwargs):
 
-		if os.getenv('MMGEN_RPC_FAIL_ON_COMMAND') == cmd:
+		if g.rpc_fail_on_command == cmd:
 			cmd = 'badcommand_' + cmd
 
 		cf = { 'timeout':g.http_timeout, 'batch':False, 'on_fail':'raise' }

+ 2 - 2
mmgen/term.py

@@ -38,7 +38,7 @@ except:
 
 def _kb_hold_protect_unix():
 
-	if os.getenv('MMGEN_TEST_SUITE'): return
+	if g.test_suite: return
 
 	fd = sys.stdin.fileno()
 	old = termios.tcgetattr(fd)
@@ -64,7 +64,7 @@ def _get_keypress_unix(prompt='',immed_chars='',prehold_protect=True,num_chars=5
 	old = termios.tcgetattr(fd)
 	tty.setcbreak(fd)
 	immed_chars = immed_chars.encode()
-	if os.getenv('MMGEN_TEST_SUITE'): prehold_protect = False
+	if g.test_suite: prehold_protect = False
 	while True:
 		# Protect against held-down key before read()
 		key = select([sys.stdin], [], [], timeout)[0]

+ 5 - 7
mmgen/tx.py

@@ -89,7 +89,7 @@ def segwit_is_active(exit_on_error=False):
 			and 'segwit' in d['bip9_softforks']
 			and d['bip9_softforks']['segwit']['status'] == 'active'):
 		return True
-	if g.skip_segwit_active_check:
+	if g.test_suite:
 		return True
 	if exit_on_error:
 		die(2,'Segwit not active on this chain.  Exiting')
@@ -731,7 +731,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 			msg('OK')
 			return True
 		except Exception as e:
-			if os.getenv('MMGEN_TRACEBACK'):
+			if g.traceback:
 				import traceback
 				ymsg('\n'+''.join(traceback.format_exception(*sys.exc_info())))
 			try: m = '{}'.format(e.args[0])
@@ -897,9 +897,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 
 		self.check_hex_tx_matches_mmgen_tx(DeserializedTX(self.hex))
 
-		bogus_send = os.getenv('MMGEN_BOGUS_SEND')
-
-		if self.has_segwit_outputs() and not segwit_is_active() and not bogus_send:
+		if self.has_segwit_outputs() and not segwit_is_active() and not g.bogus_send:
 			m = 'Transaction has MMGen Segwit outputs, but this blockchain does not support Segwit'
 			die(2,m+' at the current height')
 
@@ -911,7 +909,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 
 		if prompt_user: self.confirm_send()
 
-		ret = None if bogus_send else g.rpch.sendrawtransaction(self.hex,on_fail='return')
+		ret = None if g.bogus_send else g.rpch.sendrawtransaction(self.hex,on_fail='return')
 
 		from mmgen.rpc import rpc_error,rpc_errmsg
 		if rpc_error(ret):
@@ -932,7 +930,7 @@ Selected non-{pnm} inputs: {{}}""".strip().format(pnm=g.proj_name,pnl=g.proj_nam
 			if exit_on_fail: sys.exit(1)
 			return False
 		else:
-			if bogus_send:
+			if g.bogus_send:
 				m = 'BOGUS transaction NOT sent: {}'
 			else:
 				assert ret == self.coin_txid, 'txid mismatch (after sending)'