tooltest.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 = {
  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=''):
  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. if ret == idata: ok()
  219. else:
  220. die(3,red(
  221. "Error: values don't match:\nIn: %s\nOut: %s" % (repr(idata),repr(ret))))
  222. return ret
  223. def run_cmd_nochk(self,name,f1,kwargs=''):
  224. odata = read_from_file(f1).rstrip()
  225. ret = self.run_cmd(name,[odata],kwargs=kwargs)
  226. vmsg('In: ' + repr(odata))
  227. vmsg('Out: ' + repr(ret))
  228. return ret
  229. def run_cmd_out(self,name,carg=None,Return=False,kwargs='',fn_idx='',extra_msg='',literal=False,chkdata='',hush=False):
  230. if carg: write_to_tmpfile(cfg,'%s%s.in' % (name,fn_idx),carg+'\n')
  231. ret = self.run_cmd(name,([],[carg])[bool(carg)],kwargs=kwargs,extra_msg=extra_msg)
  232. if carg: vmsg('In: ' + repr(carg))
  233. vmsg('Out: ' + (repr(ret),ret.decode('utf8'))[literal])
  234. if ret or ret == '':
  235. write_to_tmpfile(cfg,'%s%s.out' % (name,fn_idx),ret+'\n')
  236. if chkdata:
  237. cmp_or_die(ret,chkdata)
  238. return
  239. if Return: return ret
  240. else:
  241. if not hush: ok()
  242. else:
  243. die(3,red("Error for command '%s'" % name))
  244. def run_cmd_randinput(self,name,strip=True):
  245. s = os.urandom(128)
  246. fn = name+'.in'
  247. write_to_tmpfile(cfg,fn,s,binary=True)
  248. ret = self.run_cmd(name,[get_tmpfile_fn(cfg,fn)],strip=strip)
  249. fn = name+'.out'
  250. write_to_tmpfile(cfg,fn,ret+'\n')
  251. ok()
  252. vmsg('Returned: %s' % ret)
  253. # Util
  254. def Strtob58(self,name): self.run_cmd_out(name,getrandstr(16))
  255. def B58tostr(self,name,f1,f2): self.run_cmd_chk(name,f1,f2)
  256. def Hextob58(self,name): self.run_cmd_out(name,getrandhex(32))
  257. def B58tohex(self,name,f1,f2): self.run_cmd_chk(name,f1,f2)
  258. def B58randenc(self,name):
  259. ret = self.run_cmd_out(name,Return=True)
  260. ok_or_die(ret,is_b58_str,'base 58 string')
  261. def Hextob32(self,name): self.run_cmd_out(name,getrandhex(24))
  262. def B32tohex(self,name,f1,f2): self.run_cmd_chk(name,f1,f2)
  263. def Randhex(self,name):
  264. ret = self.run_cmd_out(name,Return=True)
  265. ok_or_die(ret,binascii.unhexlify,'hex string')
  266. def Id6(self,name): self.run_cmd_randinput(name)
  267. def Id8(self,name): self.run_cmd_randinput(name)
  268. def Str2id6(self,name):
  269. s = getrandstr(120,no_space=True)
  270. s2 = ' %s %s %s %s %s ' % (s[:3],s[3:9],s[9:29],s[29:50],s[50:120])
  271. ret1 = self.run_cmd(name,[s],extra_msg='unspaced input'); ok()
  272. ret2 = self.run_cmd(name,[s2],extra_msg='spaced input')
  273. cmp_or_die(ret1,ret2)
  274. vmsg('Returned: %s' % ret1)
  275. def Hash160(self,name): self.run_cmd_out(name,getrandhex(16))
  276. def Hash256(self,name): self.run_cmd_out(name,getrandstr(16))
  277. def Hexreverse(self,name): self.run_cmd_out(name,getrandhex(24))
  278. def Hexlify(self,name): self.run_cmd_out(name,getrandstr(24))
  279. def Hexdump(self,name): self.run_cmd_randinput(name,strip=False)
  280. def Unhexdump(self,name,fn1,fn2):
  281. ret = self.run_cmd(name,[fn2],strip=False)
  282. orig = read_from_file(fn1,binary=True)
  283. cmp_or_die(orig,ret)
  284. def Rand2file(self,name):
  285. of = name + '.out'
  286. dlen = 1024
  287. self.run_cmd(name,[of,str(1024),'threads=4','silent=1'],strip=False)
  288. d = read_from_tmpfile(cfg,of,binary=True)
  289. cmp_or_die(dlen,len(d))
  290. # Bitcoin
  291. def Randwif(self,name):
  292. for n,k in enumerate(['','compressed=1']):
  293. ret = self.run_cmd_out(name,kwargs=k,Return=True,fn_idx=n+1)
  294. ok_or_die(ret,is_wif,'WIF key')
  295. def Randpair(self,name):
  296. for n,k in enumerate(['','compressed=1','segwit=1 compressed=1']):
  297. wif,addr = self.run_cmd_out(name,kwargs=k,Return=True,fn_idx=n+1).split()
  298. ok_or_die(wif,is_wif,'WIF key',skip_ok=True)
  299. ok_or_die(addr,is_btc_addr,'Bitcoin address')
  300. def Wif2addr(self,name,f1,f2,f3):
  301. for n,f,k,m in (1,f1,'',''),(2,f2,'','compressed'),(3,f3,'segwit=1','compressed'):
  302. wif = read_from_file(f).split()[0]
  303. self.run_cmd_out(name,wif,kwargs=k,fn_idx=n,extra_msg=m)
  304. def Wif2hex(self,name,f1,f2,f3):
  305. for n,f,m in (1,f1,''),(2,f2,'compressed'),(3,f3,'compressed for segwit'):
  306. wif = read_from_file(f).split()[0]
  307. self.run_cmd_out(name,wif,fn_idx=n,extra_msg=m)
  308. def Privhex2addr(self,name,f1,f2,f3):
  309. keys = [read_from_file(f).rstrip() for f in f1,f2,f3]
  310. for n,k in enumerate(('','compressed=1','compressed=1 segwit=1')):
  311. ret = self.run_cmd(name,[keys[n]],kwargs=k).rstrip()
  312. iaddr = read_from_tmpfile(cfg,'Randpair{}.out'.format(n+1)).split()[-1]
  313. cmp_or_die(iaddr,ret)
  314. def Hex2wif(self,name,f1,f2,f3,f4):
  315. for n,fi,fo,k in (1,f1,f2,''),(2,f3,f4,'compressed=1'):
  316. ret = self.run_cmd_chk(name,fi,fo,kwargs=k)
  317. def Addr2hexaddr(self,name,f1,f2):
  318. for n,f,m in (1,f1,''),(2,f2,'from compressed'):
  319. addr = read_from_file(f).split()[-1]
  320. self.run_cmd_out(name,addr,fn_idx=n,extra_msg=m)
  321. def Hexaddr2addr(self,name,f1,f2,f3,f4):
  322. for n,fi,fo,m in (1,f1,f2,''),(2,f3,f4,'from compressed'):
  323. self.run_cmd_chk(name,fi,fo,extra_msg=m)
  324. def Privhex2pubhex(self,name,f1,f2,f3): # from hex2wif
  325. addr = read_from_file(f3).strip()
  326. self.run_cmd_out(name,addr,kwargs='compressed=1',fn_idx=3)
  327. def Pubhex2redeem_script(self,name,f1,f2,f3): # from above
  328. addr = read_from_file(f3).strip()
  329. self.run_cmd_out(name,addr,fn_idx=3)
  330. rs = read_from_tmpfile(cfg,name+'3.out').strip()
  331. self.run_cmd_out('pubhex2addr',rs,kwargs='p2sh=1',fn_idx=3,hush=True)
  332. addr1 = read_from_tmpfile(cfg,'pubhex2addr3.out').strip()
  333. addr2 = read_from_tmpfile(cfg,'Randpair3.out').split()[1]
  334. cmp_or_die(addr1,addr2)
  335. def Wif2redeem_script(self,name,f1,f2,f3): # compare output with above
  336. wif = read_from_file(f3).split()[0]
  337. ret1 = self.run_cmd_out(name,wif,fn_idx=3,Return=True)
  338. ret2 = read_from_tmpfile(cfg,'Pubhex2redeem_script3.out').strip()
  339. cmp_or_die(ret1,ret2)
  340. def Wif2segwit_pair(self,name,f1,f2): # does its own checking, so just run
  341. wif = read_from_file(f2).split()[0]
  342. self.run_cmd_out(name,wif,fn_idx=2)
  343. def Pubhex2addr(self,name,f1,f2,f3):
  344. addr = read_from_file(f3).strip()
  345. self.run_cmd_out(name,addr,fn_idx=3)
  346. def Pipetest(self,name,f1,f2,f3):
  347. test_msg('command piping')
  348. wif = read_from_file(f3).split()[0]
  349. 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))
  350. p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  351. res = p.stdout.read().strip()
  352. addr = read_from_tmpfile(cfg,'Wif2addr3.out').strip()
  353. cmp_or_die(res,addr)
  354. # Mnemonic
  355. def Hex2mn(self,name):
  356. for n,size,m in(1,16,'128-bit'),(2,24,'192-bit'),(3,32,'256-bit'):
  357. hexnum = getrandhex(size)
  358. self.run_cmd_out(name,hexnum,fn_idx=n,extra_msg=m)
  359. def Mn2hex(self,name,f1,f2,f3,f4,f5,f6):
  360. for f_i,f_o,m in (f1,f2,'128-bit'),(f3,f4,'192-bit'),(f5,f6,'256-bit'):
  361. self.run_cmd_chk(name,f_i,f_o,extra_msg=m)
  362. def Mn_rand128(self,name): self.run_cmd_out(name)
  363. def Mn_rand192(self,name): self.run_cmd_out(name)
  364. def Mn_rand256(self,name): self.run_cmd_out(name)
  365. def Mn_stats(self,name): self.run_cmd_out(name)
  366. def Mn_printlist(self,name):
  367. self.run_cmd(name,[])
  368. ok()
  369. # RPC
  370. def Addrfile_chksum(self,name):
  371. fn = os.path.join(cfg['refdir'],cfg['addrfile'])
  372. self.run_cmd_out(name,fn,literal=True,chkdata=cfg['addrfile_chk'])
  373. def Getbalance(self,name):
  374. self.run_cmd_out(name,literal=True)
  375. def Listaddresses(self,name):
  376. self.run_cmd_out(name,literal=True)
  377. def Twview(self,name):
  378. self.run_cmd_out(name,literal=True)
  379. def Txview(self,name):
  380. fn = os.path.join(cfg['refdir'],cfg['txfile'])
  381. self.run_cmd_out(name,fn,literal=True)
  382. # main()
  383. import time
  384. start_time = int(time.time())
  385. ts = MMGenToolTestSuite()
  386. mk_tmpdir(cfg['tmpdir'])
  387. if cmd_args:
  388. if len(cmd_args) != 1:
  389. die(1,'Only one command may be specified')
  390. cmd = cmd_args[0]
  391. if cmd in cmd_data:
  392. msg('Running tests for %s:' % cmd_data[cmd]['desc'])
  393. ts.do_cmds(cmd)
  394. elif cmd == 'clean':
  395. cleandir(cfg['tmpdir'])
  396. sys.exit(0)
  397. else:
  398. die(1,"'%s': unrecognized command" % cmd)
  399. else:
  400. cleandir(cfg['tmpdir'])
  401. for cmd in cmd_data:
  402. msg('Running tests for %s:' % cmd_data[cmd]['desc'])
  403. ts.do_cmds(cmd)
  404. if cmd is not cmd_data.keys()[-1]: msg('')
  405. t = int(time.time()) - start_time
  406. msg(green(
  407. 'All requested tests finished OK, elapsed time: %02i:%02i' % (t/60,t%60)))