ct_misc.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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.cmdtest_py_d.ct_misc: Miscellaneous test groups for the cmdtest.py test suite
  20. """
  21. import sys,os,re,time
  22. from mmgen.util import ymsg
  23. from ..include.common import cfg,start_test_daemons,stop_test_daemons,imsg
  24. from .common import get_file_with_ext,dfl_words_file
  25. from .ct_base import CmdTestBase
  26. from .ct_main import CmdTestMain
  27. class CmdTestDev(CmdTestBase):
  28. 'developer scripts'
  29. networks = ('btc',)
  30. cmd_group = (
  31. ('compute_file_chksum', 'scripts/compute-file-chksum.py'),
  32. ('create_bip_hd_chain_params', 'scripts/create-bip-hd-chain-params.py'),
  33. )
  34. tmpdir_nums = [99]
  35. color = True
  36. def _spawn(self,script,args):
  37. return self.spawn(script,args,cmd_dir='.',no_exec_wrapper=True)
  38. def compute_file_chksum(self):
  39. t = self._spawn('scripts/compute-file-chksum.py', ['test/ref/25EFA3[2.34].testnet.rawtx'])
  40. t.expect('3df942')
  41. return t
  42. def create_bip_hd_chain_params(self):
  43. t = self._spawn('scripts/create-bip-hd-chain-params.py', ['test/ref/altcoin/slip44-mini.json'])
  44. t.expect('[defaults]')
  45. t.expect(r"secp.*0488ade4.*0488b21e.*0'\/0\/0",regex=True)
  46. t.expect('[bip-44]')
  47. t.expect('[bip-49]')
  48. t.match_expect_list(['0','BTC','x','m','P2SH','049d7878','049d7cb2','80','05','x','Bitcoin','1'])
  49. return t
  50. class CmdTestMisc(CmdTestBase):
  51. 'miscellaneous tests (RPC backends, xmrwallet_txview, term)'
  52. networks = ('btc',)
  53. tmpdir_nums = [99]
  54. passthru_opts = ('daemon_data_dir','rpc_port')
  55. cmd_group = (
  56. ('rpc_backends', 'RPC backends'),
  57. ('xmrwallet_txview', "'mmgen-xmrwallet' txview"),
  58. ('xmrwallet_txlist', "'mmgen-xmrwallet' txlist"),
  59. ('coin_daemon_info', "'examples/coin-daemon-info.py'"),
  60. ('examples_bip_hd', "'examples/bip_hd.py'"),
  61. ('term_echo', "term.set('echo')"),
  62. ('term_cleanup', 'term.register_cleanup()'),
  63. )
  64. need_daemon = True
  65. color = True
  66. def rpc_backends(self):
  67. backends = cfg._autoset_opts['rpc_backend'][1]
  68. for b in backends:
  69. t = self.spawn_chk('mmgen-tool',[f'--rpc-backend={b}','daemon_version'],extra_desc=f'({b})')
  70. return t
  71. def xmrwallet_txview(self,op='txview'):
  72. if cfg.no_altcoin:
  73. return 'skip'
  74. files = get_file_with_ext('test/ref/monero','tx',no_dot=True,delete=False,return_list=True)
  75. t = self.spawn( 'mmgen-xmrwallet', [op] + files )
  76. res = t.read(strip_color=True)
  77. if op == 'txview':
  78. for s in (
  79. 'Amount: 0.74 XMR',
  80. 'Dest: 56VQ9M6k',
  81. ):
  82. assert s in res, f'{s} not in {res}'
  83. elif op == 'txlist':
  84. assert re.search( '3EBD06-.*D94583-.*8BFA29-', res, re.DOTALL )
  85. return t
  86. def xmrwallet_txlist(self):
  87. return self.xmrwallet_txview(op='txlist')
  88. def examples_bip_hd(self):
  89. return self.spawn('examples/bip_hd.py',cmd_dir='.')
  90. def coin_daemon_info(self):
  91. if cfg.no_altcoin:
  92. coins = ['btc']
  93. else:
  94. coins = ['btc','ltc','eth']
  95. start_test_daemons('ltc','eth')
  96. t = self.spawn('examples/coin-daemon-info.py',coins,cmd_dir='.')
  97. for coin in coins:
  98. t.expect(coin.upper() + r'\s+mainnet\s+Up',regex=True)
  99. if cfg.pexpect_spawn:
  100. t.send('q')
  101. if not cfg.no_altcoin:
  102. stop_test_daemons('ltc','eth')
  103. return t
  104. def term_echo(self):
  105. def test_echo():
  106. t.expect('echo> ','foo\n')
  107. t.expect('foo')
  108. def test_noecho():
  109. t.expect('noecho> ','foo\n')
  110. import pexpect
  111. try:
  112. t.expect('foo')
  113. except pexpect.TIMEOUT:
  114. imsg('[input not echoed - OK]')
  115. t.send('x')
  116. if self.skip_for_win():
  117. return 'skip'
  118. t = self.spawn('test/misc/term_ni.py',['echo'],cmd_dir='.',pexpect_spawn=True,timeout=1)
  119. t.p.logfile = None
  120. t.p.logfile_read = sys.stdout if cfg.verbose or cfg.exact_output else None
  121. t.p.logfile_send = None
  122. test_noecho()
  123. test_echo()
  124. test_noecho()
  125. return t
  126. def term_cleanup(self):
  127. if self.skip_for_win():
  128. return 'skip'
  129. return self.spawn('test/misc/term_ni.py',['cleanup'],cmd_dir='.',pexpect_spawn=True)
  130. class CmdTestHelp(CmdTestBase):
  131. 'help, info and usage screens'
  132. networks = ('btc','ltc','bch','eth','xmr')
  133. passthru_opts = ('daemon_data_dir','rpc_port','coin','testnet')
  134. cmd_group = (
  135. ('usage', (1,'usage message',[])),
  136. ('version', (1,'version message',[])),
  137. ('license', (1,'license message',[])),
  138. ('helpscreens', (1,'help screens', [])),
  139. ('longhelpscreens', (1,'help screens (--longhelp)',[])),
  140. ('show_hash_presets', (1,'info screen (--show-hash-presets)',[])),
  141. ('tool_help', (1,"'mmgen-tool' usage screen",[])),
  142. ('tool_cmd_usage', (1,"'mmgen-tool' usage screen",[])),
  143. ('test_help', (1,"'cmdtest.py' help screens",[])),
  144. ('tooltest_help', (1,"'tooltest.py' help screens",[])),
  145. )
  146. def usage(self):
  147. t = self.spawn('mmgen-walletgen',['foo'])
  148. t.expect('MMGenSystemExit(1)')
  149. t.expect('USAGE: mmgen-walletgen')
  150. t.req_exit_val = 1
  151. return t
  152. def version(self):
  153. t = self.spawn('mmgen-tool',['--version'])
  154. t.expect('MMGEN-TOOL version')
  155. return t
  156. def license(self):
  157. t = self.spawn(
  158. 'mmgen-walletconv',
  159. ['--stdout','--in-fmt=hex','--out-fmt=hex'],
  160. env = {'MMGEN_NO_LICENSE':''} )
  161. t.expect('to continue: ', 'w')
  162. t.expect('TERMS AND CONDITIONS') # start of GPL text
  163. if cfg.pexpect_spawn:
  164. t.send('G')
  165. t.expect('return for a fee.') # end of GPL text
  166. if cfg.pexpect_spawn:
  167. t.send('q')
  168. t.expect('to continue: ', 'c')
  169. t.expect('data: ','beadcafe'*4 + '\n')
  170. t.expect('to confirm: ', 'YES\n')
  171. return t
  172. def spawn_chk_expect(self,*args,**kwargs):
  173. expect = kwargs.pop('expect')
  174. t = self.spawn(*args,**kwargs)
  175. t.expect(expect)
  176. if t.pexpect_spawn:
  177. time.sleep(0.4)
  178. t.send('q')
  179. t.read()
  180. t.ok()
  181. t.skip_ok = True
  182. return t
  183. def helpscreens(self,arg='--help',scripts=(),expect='USAGE:.*OPTIONS:',pager=True):
  184. scripts = list(scripts) or [s.replace('mmgen-','') for s in os.listdir('cmds')]
  185. if 'tx' not in self.proto.mmcaps:
  186. scripts = [s for s in scripts if not (s == 'regtest' or s.startswith('tx'))]
  187. if self.proto.coin not in ('BTC','XMR') and 'xmrwallet' in scripts:
  188. scripts.remove('xmrwallet')
  189. if sys.platform == 'win32' and 'autosign' in scripts:
  190. scripts.remove('autosign')
  191. for s in sorted(scripts):
  192. t = self.spawn(f'mmgen-{s}',[arg],extra_desc=f'(mmgen-{s})')
  193. t.expect(expect,regex=True)
  194. if pager and t.pexpect_spawn:
  195. time.sleep(0.2)
  196. t.send('q')
  197. t.read()
  198. t.ok()
  199. t.skip_ok = True
  200. return t
  201. def longhelpscreens(self):
  202. return self.helpscreens(arg='--longhelp',expect='USAGE:.*LONG OPTIONS:')
  203. def show_hash_presets(self):
  204. return self.helpscreens(
  205. arg = '--show-hash-presets',
  206. scripts = (
  207. 'walletgen','walletconv','walletchk','passchg','subwalletgen',
  208. 'addrgen','keygen','passgen',
  209. 'txsign','txdo','txbump'),
  210. expect = 'Available parameters.*Preset',
  211. pager = False )
  212. def tool_help(self):
  213. if os.getenv('PYTHONOPTIMIZE') == '2':
  214. ymsg('Skipping tool help with PYTHONOPTIMIZE=2 (no docstrings)')
  215. return 'skip'
  216. for arg in (
  217. 'help',
  218. 'usage',
  219. ):
  220. t = self.spawn_chk_expect(
  221. 'mmgen-tool',
  222. [arg],
  223. extra_desc = f'(mmgen-tool {arg})',
  224. expect = 'GENERAL USAGE' )
  225. return t
  226. def tool_cmd_usage(self):
  227. if os.getenv('PYTHONOPTIMIZE') == '2':
  228. ymsg('Skipping tool cmd usage with PYTHONOPTIMIZE=2 (no docstrings)')
  229. return 'skip'
  230. from mmgen.main_tool import mods
  231. for cmdlist in mods.values():
  232. for cmd in cmdlist:
  233. t = self.spawn_chk( 'mmgen-tool', ['help',cmd], extra_desc=f'({cmd})' )
  234. return t
  235. def test_help(self):
  236. for arg,expect in (
  237. ('--help','USAGE'),
  238. ('--list-cmds','AVAILABLE COMMANDS'),
  239. ('--list-cmd-groups','AVAILABLE COMMAND GROUPS')
  240. ):
  241. t = self.spawn_chk_expect(
  242. 'cmdtest.py',
  243. [arg],
  244. cmd_dir = 'test',
  245. extra_desc = f'(cmdtest.py {arg})',
  246. expect = expect )
  247. return t
  248. def tooltest_help(self):
  249. for arg,expect in (
  250. ('--list-cmds','Available commands'),
  251. ('--testing-status','Testing status')
  252. ):
  253. t = self.spawn_chk_expect(
  254. 'tooltest.py',
  255. [arg],
  256. cmd_dir = 'test',
  257. extra_desc = f'(tooltest.py {arg})',
  258. expect = expect )
  259. return t
  260. class CmdTestOutput(CmdTestBase):
  261. 'screen output'
  262. networks = ('btc',)
  263. cmd_group = (
  264. ('output_gr', (1,"Greek text", [])),
  265. ('output_ru', (1,"Russian text", [])),
  266. ('output_zh', (1,"Chinese text", [])),
  267. ('output_jp', (1,"Japanese text", [])),
  268. ('oneshot_warning', (1,"Oneshot warnings", [])),
  269. ('oneshot_warning_term', (1,"Oneshot warnings (pexpect_spawn)", []))
  270. )
  271. color = True
  272. def screen_output(self,lang):
  273. return self.spawn('test/misc/utf8_output.py',[lang],cmd_dir='.')
  274. def output_gr(self):
  275. return self.screen_output('gr')
  276. def output_ru(self):
  277. return self.screen_output('ru')
  278. def output_zh(self):
  279. return self.screen_output('zh')
  280. def output_jp(self):
  281. return self.screen_output('jp')
  282. def oneshot_warning(self,pexpect_spawn=None):
  283. t = self.spawn('test/misc/oneshot_warning.py',cmd_dir='.',pexpect_spawn=pexpect_spawn)
  284. nl = '\r\n' if sys.platform == 'win32' or t.pexpect_spawn else '\n'
  285. for s in (
  286. f'pw{nl}wg1',
  287. 'foo is experimental',
  288. 'wg2', 'The bar command is dangerous',
  289. 'wg3', 'baz variant alpha',
  290. 'wg4', 'baz variant beta',
  291. 'w1', 'foo variant alpha',
  292. 'w2', 'foo variant beta',
  293. 'w3', 'bar is experimental',
  294. 'pw',
  295. "passphrase from file 'A'",
  296. "passphrase from file 'B'",
  297. f'wg1{nl}wg2{nl}wg3{nl}wg4{nl}w1{nl}w2{nl}w3',
  298. 'pw',
  299. "passphrase from file 'A'",
  300. "passphrase from file 'B'",
  301. f'wg1{nl}wg2{nl}wg3{nl}wg4{nl}w1{nl}w2{nl}w3',
  302. 'bottom',
  303. ):
  304. t.expect(s)
  305. return t
  306. def oneshot_warning_term(self):
  307. if self.skip_for_win():
  308. return 'skip'
  309. return self.oneshot_warning(pexpect_spawn=True)
  310. class CmdTestRefTX(CmdTestMain,CmdTestBase):
  311. 'create a reference transaction file (administrative command)'
  312. segwit_opts_ok = False
  313. passthru_opts = ('daemon_data_dir','rpc_port','coin','testnet')
  314. tmpdir_nums = [31,32,33,34]
  315. need_daemon = True
  316. cmd_group = (
  317. ('ref_tx_addrgen1', (31,'address generation (legacy)', [[[],1]])),
  318. ('ref_tx_addrgen2', (32,'address generation (compressed)', [[[],1]])),
  319. ('ref_tx_addrgen3', (33,'address generation (segwit)', [[[],1]])),
  320. ('ref_tx_addrgen4', (34,'address generation (bech32)', [[[],1]])),
  321. ('ref_tx_txcreate', (31,'transaction creation',
  322. ([['addrs'],31],[['addrs'],32],[['addrs'],33],[['addrs'],34]))),
  323. )
  324. def __init__(self,trunner,cfgs,spawn):
  325. if cfgs:
  326. for n in self.tmpdir_nums:
  327. cfgs[str(n)].update({ 'addr_idx_list': '1-2',
  328. 'segwit': n in (33,34),
  329. 'dep_generators': { 'addrs':'ref_tx_addrgen'+str(n)[-1] }})
  330. CmdTestMain.__init__(self,trunner,cfgs,spawn)
  331. def ref_tx_addrgen(self,atype):
  332. if atype not in self.proto.mmtypes:
  333. return
  334. return self.spawn('mmgen-addrgen',['--outdir='+self.tmpdir,'--type='+atype,dfl_words_file,'1-2'])
  335. def ref_tx_addrgen1(self):
  336. return self.ref_tx_addrgen(atype='L')
  337. def ref_tx_addrgen2(self):
  338. return self.ref_tx_addrgen(atype='C')
  339. def ref_tx_addrgen3(self):
  340. return self.ref_tx_addrgen(atype='S')
  341. def ref_tx_addrgen4(self):
  342. return self.ref_tx_addrgen(atype='B')
  343. def ref_tx_txcreate(self,f1,f2,f3,f4):
  344. sources = ['31','32']
  345. if 'S' in self.proto.mmtypes:
  346. sources += ['33']
  347. if 'B' in self.proto.mmtypes:
  348. sources += ['34']
  349. return self.txcreate_common(
  350. addrs_per_wallet = 2,
  351. sources = sources,
  352. add_args = ['--locktime=1320969600'],
  353. do_label = True)