Browse Source

test suite: use getrand() instead of os.urandom()

The MMGen Project 3 years ago
parent
commit
0493f8077b

+ 3 - 2
test/gentest.py

@@ -28,6 +28,7 @@ os.environ['MMGEN_TEST_SUITE'] = '1'
 
 # Import these _after_ local path's been added to sys.path
 from mmgen.common import *
+from test.include.common import getrand
 
 rounds = 100
 opts_data = {
@@ -308,14 +309,14 @@ def gentool_test(kg_a,kg_b,ag,rounds):
 
 	qmsg(purple('random input:'))
 	for i in range(rounds):
-		do_compare_test(i,rounds,os.urandom(32))
+		do_compare_test(i,rounds,getrand(32))
 	qmsg(green('\rOK            ' if opt.verbose else 'OK'))
 
 def speed_test(kg,ag,rounds):
 	m = "Testing speed of address generator '{}' for coin {}"
 	qmsg(green(m.format(kg.desc,proto.coin)))
 	from struct import pack,unpack
-	seed = os.urandom(28)
+	seed = getrand(28)
 	qmsg('Incrementing key with each round')
 	qmsg('Starting key: {}'.format(
 		(seed + pack('I',0)).hex()

+ 3 - 2
test/hashfunc.py

@@ -22,6 +22,7 @@ test/hashfunc.py: Test internal implementations of SHA256, SHA512 and Keccak256
 import sys,os
 import include.tests_header
 from mmgen.util import die
+from test.include.common import getrand
 
 assert len(sys.argv) in (2,3),"Test takes 1 or 2 arguments: test name, plus optional rounds count"
 test = sys.argv[1].capitalize()
@@ -76,8 +77,8 @@ class TestHashFunc(object):
 		for i in range(rounds):
 			if i+1 in (1,rounds) or not (i+1) % 10:
 				msg(f'\rTesting random input data:    {i+1:4}/{rounds} ')
-			dlen = int(os.urandom(4).hex(),16) >> 18
-			self.compare_hashes(dlen,os.urandom(dlen))
+			dlen = int(getrand(4).hex(),16) >> 18
+			self.compare_hashes(dlen,getrand(dlen))
 		msg('OK\n')
 
 class TestKeccak(TestHashFunc):

+ 6 - 7
test/include/common.py

@@ -66,25 +66,24 @@ sample_mn = {
 ref_kafile_pass = 'kafile password'
 ref_kafile_hash_preset = '1'
 
-def ts_urandom(n):
-	assert n < 70, f'{n} > len(sample_text) (69 bytes)'
-	return sample_text.encode()[:n] if g.test_suite_deterministic else os.urandom(n)
+def getrand(n):
+	return os.urandom(n)
 
 def getrandnum(n):
-	return int(ts_urandom(n).hex(),16)
+	return int(getrand(n).hex(),16)
 
 def getrandhex(n):
-	return ts_urandom(n).hex()
+	return getrand(n).hex()
 
 def getrandnum_range(nbytes,rn_max):
 	while True:
-		rn = int(ts_urandom(nbytes).hex(),16)
+		rn = int(getrand(nbytes).hex(),16)
 		if rn < rn_max:
 			return rn
 
 def getrandstr(num_chars,no_space=False):
 	n,m = (94,33) if no_space else (95,32)
-	return ''.join([chr(i%n+m) for i in list(os.urandom(num_chars))])
+	return ''.join( chr(i % n + m) for i in list(getrand(num_chars)) )
 
 def get_data_dir():
 	return os.path.join('test','data_dir' + ('','-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])

+ 2 - 1
test/objattrtest_py_d/oat_common.py

@@ -16,11 +16,12 @@ from mmgen.protocol import *
 from mmgen.addr import *
 from mmgen.tx import *
 from mmgen.tw import *
+from ..include.common import getrand
 
 from collections import namedtuple
 atd = namedtuple('attrtest_entry',['attrs','args','kwargs'])
 
-seed_bin = os.urandom(32)
+seed_bin = getrand(32)
 
 # use the constructors here! otherwise reassignment test might fail when
 # reassignment would otherwise succeed

+ 1 - 1
test/objtest_py_d/ot_common.py

@@ -11,4 +11,4 @@ import os
 from mmgen.globalvars import g
 from ..include.common import *
 
-r32,r24,r16,r17,r18 = os.urandom(32),os.urandom(24),os.urandom(16),os.urandom(17),os.urandom(18)
+r32,r24,r16,r17,r18 = getrand(32),getrand(24),getrand(16),getrand(17),getrand(18)

+ 1 - 1
test/test_py_d/common.py

@@ -82,7 +82,7 @@ def confirm_continue():
 		raise KeyboardInterrupt('Exiting at user request')
 
 def randbool():
-	return os.urandom(1).hex()[0] in '02468ace'
+	return getrand(1).hex()[0] in '02468ace'
 
 def disable_debug():
 	global save_debug

+ 2 - 1
test/test_py_d/input.py

@@ -12,6 +12,7 @@ input.py: Shared input routines for the test.py test suite
 
 import os,time
 from .common import randbool
+from ..include.common import getrand
 
 def stealth_mnemonic_entry(t,mne,mn,entry_mode,pad_entry=False):
 
@@ -19,7 +20,7 @@ def stealth_mnemonic_entry(t,mne,mn,entry_mode,pad_entry=False):
 		def get_pad_chars(n):
 			ret = ''
 			for i in range(n):
-				m = int.from_bytes(os.urandom(1),'big') % 32
+				m = int.from_bytes(getrand(1),'big') % 32
 				ret += r'123579!@#$%^&*()_+-=[]{}"?/,.<>|'[m]
 			return ret
 		ret = []

+ 3 - 3
test/test_py_d/ts_main.py

@@ -312,7 +312,7 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
 				f'{self.proto.base_coin.lower()}:{coinaddr}' if non_mmgen
 				else f'{al_id}:{idx}{lbl}' ),
 			'vout': int(getrandnum(4) % 8),
-			'txid': os.urandom(32).hex(),
+			'txid': getrandhex(32),
 			'amount': self.proto.coin_amt('{}.{}'.format(
 				amt1 + getrandnum(4) % amt2,
 				getrandnum(4) % 100000000 )),
@@ -338,7 +338,7 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
 			from mmgen.obj import PrivKey
 			privkey = PrivKey(
 				self.proto,
-				os.urandom(32),
+				getrand(32),
 				compressed  = non_mmgen_input_compressed,
 				pubkey_type = 'std' )
 			from mmgen.addr import AddrGenerator,KeyGenerator
@@ -379,7 +379,7 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
 
 	def _make_txcreate_cmdline(self,tx_data):
 		from mmgen.obj import PrivKey
-		privkey = PrivKey(self.proto,os.urandom(32),compressed=True,pubkey_type='std')
+		privkey = PrivKey(self.proto,getrand(32),compressed=True,pubkey_type='std')
 		t = ('compressed','segwit')['S' in self.proto.mmtypes]
 		from mmgen.addr import AddrGenerator,KeyGenerator
 		rand_coinaddr = AddrGenerator(self.proto,t).to_addr(KeyGenerator(self.proto,'std').to_pubhex(privkey))

+ 7 - 5
test/test_py_d/ts_regtest.py

@@ -736,11 +736,13 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
 		from mmgen.tool import tool_api
 		t = tool_api()
 		t.init_coin(self.proto.coin,self.proto.network)
-		t.usr_randchars = 0
-		t.addrtype = 'legacy'
-		ret = [t.randpair()]
-		t.addrtype = 'compressed'
-		return ret + [t.randpair() for i in range(n-1)]
+
+		def gen_addr(Type):
+			t.addrtype = Type
+			wif = t.hex2wif(getrandhex(32))
+			return ( wif, t.wif2addr(wif) )
+
+		return [gen_addr('legacy')] + [gen_addr('compressed') for i in range(n-1)]
 
 	def bob_pre_import(self):
 		pairs = self._gen_pairs(5)

+ 1 - 1
test/test_py_d/ts_tool.py

@@ -50,7 +50,7 @@ class TestSuiteTool(TestSuiteMain,TestSuiteBase):
 
 	def tool_encrypt(self):
 		infile = joinpath(self.tmpdir,self.enc_infn)
-		write_to_file(infile,os.urandom(1033),binary=True)
+		write_to_file(infile,getrand(1033),binary=True)
 		t = self.spawn('mmgen-tool',['-d',self.tmpdir,self.usr_rand_arg,'encrypt',infile])
 		t.usr_rand(self.usr_rand_chars)
 		t.hash_preset('user data','1')

+ 1 - 1
test/tooltest.py

@@ -276,7 +276,7 @@ class MMGenToolTestUtils(object):
 			rdie(3,f'Error for command {name!r}')
 
 	def run_cmd_randinput(self,name,strip=True,add_opts=[]):
-		s = os.urandom(128)
+		s = getrand(128)
 		fn = name+'.in'
 		write_to_tmpfile(cfg,fn,s,binary=True)
 		ret = self.run_cmd(name,[get_tmpfile(cfg,fn)],strip=strip,add_opts=add_opts)