tooltest.py 16 KB

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