ct_autosign.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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_autosign: Autosign tests for the cmdtest.py test suite
  20. """
  21. import sys,os,time,shutil
  22. from subprocess import run,DEVNULL
  23. from pathlib import Path
  24. from mmgen.cfg import Config
  25. from mmgen.color import red,green,blue,yellow,cyan,orange,purple,gray
  26. from mmgen.util import msg,suf,die,indent,fmt
  27. from mmgen.led import LEDControl
  28. from mmgen.autosign import Autosign, Signable
  29. from ..include.common import (
  30. cfg,
  31. omsg,
  32. omsg_r,
  33. oqmsg,
  34. oqmsg_r,
  35. start_test_daemons,
  36. stop_test_daemons,
  37. joinpath,
  38. imsg,
  39. read_from_file,
  40. silence,
  41. end_silence,
  42. )
  43. from .common import ref_dir,dfl_words_file,dfl_bip39_file
  44. from .ct_base import CmdTestBase
  45. from .input import stealth_mnemonic_entry
  46. class CmdTestAutosignBase(CmdTestBase):
  47. networks = ('btc',)
  48. tmpdir_nums = [18]
  49. color = True
  50. win_skip = True
  51. threaded = False
  52. daemon_coins = []
  53. def __init__(self,trunner,cfgs,spawn):
  54. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  55. if trunner is None:
  56. return
  57. self.silent_mount = self.live or not (cfg.exact_output or cfg.verbose)
  58. self.network_ids = [c+'_tn' for c in self.daemon_coins] + self.daemon_coins
  59. self._create_autosign_instances(create_dirs=not cfg.skipping_deps)
  60. if not (cfg.skipping_deps or self.live):
  61. self._create_removable_device()
  62. self.opts = ['--coins='+','.join(self.coins)]
  63. if not self.live:
  64. self.spawn_env['MMGEN_TEST_SUITE_ROOT_PFX'] = self.tmpdir
  65. if self.threaded:
  66. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_THREADED'] = '1'
  67. def _create_autosign_instances(self,create_dirs):
  68. d = {'offline': {'name':'asi'}}
  69. if self.have_online:
  70. d['online'] = {'name':'asi_online'}
  71. for subdir,data in d.items():
  72. if create_dirs and not self.live:
  73. for k in ('mountpoint','wallet_dir','dev_label_dir'):
  74. if k == 'wallet_dir' and subdir == 'online':
  75. continue
  76. (Path(self.tmpdir) / (subdir + getattr(Autosign,'dfl_'+k))).mkdir(parents=True,exist_ok=True)
  77. setattr(self,data['name'],
  78. Autosign(
  79. Config({
  80. 'coins': ','.join(self.coins),
  81. 'test_suite': True,
  82. 'test_suite_xmr_autosign': self.name == 'CmdTestXMRAutosign',
  83. 'test_suite_autosign_threaded': self.threaded,
  84. 'test_suite_root_pfx': None if self.live else self.tmpdir,
  85. 'online': subdir == 'online',
  86. })))
  87. def _create_removable_device(self):
  88. redir = DEVNULL
  89. img_file = str(self.asi.fs_image_path)
  90. run(['truncate', '--size=10M', img_file], check=True)
  91. run(['/sbin/mkfs.ext2', '-E', f'root_owner={os.getuid()}:{os.getgid()}', img_file],
  92. stdout=redir, stderr=redir, check=True)
  93. def start_daemons(self):
  94. self.spawn('',msg_only=True)
  95. start_test_daemons(*self.network_ids)
  96. return 'ok'
  97. def stop_daemons(self):
  98. self.spawn('',msg_only=True)
  99. stop_test_daemons(*self.network_ids)
  100. return 'ok'
  101. def run_setup(
  102. self,
  103. mn_type = None,
  104. mn_file = None,
  105. use_dfl_wallet = False,
  106. seed_len = None,
  107. usr_entry_modes = False,
  108. passwd = 'abc'):
  109. mn_desc = mn_type or 'default'
  110. mn_type = mn_type or 'mmgen'
  111. t = self.spawn(
  112. 'mmgen-autosign',
  113. self.opts
  114. + ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}'])
  115. + ([f'--seed-len={seed_len}'] if seed_len else [])
  116. + ['setup'],
  117. no_passthru_opts = True)
  118. if use_dfl_wallet:
  119. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'y' )
  120. t.passphrase('MMGen wallet', passwd)
  121. else:
  122. if use_dfl_wallet is not None: # None => no dfl wallet present
  123. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'n' )
  124. mn_file = mn_file or { 'mmgen': dfl_words_file, 'bip39': dfl_bip39_file }[mn_type]
  125. mn = read_from_file(mn_file).strip().split()
  126. if not seed_len:
  127. t.expect('words: ',{ 12:'1', 18:'2', 24:'3' }[len(mn)])
  128. t.expect('OK? (Y/n): ','\n')
  129. from mmgen.mn_entry import mn_entry
  130. entry_mode = 'full'
  131. mne = mn_entry(cfg, mn_type, entry_mode)
  132. if usr_entry_modes:
  133. t.expect('user-configured')
  134. else:
  135. t.expect(
  136. 'Type a number.*: ',
  137. str(mne.entry_modes.index(entry_mode) + 1),
  138. regex = True)
  139. stealth_mnemonic_entry(t,mne,mn,entry_mode)
  140. t.written_to_file('Autosign wallet')
  141. return t
  142. @property
  143. def device_inserted(self):
  144. return self.asi.dev_label_path.exists()
  145. def insert_device(self):
  146. self.asi.dev_label_path.touch()
  147. def remove_device(self):
  148. if self.asi.dev_label_path.exists():
  149. self.asi.dev_label_path.unlink()
  150. def _mount_ops(self, loc, cmd, *args, **kwargs):
  151. return getattr(getattr(self,loc),cmd)(*args, silent=self.silent_mount, **kwargs)
  152. def do_mount(self, *args, **kwargs):
  153. return self._mount_ops('asi', 'do_mount', *args, **kwargs)
  154. def do_umount(self, *args, **kwargs):
  155. return self._mount_ops('asi', 'do_umount', *args, **kwargs)
  156. def _gen_listing(self):
  157. for k in self.asi.dirs:
  158. d = getattr(self.asi,k)
  159. if d.is_dir():
  160. yield '{:12} {}'.format(
  161. str(Path(*d.parts[6:])) + ':',
  162. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  163. class CmdTestAutosignClean(CmdTestAutosignBase):
  164. have_online = False
  165. live = False
  166. simulate_led = True
  167. no_insert_check = False
  168. coins = ['btc']
  169. tmpdir_nums = [38]
  170. cmd_group = (
  171. ('clean_no_xmr', 'cleaning signable file directories (no XMR)'),
  172. ('clean_xmr_only', 'cleaning signable file directories (XMR-only)'),
  173. ('clean_all', 'cleaning signable file directories (with XMR)'),
  174. )
  175. def create_fake_tx_files(self):
  176. imsg('Creating fake transaction files')
  177. if not self.asi.xmr_only:
  178. for fn in (
  179. 'a.rawtx', 'a.sigtx',
  180. 'b.rawtx', 'b.sigtx',
  181. 'c.rawtx',
  182. 'd.sigtx',
  183. ):
  184. (self.asi.tx_dir / fn).touch()
  185. for fn in (
  186. 'a.arawtx', 'a.asigtx', 'a.asubtx',
  187. 'b.arawtx', 'b.asigtx',
  188. 'c.asubtx',
  189. 'd.arawtx', 'd.asubtx',
  190. 'e.arawtx',
  191. 'f.asigtx', 'f.asubtx',
  192. ):
  193. (self.asi.txauto_dir / fn).touch()
  194. for fn in (
  195. 'a.rawmsg.json', 'a.sigmsg.json',
  196. 'b.rawmsg.json',
  197. 'c.sigmsg.json',
  198. 'd.rawmsg.json', 'd.sigmsg.json',
  199. ):
  200. (self.asi.msg_dir / fn).touch()
  201. if self.asi.have_xmr:
  202. for fn in (
  203. 'a.rawtx', 'a.sigtx', 'a.subtx',
  204. 'b.rawtx', 'b.sigtx',
  205. 'c.subtx',
  206. 'd.rawtx', 'd.subtx',
  207. 'e.rawtx',
  208. 'f.sigtx', 'f.subtx',
  209. ):
  210. (self.asi.xmr_tx_dir / fn).touch()
  211. for fn in (
  212. 'a.raw', 'a.sig',
  213. 'b.raw',
  214. 'c.sig',
  215. ):
  216. (self.asi.xmr_outputs_dir / fn).touch()
  217. return 'ok'
  218. def clean_no_xmr(self):
  219. return self._clean('btc,ltc,eth')
  220. def clean_xmr_only(self):
  221. self.asi = Autosign(Config({'_clone': self.asi.cfg, 'coins': 'xmr'}))
  222. return self._clean('xmr')
  223. def clean_all(self):
  224. self.asi = Autosign(Config({'_clone': self.asi.cfg, 'coins': 'xmr,btc,bch,eth'}))
  225. return self._clean('xmr,btc,bch,eth')
  226. def _clean(self,coins):
  227. self.spawn('', msg_only=True)
  228. self.insert_device()
  229. silence()
  230. self.do_mount()
  231. end_silence()
  232. self.create_fake_tx_files()
  233. before = '\n'.join(self._gen_listing())
  234. t = self.spawn('mmgen-autosign', [f'--coins={coins}','clean'], no_msg=True)
  235. out = t.read()
  236. self.do_mount()
  237. self.remove_device()
  238. after = '\n'.join(self._gen_listing())
  239. chk_non_xmr = """
  240. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  241. txauto: a.asubtx b.asigtx c.asubtx d.asubtx e.arawtx f.asubtx
  242. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  243. """
  244. chk_xmr = """
  245. xmr: outputs tx
  246. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  247. xmr/outputs:
  248. """
  249. chk = ''
  250. shred_count = 0
  251. if not self.asi.xmr_only:
  252. for k in ('tx_dir', 'txauto_dir', 'msg_dir'):
  253. shutil.rmtree(getattr(self.asi, k))
  254. chk += chk_non_xmr.rstrip()
  255. shred_count += 9
  256. if self.asi.have_xmr:
  257. shutil.rmtree(self.asi.xmr_dir)
  258. chk += chk_xmr.rstrip()
  259. shred_count += 9
  260. self.do_umount()
  261. imsg(f'\nBefore cleaning:\n{before}')
  262. imsg(f'\nAfter cleaning:\n{after}')
  263. assert f'{shred_count} files shredded' in out
  264. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  265. return t
  266. class CmdTestAutosignThreaded(CmdTestAutosignBase):
  267. have_online = True
  268. live = False
  269. no_insert_check = False
  270. threaded = True
  271. def autosign_start_thread(self):
  272. def run():
  273. t = self.spawn(
  274. 'mmgen-autosign',
  275. self.opts + ['--full-summary', 'wait'],
  276. direct_exec = True,
  277. no_passthru_opts = True,
  278. spawn_env_override = self.spawn_env | {'EXEC_WRAPPER_DO_RUNTIME_MSG': ''})
  279. self.write_to_tmpfile('autosign_thread_pid',str(t.ep.pid))
  280. import threading
  281. threading.Thread(target=run, name='Autosign wait loop').start()
  282. time.sleep(0.2)
  283. return 'silent'
  284. def autosign_kill_thread(self):
  285. self.spawn('',msg_only=True)
  286. pid = int(self.read_from_tmpfile('autosign_thread_pid'))
  287. self.delete_tmpfile('autosign_thread_pid')
  288. from signal import SIGTERM
  289. imsg(purple(f'Killing autosign wait loop [PID {pid}]'))
  290. try:
  291. os.kill(pid,SIGTERM)
  292. except:
  293. imsg(yellow(f'{pid}: no such process'))
  294. return 'ok'
  295. def _wait_signed(self,desc):
  296. oqmsg_r(gray(f'→ offline wallet{"s" if desc.endswith("s") else ""} waiting for {desc}'))
  297. assert not self.device_inserted, f'‘{self.asi.dev_label_path}’ is inserted!'
  298. assert not self.asi.mountpoint.is_mount(), f'‘{self.asi.mountpoint}’ is mounted!'
  299. self.insert_device()
  300. while True:
  301. oqmsg_r(gray('.'))
  302. if self.asi.mountpoint.is_mount():
  303. oqmsg_r(gray(' signing '))
  304. break
  305. time.sleep(0.2)
  306. while True:
  307. oqmsg_r(gray('>'))
  308. if not self.asi.mountpoint.is_mount():
  309. oqmsg(gray(' done'))
  310. break
  311. time.sleep(0.2)
  312. imsg('')
  313. self.remove_device()
  314. return 'ok'
  315. @property
  316. def device_inserted_online(self):
  317. return self.asi_online.dev_label_path.exists()
  318. def insert_device_online(self):
  319. self.asi_online.dev_label_path.touch()
  320. def remove_device_online(self):
  321. if self.asi_online.dev_label_path.exists():
  322. self.asi_online.dev_label_path.unlink()
  323. def do_mount_online(self, *args, **kwargs):
  324. return self._mount_ops('asi_online', 'do_mount', *args, **kwargs)
  325. def do_umount_online(self, *args, **kwargs):
  326. return self._mount_ops('asi_online', 'do_umount', *args, **kwargs)
  327. async def txview(self):
  328. self.spawn('', msg_only=True)
  329. self.do_mount()
  330. src = Path(self.asi.txauto_dir)
  331. from mmgen.tx import CompletedTX
  332. txs = sorted(
  333. [await CompletedTX(cfg=cfg, filename=path, quiet_open=True) for path in sorted(src.iterdir())],
  334. key = lambda x: x.timestamp)
  335. for tx in txs:
  336. imsg(blue(f'\nViewing ‘{tx.infile.name}’:'))
  337. out = tx.info.format(terse=True)
  338. imsg(indent(out, indent=' '))
  339. self.do_umount()
  340. return 'ok'
  341. class CmdTestAutosign(CmdTestAutosignBase):
  342. 'autosigning transactions for all supported coins'
  343. coins = ['btc','bch','ltc','eth']
  344. daemon_coins = ['btc','bch','ltc']
  345. txfile_coins = ['btc','bch','ltc','eth','mm1','etc']
  346. have_online = False
  347. live = False
  348. simulate_led = True
  349. no_insert_check = True
  350. filedir_map = (
  351. ('btc',''),
  352. ('bch',''),
  353. ('ltc','litecoin'),
  354. ('eth','ethereum'),
  355. ('mm1','ethereum'),
  356. ('etc','ethereum_classic'),
  357. )
  358. cmd_group = (
  359. ('start_daemons', 'starting daemons'),
  360. ('copy_tx_files', 'copying transaction files'),
  361. ('gen_key', 'generating key'),
  362. ('create_dfl_wallet', 'creating default MMGen wallet'),
  363. ('bad_opt1', 'running ‘mmgen-autosign’ with --seed-len in invalid context'),
  364. ('bad_opt2', 'running ‘mmgen-autosign’ with --mnemonic-fmt in invalid context'),
  365. ('bad_opt3', 'running ‘mmgen-autosign’ with --led in invalid context'),
  366. ('run_setup_dfl_wallet', 'running ‘autosign setup’ (with default wallet)'),
  367. ('sign_quiet', 'signing transactions (--quiet)'),
  368. ('remove_signed_txfiles', 'removing signed transaction files'),
  369. ('run_setup_bip39', 'running ‘autosign setup’ (BIP39 mnemonic)'),
  370. ('create_bad_txfiles', 'creating bad transaction files'),
  371. ('sign_full_summary', 'signing transactions (--full-summary)'),
  372. ('remove_signed_txfiles_btc','removing transaction files (BTC only)'),
  373. ('remove_bad_txfiles', 'removing bad transaction files'),
  374. ('sign_led', 'signing transactions (--led - BTC files only)'),
  375. ('remove_signed_txfiles', 'removing signed transaction files'),
  376. ('sign_stealth_led', 'signing transactions (--stealth-led)'),
  377. ('remove_signed_txfiles', 'removing signed transaction files'),
  378. ('copy_msgfiles', 'copying message files'),
  379. ('sign_quiet_msg', 'signing transactions and messages (--quiet)'),
  380. ('remove_signed_txfiles', 'removing signed transaction files'),
  381. ('create_bad_txfiles2', 'creating bad transaction files'),
  382. ('remove_signed_msgfiles', 'removing signed message files'),
  383. ('create_invalid_msgfile', 'creating invalid message file'),
  384. ('sign_full_summary_msg', 'signing transactions and messages (--full-summary)'),
  385. ('remove_invalid_msgfile', 'removing invalid message file'),
  386. ('remove_bad_txfiles2', 'removing bad transaction files'),
  387. ('sign_no_unsigned', 'signing transactions and messages (nothing to sign)'),
  388. ('sign_no_unsigned_xmr', 'signing transactions and messages (nothing to sign, with XMR)'),
  389. ('sign_no_unsigned_xmronly', 'signing transactions and messages (nothing to sign, XMR-only)'),
  390. ('wipe_key', 'wiping the wallet encryption key'),
  391. ('stop_daemons', 'stopping daemons'),
  392. ('sign_bad_no_daemon', 'signing transactions (error, no daemons running)'),
  393. )
  394. def __init__(self,trunner,cfgs,spawn):
  395. super().__init__(trunner,cfgs,spawn)
  396. if trunner is None:
  397. return
  398. if self.live and not cfg.exact_output:
  399. die(1,red('autosign_live tests must be run with --exact-output enabled!'))
  400. if self.no_insert_check:
  401. self.opts.append('--no-insert-check')
  402. self.tx_file_ops('set_count') # initialize self.tx_count here so we can resume anywhere
  403. self.bad_tx_count = 0
  404. def gen_msg_fns():
  405. fmap = dict(self.filedir_map)
  406. for coin in self.coins:
  407. if coin == 'xmr':
  408. continue
  409. sdir = os.path.join('test','ref',fmap[coin])
  410. for fn in os.listdir(sdir):
  411. if fn.endswith(f'[{coin.upper()}].rawmsg.json'):
  412. yield os.path.join(sdir,fn)
  413. self.ref_msgfiles = tuple(gen_msg_fns())
  414. self.good_msg_count = 0
  415. self.bad_msg_count = 0
  416. if self.simulate_led:
  417. LEDControl.create_dummy_control_files()
  418. self.have_dummy_control_files = True
  419. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  420. def __del__(self):
  421. if hasattr(self,'have_dummy_control_files'):
  422. LEDControl.delete_dummy_control_files()
  423. def gen_key(self):
  424. t = self.spawn( 'mmgen-autosign', self.opts + ['gen_key'] )
  425. t.expect_getend('Wrote key file ')
  426. return t
  427. def create_dfl_wallet(self):
  428. t = self.spawn( 'mmgen-walletconv', [
  429. f'--outdir={cfg.data_dir}',
  430. '--usr-randchars=0', '--quiet', '--hash-preset=1', '--label=foo',
  431. 'test/ref/98831F3A.hex'
  432. ]
  433. )
  434. t.passphrase_new('new MMGen wallet','abc')
  435. t.written_to_file('MMGen wallet')
  436. return t
  437. def _bad_opt(self, cmdline, expect):
  438. t = self.spawn('mmgen-autosign', ['--coins=btc'] + cmdline, exit_val=1)
  439. t.expect(expect)
  440. return t
  441. def bad_opt1(self):
  442. return self._bad_opt(['--seed-len=128'], 'makes sense')
  443. def bad_opt2(self):
  444. return self._bad_opt(['--mnemonic-fmt=bip39', 'wait'], 'makes sense')
  445. def bad_opt3(self):
  446. return self._bad_opt(['--led', 'gen_key'], 'makes no sense')
  447. def run_setup_dfl_wallet(self):
  448. return self.run_setup(mn_type='default',use_dfl_wallet=True)
  449. def run_setup_bip39(self):
  450. from mmgen.cfgfile import mmgen_cfg_file
  451. fn = mmgen_cfg_file(cfg,'usr').fn
  452. old_data = mmgen_cfg_file(cfg,'usr').get_data(fn)
  453. new_data = [d.replace('bip39:fixed','bip39:full')[2:]
  454. if d.startswith('# mnemonic_entry_modes') else d for d in old_data]
  455. with open(fn, 'w') as fh:
  456. fh.write('\n'.join(new_data) + '\n')
  457. t = self.run_setup(
  458. mn_type = 'bip39',
  459. seed_len = 256,
  460. usr_entry_modes = True)
  461. with open(fn, 'w') as fh:
  462. fh.write('\n'.join(old_data) + '\n')
  463. return t
  464. def copy_tx_files(self):
  465. self.spawn('',msg_only=True)
  466. return self.tx_file_ops('copy')
  467. def remove_signed_txfiles(self):
  468. self.tx_file_ops('remove_signed')
  469. return 'skip'
  470. def remove_signed_txfiles_btc(self):
  471. self.tx_file_ops('remove_signed',txfile_coins=['btc'])
  472. return 'skip'
  473. def tx_file_ops(self,op,txfile_coins=[]):
  474. assert op in ('copy','set_count','remove_signed')
  475. from .ct_ref import CmdTestRef
  476. def gen():
  477. d = CmdTestRef.sources['ref_tx_file']
  478. dirmap = [e for e in self.filedir_map if e[0] in (txfile_coins or self.txfile_coins)]
  479. for coin,coindir in dirmap:
  480. for network in (0,1):
  481. fn = d[coin][network]
  482. if fn:
  483. yield (coindir,fn)
  484. data = list(gen()) + [('','25EFA3[2.34].testnet.rawtx')] # TX with 2 non-MMGen outputs
  485. self.tx_count = len(data)
  486. if op == 'set_count':
  487. return
  488. silence()
  489. self.do_mount()
  490. end_silence()
  491. for coindir,fn in data:
  492. src = joinpath(ref_dir,coindir,fn)
  493. if cfg.debug_utf8:
  494. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  495. fn = fn[:-len(ext)] + '-α' + ext
  496. target = joinpath(self.asi.tx_dir, fn)
  497. if not op == 'remove_signed':
  498. shutil.copyfile(src,target)
  499. try:
  500. os.unlink(target.replace('.rawtx','.sigtx'))
  501. except:
  502. pass
  503. self.do_umount()
  504. return 'ok'
  505. def create_bad_txfiles(self):
  506. return self.bad_txfiles('create')
  507. def remove_bad_txfiles(self):
  508. return self.bad_txfiles('remove')
  509. create_bad_txfiles2 = create_bad_txfiles
  510. remove_bad_txfiles2 = remove_bad_txfiles
  511. def bad_txfiles(self,op):
  512. self.do_mount()
  513. # create or delete 2 bad tx files
  514. self.spawn('',msg_only=True)
  515. fns = [joinpath(self.asi.tx_dir, f'bad{n}.rawtx') for n in (1,2)]
  516. if op == 'create':
  517. for fn in fns:
  518. with open(fn,'w') as fp:
  519. fp.write('bad tx data\n')
  520. self.bad_tx_count = 2
  521. elif op == 'remove':
  522. for fn in fns:
  523. try:
  524. os.unlink(fn)
  525. except:
  526. pass
  527. self.bad_tx_count = 0
  528. self.do_umount()
  529. return 'ok'
  530. def copy_msgfiles(self):
  531. return self.msgfile_ops('copy')
  532. def remove_signed_msgfiles(self):
  533. return self.msgfile_ops('remove_signed')
  534. def create_invalid_msgfile(self):
  535. return self.msgfile_ops('create_invalid')
  536. def remove_invalid_msgfile(self):
  537. return self.msgfile_ops('remove_invalid')
  538. def msgfile_ops(self,op):
  539. self.spawn('',msg_only=True)
  540. destdir = joinpath(self.asi.mountpoint,'msg')
  541. self.do_mount()
  542. os.makedirs(destdir,exist_ok=True)
  543. if op.endswith('_invalid'):
  544. fn = os.path.join(destdir,'DEADBE[BTC].rawmsg.json')
  545. if op == 'create_invalid':
  546. with open(fn,'w') as fp:
  547. fp.write('bad data\n')
  548. self.bad_msg_count += 1
  549. elif op == 'remove_invalid':
  550. os.unlink(fn)
  551. self.bad_msg_count -= 1
  552. else:
  553. for fn in self.ref_msgfiles:
  554. if op == 'copy':
  555. if os.path.basename(fn) == 'ED405C[BTC].rawmsg.json': # contains bad Seed ID
  556. self.bad_msg_count += 1
  557. else:
  558. self.good_msg_count += 1
  559. imsg(f'Copying: {fn} -> {destdir}')
  560. shutil.copy2(fn,destdir)
  561. elif op == 'remove_signed':
  562. os.unlink(os.path.join( destdir, os.path.basename(fn).replace('rawmsg','sigmsg') ))
  563. self.do_umount()
  564. return 'ok'
  565. def do_sign(self, args=[], have_msg=False, exc_exit_val=None):
  566. tx_desc = Signable.transaction.desc
  567. t = self.spawn(
  568. 'mmgen-autosign',
  569. self.opts + args,
  570. exit_val = exc_exit_val or (1 if self.bad_tx_count or (have_msg and self.bad_msg_count) else None))
  571. if exc_exit_val:
  572. return t
  573. t.expect(
  574. f'{self.tx_count} {tx_desc}{suf(self.tx_count)} signed' if self.tx_count else
  575. f'No unsigned {tx_desc}s')
  576. if self.bad_tx_count:
  577. t.expect(f'{self.bad_tx_count} {tx_desc}{suf(self.bad_tx_count)} failed to sign')
  578. if have_msg:
  579. t.expect(
  580. f'{self.good_msg_count} message file{suf(self.good_msg_count)}{{0,1}} signed'
  581. if self.good_msg_count else
  582. 'No unsigned message files', regex=True)
  583. if self.bad_msg_count:
  584. t.expect(
  585. f'{self.bad_msg_count} message file{suf(self.bad_msg_count)}{{0,1}} failed to sign',
  586. regex = True)
  587. t.read()
  588. imsg('')
  589. return t
  590. def sign_quiet(self):
  591. return self.do_sign(['--quiet'])
  592. def sign_full_summary(self):
  593. return self.do_sign(['--full-summary'])
  594. def sign_led(self):
  595. return self.do_sign(['--quiet', '--led'])
  596. def sign_stealth_led(self):
  597. return self.do_sign(['--quiet', '--stealth-led'])
  598. def sign_quiet_msg(self):
  599. return self.do_sign(['--quiet'], have_msg=True)
  600. def sign_full_summary_msg(self):
  601. return self.do_sign(['--full-summary'], have_msg=True)
  602. def sign_bad_no_daemon(self):
  603. t = self.do_sign(exc_exit_val=2)
  604. t.expect('listening on the correct port')
  605. return t
  606. def sign_no_unsigned(self):
  607. return self._sign_no_unsigned(
  608. coins = 'BTC',
  609. present = ['non_xmr_signables'],
  610. absent = ['xmr_signables'])
  611. def sign_no_unsigned_xmr(self):
  612. return self._sign_no_unsigned(
  613. coins = 'XMR,BTC',
  614. present = ['xmr_signables','non_xmr_signables'])
  615. def sign_no_unsigned_xmronly(self):
  616. return self._sign_no_unsigned(
  617. coins = 'XMR',
  618. present = ['xmr_signables'],
  619. absent = ['non_xmr_signables'])
  620. def _sign_no_unsigned(self,coins,present=[],absent=[]):
  621. t = self.spawn('mmgen-autosign', ['--quiet', '--no-insert-check', f'--coins={coins}'])
  622. res = t.read()
  623. for signable_list in present:
  624. for signable_clsname in getattr(Signable,signable_list):
  625. desc = getattr(Signable, signable_clsname).desc
  626. assert f'No unsigned {desc}s' in res, f'‘No unsigned {desc}s’ missing in output'
  627. for signable_list in absent:
  628. for signable_clsname in getattr(Signable,signable_list):
  629. desc = getattr(Signable, signable_clsname).desc
  630. assert not f'No unsigned {desc}s' in res, f'‘No unsigned {desc}s’ should be absent in output'
  631. return t
  632. def wipe_key(self):
  633. t = self.spawn('mmgen-autosign', ['--quiet', '--no-insert-check', 'wipe_key'])
  634. t.expect('Shredding')
  635. return t
  636. class CmdTestAutosignBTC(CmdTestAutosign):
  637. 'autosigning BTC transactions'
  638. coins = ['btc']
  639. daemon_coins = ['btc']
  640. txfile_coins = ['btc']
  641. class CmdTestAutosignLive(CmdTestAutosignBTC):
  642. 'live autosigning BTC transactions'
  643. live = True
  644. simulate_led = False
  645. no_insert_check = False
  646. cmd_group = (
  647. ('start_daemons', 'starting daemons'),
  648. ('copy_tx_files', 'copying transaction files'),
  649. ('gen_key', 'generating key'),
  650. ('run_setup_mmgen', 'running ‘autosign setup’ (MMGen native mnemonic)'),
  651. ('sign_live', 'signing transactions'),
  652. ('create_bad_txfiles', 'creating bad transaction files'),
  653. ('sign_live_led', 'signing transactions (--led)'),
  654. ('remove_bad_txfiles', 'removing bad transaction files'),
  655. ('sign_live_stealth_led','signing transactions (--stealth-led)'),
  656. ('stop_daemons', 'stopping daemons'),
  657. )
  658. def __init__(self,trunner,cfgs,spawn):
  659. super().__init__(trunner,cfgs,spawn)
  660. if trunner is None:
  661. return
  662. try:
  663. cf = LEDControl(enabled=True,simulate=self.simulate_led)
  664. except Exception as e:
  665. msg(str(e))
  666. die(2,'LEDControl initialization failed')
  667. for path in (cf.board.status,cf.board.trigger):
  668. if path:
  669. run(['sudo','chmod','0666',path],check=True)
  670. def run_setup_mmgen(self):
  671. return self.run_setup(mn_type='mmgen',use_dfl_wallet=None)
  672. def sign_live(self):
  673. return self.do_sign_live()
  674. def sign_live_led(self):
  675. return self.do_sign_live(['--led'], 'The LED should start blinking slowly now')
  676. def sign_live_stealth_led(self):
  677. return self.do_sign_live(['--stealth-led'], 'You should see no LED activity now')
  678. def do_sign_live(self,led_opts=None,led_msg=None):
  679. def prompt_remove():
  680. omsg_r(orange('\nExtract removable device and then hit ENTER '))
  681. input()
  682. def prompt_insert_sign(t):
  683. omsg(orange(insert_msg))
  684. t.expect(f'{self.tx_count} non-automount transactions signed')
  685. if self.bad_tx_count:
  686. t.expect(f'{self.bad_tx_count} non-automount transactions failed to sign')
  687. t.expect('Waiting')
  688. if led_opts:
  689. opts_msg = '‘' + ' '.join(led_opts) + '’'
  690. info_msg = 'Running ‘mmgen-autosign wait’ with {}. {}'.format(opts_msg, led_msg)
  691. insert_msg = 'Insert removable device and watch for fast LED activity during signing'
  692. else:
  693. opts_msg = 'no LED'
  694. info_msg = 'Running ‘mmgen-autosign wait’'
  695. insert_msg = 'Insert removable device '
  696. self.spawn('', msg_only=True)
  697. self.do_umount()
  698. prompt_remove()
  699. omsg('\n' + cyan(indent(info_msg)))
  700. t = self.spawn(
  701. 'mmgen-autosign',
  702. self.opts + (led_opts or []) + ['--quiet', '--no-summary', 'wait'],
  703. no_msg = True,
  704. exit_val = 1)
  705. if not cfg.exact_output:
  706. omsg('')
  707. prompt_insert_sign(t)
  708. self.do_mount() # race condition due to device insertion detection
  709. self.remove_signed_txfiles()
  710. self.do_umount()
  711. imsg(purple('\nKilling wait loop!'))
  712. t.kill(2) # 2 = SIGINT
  713. if self.simulate_led and led_opts:
  714. t.expect('Stopping LED')
  715. return t
  716. class CmdTestAutosignLiveSimulate(CmdTestAutosignLive):
  717. 'live autosigning BTC transactions with simulated LED support'
  718. simulate_led = True