Browse Source

minor fixes and cleanups

The MMGen Project 3 years ago
parent
commit
d99c75216d
10 changed files with 41 additions and 28 deletions
  1. 3 2
      mmgen/daemon.py
  2. 2 2
      mmgen/opts.py
  3. 8 2
      mmgen/protocol.py
  4. 7 9
      mmgen/regtest.py
  5. 1 1
      mmgen/rpc.py
  6. 1 1
      mmgen/tw.py
  7. 3 3
      mmgen/tx.py
  8. 2 2
      test/test.py
  9. 1 1
      test/test_py_d/ts_ethdev.py
  10. 13 5
      test/test_py_d/ts_regtest.py

+ 3 - 2
mmgen/daemon.py

@@ -452,8 +452,9 @@ class CoinDaemon(Daemon):
 	def pre_start(self):
 	def pre_start(self):
 		os.makedirs(self.datadir,exist_ok=True)
 		os.makedirs(self.datadir,exist_ok=True)
 
 
-		if self.cfg_file and not self.flag.keep_cfg_file:
-			open(f'{self.datadir}/{self.cfg_file}','w').write(self.cfg_file_hdr)
+		if self.test_suite or self.network == 'regtest':
+			if self.cfg_file and not self.flag.keep_cfg_file:
+				open(f'{self.datadir}/{self.cfg_file}','w').write(self.cfg_file_hdr)
 
 
 		if self.use_pidfile and os.path.exists(self.pidfile):
 		if self.use_pidfile and os.path.exists(self.pidfile):
 			# Parity overwrites the data in the existing pidfile without zeroing it first, leading
 			# Parity overwrites the data in the existing pidfile without zeroing it first, leading

+ 2 - 2
mmgen/opts.py

