tooltest.py 16 KB

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