Browse Source

New options for write_data_to_file(); minor fixes

New options:
- 'ignore_opt_outdir': override creation of absolute path
- 'check_data','cmp_data': check data before writing
MMGen 6 years ago
parent
commit
80df86aca7
4 changed files with 35 additions and 22 deletions
  1. 1 0
      mmgen/altcoins/eth/tw.py
  2. 2 2
      mmgen/test.py
  3. 25 14
      mmgen/util.py
  4. 7 6
      test/test.py

+ 1 - 0
mmgen/altcoins/eth/tw.py

@@ -135,6 +135,7 @@ class EthereumTwAddrList(TwAddrList):
 		rpc_init()
 		rpc_init()
 #		cur_blk = int(g.rpch.eth_blockNumber(),16)
 #		cur_blk = int(g.rpch.eth_blockNumber(),16)
 
 
+		from mmgen.obj import CoinAddr
 		for mmid,d in tw.items():
 		for mmid,d in tw.items():
 #			if d['confirmations'] < minconf: continue
 #			if d['confirmations'] < minconf: continue
 			label = TwLabel(mmid+' '+d['comment'],on_fail='raise')
 			label = TwLabel(mmid+' '+d['comment'],on_fail='raise')

+ 2 - 2
mmgen/test.py

@@ -82,8 +82,8 @@ def write_to_tmpfile(cfg,fn,data,binary=False):
 		os.path.join(cfg['tmpdir'],fn),
 		os.path.join(cfg['tmpdir'],fn),
 		data,
 		data,
 		silent=True,
 		silent=True,
-		binary=binary
-	)
+		binary=binary,
+		ignore_opt_outdir=True)
 
 
 def read_from_file(fn,binary=False):
 def read_from_file(fn,binary=False):
 	from mmgen.util import get_data_from_file
 	from mmgen.util import get_data_from_file

+ 25 - 14
mmgen/util.py

@@ -528,19 +528,18 @@ def confirm_or_exit(message,q,expect='YES',exit_msg='Exiting at user request'):
 	if my_raw_input(a+b).strip() != expect:
 	if my_raw_input(a+b).strip() != expect:
 		die(1,exit_msg)
 		die(1,exit_msg)
 
 
-def write_data_to_file(
-		outfile,
-		data,
-		desc='data',
-		ask_write=False,
-		ask_write_prompt='',
-		ask_write_default_yes=True,
-		ask_overwrite=True,
-		ask_tty=True,
-		no_tty=False,
-		silent=False,
-		binary=False
-	):
+def write_data_to_file( outfile,data,desc='data',
+						ask_write=False,
+						ask_write_prompt='',
+						ask_write_default_yes=True,
+						ask_overwrite=True,
+						ask_tty=True,
+						no_tty=False,
+						silent=False,
+						binary=False,
+						ignore_opt_outdir=False,
+						check_data=False,
+						cmp_data=None):
 
 
 	if silent: ask_tty = ask_overwrite = False
 	if silent: ask_tty = ask_overwrite = False
 	if opt.quiet: ask_overwrite = False
 	if opt.quiet: ask_overwrite = False
