tooltest.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test/tooltest.py: Tests for the 'mmgen-tool' utility
  20. """
  21. import sys,os,subprocess,binascii
  22. repo_root = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),os.pardir)))
  23. os.chdir(repo_root)
  24. sys.path.__setitem__(0,repo_root)
  25. os.environ['MMGEN_TEST_SUITE'] = '1'
  26. # Import this _after_ local path's been added to sys.path
  27. from mmgen.common import *
  28. from mmgen.test import *
  29. opts_data = lambda: {
  30. 'desc': "Test suite for the 'mmgen-tool' utility",
  31. 'usage':'[options] [command]',
  32. 'options': """
  33. -h, --help Print this help message
  34. -C, --coverage Produce code coverage info using trace module
  35. --, --longhelp Print help message for long options (common options)
  36. -l, --list-cmds List and describe the tests and commands in this test suite
  37. -L, --list-names List the names of all tested 'mmgen-tool' commands
  38. -s, --system Test scripts and modules installed on system rather than
  39. those in the repo root
  40. -t, --type=t Specify address type (valid options: 'zcash_z')
  41. -v, --verbose Produce more verbose output
  42. """,
  43. 'notes': """
  44. If no command is given, the whole suite of tests is run.
  45. """
  46. }
  47. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  48. cmd_args = opts.init(opts_data,add_opts=['exact_output','profile'])
  49. from collections import OrderedDict
  50. cmd_data = OrderedDict([
  51. ('util', {
  52. 'desc': 'base conversion, hashing and file utilities',
  53. 'cmd_data': OrderedDict([
  54. ('strtob58', ()),
  55. ('b58tostr', ('strtob58','io')),
  56. ('hextob58', ()),
  57. ('b58tohex', ('hextob58','io')),
  58. ('b58randenc', ()),
  59. ('hextob32', ()),
  60. ('b32tohex', ('hextob32','io')),
  61. ('randhex', ()),
  62. ('id6', ()),
  63. ('id8', ()),
  64. ('str2id6', ()),
  65. ('hash160', ()),
  66. ('hash256', ()),
  67. ('hexreverse', ()),
  68. ('hexlify', ()),
  69. ('hexdump', ()),
  70. ('unhexdump', ('hexdump','io')),
  71. ('rand2file', ()),
  72. ])
  73. }
  74. ),
  75. ('cryptocoin', {
  76. 'desc': 'Cryptocoin address/key commands',
  77. 'cmd_data': OrderedDict([
  78. ('randwif', ()),
  79. ('randpair', ()), # create 4 pairs: uncomp,comp,segwit,bech32
  80. ('wif2addr', ('randpair','o4')),
  81. ('wif2hex', ('randpair','o4')),
  82. ('privhex2pubhex', ('wif2hex','o3')), # segwit only
  83. ('pubhex2addr', ('privhex2pubhex','o3')), # segwit only
  84. ('hex2wif', ('wif2hex','io2')), # uncomp, comp
  85. ('addr2hexaddr', ('randpair','o4'))] + # uncomp, comp, bech32
  86. ([],[
  87. ('pubhash2addr', ('addr2hexaddr','io4')) # uncomp, comp, bech32
  88. ])[opt.type != 'zcash_z'] +
  89. ([],[
  90. ('pubhex2redeem_script', ('privhex2pubhex','o3')),
  91. ('wif2redeem_script', ('randpair','o3')),
  92. ('wif2segwit_pair', ('randpair','o2')),
  93. ('privhex2addr', ('wif2hex','o4')), # compare with output of randpair
  94. ('pipetest', ('randpair','o3'))
  95. ])[g.coin in ('BTC','LTC')]
  96. )
  97. }
  98. ),
  99. ('mnemonic', {
  100. 'desc': 'mnemonic commands',
  101. 'cmd_data': OrderedDict([
  102. ('hex2mn', ()),
  103. ('mn2hex', ('hex2mn','io3')),
  104. ('mn_rand128', ()),
  105. ('mn_rand192', ()),
  106. ('mn_rand256', ()),
  107. ('mn_stats', ()),
  108. ('mn_printlist', ()),
  109. ])
  110. }
  111. ),
  112. ('rpc', {
  113. 'desc': 'Coin daemon RPC commands',
  114. 'cmd_data': OrderedDict([
  115. # ('keyaddrfile_chksum', ()), # interactive
  116. ('addrfile_chksum', ()),
  117. ('getbalance', ()),
  118. ('listaddresses', ()),
  119. ('twview', ()),
  120. ('txview', ()),
  121. ])
  122. }
  123. ),
  124. ])
  125. cfg = {
  126. 'name': 'the tool utility',
  127. 'enc_passwd': 'Ten Satoshis',
  128. 'tmpdir': 'test/tmp10',
  129. 'tmpdir_num': 10,
  130. 'refdir': 'test/ref',
  131. 'txfile': {
  132. 'btc': ('0B8D5A[15.31789,14,tl=1320969600].rawtx',
  133. '0C7115[15.86255,14,tl=1320969600].testnet.rawtx'),
  134. 'bch': ('460D4D-BCH[10.19764,tl=1320969600].rawtx',
  135. '359FD5-BCH[6.68868,tl=1320969600].testnet.rawtx'),
  136. 'ltc': ('AF3CDF-LTC[620.76194,1453,tl=1320969600].rawtx',
  137. 'A5A1E0-LTC[1454.64322,1453,tl=1320969600].testnet.rawtx'),
  138. },
  139. 'addrfile': '98831F3A{}[1,31-33,500-501,1010-1011]{}.addrs',
  140. 'addrfile_chk': {
  141. 'btc': ('6FEF 6FB9 7B13 5D91','424E 4326 CFFE 5F51'),
  142. 'bch': ('6FEF 6FB9 7B13 5D91','424E 4326 CFFE 5F51'),
  143. 'ltc': ('AD52 C3FE 8924 AAF0','4EBE 2E85 E969 1B30'),
  144. }
  145. }
  146. ref_subdir = '' if g.proto.base_coin == 'BTC' else g.proto.name
  147. altcoin_pfx = '' if g.proto.base_coin == 'BTC' else '-'+g.proto.base_coin
  148. tn_ext = ('','.testnet')[g.testnet]
  149. mmgen_cmd = 'mmgen-tool'
  150. if not opt.system:
  151. os.environ['PYTHONPATH'] = repo_root
  152. mmgen_cmd = os.path.relpath(os.path.join(repo_root,'cmds',mmgen_cmd))
  153. spawn_cmd = [mmgen_cmd]
  154. if opt.coverage:
  155. d,f = init_coverage()
  156. spawn_cmd = ['python','-m','trace','--count','--coverdir='+d,'--file='+f] + spawn_cmd
  157. elif g.platform == 'win':
  158. spawn_cmd = ['python'] + spawn_cmd
  159. add_spawn_args = ['--data-dir='+cfg['tmpdir']] + ['--{}{}'.format(
  160. k.replace('_','-'),'='+getattr(opt,k) if getattr(opt,k) != True else '')
  161. for k in ('testnet','rpc_host','regtest','coin','type') if getattr(opt,k)]
  162. if opt.list_cmds:
  163. fs = ' {:<{w}} - {}'
  164. Msg('Available commands:')
  165. w = max(map(len,cmd_data))
  166. for cmd in cmd_data:
  167. Msg(fs.format(cmd,cmd_data[cmd]['desc'],w=w))
  168. Msg('\nAvailable utilities:')
  169. Msg(fs.format('clean','Clean the tmp directory',w=w))
  170. sys.exit(0)
  171. if opt.list_names:
  172. tested_here = []
  173. for v in cmd_data.values():
  174. tested_here += list(v['cmd_data'].keys())
  175. msg('{}\n{}'.format(green("Tested 'mmgen-tool' commands:"),'\n'.join(sorted(c.lower() for c in tested_here))))
  176. import mmgen.tool
  177. tested_in_test_py = (
  178. 'encrypt','decrypt','find_incog_data',
  179. 'addrfile_chksum','keyaddrfile_chksum','passwdfile_chksum',
  180. 'add_label','remove_label','remove_address',
  181. 'getbalance','listaddresses','listaddress','twview')
  182. tested_in_test_release = ('keyaddrlist2monerowallets','syncmonerowallets')
  183. tested_in_tooltest2 = subprocess.check_output(['test/tooltest2.py','--list-tested-cmds']).decode().split()
  184. ignore = ('help','usage')
  185. uc = sorted(c.lower() for c in (
  186. set(mmgen.tool.cmd_data.keys()) -
  187. set(ignore) -
  188. set(tested_here) -
  189. set(tested_in_tooltest2) -
  190. set(tested_in_test_py) -
  191. set(tested_in_test_release)
  192. ))
  193. msg('\n{}\n{}'.format(yellow('Untested commands:'),'\n'.join(uc)))
  194. die()
  195. from mmgen.tx import is_wif,is_coin_addr
  196. msg_w = 33
  197. def test_msg(m):
  198. m2 = 'Testing {}'.format(m)
  199. msg_r(green(m2+'\n') if opt.verbose else '{:{w}}'.format(m2,w=msg_w+8))
  200. maybe_compressed = ('','compressed')['C' in g.proto.mmtypes]
  201. maybe_segwit = ('','segwit')['S' in g.proto.mmtypes]
  202. maybe_bech32 = ('','bech32')['B' in g.proto.mmtypes]
  203. maybe_type_compressed = ([],['--type=compressed'])['C' in g.proto.mmtypes]
  204. maybe_type_segwit = ([],['--type=segwit'])['S' in g.proto.mmtypes]
  205. maybe_type_bech32 = ([],['--type=bech32'])['B' in g.proto.mmtypes]
  206. class MMGenToolTestUtils(object):
  207. def run_cmd(self,name,tool_args,kwargs='',extra_msg='',silent=False,strip=True,add_opts=[],binary=False):
  208. sys_cmd = (
  209. spawn_cmd +
  210. add_spawn_args +
  211. ['-r0','-d',cfg['tmpdir']] +
  212. add_opts +
  213. [name.lower()] +
  214. tool_args +
  215. kwargs.split()
  216. )
  217. if extra_msg: extra_msg = '({})'.format(extra_msg)
  218. full_name = ' '.join([name.lower()]+add_opts+kwargs.split()+extra_msg.split())
  219. if not silent:
  220. if opt.verbose:
  221. sys.stderr.write(green('Testing {}\nExecuting '.format(full_name)))
  222. sys.stderr.write(cyan(' '.join(sys_cmd)+'\n'))
  223. else:
  224. msg_r('Testing {:{w}}'.format(full_name+':',w=msg_w))
  225. p = subprocess.Popen(sys_cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  226. a,b = p.communicate()
  227. if not binary: a = a.decode()
  228. retcode = p.wait()
  229. if retcode != 0:
  230. msg('{}\n{}\n{}'.format(red('FAILED'),yellow('Command stderr output:'),b.decode()))
  231. rdie(1,'Called process returned with an error (retcode {})'.format(retcode))
  232. return (a,a.rstrip())[bool(strip)]
  233. def run_cmd_chk(self,name,f1,f2,kwargs='',extra_msg='',strip_hex=False,add_opts=[]):
  234. idata = read_from_file(f1).rstrip()
  235. odata = read_from_file(f2).rstrip()
  236. ret = self.run_cmd(name,[odata],kwargs=kwargs,extra_msg=extra_msg,add_opts=add_opts)
  237. vmsg('In: ' + repr(odata))
  238. vmsg('Out: ' + repr(ret))
  239. def cmp_equal(a,b):
  240. return (a.lstrip('0') == b.lstrip('0')) if strip_hex else (a == b)
  241. if cmp_equal(ret,idata): ok()
  242. else:
  243. fs = "Error: values don't match:\nIn: {!r}\nOut: {!r}"
  244. rdie(3,fs.format(idata,ret))
  245. return ret
  246. def run_cmd_nochk(self,name,f1,kwargs='',add_opts=[]):
  247. odata = read_from_file(f1).rstrip()
  248. ret = self.run_cmd(name,[odata],kwargs=kwargs,add_opts=add_opts)
  249. vmsg('In: ' + repr(odata))
  250. vmsg('Out: ' + repr(ret))
  251. return ret
  252. def run_cmd_out(self,name,carg=None,Return=False,kwargs='',fn_idx='',extra_msg='',
  253. literal=False,chkdata='',hush=False,add_opts=[]):
  254. if carg: write_to_tmpfile(cfg,'{}{}.in'.format(name,fn_idx),carg+'\n')
  255. ret = self.run_cmd(name,([],[carg])[bool(carg)],kwargs=kwargs,
  256. extra_msg=extra_msg,add_opts=add_opts)
  257. if carg: vmsg('In: ' + repr(carg))
  258. vmsg('Out: ' + (repr(ret),ret)[literal])
  259. if ret or ret == '':
  260. write_to_tmpfile(cfg,'{}{}.out'.format(name,fn_idx),ret+'\n')
  261. if chkdata:
  262. cmp_or_die(ret,chkdata)
  263. return
  264. if Return: return ret
  265. else:
  266. if not hush: ok()
  267. else:
  268. rdie(3,"Error for command '{}'".format(name))
  269. def run_cmd_randinput(self,name,strip=True,add_opts=[]):
  270. s = os.urandom(128)
  271. fn = name+'.in'
  272. write_to_tmpfile(cfg,fn,s,binary=True)
  273. ret = self.run_cmd(name,[get_tmpfile_fn(cfg,fn)],strip=strip,add_opts=add_opts)
  274. fn = name+'.out'
  275. write_to_tmpfile(cfg,fn,ret+'\n')
  276. ok()
  277. vmsg('Returned: {}'.format(ret))
  278. tu = MMGenToolTestUtils()
  279. class MMGenToolTestCmds(object):
  280. # Util
  281. def strtob58(self,name): tu.run_cmd_out(name,getrandstr(16))
  282. def b58tostr(self,name,f1,f2): tu.run_cmd_chk(name,f1,f2)
  283. def hextob58(self,name): tu.run_cmd_out(name,getrandhex(32))
  284. def b58tohex(self,name,f1,f2): tu.run_cmd_chk(name,f1,f2,strip_hex=True)
  285. def b58randenc(self,name):
  286. ret = tu.run_cmd_out(name,Return=True)
  287. ok_or_die(ret,is_b58_str,'base 58 string')
  288. def hextob32(self,name): tu.run_cmd_out(name,getrandhex(24))
  289. def b32tohex(self,name,f1,f2): tu.run_cmd_chk(name,f1,f2,strip_hex=True)
  290. def randhex(self,name):
  291. ret = tu.run_cmd_out(name,Return=True)
  292. ok_or_die(ret,binascii.unhexlify,'hex string')
  293. def id6(self,name): tu.run_cmd_randinput(name)
  294. def id8(self,name): tu.run_cmd_randinput(name)
  295. def str2id6(self,name):
  296. s = getrandstr(120,no_space=True)
  297. s2 = ' {} {} {} {} {} '.format(s[:3],s[3:9],s[9:29],s[29:50],s[50:120])
  298. ret1 = tu.run_cmd(name,[s],extra_msg='unspaced input'); ok()
  299. ret2 = tu.run_cmd(name,[s2],extra_msg='spaced input')
  300. cmp_or_die(ret1,ret2)
  301. vmsg('Returned: {}'.format(ret1))
  302. def hash160(self,name): tu.run_cmd_out(name,getrandhex(16))
  303. def hash256(self,name): tu.run_cmd_out(name,getrandstr(16))
  304. def hexreverse(self,name): tu.run_cmd_out(name,getrandhex(24))
  305. def hexlify(self,name): tu.run_cmd_out(name,getrandstr(24))
  306. def hexdump(self,name): tu.run_cmd_randinput(name,strip=False)
  307. def unhexdump(self,name,fn1,fn2):
  308. ret = tu.run_cmd(name,[fn2],strip=False,binary=True)
  309. orig = read_from_file(fn1,binary=True)
  310. cmp_or_die(orig,ret)
  311. def rand2file(self,name):
  312. of = name + '.out'
  313. dlen = 1024
  314. tu.run_cmd(name,[of,str(1024),'threads=4','silent=1'],strip=False)
  315. d = read_from_tmpfile(cfg,of,binary=True)
  316. cmp_or_die(dlen,len(d))
  317. # Cryptocoin
  318. def randwif(self,name):
  319. for n,k in enumerate(['',maybe_compressed]):
  320. ao = ['--type='+k] if k else []
  321. ret = tu.run_cmd_out(name,add_opts=ao,Return=True,fn_idx=n+1)
  322. ok_or_die(ret,is_wif,'WIF key')
  323. def randpair(self,name):
  324. for n,k in enumerate(['',maybe_compressed,maybe_segwit,maybe_bech32]):
  325. ao = ['--type='+k] if k else []
  326. wif,addr = tu.run_cmd_out(name,add_opts=ao,Return=True,fn_idx=n+1).split()
  327. ok_or_die(wif,is_wif,'WIF key',skip_ok=True)
  328. ok_or_die(addr,is_coin_addr,'Coin address')
  329. def wif2addr(self,name,f1,f2,f3,f4):
  330. for n,f,k,m in (
  331. (1,f1,'',''),
  332. (2,f2,'',maybe_compressed),
  333. (3,f3,maybe_segwit,''),
  334. (4,f4,maybe_bech32,'')
  335. ):
  336. ao = ['--type='+k] if k else []
  337. wif = read_from_file(f).split()[0]
  338. tu.run_cmd_out(name,wif,add_opts=ao,fn_idx=n,extra_msg=m)
  339. def wif2hex(self,name,f1,f2,f3,f4):
  340. for n,f,m in (
  341. (1,f1,''),
  342. (2,f2,maybe_compressed),
  343. (3,f3,'{} for {}'.format(maybe_compressed,maybe_segwit)),
  344. (4,f4,'{} for {}'.format(maybe_compressed,maybe_bech32))
  345. ):
  346. wif = read_from_file(f).split()[0]
  347. tu.run_cmd_out(name,wif,fn_idx=n,extra_msg=m)
  348. def privhex2addr(self,name,f1,f2,f3,f4):
  349. keys = [read_from_file(f).rstrip() for f in (f1,f2,f3,f4)]
  350. for n,k in enumerate(('',maybe_compressed,maybe_segwit,maybe_bech32)):
  351. ao = ['--type='+k] if k else []
  352. ret = tu.run_cmd(name,[keys[n]],add_opts=ao).rstrip()
  353. iaddr = read_from_tmpfile(cfg,'randpair{}.out'.format(n+1)).split()[-1]
  354. vmsg('Out: {}'.format(ret))
  355. cmp_or_die(iaddr,ret)
  356. def hex2wif(self,name,f1,f2,f3,f4):
  357. for n,fi,fo,k in ((1,f1,f2,''),(2,f3,f4,maybe_compressed)):
  358. ao = ['--type='+k] if k else []
  359. ret = tu.run_cmd_chk(name,fi,fo,add_opts=ao)
  360. def addr2hexaddr(self,name,f1,f2,f3,f4):
  361. for n,f,m,ao in (
  362. (1,f1,'',[]),
  363. (2,f2,'from {}'.format(maybe_compressed),[]),
  364. (4,f4,'',maybe_type_bech32),
  365. ):
  366. addr = read_from_file(f).split()[-1]
  367. tu.run_cmd_out(name,addr,fn_idx=n,add_opts=ao,extra_msg=m)
  368. def pubhash2addr(self,name,f1,f2,f3,f4,f5,f6,f7,f8):
  369. for n,fi,fo,m,ao in (
  370. (1,f1,f2,'',[]),
  371. (2,f3,f4,'from {}'.format(maybe_compressed),[]),
  372. (4,f7,f8,'',maybe_type_bech32)
  373. ):
  374. tu.run_cmd_chk(name,fi,fo,add_opts=ao,extra_msg=m)
  375. def privhex2pubhex(self,name,f1,f2,f3): # from Hex2wif
  376. addr = read_from_file(f3).strip()
  377. tu.run_cmd_out(name,addr,add_opts=maybe_type_compressed,fn_idx=3) # what about uncompressed?
  378. def pubhex2redeem_script(self,name,f1,f2,f3): # from above
  379. addr = read_from_file(f3).strip()
  380. tu.run_cmd_out(name,addr,fn_idx=3)
  381. rs = read_from_tmpfile(cfg,name+'3.out').strip()
  382. tu.run_cmd_out('pubhex2addr',rs,add_opts=maybe_type_segwit,fn_idx=3,hush=True)
  383. addr1 = read_from_tmpfile(cfg,'pubhex2addr3.out').strip()
  384. addr2 = read_from_tmpfile(cfg,'randpair3.out').split()[1]
  385. cmp_or_die(addr1,addr2)
  386. def wif2redeem_script(self,name,f1,f2,f3): # compare output with above
  387. wif = read_from_file(f3).split()[0]
  388. ret1 = tu.run_cmd_out(name,wif,add_opts=maybe_type_segwit,fn_idx=3,Return=True)
  389. ret2 = read_from_tmpfile(cfg,'pubhex2redeem_script3.out').strip()
  390. cmp_or_die(ret1,ret2)
  391. def wif2segwit_pair(self,name,f1,f2): # does its own checking, so just run
  392. wif = read_from_file(f2).split()[0]
  393. tu.run_cmd_out(name,wif,add_opts=maybe_type_segwit,fn_idx=2)
  394. def pubhex2addr(self,name,f1,f2,f3):
  395. addr = read_from_file(f3).strip()
  396. tu.run_cmd_out(name,addr,add_opts=maybe_type_segwit,fn_idx=3)
  397. def pipetest(self,name,f1,f2,f3):
  398. wif = read_from_file(f3).split()[0]
  399. cmd = ( '{c} {a} wif2hex {wif} | ' +
  400. '{c} {a} --type=compressed privhex2pubhex - | ' +
  401. '{c} {a} pubhex2redeem_script - | ' +
  402. '{c} {a} --type=segwit pubhex2addr -').format(
  403. c=' '.join(spawn_cmd),
  404. a=' '.join(add_spawn_args),
  405. wif=wif)
  406. test_msg('command piping')
  407. if opt.verbose:
  408. sys.stderr.write(green('Executing ') + cyan(cmd) + '\n')
  409. p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  410. res = p.stdout.read().decode().strip()
  411. addr = read_from_tmpfile(cfg,'wif2addr3.out').strip()
  412. cmp_or_die(res,addr)
  413. # Mnemonic
  414. def hex2mn(self,name):
  415. for n,size,m in ((1,16,'128-bit'),(2,24,'192-bit'),(3,32,'256-bit')):
  416. hexnum = getrandhex(size)
  417. tu.run_cmd_out(name,hexnum,fn_idx=n,extra_msg=m)
  418. def mn2hex(self,name,f1,f2,f3,f4,f5,f6):
  419. for f_i,f_o,m in ((f1,f2,'128-bit'),(f3,f4,'192-bit'),(f5,f6,'256-bit')):
  420. tu.run_cmd_chk(name,f_i,f_o,extra_msg=m,strip_hex=True)
  421. def mn_rand128(self,name): tu.run_cmd_out(name)
  422. def mn_rand192(self,name): tu.run_cmd_out(name)
  423. def mn_rand256(self,name): tu.run_cmd_out(name)
  424. def mn_stats(self,name): tu.run_cmd_out(name)
  425. def mn_printlist(self,name):
  426. tu.run_cmd(name,[])
  427. ok()
  428. # RPC
  429. def addrfile_chksum(self,name):
  430. fn = os.path.join(cfg['refdir'],ref_subdir,cfg['addrfile'].format(altcoin_pfx,tn_ext))
  431. tu.run_cmd_out(name,fn,literal=True,chkdata=cfg['addrfile_chk'][g.coin.lower()][g.testnet])
  432. def getbalance(self,name):
  433. tu.run_cmd_out(name,literal=True)
  434. def listaddresses(self,name):
  435. tu.run_cmd_out(name,literal=True)
  436. def twview(self,name):
  437. tu.run_cmd_out(name,literal=True)
  438. def txview(self,name):
  439. fn = os.path.join(cfg['refdir'],ref_subdir,cfg['txfile'][g.coin.lower()][bool(tn_ext)])
  440. tu.run_cmd_out(name,fn,literal=True)
  441. # main()
  442. import time
  443. start_time = int(time.time())
  444. mk_tmpdir(cfg['tmpdir'])
  445. def gen_deps_for_cmd(cmd,cdata):
  446. fns = []
  447. if cdata:
  448. name,code = cdata
  449. io,count = (code[:-1],int(code[-1])) if code[-1] in '0123456789' else (code,1)
  450. for c in range(count):
  451. fns += ['{}{}{}'.format(name,('',c+1)[count > 1],('.out','.in')[ch=='i']) for ch in io]
  452. return fns
  453. def do_cmds(cmd_group):
  454. tc = MMGenToolTestCmds()
  455. gdata = cmd_data[cmd_group]['cmd_data']
  456. for cmd in gdata:
  457. fns = gen_deps_for_cmd(cmd,gdata[cmd])
  458. cmdline = [cmd] + [os.path.join(cfg['tmpdir'],fn) for fn in fns]
  459. getattr(tc,cmd)(*cmdline)
  460. if cmd_args:
  461. if len(cmd_args) != 1:
  462. die(1,'Only one command may be specified')
  463. cmd = cmd_args[0]
  464. if cmd in cmd_data:
  465. msg('Running tests for {}:'.format(cmd_data[cmd]['desc']))
  466. do_cmds(cmd)
  467. elif cmd == 'clean':
  468. cleandir(cfg['tmpdir'])
  469. sys.exit(0)
  470. else:
  471. die(1,"'{}': unrecognized command".format(cmd))
  472. else:
  473. cleandir(cfg['tmpdir'])
  474. for cmd in cmd_data:
  475. msg('Running tests for {}:'.format(cmd_data[cmd]['desc']))
  476. do_cmds(cmd)
  477. if cmd is not list(cmd_data.keys())[-1]: msg('')
  478. t = int(time.time()) - start_time
  479. gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t//60,t%60))