tooltest.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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,binascii
  22. from subprocess import run,PIPE
  23. from include.tests_header import repo_root
  24. from mmgen.common import *
  25. from test.include.common import *
  26. opts_data = {
  27. 'text': {
  28. 'desc': "Test suite for the 'mmgen-tool' utility",
  29. 'usage':'[options] [command]',
  30. 'options': """
  31. -h, --help Print this help message
  32. -C, --coverage Produce code coverage info using trace module
  33. -d, --debug Produce debugging output (stderr from spawned script)
  34. --, --longhelp Print help message for long options (common options)
  35. -l, --list-cmds List and describe the tests and commands in this test suite
  36. -L, --list-names List the names of all tested 'mmgen-tool' commands
  37. -s, --system Test scripts and modules installed on system rather than
  38. those in the repo root
  39. -t, --type=t Specify address type (valid options: 'zcash_z')
  40. -v, --verbose Produce more verbose output
  41. """,
  42. 'notes': """
  43. If no command is given, the whole suite of tests is run.
  44. """
  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. cmd_data = {
  50. 'cryptocoin': {
  51. 'desc': 'Cryptocoin address/key commands',
  52. 'cmd_data': {
  53. 'randwif': (),
  54. 'randpair': (), # create 4 pairs: uncomp,comp,segwit,bech32
  55. 'wif2addr': ('randpair','o4'),
  56. 'wif2hex': ('randpair','o4'),
  57. 'privhex2pubhex': ('wif2hex','o3'), # segwit only
  58. 'pubhex2addr': ('privhex2pubhex','o3'), # segwit only
  59. 'hex2wif': ('wif2hex','io2'), # uncomp, comp
  60. 'addr2pubhash': ('randpair','o4'), # uncomp, comp, bech32
  61. 'pubhash2addr': ('addr2pubhash','io4'), # uncomp, comp, bech32
  62. },
  63. },
  64. 'mnemonic': {
  65. 'desc': 'mnemonic commands',
  66. 'cmd_data': {
  67. 'hex2mn': (),
  68. 'mn2hex': ('hex2mn','io3'),
  69. 'mn_rand128': (),
  70. 'mn_rand192': (),
  71. 'mn_rand256': (),
  72. 'mn_stats': (),
  73. 'mn_printlist': (),
  74. },
  75. },
  76. }
  77. if g.coin in ('BTC','LTC'):
  78. cmd_data['cryptocoin']['cmd_data'].update({
  79. 'pubhex2redeem_script': ('privhex2pubhex','o3'),
  80. 'wif2redeem_script': ('randpair','o3'),
  81. 'wif2segwit_pair': ('randpair','o2'),
  82. 'privhex2addr': ('wif2hex','o4'), # compare with output of randpair
  83. 'pipetest': ('randpair','o3')
  84. })
  85. if opt.type == 'zcash_z':
  86. del cmd_data['cryptocoin']['cmd_data']['pubhash2addr']
  87. cfg = {
  88. 'name': 'the tool utility',
  89. 'enc_passwd': 'Ten Satoshis',
  90. 'tmpdir': 'test/tmp10',
  91. 'tmpdir_num': 10,
  92. 'refdir': 'test/ref',
  93. 'txfile': {
  94. 'btc': ('0B8D5A[15.31789,14,tl=1320969600].rawtx',
  95. '0C7115[15.86255,14,tl=1320969600].testnet.rawtx'),
  96. 'bch': ('460D4D-BCH[10.19764,tl=1320969600].rawtx',
  97. '359FD5-BCH[6.68868,tl=1320969600].testnet.rawtx'),
  98. 'ltc': ('AF3CDF-LTC[620.76194,1453,tl=1320969600].rawtx',
  99. 'A5A1E0-LTC[1454.64322,1453,tl=1320969600].testnet.rawtx'),
  100. },
  101. 'addrfile': '98831F3A{}[1,31-33,500-501,1010-1011]{}.addrs',
  102. 'addrfile_chk': {
  103. 'btc': ('6FEF 6FB9 7B13 5D91','424E 4326 CFFE 5F51'),
  104. 'bch': ('6FEF 6FB9 7B13 5D91','424E 4326 CFFE 5F51'),
  105. 'ltc': ('AD52 C3FE 8924 AAF0','4EBE 2E85 E969 1B30'),
  106. }
  107. }
  108. ref_subdir = '' if g.proto.base_coin == 'BTC' else g.proto.name
  109. altcoin_pfx = '' if g.proto.base_coin == 'BTC' else '-'+g.proto.base_coin
  110. tn_ext = ('','.testnet')[g.testnet]
  111. mmgen_cmd = 'mmgen-tool'
  112. if not opt.system:
  113. os.environ['PYTHONPATH'] = repo_root
  114. mmgen_cmd = os.path.relpath(os.path.join(repo_root,'cmds',mmgen_cmd))
  115. spawn_cmd = [mmgen_cmd]
  116. if opt.coverage:
  117. d,f = init_coverage()
  118. spawn_cmd = ['python3','-m','trace','--count','--coverdir='+d,'--file='+f] + spawn_cmd
  119. elif g.platform == 'win':
  120. spawn_cmd = ['python3'] + spawn_cmd
  121. add_spawn_args = ['--data-dir='+cfg['tmpdir']] + ['--{}{}'.format(
  122. k.replace('_','-'),'='+getattr(opt,k) if getattr(opt,k) != True else '')
  123. for k in ('testnet','rpc_host','regtest','coin','type') if getattr(opt,k)]
  124. if opt.list_cmds:
  125. fs = ' {:<{w}} - {}'
  126. Msg('Available commands:')
  127. w = max(map(len,cmd_data))
  128. for cmd in cmd_data:
  129. Msg(fs.format(cmd,cmd_data[cmd]['desc'],w=w))
  130. Msg('\nAvailable utilities:')
  131. Msg(fs.format('clean','Clean the tmp directory',w=w))
  132. sys.exit(0)
  133. if opt.list_names:
  134. tcmd = ['python3','test/tooltest2.py','--list-tested-cmds']
  135. tested_in = {
  136. 'tooltest.py': [],
  137. 'test.py': (
  138. 'encrypt','decrypt','find_incog_data',
  139. 'addrfile_chksum','keyaddrfile_chksum','passwdfile_chksum',
  140. 'add_label','remove_label','remove_address','twview',
  141. 'getbalance','listaddresses','listaddress'),
  142. 'test-release.sh': ('keyaddrlist2monerowallets','syncmonerowallets'),
  143. 'tooltest2.py': run(tcmd,stdout=PIPE,check=True).stdout.decode().split()
  144. }
  145. for v in cmd_data.values():
  146. tested_in['tooltest.py'] += list(v['cmd_data'].keys())
  147. msg(green("TESTED 'MMGEN-TOOL' COMMANDS"))
  148. for l in ('tooltest.py','tooltest2.py','test.py','test-release.sh'):
  149. msg(blue(l+':'))
  150. msg(' '+'\n '.join(sorted(tested_in[l])))
  151. ignore = ()
  152. from mmgen.tool import MMGenToolCmd
  153. uc = sorted(
  154. set(MMGenToolCmds) -
  155. set(ignore) -
  156. set(tested_in['tooltest.py']) -
  157. set(tested_in['tooltest2.py']) -
  158. set(tested_in['test.py']) -
  159. set(tested_in['test-release.sh'])
  160. )
  161. die(0,'\n{}\n {}'.format(yellow('Untested commands:'),'\n '.join(uc)))
  162. from mmgen.tx import is_wif,is_coin_addr
  163. msg_w = 35
  164. def test_msg(m):
  165. m2 = 'Testing {}'.format(m)
  166. msg_r(green(m2+'\n') if opt.verbose else '{:{w}}'.format(m2,w=msg_w+8))
  167. compressed = ('','compressed')['C' in g.proto.mmtypes]
  168. segwit = ('','segwit')['S' in g.proto.mmtypes]
  169. bech32 = ('','bech32')['B' in g.proto.mmtypes]
  170. type_compressed_arg = ([],['--type=compressed'])['C' in g.proto.mmtypes]
  171. type_segwit_arg = ([],['--type=segwit'])['S' in g.proto.mmtypes]
  172. type_bech32_arg = ([],['--type=bech32'])['B' in g.proto.mmtypes]
  173. class MMGenToolTestUtils(object):
  174. def run_cmd(self,name,tool_args,kwargs='',extra_msg='',silent=False,strip=True,add_opts=[],binary=False):
  175. sys_cmd = (
  176. spawn_cmd +
  177. add_spawn_args +
  178. ['-r0','-d',cfg['tmpdir']] +
  179. add_opts +
  180. [name.lower()] +
  181. tool_args +
  182. kwargs.split()
  183. )
  184. if extra_msg: extra_msg = '({})'.format(extra_msg)
  185. full_name = ' '.join([name.lower()]+add_opts+kwargs.split()+extra_msg.split())
  186. if not silent:
  187. if opt.verbose:
  188. sys.stderr.write(green('Testing {}\nExecuting '.format(full_name)))
  189. sys.stderr.write(cyan(' '.join(sys_cmd)+'\n'))
  190. else:
  191. msg_r('Testing {:{w}}'.format(full_name+':',w=msg_w))
  192. cp = run(sys_cmd,stdout=PIPE,stderr=PIPE)
  193. out = cp.stdout
  194. err = cp.stderr
  195. if opt.debug:
  196. try: dmsg(err.decode())
  197. except: dmsg(repr(err))
  198. if not binary:
  199. out = out.decode()
  200. if cp.returncode != 0:
  201. msg('{}\n{}\n{}'.format(red('FAILED'),yellow('Command stderr output:'),err.decode()))
  202. rdie(1,'Called process returned with an error (retcode {})'.format(cp.returncode))
  203. return (out,out.rstrip())[bool(strip)]
  204. def run_cmd_chk(self,name,f1,f2,kwargs='',extra_msg='',strip_hex=False,add_opts=[]):
  205. idata = read_from_file(f1).rstrip()
  206. odata = read_from_file(f2).rstrip()
  207. ret = self.run_cmd(name,[odata],kwargs=kwargs,extra_msg=extra_msg,add_opts=add_opts)
  208. vmsg('In: ' + repr(odata))
  209. vmsg('Out: ' + repr(ret))
  210. def cmp_equal(a,b):
  211. return (a.lstrip('0') == b.lstrip('0')) if strip_hex else (a == b)
  212. if cmp_equal(ret,idata): ok()
  213. else:
  214. fs = "Error: values don't match:\nIn: {!r}\nOut: {!r}"
  215. rdie(3,fs.format(idata,ret))
  216. return ret
  217. def run_cmd_nochk(self,name,f1,kwargs='',add_opts=[]):
  218. odata = read_from_file(f1).rstrip()
  219. ret = self.run_cmd(name,[odata],kwargs=kwargs,add_opts=add_opts)
  220. vmsg('In: ' + repr(odata))
  221. vmsg('Out: ' + repr(ret))
  222. return ret
  223. def run_cmd_out(self,name,carg=None,Return=False,kwargs='',fn_idx='',extra_msg='',
  224. literal=False,chkdata='',hush=False,add_opts=[]):
  225. if carg: write_to_tmpfile(cfg,'{}{}.in'.format(name,fn_idx),carg+'\n')
  226. ret = self.run_cmd(name,([],[carg])[bool(carg)],kwargs=kwargs,
  227. extra_msg=extra_msg,add_opts=add_opts)
  228. if carg: vmsg('In: ' + repr(carg))
  229. vmsg('Out: ' + (repr(ret),ret)[literal])
  230. if ret or ret == '':
  231. write_to_tmpfile(cfg,'{}{}.out'.format(name,fn_idx),ret+'\n')
  232. if chkdata:
  233. cmp_or_die(ret,chkdata)
  234. return
  235. if Return: return ret
  236. else:
  237. if not hush: ok()
  238. else:
  239. rdie(3,"Error for command '{}'".format(name))
  240. def run_cmd_randinput(self,name,strip=True,add_opts=[]):
  241. s = os.urandom(128)
  242. fn = name+'.in'
  243. write_to_tmpfile(cfg,fn,s,binary=True)
  244. ret = self.run_cmd(name,[get_tmpfile(cfg,fn)],strip=strip,add_opts=add_opts)
  245. fn = name+'.out'
  246. write_to_tmpfile(cfg,fn,ret+'\n')
  247. ok()
  248. vmsg('Returned: {}'.format(ret))
  249. tu = MMGenToolTestUtils()
  250. def ok_or_die(val,chk_func,s,skip_ok=False):
  251. try: ret = chk_func(val)
  252. except: ret = False
  253. if ret:
  254. if not skip_ok: ok()
  255. else:
  256. rdie(3,"Returned value '{}' is not a {}".format((val,s)))
  257. class MMGenToolTestCmds(object):
  258. # Cryptocoin
  259. def randwif(self,name):
  260. for n,k in enumerate(['',compressed]):
  261. ao = ['--type='+k] if k else []
  262. ret = tu.run_cmd_out(name,add_opts=ao,Return=True,fn_idx=n+1)
  263. ok_or_die(ret,is_wif,'WIF key')
  264. def randpair(self,name):
  265. for n,k in enumerate(['',compressed,segwit,bech32]):
  266. ao = ['--type='+k] if k else []
  267. wif,addr = tu.run_cmd_out(name,add_opts=ao,Return=True,fn_idx=n+1,literal=True).split()
  268. ok_or_die(wif,is_wif,'WIF key',skip_ok=True)
  269. ok_or_die(addr,is_coin_addr,'Coin address')
  270. def wif2addr(self,name,f1,f2,f3,f4):
  271. for n,f,k in (
  272. (1,f1,''),
  273. (2,f2,compressed),
  274. (3,f3,segwit),
  275. (4,f4,bech32)
  276. ):
  277. ao = ['--type='+k] if k else []
  278. wif = read_from_file(f).split()[0]
  279. tu.run_cmd_out(name,wif,add_opts=ao,fn_idx=n)
  280. def wif2hex(self,name,f1,f2,f3,f4):
  281. for n,f,m in (
  282. (1,f1,''),
  283. (2,f2,compressed),
  284. (3,f3,'{} for {}'.format(compressed or 'uncompressed',segwit or 'p2pkh')),
  285. (4,f4,'{} for {}'.format(compressed or 'uncompressed',bech32 or 'p2pkh'))
  286. ):
  287. wif = read_from_file(f).split()[0]
  288. tu.run_cmd_out(name,wif,fn_idx=n,extra_msg=m)
  289. def privhex2addr(self,name,f1,f2,f3,f4):
  290. keys = [read_from_file(f).rstrip() for f in (f1,f2,f3,f4)]
  291. for n,k in enumerate(('',compressed,segwit,bech32)):
  292. ao = ['--type='+k] if k else []
  293. ret = tu.run_cmd(name,[keys[n]],add_opts=ao).rstrip()
  294. iaddr = read_from_tmpfile(cfg,'randpair{}.out'.format(n+1)).split()[-1]
  295. vmsg('Out: {}'.format(ret))
  296. cmp_or_die(iaddr,ret)
  297. ok()
  298. def hex2wif(self,name,f1,f2,f3,f4):
  299. for n,fi,fo,k in ((1,f1,f2,''),(2,f3,f4,compressed)):
  300. ao = ['--type='+k] if k else []
  301. ret = tu.run_cmd_chk(name,fi,fo,add_opts=ao)
  302. def addr2pubhash(self,name,f1,f2,f3,f4):
  303. for n,f,m,ao in (
  304. (1,f1,'',[]),
  305. (2,f2,'from {}'.format(compressed or 'uncompressed'),[]),
  306. (4,f4,'',type_bech32_arg),
  307. ):
  308. addr = read_from_file(f).split()[-1]
  309. tu.run_cmd_out(name,addr,fn_idx=n,add_opts=ao,extra_msg=m)
  310. def pubhash2addr(self,name,f1,f2,f3,f4,f5,f6,f7,f8):
  311. for n,fi,fo,m,ao in (
  312. (1,f1,f2,'',[]),
  313. (2,f3,f4,'from {}'.format(compressed or 'uncompressed'),[]),
  314. (4,f7,f8,'',type_bech32_arg)
  315. ):
  316. tu.run_cmd_chk(name,fi,fo,add_opts=ao,extra_msg=m)
  317. def privhex2pubhex(self,name,f1,f2,f3): # from Hex2wif
  318. addr = read_from_file(f3).strip()
  319. tu.run_cmd_out(name,addr,add_opts=type_compressed_arg,fn_idx=3) # what about uncompressed?
  320. def pubhex2redeem_script(self,name,f1,f2,f3): # from above
  321. addr = read_from_file(f3).strip()
  322. tu.run_cmd_out(name,addr,add_opts=type_segwit_arg,fn_idx=3)
  323. type_save = opt.type
  324. opt.type = 'segwit'
  325. rs = read_from_tmpfile(cfg,'privhex2pubhex3.out').strip()
  326. tu.run_cmd_out('pubhex2addr',rs,add_opts=type_segwit_arg,fn_idx=3,hush=True)
  327. opt.type = type_save
  328. addr1 = read_from_tmpfile(cfg,'pubhex2addr3.out').strip()
  329. addr2 = read_from_tmpfile(cfg,'randpair3.out').split()[1]
  330. cmp_or_die(addr1,addr2)
  331. ok()
  332. def wif2redeem_script(self,name,f1,f2,f3): # compare output with above
  333. wif = read_from_file(f3).split()[0]
  334. ret1 = tu.run_cmd_out(name,wif,add_opts=type_segwit_arg,fn_idx=3,Return=True)
  335. ret2 = read_from_tmpfile(cfg,'pubhex2redeem_script3.out').strip()
  336. cmp_or_die(ret1,ret2)
  337. ok()
  338. def wif2segwit_pair(self,name,f1,f2): # does its own checking, so just run
  339. wif = read_from_file(f2).split()[0]
  340. tu.run_cmd_out(name,wif,add_opts=type_segwit_arg,fn_idx=2)
  341. def pubhex2addr(self,name,f1,f2,f3):
  342. addr = read_from_file(f3).strip()
  343. tu.run_cmd_out(name,addr,add_opts=type_segwit_arg,fn_idx=3)
  344. def pipetest(self,name,f1,f2,f3):
  345. wif = read_from_file(f3).split()[0]
  346. cmd = ( '{c} {a} wif2hex {wif}' +
  347. ' | {c} {a} --type=compressed privhex2pubhex -' +
  348. ' | {c} {a} --type=segwit pubhex2redeem_script -' +
  349. ' | {c} {a} hash160 -' +
  350. ' | {c} {a} --type=segwit pubhash2addr -').format(
  351. c=' '.join(spawn_cmd),
  352. a=' '.join(add_spawn_args),
  353. wif=wif)
  354. test_msg('command piping')
  355. if opt.verbose:
  356. sys.stderr.write(green('Executing ') + cyan(cmd) + '\n')
  357. res = run(cmd,stdout=PIPE,shell=True).stdout.decode().strip()
  358. addr = read_from_tmpfile(cfg,'wif2addr3.out').strip()
  359. cmp_or_die(addr,res)
  360. ok()
  361. # Mnemonic
  362. def hex2mn(self,name):
  363. for n,size,m in ((1,16,'128-bit'),(2,24,'192-bit'),(3,32,'256-bit')):
  364. hexnum = getrandhex(size)
  365. tu.run_cmd_out(name,hexnum,fn_idx=n,extra_msg=m)
  366. def mn2hex(self,name,f1,f2,f3,f4,f5,f6):
  367. for f_i,f_o,m in ((f1,f2,'128-bit'),(f3,f4,'192-bit'),(f5,f6,'256-bit')):
  368. tu.run_cmd_chk(name,f_i,f_o,extra_msg=m,strip_hex=True)
  369. def mn_rand128(self,name): tu.run_cmd_out(name)
  370. def mn_rand192(self,name): tu.run_cmd_out(name)
  371. def mn_rand256(self,name): tu.run_cmd_out(name)
  372. def mn_stats(self,name): tu.run_cmd_out(name)
  373. def mn_printlist(self,name):
  374. tu.run_cmd(name,[])
  375. ok()
  376. # main()
  377. import time
  378. start_time = int(time.time())
  379. mk_tmpdir(cfg['tmpdir'])
  380. def gen_deps_for_cmd(cmd,cdata):
  381. fns = []
  382. if cdata:
  383. name,code = cdata
  384. io,count = (code[:-1],int(code[-1])) if code[-1] in '0123456789' else (code,1)
  385. for c in range(count):
  386. fns += ['{}{}{}'.format(name,('',c+1)[count > 1],('.out','.in')[ch=='i']) for ch in io]
  387. return fns
  388. def do_cmds(cmd_group):
  389. tc = MMGenToolTestCmds()
  390. gdata = cmd_data[cmd_group]['cmd_data']
  391. for cmd in gdata:
  392. fns = gen_deps_for_cmd(cmd,gdata[cmd])
  393. cmdline = [cmd] + [os.path.join(cfg['tmpdir'],fn) for fn in fns]
  394. getattr(tc,cmd)(*cmdline)
  395. try:
  396. if cmd_args:
  397. if len(cmd_args) != 1:
  398. die(1,'Only one command may be specified')
  399. cmd = cmd_args[0]
  400. if cmd in cmd_data:
  401. msg('Running tests for {}:'.format(cmd_data[cmd]['desc']))
  402. do_cmds(cmd)
  403. elif cmd == 'clean':
  404. cleandir(cfg['tmpdir'],do_msg=True)
  405. sys.exit(0)
  406. else:
  407. die(1,"'{}': unrecognized command".format(cmd))
  408. else:
  409. cleandir(cfg['tmpdir'],do_msg=True)
  410. for cmd in cmd_data:
  411. msg('Running tests for {}:'.format(cmd_data[cmd]['desc']))
  412. do_cmds(cmd)
  413. if cmd is not list(cmd_data.keys())[-1]: msg('')
  414. except KeyboardInterrupt:
  415. die(1,green('\nExiting at user request'))
  416. t = int(time.time()) - start_time
  417. gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t//60,t%60))