tooltest.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  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
  22. pn = os.path.dirname(sys.argv[0])
  23. os.chdir(os.path.join(pn,os.pardir))
  24. sys.path.__setitem__(0,os.path.abspath(os.curdir))
  25. # Import this _after_ local path's been added to sys.path
  26. from mmgen.common import *
  27. from collections import OrderedDict
  28. cmd_data = OrderedDict([
  29. ('util', {
  30. 'desc': 'base conversion, hashing and file utilities',
  31. 'cmd_data': OrderedDict([
  32. ('Strtob58', ()),
  33. ('B58tostr', ('Strtob58','io')),
  34. ('Hextob58', ()),
  35. ('B58tohex', ('Hextob58','io')),
  36. ('B58randenc', ()),
  37. ('Hextob32', ()),
  38. ('B32tohex', ('Hextob32','io')),
  39. ('Randhex', ()),
  40. ('Id6', ()),
  41. ('Id8', ()),
  42. ('Str2id6', ()),
  43. ('Hash160', ()),
  44. ('Hash256', ()),
  45. ('Hexreverse', ()),
  46. ('Hexlify', ()),
  47. ('Hexdump', ()),
  48. ('Unhexdump', ('Hexdump','io')),
  49. ('Rand2file', ()),
  50. ])
  51. }
  52. ),
  53. ('bitcoin', {
  54. 'desc': 'Bitcoin address/key commands',
  55. 'cmd_data': OrderedDict([
  56. ('Randwif', ()),
  57. ('Randpair', ()), # create 3 pairs: uncomp,comp,segwit
  58. ('Wif2addr', ('Randpair','o3')),
  59. ('Wif2hex', ('Randpair','o3')),
  60. ('Privhex2pubhex', ('Wif2hex','o3')),
  61. ('Pubhex2addr', ('Privhex2pubhex','o3')),
  62. ('Pubhex2redeem_script', ('Privhex2pubhex','o3')),
  63. ('Wif2redeem_script', ('Randpair','o3')),
  64. ('Wif2segwit_pair', ('Randpair','o2')),
  65. ('Privhex2addr', ('Wif2hex','o3')), # compare with output of Randpair
  66. ('Hex2wif', ('Wif2hex','io2')),
  67. ('Addr2hexaddr', ('Randpair','o2')),
  68. ('Hexaddr2addr', ('Addr2hexaddr','io2')),
  69. ('Pipetest', ('Randpair','o3')),
  70. ])
  71. }
  72. ),
  73. ('mnemonic', {
  74. 'desc': 'mnemonic commands',
  75. 'cmd_data': OrderedDict([
  76. ('Hex2mn', ()),
  77. ('Mn2hex', ('Hex2mn','io3')),
  78. ('Mn_rand128', ()),
  79. ('Mn_rand192', ()),
  80. ('Mn_rand256', ()),
  81. ('Mn_stats', ()),
  82. ('Mn_printlist', ()),
  83. ])
  84. }
  85. ),
  86. ('rpc', {
  87. 'desc': 'Bitcoind RPC commands',
  88. 'cmd_data': OrderedDict([
  89. # ('keyaddrfile_chksum', ()), # interactive
  90. ('Addrfile_chksum', ()),
  91. ('Getbalance', ()),
  92. ('Listaddresses', ()),
  93. ('Twview', ()),
  94. ('Txview', ()),
  95. ])
  96. }
  97. ),
  98. ])
  99. cfg = {
  100. 'name': 'the tool utility',
  101. 'enc_passwd': 'Ten Satoshis',
  102. 'tmpdir': 'test/tmp10',
  103. 'tmpdir_num': 10,
  104. 'refdir': 'test/ref',
  105. 'txfile': 'FFB367[1.234].rawtx',
  106. 'addrfile': '98831F3A[1,31-33,500-501,1010-1011].addrs',
  107. 'addrfile_chk': '6FEF 6FB9 7B13 5D91',
  108. }
  109. opts_data = lambda: {
  110. 'desc': "Test suite for the 'mmgen-tool' utility",
  111. 'usage':'[options] [command]',
  112. 'options': """
  113. -h, --help Print this help message
  114. --, --longhelp Print help message for long options (common options)
  115. -l, --list-cmds List and describe the tests and commands in this test suite
  116. -L, --list-names List the names of all tested 'mmgen-tool' commands
  117. -s, --system Test scripts and modules installed on system rather than
  118. those in the repo root
  119. -v, --verbose Produce more verbose output
  120. """,
  121. 'notes': """
  122. If no command is given, the whole suite of tests is run.
  123. """
  124. }
  125. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  126. cmd_args = opts.init(opts_data,add_opts=['exact_output','profile'])
  127. spawn_cmd = ['python',os.path.join(os.curdir,'mmgen-tool') if not opt.system else 'mmgen-tool']
  128. add_spawn_args = ' '.join(['{} {}'.format(
  129. '--'+k.replace('_','-'),
  130. getattr(opt,k) if getattr(opt,k) != True else ''
  131. ) for k in ('testnet','rpc_host','regtest') if getattr(opt,k)]).split()
  132. add_spawn_args += [ '--data-dir', cfg['tmpdir']] # ignore ~/.mmgen
  133. if opt.system: sys.path.pop(0)
  134. if opt.list_cmds:
  135. fs = ' {:<{w}} - {}'
  136. Msg('Available commands:')
  137. w = max([len(i) for i in cmd_data])
  138. for cmd in cmd_data:
  139. Msg(fs.format(cmd,cmd_data[cmd]['desc'],w=w))
  140. Msg('\nAvailable utilities:')
  141. Msg(fs.format('clean','Clean the tmp directory',w=w))
  142. sys.exit(0)
  143. if opt.list_names:
  144. acc = []
  145. for v in cmd_data.values():
  146. acc += v['cmd_data'].keys()
  147. tc = sorted(c.lower() for c in acc)
  148. msg('{}\n{}'.format(green('Tested commands:'),'\n'.join(tc)))
  149. import mmgen.tool
  150. tested_in_tool = ('Encrypt','Decrypt','Find_incog_data','Keyaddrfile_chksum','Passwdfile_chksum')
  151. ignore = ('Help','Usage')
  152. uc = sorted(c.lower() for c in set(mmgen.tool.cmd_data.keys()) - set(acc) - set(ignore) - set(tested_in_tool))
  153. msg('\n{}\n{}'.format(yellow('Untested commands:'),'\n'.join(uc)))
  154. die()
  155. import binascii
  156. from mmgen.test import *
  157. from mmgen.tx import is_wif,is_btc_addr
  158. msg_w = 35
  159. def test_msg(m):
  160. m2 = 'Testing {}'.format(m)
  161. msg_r(green(m2+'\n') if opt.verbose else '{:{w}}'.format(m2,w=msg_w+8))
  162. class MMGenToolTestSuite(object):
  163. def __init__(self):
  164. pass
  165. def gen_deps_for_cmd(self,cmd,cdata):
  166. fns = []
  167. if cdata:
  168. name,code = cdata
  169. io,count = (code[:-1],int(code[-1])) if code[-1] in '0123456789' else (code,1)
  170. for c in range(count):
  171. fns += ['%s%s%s' % (
  172. name,
  173. ('',c+1)[count > 1],
  174. ('.out','.in')[ch=='i']
  175. ) for ch in io]
  176. return fns
  177. def get_num_exts_for_cmd(self,cmd,dpy): # dpy required here
  178. num = str(tool_cfgs['tmpdir_num'])
  179. # return only first file - a hack
  180. exts = gen_deps_for_cmd(dpy)
  181. return num,exts
  182. def do_cmds(self,cmd_group):
  183. cdata = cmd_data[cmd_group]['cmd_data']
  184. for cmd in cdata: self.do_cmd(cmd,cdata[cmd])
  185. def do_cmd(self,cmd,cdata):
  186. fns = self.gen_deps_for_cmd(cmd,cdata)
  187. file_list = [os.path.join(cfg['tmpdir'],fn) for fn in fns]
  188. self.__class__.__dict__[cmd](*([self,cmd] + file_list))
  189. def run_cmd(self,name,tool_args,kwargs='',extra_msg='',silent=False,strip=True):
  190. sys_cmd = (
  191. spawn_cmd +
  192. add_spawn_args +
  193. ['-r0','-d',cfg['tmpdir'],name.lower()] +
  194. tool_args +
  195. kwargs.split()
  196. )
  197. if extra_msg: extra_msg = '({})'.format(extra_msg)
  198. full_name = ' '.join([name.lower()]+kwargs.split()+extra_msg.split())
  199. if not silent:
  200. if opt.verbose:
  201. sys.stderr.write(green('Testing {}\nExecuting '.format(full_name)))
  202. sys.stderr.write(cyan(' '.join(sys_cmd)+'\n'))
  203. else:
  204. msg_r('Testing {:{w}}'.format(full_name+':',w=msg_w))
  205. p = subprocess.Popen(sys_cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  206. a,b = p.communicate()
  207. retcode = p.wait()
  208. if retcode != 0:
  209. msg('%s\n%s\n%s'%(red('FAILED'),yellow('Command stderr output:'),b))
  210. die(1,red('Called process returned with an error (retcode %s)' % retcode))
  211. return (a,a.rstrip())[bool(strip)]
  212. def run_cmd_chk(self,name,f1,f2,kwargs='',extra_msg='',strip_hex=False):
  213. idata = read_from_file(f1).rstrip()
  214. odata = read_from_file(f2).rstrip()
  215. ret = self.run_cmd(name,[odata],kwargs=kwargs,extra_msg=extra_msg)
  216. vmsg('In: ' + repr(odata))
  217. vmsg('Out: ' + repr(ret))
  218. def cmp_equal(a,b):
  219. return (a.lstrip('0') == b.lstrip('0')) if strip_hex else (a == b)
  220. if cmp_equal(ret,idata): ok()
  221. else:
  222. die(3,red(
  223. "Error: values don't match:\nIn: %s\nOut: %s" % (repr(idata),repr(ret))))
  224. return ret
  225. def run_cmd_nochk(self,name,f1,kwargs=''):
  226. odata = read_from_file(f1).rstrip()
  227. ret = self.run_cmd(name,[odata],kwargs=kwargs)
  228. vmsg('In: ' + repr(odata))
  229. vmsg('Out: ' + repr(ret))
  230. return ret
  231. def run_cmd_out(self,name,carg=None,Return=False,kwargs='',fn_idx='',extra_msg='',literal=False,chkdata='',hush=False):
  232. if carg: write_to_tmpfile(cfg,'%s%s.in' % (name,fn_idx),carg+'\n')
  233. ret = self.run_cmd(name,([],[carg])[bool(carg)],kwargs=kwargs,extra_msg=extra_msg)
  234. if carg: vmsg('In: ' + repr(carg))
  235. vmsg('Out: ' + (repr(ret),ret.decode('utf8'))[literal])
  236. if ret or ret == '':
  237. write_to_tmpfile(cfg,'%s%s.out' % (name,fn_idx),ret+'\n')
  238. if chkdata:
  239. cmp_or_die(ret,chkdata)
  240. return
  241. if Return: return ret
  242. else:
  243. if not hush: ok()
  244. else:
  245. die(3,red("Error for command '%s'" % name))
  246. def run_cmd_randinput(self,name,strip=True):
  247. s = os.urandom(128)
  248. fn = name+'.in'
  249. write_to_tmpfile(cfg,fn,s,binary=True)
  250. ret = self.run_cmd(name,[get_tmpfile_fn(cfg,fn)],strip=strip)
  251. fn = name+'.out'
  252. write_to_tmpfile(cfg,fn,ret+'\n')
  253. ok()
  254. vmsg('Returned: %s' % ret)
  255. # Util
  256. def Strtob58(self,name): self.run_cmd_out(name,getrandstr(16))
  257. def B58tostr(self,name,f1,f2): self.run_cmd_chk(name,f1,f2)
  258. def Hextob58(self,name): self.run_cmd_out(name,getrandhex(32))
  259. def B58tohex(self,name,f1,f2): self.run_cmd_chk(name,f1,f2,strip_hex=True)
  260. def B58randenc(self,name):
  261. ret = self.run_cmd_out(name,Return=True)
  262. ok_or_die(ret,is_b58_str,'base 58 string')
  263. def Hextob32(self,name): self.run_cmd_out(name,getrandhex(24))
  264. def B32tohex(self,name,f1,f2): self.run_cmd_chk(name,f1,f2,strip_hex=True)
  265. def Randhex(self,name):
  266. ret = self.run_cmd_out(name,Return=True)
  267. ok_or_die(ret,binascii.unhexlify,'hex string')
  268. def Id6(self,name): self.run_cmd_randinput(name)
  269. def Id8(self,name): self.run_cmd_randinput(name)
  270. def Str2id6(self,name):
  271. s = getrandstr(120,no_space=True)
  272. s2 = ' %s %s %s %s %s ' % (s[:3],s[3:9],s[9:29],s[29:50],s[50:120])
  273. ret1 = self.run_cmd(name,[s],extra_msg='unspaced input'); ok()
  274. ret2 = self.run_cmd(name,[s2],extra_msg='spaced input')
  275. cmp_or_die(ret1,ret2)
  276. vmsg('Returned: %s' % ret1)
  277. def Hash160(self,name): self.run_cmd_out(name,getrandhex(16))
  278. def Hash256(self,name): self.run_cmd_out(name,getrandstr(16))
  279. def Hexreverse(self,name): self.run_cmd_out(name,getrandhex(24))
  280. def Hexlify(self,name): self.run_cmd_out(name,getrandstr(24))
  281. def Hexdump(self,name): self.run_cmd_randinput(name,strip=False)
  282. def Unhexdump(self,name,fn1,fn2):
  283. ret = self.run_cmd(name,[fn2],strip=False)
  284. orig = read_from_file(fn1,binary=True)
  285. cmp_or_die(orig,ret)
  286. def Rand2file(self,name):
  287. of = name + '.out'
  288. dlen = 1024
  289. self.run_cmd(name,[of,str(1024),'threads=4','silent=1'],strip=False)
  290. d = read_from_tmpfile(cfg,of,binary=True)
  291. cmp_or_die(dlen,len(d))
  292. # Bitcoin
  293. def Randwif(self,name):
  294. for n,k in enumerate(['','compressed=1']):
  295. ret = self.run_cmd_out(name,kwargs=k,Return=True,fn_idx=n+1)
  296. ok_or_die(ret,is_wif,'WIF key')
  297. def Randpair(self,name):
  298. for n,k in enumerate(['','compressed=1','segwit=1 compressed=1']):
  299. wif,addr = self.run_cmd_out(name,kwargs=k,Return=True,fn_idx=n+1).split()
  300. ok_or_die(wif,is_wif,'WIF key',skip_ok=True)
  301. ok_or_die(addr,is_btc_addr,'Bitcoin address')
  302. def Wif2addr(self,name,f1,f2,f3):
  303. for n,f,k,m in ((1,f1,'',''),(2,f2,'','compressed'),(3,f3,'segwit=1','compressed')):
  304. wif = read_from_file(f).split()[0]
  305. self.run_cmd_out(name,wif,kwargs=k,fn_idx=n,extra_msg=m)
  306. def Wif2hex(self,name,f1,f2,f3):
  307. for n,f,m in ((1,f1,''),(2,f2,'compressed'),(3,f3,'compressed for segwit')):
  308. wif = read_from_file(f).split()[0]
  309. self.run_cmd_out(name,wif,fn_idx=n,extra_msg=m)
  310. def Privhex2addr(self,name,f1,f2,f3):
  311. keys = [read_from_file(f).rstrip() for f in (f1,f2,f3)]
  312. for n,k in enumerate(('','compressed=1','compressed=1 segwit=1')):
  313. ret = self.run_cmd(name,[keys[n]],kwargs=k).rstrip()
  314. iaddr = read_from_tmpfile(cfg,'Randpair{}.out'.format(n+1)).split()[-1]
  315. cmp_or_die(iaddr,ret)
  316. def Hex2wif(self,name,f1,f2,f3,f4):
  317. for n,fi,fo,k in ((1,f1,f2,''),(2,f3,f4,'compressed=1')):
  318. ret = self.run_cmd_chk(name,fi,fo,kwargs=k)
  319. def Addr2hexaddr(self,name,f1,f2):
  320. for n,f,m in ((1,f1,''),(2,f2,'from compressed')):
  321. addr = read_from_file(f).split()[-1]
  322. self.run_cmd_out(name,addr,fn_idx=n,extra_msg=m)
  323. def Hexaddr2addr(self,name,f1,f2,f3,f4):
  324. for n,fi,fo,m in ((1,f1,f2,''),(2,f3,f4,'from compressed')):
  325. self.run_cmd_chk(name,fi,fo,extra_msg=m)
  326. def Privhex2pubhex(self,name,f1,f2,f3): # from Hex2wif
  327. addr = read_from_file(f3).strip()
  328. self.run_cmd_out(name,addr,kwargs='compressed=1',fn_idx=3)
  329. def Pubhex2redeem_script(self,name,f1,f2,f3): # from above
  330. addr = read_from_file(f3).strip()
  331. self.run_cmd_out(name,addr,fn_idx=3)
  332. rs = read_from_tmpfile(cfg,name+'3.out').strip()
  333. self.run_cmd_out('pubhex2addr',rs,kwargs='p2sh=1',fn_idx=3,hush=True)
  334. addr1 = read_from_tmpfile(cfg,'pubhex2addr3.out').strip()
  335. addr2 = read_from_tmpfile(cfg,'Randpair3.out').split()[1]
  336. cmp_or_die(addr1,addr2)
  337. def Wif2redeem_script(self,name,f1,f2,f3): # compare output with above
  338. wif = read_from_file(f3).split()[0]
  339. ret1 = self.run_cmd_out(name,wif,fn_idx=3,Return=True)
  340. ret2 = read_from_tmpfile(cfg,'Pubhex2redeem_script3.out').strip()
  341. cmp_or_die(ret1,ret2)
  342. def Wif2segwit_pair(self,name,f1,f2): # does its own checking, so just run
  343. wif = read_from_file(f2).split()[0]
  344. self.run_cmd_out(name,wif,fn_idx=2)
  345. def Pubhex2addr(self,name,f1,f2,f3):
  346. addr = read_from_file(f3).strip()
  347. self.run_cmd_out(name,addr,fn_idx=3)
  348. def Pipetest(self,name,f1,f2,f3):
  349. test_msg('command piping')
  350. wif = read_from_file(f3).split()[0]
  351. cmd = '{tc} {sa} wif2hex {wif} | {tc} privhex2pubhex - compressed=1 | {tc} pubhex2redeem_script - | {tc} {sa} pubhex2addr - p2sh=1'.format(wif=wif,sa=' '.join(add_spawn_args),tc=' '.join(spawn_cmd))
  352. p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  353. res = p.stdout.read().strip()
  354. addr = read_from_tmpfile(cfg,'Wif2addr3.out').strip()
  355. cmp_or_die(res,addr)
  356. # Mnemonic
  357. def Hex2mn(self,name):
  358. for n,size,m in ((1,16,'128-bit'),(2,24,'192-bit'),(3,32,'256-bit')):
  359. hexnum = getrandhex(size)
  360. self.run_cmd_out(name,hexnum,fn_idx=n,extra_msg=m)
  361. def Mn2hex(self,name,f1,f2,f3,f4,f5,f6):
  362. for f_i,f_o,m in ((f1,f2,'128-bit'),(f3,f4,'192-bit'),(f5,f6,'256-bit')):
  363. self.run_cmd_chk(name,f_i,f_o,extra_msg=m)
  364. def Mn_rand128(self,name): self.run_cmd_out(name)
  365. def Mn_rand192(self,name): self.run_cmd_out(name)
  366. def Mn_rand256(self,name): self.run_cmd_out(name)
  367. def Mn_stats(self,name): self.run_cmd_out(name)
  368. def Mn_printlist(self,name):
  369. self.run_cmd(name,[])
  370. ok()
  371. # RPC
  372. def Addrfile_chksum(self,name):
  373. fn = os.path.join(cfg['refdir'],cfg['addrfile'])
  374. self.run_cmd_out(name,fn,literal=True,chkdata=cfg['addrfile_chk'])
  375. def Getbalance(self,name):
  376. self.run_cmd_out(name,literal=True)
  377. def Listaddresses(self,name):
  378. self.run_cmd_out(name,literal=True)
  379. def Twview(self,name):
  380. self.run_cmd_out(name,literal=True)
  381. def Txview(self,name):
  382. fn = os.path.join(cfg['refdir'],cfg['txfile'])
  383. self.run_cmd_out(name,fn,literal=True)
  384. # main()
  385. import time
  386. start_time = int(time.time())
  387. ts = MMGenToolTestSuite()
  388. mk_tmpdir(cfg['tmpdir'])
  389. if cmd_args:
  390. if len(cmd_args) != 1:
  391. die(1,'Only one command may be specified')
  392. cmd = cmd_args[0]
  393. if cmd in cmd_data:
  394. msg('Running tests for %s:' % cmd_data[cmd]['desc'])
  395. ts.do_cmds(cmd)
  396. elif cmd == 'clean':
  397. cleandir(cfg['tmpdir'])
  398. sys.exit(0)
  399. else:
  400. die(1,"'%s': unrecognized command" % cmd)
  401. else:
  402. cleandir(cfg['tmpdir'])
  403. for cmd in cmd_data:
  404. msg('Running tests for %s:' % cmd_data[cmd]['desc'])
  405. ts.do_cmds(cmd)
  406. if cmd is not cmd_data.keys()[-1]: msg('')
  407. t = int(time.time()) - start_time
  408. msg(green(
  409. 'All requested tests finished OK, elapsed time: %02i:%02i' % (t/60,t%60)))