@@ -288,7 +288,7 @@ def init(opts_data=None,add_opts=None,init_opts=None,opt_filter=None,parse_only=
 	from .term import init_term
 	from .term import init_term
 	init_term()
 	init_term()
 
 
-	if not opt.skip_cfg_file:
+	if not (opt.skip_cfg_file or opt.bob or opt.alice or g.prog_name == 'mmgen-regtest'):
 		from .cfg import cfg_file
 		from .cfg import cfg_file
 		# check for changes in system template file - term must be initialized
 		# check for changes in system template file - term must be initialized
 		cfg_file('sample')
 		cfg_file('sample')
@@ -333,7 +333,7 @@ def init(opts_data=None,add_opts=None,init_opts=None,opt_filter=None,parse_only=
 	g.coin = g.coin.upper() or 'BTC'
 	g.coin = g.coin.upper() or 'BTC'
 	g.token = g.token.upper() or None
 	g.token = g.token.upper() or None
 
 
-	if g.prog_name == 'mmgen-regtest' or g.bob or g.alice:
+	if g.bob or g.alice or g.prog_name == 'mmgen-regtest':
 		g.regtest = True
 		g.regtest = True
 		g.rpc_host = 'localhost'
 		g.rpc_host = 'localhost'
 		g.data_dir = os.path.join(g.data_dir_root,'regtest',g.coin.lower(),('alice','bob')[g.bob])
 		g.data_dir = os.path.join(g.data_dir_root,'regtest',g.coin.lower(),('alice','bob')[g.bob])

+ 8 - 2
mmgen/protocol.py

@@ -265,7 +265,10 @@ class CoinProtocol(MMGenObject):
 			else:
 			else:
 				raise ValueError(f'{len(key)}: invalid key length')
 				raise ValueError(f'{len(key)}: invalid key length')
 
 
-			return parsed_wif(key[:self.privkey_len], pubkey_type, compressed)
+			return parsed_wif(
+				sec         = key[:self.privkey_len],
+				pubkey_type = pubkey_type,
+				compressed  = compressed )
 
 
 		def parse_addr(self,addr):
 		def parse_addr(self,addr):
 
 
@@ -375,7 +378,10 @@ class CoinProtocol(MMGenObject):
 			return hexpriv
 			return hexpriv
 
 
 		def parse_wif(self,wif):
 		def parse_wif(self,wif):
-			return parsed_wif(bytes.fromhex(wif), self.pubkey_type, False)
+			return parsed_wif(
+				sec         = bytes.fromhex(wif),
+				pubkey_type = self.pubkey_type,
+				compressed  = False )
 
 
 	class Ethereum(DummyWIF,Secp256k1):
 	class Ethereum(DummyWIF,Secp256k1):
 
 

+ 7 - 9
mmgen/regtest.py

@@ -40,15 +40,15 @@ def create_data_dir(data_dir):
 	except: pass
 	except: pass
 
 
 def create_hdseed(proto):
 def create_hdseed(proto):
-	# cTqgRxqSER1iZ4SoUKhaXUF3PzEADyhjHPXf19KW78GGGW7RxSWz hdseed=1
-	#   addr=bcrt1q2lew38703pdzvq529hefsl9f9z9a3j3mxwt4f0
-	# cPNPEyVQpX5H9MKDwt73BScKvDh3Kk8MMEGowneT2RKFZ7Dfh3FL label=
-	#   addr=bcrt1qy7hwy8jx7w7lmm8v63hur5xzvqqhcyk8w85v9h hdkeypath=m/0'/0'/0'
+	# cTyMdQ2BgfAsjopRVZrj7AoEGp97pKfrC2NkqLuwHr4KHfPNAKwp hdseed=1
+	#   addr=bcrt1qaq8t3pakcftpk095tnqfv5cmmczysls024atnd
+	# cTEkSYCWKvNo757uwFPd4yuCXsbZvfJDipHsHWFRapXpnikMHvgn label=
+	#   addr=bcrt1q537rgyctcqdgs8nm8gvku05znka4h2m00lx8ps hdkeypath=m/0'/0'/0'
 	from .tool import tool_api
 	from .tool import tool_api
 	t = tool_api()
 	t = tool_api()
 	t.init_coin(proto.coin,proto.network)
 	t.init_coin(proto.coin,proto.network)
 	t.addrtype = 'bech32'
 	t.addrtype = 'bech32'
-	return t.hex2wif('babaeb1a'*8)
+	return t.hex2wif('beadcafe'*8)
 
 
 def cliargs_convert(args):
 def cliargs_convert(args):
 	def gen():
 	def gen():
@@ -122,7 +122,7 @@ class MMGenRegtest(MMGenObject):
 
 
 		rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
 		rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
 		for user in ('miner','bob','alice'):
 		for user in ('miner','bob','alice'):
-			gmsg(f'Creating {capfirst(user)}’s wallet')
+			gmsg(f'Creating {capfirst(user)}’s tracking wallet')
 			await rpc.icall(
 			await rpc.icall(
 				'createwallet',
 				'createwallet',
 				wallet_name     = user,
 				wallet_name     = user,
@@ -159,8 +159,6 @@ class MMGenRegtest(MMGenObject):
 			await self.rpc_call('loadwallet',user,start_daemon=False)
 			await self.rpc_call('loadwallet',user,start_daemon=False)
 
 
 	async def rpc_call(self,*args,wallet=None,start_daemon=True):
 	async def rpc_call(self,*args,wallet=None,start_daemon=True):
-		# g.prog_name == 'mmgen-regtest' test is used by .rpc to identify caller, so require this:
-		assert g.prog_name == 'mmgen-regtest', 'only mmgen-regtest util is allowed to use this method'
 		if start_daemon and self.d.state == 'stopped':
 		if start_daemon and self.d.state == 'stopped':
 			await self.start_daemon()
 			await self.start_daemon()
 		rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
 		rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
@@ -177,7 +175,7 @@ class MMGenRegtest(MMGenObject):
 			msg(f'{g.coin} regtest daemon already stopped')
 			msg(f'{g.coin} regtest daemon already stopped')
 		else:
 		else:
 			msg(f'Stopping {g.coin} regtest daemon')
 			msg(f'Stopping {g.coin} regtest daemon')
-			await self.rpc_call('stop',start_daemon=False)
+			self.d.stop(silent=True)
 
 
 	def state(self):
 	def state(self):
 		msg(self.d.state)
 		msg(self.d.state)

+ 1 - 1
mmgen/rpc.py

@@ -464,7 +464,7 @@ class BitcoinRPCClient(RPCClient,metaclass=AsyncInit):
 			if len((await self.call('help',func)).split('\n')) > 3:
 			if len((await self.call('help',func)).split('\n')) > 3:
 				self.caps += (cap,)
 				self.caps += (cap,)
 
 
-		if not (g.prog_name == 'mmgen-regtest' or g.bob or g.alice):
+		if not self.chain == 'regtest':
 			await self.check_tracking_wallet()
 			await self.check_tracking_wallet()
 
 
 	async def check_tracking_wallet(self,wallet_checked=[]):
 	async def check_tracking_wallet(self,wallet_checked=[]):

+ 1 - 1
mmgen/tw.py

@@ -797,7 +797,7 @@ class TrackingWallet(MMGenObject,metaclass=AsyncInit):
 		if g.debug:
 		if g.debug:
 			print_stack_trace(f'TW DEL {self!r}')
 			print_stack_trace(f'TW DEL {self!r}')
 
 
-		if self.mode == 'w':
+		if getattr(self,'mode',None) == 'w': # mode attr might not exist in this state
 			self.write()
 			self.write()
 		elif g.debug:
 		elif g.debug:
 			msg('read-only wallet, doing nothing')
 			msg('read-only wallet, doing nothing')

+ 3 - 3
mmgen/tx.py

@@ -1466,13 +1466,13 @@ class MMGenTX:
 					ret = False
 					ret = False
 
 
 			if ret == False: # TODO: test send errors
 			if ret == False: # TODO: test send errors
-				if 'Signature must use SIGHASH_FORKID' in errmsg:
+				if errmsg.count('Signature must use SIGHASH_FORKID'):
 					m = ('The Aug. 1 2017 UAHF has activated on this chain.\n'
 					m = ('The Aug. 1 2017 UAHF has activated on this chain.\n'
 						+ 'Re-run the script with the --coin=bch option.' )
 						+ 'Re-run the script with the --coin=bch option.' )
-				elif 'Illegal use of SIGHASH_FORKID' in errmsg:
+				elif errmsg.count('Illegal use of SIGHASH_FORKID'):
 					m  = ('The Aug. 1 2017 UAHF is not yet active on this chain.\n'
 					m  = ('The Aug. 1 2017 UAHF is not yet active on this chain.\n'
 						+ 'Re-run the script without the --coin=bch option.' )
 						+ 'Re-run the script without the --coin=bch option.' )
-				elif '64: non-final' in errmsg:
+				elif errmsg.count('64: non-final'):
 					m = "Transaction with nLockTime {!r} can't be included in this block!".format(
 					m = "Transaction with nLockTime {!r} can't be included in this block!".format(
 						strfmt_locktime(self.get_hex_locktime()) )
 						strfmt_locktime(self.get_hex_locktime()) )
 				else:
 				else:

+ 2 - 2
test/test.py

@@ -735,8 +735,8 @@ class TestSuiteRunner(object):
 	def end_msg(self):
 	def end_msg(self):
 		t = int(time.time() - self.start_time)
 		t = int(time.time() - self.start_time)
 		sys.stderr.write(green(
 		sys.stderr.write(green(
-			f'{self.cmd_total} test{suf(self.cmd_total)} performed.' +
-			('' if opt.no_timings else f'  Elapsed time: {t//60:02d}:{t%60:02d}\n')
+			f'{self.cmd_total} test{suf(self.cmd_total)} performed' +
+			('\n' if opt.no_timings else f'.  Elapsed time: {t//60:02d}:{t%60:02d}\n')
 		))
 		))
 
 
 	def init_group(self,gname,cmd=None,quiet=False,do_clean=True):
 	def init_group(self,gname,cmd=None,quiet=False,do_clean=True):

+ 1 - 1
test/test_py_d/ts_ethdev.py

@@ -44,7 +44,7 @@ dfl_devkey = '4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7'
 prealloc_amt = ETHAmt('1_000_000_000')
 prealloc_amt = ETHAmt('1_000_000_000')
 
 
 burn_addr  = 'deadbeef'*5
 burn_addr  = 'deadbeef'*5
-burn_addr2 = 'babaeb1a'*5
+burn_addr2 = 'beadcafe'*5
 
 
 amt1 = '999999.12345689012345678'
 amt1 = '999999.12345689012345678'
 amt2 = '888.111122223333444455'
 amt2 = '888.111122223333444455'

+ 13 - 5
test/test_py_d/ts_regtest.py

@@ -141,6 +141,7 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 	extra_spawn_args = ['--regtest=1']
 	extra_spawn_args = ['--regtest=1']
 	tmpdir_nums = [17]
 	tmpdir_nums = [17]
 	color = True
 	color = True
+	test_rbf = False
 	cmd_group = (
 	cmd_group = (
 		('setup',                    'regtest (Bob and Alice) mode setup'),
 		('setup',                    'regtest (Bob and Alice) mode setup'),
 		('daemon_version',           'mmgen-tool daemon_version'),
 		('daemon_version',           'mmgen-tool daemon_version'),
@@ -255,6 +256,9 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 		for k in rt_data:
 		for k in rt_data:
 			globals()[k] = rt_data[k][coin] if coin in rt_data[k] else None
 			globals()[k] = rt_data[k][coin] if coin in rt_data[k] else None
 
 
+		if self.proto.coin == 'BTC':
+			self.test_rbf = True # tests are non-coin-dependent, so run just once for BTC
+
 		os.environ['MMGEN_BOGUS_SEND'] = ''
 		os.environ['MMGEN_BOGUS_SEND'] = ''
 
 
 	def __del__(self):
 	def __del__(self):
@@ -369,7 +373,8 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 	def addrimport_alice(self): return self.addrimport('alice')
 	def addrimport_alice(self): return self.addrimport('alice')
 
 
 	def fund_wallet(self,user,mmtype,amt,sid=None,addr_range='1-5'):
 	def fund_wallet(self,user,mmtype,amt,sid=None,addr_range='1-5'):
-		if not sid: sid = self._user_sid(user)
+		if not sid:
+			sid = self._user_sid(user)
 		addr = self.get_addr_from_addrlist(user,sid,mmtype,0,addr_range=addr_range)
 		addr = self.get_addr_from_addrlist(user,sid,mmtype,0,addr_range=addr_range)
 		t = self.spawn('mmgen-regtest', ['send',str(addr),str(amt)])
 		t = self.spawn('mmgen-regtest', ['send',str(addr),str(amt)])
 		t.expect(f'Sending {amt} miner {self.proto.coin}')
 		t.expect(f'Sending {amt} miner {self.proto.coin}')
@@ -543,7 +548,8 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 			do_label     = False,
 			do_label     = False,
 			bad_locktime = False,
 			bad_locktime = False,
 			full_tx_view = False,
 			full_tx_view = False,
-			menu         = ['M'] ):
+			menu         = ['M'],
+			skip_passphrase = False ):
 
 
 		t = self.spawn('mmgen-txdo',
 		t = self.spawn('mmgen-txdo',
 			['-d',self.tmpdir,'-B','--'+user] +
 			['-d',self.tmpdir,'-B','--'+user] +
@@ -559,7 +565,9 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 			add_comment     = tx_label_jp,
 			add_comment     = tx_label_jp,
 			view            = 't',save=True)
 			view            = 't',save=True)
 
 
-		t.passphrase(dfl_wcls.desc,rt_pw)
+		if not skip_passphrase:
+			t.passphrase(dfl_wcls.desc,rt_pw)
+
 		t.written_to_file('Signed transaction')
 		t.written_to_file('Signed transaction')
 		self._do_confirm_send(t)
 		self._do_confirm_send(t)
 		s,exit_val = (('Transaction sent',0),("can't be included",1))[bad_locktime]
 		s,exit_val = (('Transaction sent',0),("can't be included",1))[bad_locktime]
@@ -587,14 +595,14 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 		return [self.get_addr_from_addrlist(user,sid,mmtype,idx-1)+amt_str for mmtype,idx,amt_str in data]
 		return [self.get_addr_from_addrlist(user,sid,mmtype,idx-1)+amt_str for mmtype,idx,amt_str in data]
 
 
 	def bob_rbf_1output_create(self):
 	def bob_rbf_1output_create(self):
-		if self.proto.coin != 'BTC': # non-coin-dependent test, so run just once for BTC
+		if not self.test_rbf:
 			return 'skip'
 			return 'skip'
 		out_addr = self._create_tx_outputs('alice',(('B',5,''),))
 		out_addr = self._create_tx_outputs('alice',(('B',5,''),))
 		t = self.spawn('mmgen-txcreate',['-d',self.tr.trash_dir,'-B','--bob','--rbf'] + out_addr)
 		t = self.spawn('mmgen-txcreate',['-d',self.tr.trash_dir,'-B','--bob','--rbf'] + out_addr)
 		return self.txcreate_ui_common(t,menu=[],inputs='3',interactive_fee='3s') # out amt: 199.99999343
 		return self.txcreate_ui_common(t,menu=[],inputs='3',interactive_fee='3s') # out amt: 199.99999343
 
 
 	def bob_rbf_1output_bump(self):
 	def bob_rbf_1output_bump(self):
-		if self.proto.coin != 'BTC':
+		if not self.test_rbf:
 			return 'skip'
 			return 'skip'
 		ext = '9343,3]{x}.regtest.rawtx'.format(x='-α' if g.debug_utf8 else '')
 		ext = '9343,3]{x}.regtest.rawtx'.format(x='-α' if g.debug_utf8 else '')
 		txfile = get_file_with_ext(self.tr.trash_dir,ext,delete=False,no_dot=True)
 		txfile = get_file_with_ext(self.tr.trash_dir,ext,delete=False,no_dot=True)