ts_misc.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. ts_misc.py: Miscellaneous test groups for the test.py test suite
  20. """
  21. from mmgen.globalvars import g
  22. from test.common import *
  23. from test.test_py_d.common import *
  24. from test.test_py_d.ts_base import *
  25. from test.test_py_d.ts_main import TestSuiteMain
  26. from mmgen.seed import SeedSource
  27. class TestSuiteHelp(TestSuiteBase):
  28. 'help, info and usage screens'
  29. tmpdir_nums = []
  30. passthru_opts = ('coin','testnet')
  31. cmd_group = (
  32. ('helpscreens', (1,'help screens', [])),
  33. ('longhelpscreens', (1,'help screens (--longhelp)',[])),
  34. ('opt_show_hash_presets', (1,'info screen (--show-hash-presets)',[])),
  35. ('tool_help', (1,"'mmgen-tool' usage screen",[])),
  36. ('test_help', (1,"'test.py' help screens",[])),
  37. )
  38. def helpscreens(self,
  39. arg = '--help',
  40. scripts = ( 'walletgen','walletconv','walletchk','passchg','subwalletgen',
  41. 'addrgen','keygen','passgen',
  42. 'seedsplit','seedjoin',
  43. 'txcreate','txsign','txsend','txdo','txbump',
  44. 'addrimport','tool','regtest','autosign')):
  45. for s in scripts:
  46. t = self._run_cmd('mmgen-'+s,[arg],extra_desc='(mmgen-{})'.format(s),no_output=True)
  47. return t
  48. def longhelpscreens(self):
  49. return self.helpscreens(arg='--longhelp')
  50. def opt_show_hash_presets(self):
  51. return self.helpscreens(
  52. arg = '--show-hash-presets',
  53. scripts = (
  54. 'walletgen','walletconv','walletchk','passchg','subwalletgen',
  55. 'addrgen','keygen','passgen',
  56. 'txsign','txdo','txbump'))
  57. def _run_cmd( self, cmd_name,
  58. cmd_args = [],
  59. no_msg = False,
  60. extra_desc = '',
  61. cmd_dir = 'cmds',
  62. no_output = False):
  63. t = self.spawn( cmd_name,
  64. args = cmd_args,
  65. no_msg = no_msg,
  66. extra_desc = extra_desc,
  67. cmd_dir = cmd_dir,
  68. no_output = no_output)
  69. t.read()
  70. ret = t.p.wait()
  71. if ret == 0:
  72. msg('OK')
  73. else:
  74. rdie(1,"\n'{}' returned {}".format(self.test_name,ret))
  75. t.skip_ok = True
  76. return t
  77. def tool_help(self):
  78. self._run_cmd('mmgen-tool',['help'],extra_desc="('mmgen-tool help')")
  79. return self._run_cmd('mmgen-tool',['usage'],extra_desc="('mmgen-tool usage')")
  80. def test_help(self):
  81. self._run_cmd('test.py',['-h'],cmd_dir='test')
  82. self._run_cmd('test.py',['-L'],cmd_dir='test',extra_desc='(cmd group list)')
  83. return self._run_cmd('test.py',['-l'],cmd_dir='test',extra_desc='(cmd list)')
  84. class TestSuiteOutput(TestSuiteBase):
  85. 'screen output tests'
  86. networks = ('btc',)
  87. tmpdir_nums = []
  88. cmd_group = (
  89. ('output_gr', (1,"Greek text", [])),
  90. ('output_ru', (1,"Russian text", [])),
  91. ('output_zh', (1,"Chinese text", [])),
  92. ('output_jp', (1,"Japanese text", []))
  93. )
  94. def screen_output(self,lang):
  95. t = self.spawn('test/misc/utf8_output.py',[lang],cmd_dir='.')
  96. t.read()
  97. return t
  98. def output_gr(self): return self.screen_output('gr')
  99. def output_ru(self): return self.screen_output('ru')
  100. def output_zh(self): return self.screen_output('zh')
  101. def output_jp(self): return self.screen_output('jp')
  102. class TestSuiteInput(TestSuiteBase):
  103. 'user input tests'
  104. networks = ('btc',)
  105. tmpdir_nums = []
  106. cmd_group = (
  107. ('password_entry_noecho', (1,"utf8 password entry", [])),
  108. ('password_entry_echo', (1,"utf8 password entry (echoed)", [])),
  109. ('mnemonic_entry_mmgen', (1,"stealth mnemonic entry (MMGen native)", [])),
  110. ('mnemonic_entry_bip39', (1,"stealth mnemonic entry (BIP39)", [])),
  111. )
  112. def password_entry(self,prompt,cmd_args):
  113. t = self.spawn('test/misc/password_entry.py',cmd_args,cmd_dir='.')
  114. pw = 'abc-α'
  115. t.expect(prompt,pw)
  116. ret = t.expect_getend('Entered: ')
  117. assert ret == pw,'Password mismatch! {} != {}'.format(ret,pw)
  118. return t
  119. def password_entry_noecho(self):
  120. if self.skip_for_win():
  121. msg('Perform this test by hand on MSWin with non-ASCII password abc-α:')
  122. msg(' test/misc/password_entry.py')
  123. return 'skip' # getpass() can't handle utf8, and pexpect double-escapes utf8, so skip
  124. return self.password_entry('Enter passphrase: ',[])
  125. def password_entry_echo(self):
  126. if self.skip_for_win():
  127. msg('Perform this test by hand on MSWin with non-ASCII password abc-α:')
  128. msg(' test/misc/password_entry.py --echo-passphrase')
  129. return 'skip' # pexpect double-escapes utf8, so skip
  130. return self.password_entry('Enter passphrase (echoed): ',['--echo-passphrase'])
  131. def _user_seed_entry(self,fmt,usr_rand=False,out_fmt=None):
  132. wcls = SeedSource.fmt_code_to_type(fmt)
  133. wf = os.path.join(ref_dir,'FE3C6545.{}'.format(wcls.ext))
  134. if wcls.wclass == 'mnemonic':
  135. mn = read_from_file(wf).strip().split()
  136. mn = ['foo'] + mn[:5] + ['grac','graceful'] + mn[5:]
  137. t = self.spawn('mmgen-walletconv',['-r10','-S','-i',fmt,'-o',out_fmt or fmt])
  138. t.expect('{} type: {}'.format(capfirst(wcls.wclass),wcls.mn_type))
  139. t.expect(wcls.choose_seedlen_prompt,'1')
  140. t.expect('(Y/n): ','y')
  141. if wcls.wclass == 'mnemonic':
  142. stealth_mnemonic_entry(t,mn,fmt=fmt)
  143. if not usr_rand:
  144. sid_chk = 'FE3C6545'
  145. sid = t.expect_getend('Valid {} for Seed ID '.format(wcls.desc))[:8]
  146. assert sid == sid_chk,'Seed ID mismatch! {} != {}'.format(sid,sid_chk)
  147. t.expect('to confirm: ','YES\n')
  148. t.read()
  149. return t
  150. def mnemonic_entry_mmgen(self): return self._user_seed_entry('words')
  151. def mnemonic_entry_bip39(self): return self._user_seed_entry('bip39')
  152. class TestSuiteTool(TestSuiteMain,TestSuiteBase):
  153. "tests for interactive 'mmgen-tool' commands"
  154. networks = ('btc',)
  155. segwit_opts_ok = False
  156. tmpdir_nums = [9]
  157. enc_infn = 'tool_encrypt.in'
  158. cmd_group = (
  159. ('tool_find_incog_data', (9,"'mmgen-tool find_incog_data'", [[[hincog_fn],1],[[incog_id_fn],1]])),
  160. ('tool_rand2file', (9,"'mmgen-tool rand2file'", [])),
  161. ('tool_encrypt', (9,"'mmgen-tool encrypt' (random data)", [])),
  162. ('tool_decrypt', (9,"'mmgen-tool decrypt' (random data)", [[[enc_infn+'.mmenc'],9]])),
  163. ('tool_twview_bad_comment',(9,"'mmgen-tool twview' (with bad comment)", [])),
  164. # ('tool_encrypt_ref', (9,"'mmgen-tool encrypt' (reference text)", [])),
  165. )
  166. def tool_rand2file(self):
  167. outfile = os.path.join(self.tmpdir,'rand2file.out')
  168. from mmgen.tool import MMGenToolCmd
  169. tu = MMGenToolCmd()
  170. for nbytes in ('1','1023','1K','1048575','1M','1048577','123M'):
  171. t = self.spawn( 'mmgen-tool',
  172. ['-d',self.tmpdir,'-r0','rand2file','rand2file.out',nbytes],
  173. extra_desc='({} byte{})'.format(nbytes,suf(tu.bytespec(nbytes)))
  174. )
  175. t.expect('random data written to file')
  176. t.read()
  177. t.p.wait()
  178. t.ok()
  179. t.skip_ok = True
  180. return t
  181. def tool_encrypt(self):
  182. infile = joinpath(self.tmpdir,self.enc_infn)
  183. write_to_file(infile,os.urandom(1033),binary=True)
  184. t = self.spawn('mmgen-tool',['-d',self.tmpdir,self.usr_rand_arg,'encrypt',infile])
  185. t.usr_rand(self.usr_rand_chars)
  186. t.hash_preset('user data','1')
  187. t.passphrase_new('user data',tool_enc_passwd)
  188. t.written_to_file('Encrypted data')
  189. return t
  190. def tool_decrypt(self,f1):
  191. out_fn = 'tool_encrypt.out'
  192. t = self.spawn('mmgen-tool',['-d',self.tmpdir,'decrypt',f1,'outfile='+out_fn,'hash_preset=1'])
  193. t.passphrase('user data',tool_enc_passwd)
  194. t.written_to_file('Decrypted data')
  195. d1 = self.read_from_tmpfile(self.enc_infn,binary=True)
  196. d2 = self.read_from_tmpfile(out_fn,binary=True)
  197. cmp_or_die(d1,d2)
  198. return t
  199. def tool_find_incog_data(self,f1,f2):
  200. i_id = read_from_file(f2).rstrip()
  201. vmsg('Incog ID: {}'.format(cyan(i_id)))
  202. t = self.spawn('mmgen-tool',['-d',self.tmpdir,'find_incog_data',f1,i_id])
  203. o = t.expect_getend('Incog data for ID {} found at offset '.format(i_id))
  204. if not g.platform == 'win':
  205. os.unlink(f1) # causes problems with MSYS2
  206. cmp_or_die(hincog_offset,int(o))
  207. return t
  208. def tool_twview_bad_comment(self): # test correct operation of get_tw_label()
  209. bw_save = os.getenv('MMGEN_BOGUS_WALLET_DATA')
  210. os.environ['MMGEN_BOGUS_WALLET_DATA'] = joinpath(ref_dir,'bad-comment-unspent.json')
  211. t = self.spawn('mmgen-tool',['twview'])
  212. if bw_save:
  213. os.environ['MMGEN_BOGUS_WALLET_DATA'] = bw_save
  214. t.read()
  215. t.req_exit_val = 2
  216. return t
  217. class TestSuiteRefTX(TestSuiteMain,TestSuiteBase):
  218. 'create a reference transaction file (administrative command)'
  219. segwit_opts_ok = False
  220. passthru_opts = ('coin','testnet')
  221. tmpdir_nums = [31,32,33,34]
  222. cmd_group = (
  223. ('ref_tx_addrgen1', (31,'address generation (legacy)', [[[],1]])),
  224. ('ref_tx_addrgen2', (32,'address generation (compressed)', [[[],1]])),
  225. ('ref_tx_addrgen3', (33,'address generation (segwit)', [[[],1]])),
  226. ('ref_tx_addrgen4', (34,'address generation (bech32)', [[[],1]])),
  227. ('ref_tx_txcreate', (31,'transaction creation',
  228. ([['addrs'],31],[['addrs'],32],[['addrs'],33],[['addrs'],34]))),
  229. )
  230. def __init__(self,trunner,cfgs,spawn):
  231. if cfgs:
  232. for n in self.tmpdir_nums:
  233. cfgs[str(n)].update({ 'addr_idx_list': '1-2',
  234. 'segwit': n in (33,34),
  235. 'dep_generators': { 'addrs':'ref_tx_addrgen'+str(n)[-1] }})
  236. return TestSuiteMain.__init__(self,trunner,cfgs,spawn)
  237. def ref_tx_addrgen(self,atype):
  238. if atype not in g.proto.mmtypes: return
  239. t = self.spawn('mmgen-addrgen',['--outdir='+self.tmpdir,'--type='+atype,dfl_words_file,'1-2'])
  240. t.read()
  241. return t
  242. def ref_tx_addrgen1(self): return self.ref_tx_addrgen(atype='L')
  243. def ref_tx_addrgen2(self): return self.ref_tx_addrgen(atype='C')
  244. def ref_tx_addrgen3(self): return self.ref_tx_addrgen(atype='S')
  245. def ref_tx_addrgen4(self): return self.ref_tx_addrgen(atype='B')
  246. def ref_tx_txcreate(self,f1,f2,f3,f4):
  247. sources = ['31','32']
  248. if 'S' in g.proto.mmtypes: sources += ['33']
  249. if 'B' in g.proto.mmtypes: sources += ['34']
  250. return self.txcreate_common(
  251. addrs_per_wallet = 2,
  252. sources = sources,
  253. add_args = ['--locktime=1320969600'],
  254. do_label = True )