@@ -581,7 +580,7 @@ def write_data_to_file(
 		sys.stdout.write(data)
 		sys.stdout.write(data)
 
 
 	def do_file(outfile,ask_write_prompt):
 	def do_file(outfile,ask_write_prompt):
-		if opt.outdir and not os.path.isabs(outfile):
+		if opt.outdir and not ignore_opt_outdir and not os.path.isabs(outfile):
 			outfile = make_full_path(opt.outdir,outfile)
 			outfile = make_full_path(opt.outdir,outfile)
 
 
 		if ask_write:
 		if ask_write:
@@ -597,6 +596,18 @@ def write_data_to_file(
 			msg(u"Overwriting file '{}'".format(outfile))
 			msg(u"Overwriting file '{}'".format(outfile))
 			hush = True
 			hush = True
 
 
+		# not atomic, but better than nothing
+		# if cmp_data is empty, file can be either empty or non-existent
+		if check_data:
+			try:
+				d = open(outfile,('r','rb')[bool(binary)]).read()
+			except:
+				d = ''
+			finally:
+				if d != cmp_data:
+					m = u"{} in file '{}' has been altered by some other program!  Aborting file write"
+					die(3,m.format(desc,outfile))
+
 		f = open_file_or_exit(outfile,('w','wb')[bool(binary)])
 		f = open_file_or_exit(outfile,('w','wb')[bool(binary)])
 		try:
 		try:
 			f.write(data)
 			f.write(data)

+ 7 - 6
test/test.py

@@ -1184,7 +1184,8 @@ def create_fake_unspent_data(adata,tx_data,non_mmgen_input='',non_mmgen_input_co
 		privkey = PrivKey(os.urandom(32),compressed=non_mmgen_input_compressed,pubkey_type='std')
 		privkey = PrivKey(os.urandom(32),compressed=non_mmgen_input_compressed,pubkey_type='std')
 		rand_coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator('std').to_pubhex(privkey))
 		rand_coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator('std').to_pubhex(privkey))
 		of = os.path.join(cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
 		of = os.path.join(cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
-		write_data_to_file(of,privkey.wif+'\n','compressed {} key'.format(g.proto.name),silent=True)
+		write_data_to_file(of,  privkey.wif+'\n','compressed {} key'.format(g.proto.name),
+								silent=True,ignore_opt_outdir=True)
 		out.append(create_fake_unspent_entry(rand_coinaddr,non_mmgen=True,segwit=False))
 		out.append(create_fake_unspent_entry(rand_coinaddr,non_mmgen=True,segwit=False))
 
 
 #	msg('\n'.join([repr(o) for o in out])); sys.exit(0)
 #	msg('\n'.join([repr(o) for o in out])); sys.exit(0)
@@ -1192,7 +1193,7 @@ def create_fake_unspent_data(adata,tx_data,non_mmgen_input='',non_mmgen_input_co
 
 
 def write_fake_data_to_file(d):
 def write_fake_data_to_file(d):
 	unspent_data_file = os.path.join(cfg['tmpdir'],u'unspent.json')
 	unspent_data_file = os.path.join(cfg['tmpdir'],u'unspent.json')
-	write_data_to_file(unspent_data_file,d,'Unspent outputs',silent=True)
+	write_data_to_file(unspent_data_file,d,'Unspent outputs',silent=True,ignore_opt_outdir=True)
 	os.environ['MMGEN_BOGUS_WALLET_DATA'] = unspent_data_file.encode('utf8')
 	os.environ['MMGEN_BOGUS_WALLET_DATA'] = unspent_data_file.encode('utf8')
 	bwd_msg = u'MMGEN_BOGUS_WALLET_DATA={}'.format(unspent_data_file)
 	bwd_msg = u'MMGEN_BOGUS_WALLET_DATA={}'.format(unspent_data_file)
 	if opt.print_cmdline: msg(bwd_msg)
 	if opt.print_cmdline: msg(bwd_msg)
@@ -1254,7 +1255,7 @@ def add_comments_to_addr_file(addrfile,outfile,use_labels=False):
 		else:
 		else:
 			if n % 2: a.set_comment(idx,'Test address {}'.format(n))
 			if n % 2: a.set_comment(idx,'Test address {}'.format(n))
 	a.format(enable_comments=True)
 	a.format(enable_comments=True)
-	write_data_to_file(outfile,a.fmt_data,silent=True)
+	write_data_to_file(outfile,a.fmt_data,silent=True,ignore_opt_outdir=True)
 	end_silence()
 	end_silence()
 
 
 # 100 words chosen randomly from here:
 # 100 words chosen randomly from here:
@@ -1278,7 +1279,7 @@ def make_brainwallet_file(fn):
 	rand_pairs = [wl[getrandnum_range(1,200) % len(wl)] + rand_ws_seq() for i in range(nwords)]
 	rand_pairs = [wl[getrandnum_range(1,200) % len(wl)] + rand_ws_seq() for i in range(nwords)]
 	d = ''.join(rand_pairs).rstrip() + '\n'
 	d = ''.join(rand_pairs).rstrip() + '\n'
 	if opt.verbose: msg_r('Brainwallet password:\n{}'.format(cyan(d)))
 	if opt.verbose: msg_r('Brainwallet password:\n{}'.format(cyan(d)))
-	write_data_to_file(fn,d,'brainwallet password',silent=True)
+	write_data_to_file(fn,d,'brainwallet password',silent=True,ignore_opt_outdir=True)
 
 
 def do_between():
 def do_between():
 	if opt.pause:
 	if opt.pause:
@@ -3055,8 +3056,8 @@ class MMGenTestSuite(object):
 		fn_mn = fn.replace('.rawtx','.mainnet.rawtx')
 		fn_mn = fn.replace('.rawtx','.mainnet.rawtx')
 		ok()
 		ok()
 
 
-		write_data_to_file(fn_tn,o_tn,'testnet TX data',ask_overwrite=False)
-		write_data_to_file(fn_mn,o_mn,'mainnet TX data',ask_overwrite=False)
+		write_data_to_file(fn_tn,o_tn,'testnet TX data',ask_overwrite=False,ignore_opt_outdir=True)
+		write_data_to_file(fn_mn,o_mn,'mainnet TX data',ask_overwrite=False,ignore_opt_outdir=True)
 
 
 	# END methods
 	# END methods
 	for k in (
 	for k in (