ct_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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,shutil
  22. from subprocess import run
  23. from pathlib import Path
  24. from mmgen.color import red,green,blue,purple
  25. from mmgen.util import msg,suf,die
  26. from mmgen.led import LEDControl
  27. from mmgen.autosign import Autosign,AutosignConfig
  28. from ..include.common import (
  29. cfg,
  30. omsg,
  31. omsg_r,
  32. start_test_daemons,
  33. stop_test_daemons,
  34. joinpath,
  35. imsg,
  36. read_from_file
  37. )
  38. from .common import ref_dir,dfl_words_file,dfl_bip39_file
  39. from .ct_base import CmdTestBase
  40. from .input import stealth_mnemonic_entry
  41. filedir_map = (
  42. ('btc',''),
  43. ('bch',''),
  44. ('ltc','litecoin'),
  45. ('eth','ethereum'),
  46. ('mm1','ethereum'),
  47. ('etc','ethereum_classic'),
  48. )
  49. def init_led(simulate):
  50. try:
  51. cf = LEDControl(enabled=True,simulate=simulate)
  52. except Exception as e:
  53. msg(str(e))
  54. die(2,'LEDControl initialization failed')
  55. for fn in (cf.board.status,cf.board.trigger):
  56. if fn:
  57. run(['sudo','chmod','0666',fn],check=True)
  58. def check_mountpoint(asi):
  59. if not asi.mountpoint.is_mount():
  60. try:
  61. run(['mount',asi.mountpoint],check=True)
  62. imsg(f'Mounted {asi.mountpoint}')
  63. except:
  64. die(2,f'Could not mount {asi.mountpoint}! Exiting')
  65. if not asi.tx_dir.is_dir():
  66. die(2,f'Directory {asi.tx_dir} does not exist! Exiting')
  67. def do_mount(mountpoint):
  68. if not os.path.ismount(mountpoint):
  69. try:
  70. run(['mount',mountpoint],check=True)
  71. except:
  72. pass
  73. def do_umount(mountpoint):
  74. if os.path.ismount(mountpoint):
  75. try:
  76. run(['umount',mountpoint],check=True)
  77. except:
  78. pass
  79. class CmdTestAutosignBase(CmdTestBase):
  80. networks = ('btc',)
  81. tmpdir_nums = [18]
  82. color = True
  83. mountpoint_basename = 'mmgen_autosign'
  84. no_insert_check = True
  85. win_skip = True
  86. def __init__(self,trunner,cfgs,spawn):
  87. super().__init__(trunner,cfgs,spawn)
  88. if trunner is None:
  89. return
  90. self.network_ids = [c+'_tn' for c in self.daemon_coins] + self.daemon_coins
  91. if not self.live:
  92. self.wallet_dir = Path( self.tmpdir, 'dev.shm.autosign' )
  93. self.asi = Autosign(
  94. AutosignConfig({
  95. 'coins': ','.join(self.coins),
  96. 'mountpoint': (
  97. None if self.live else
  98. os.path.join(self.tmpdir,self.mountpoint_basename)
  99. ),
  100. 'wallet_dir': None if self.live else self.wallet_dir,
  101. 'test_suite': True,
  102. 'test_suite_xmr_autosign': self.name == 'CmdTestXMRAutosign',
  103. })
  104. )
  105. self.mountpoint = self.asi.mountpoint
  106. if self.simulate and not cfg.exact_output:
  107. die(1,red('This command must be run with --exact-output enabled!'))
  108. if self.simulate or not self.live:
  109. LEDControl.create_dummy_control_files()
  110. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  111. self.opts = ['--coins='+','.join(self.coins)]
  112. if self.live:
  113. check_mountpoint(self.asi)
  114. init_led(self.simulate)
  115. else:
  116. self.asi.tx_dir.mkdir(parents=True,exist_ok=True) # creates mountpoint
  117. self.wallet_dir.mkdir(parents=True,exist_ok=True)
  118. self.opts.extend([
  119. f'--mountpoint={self.mountpoint}',
  120. f'--wallet-dir={self.wallet_dir}',
  121. ])
  122. if self.no_insert_check:
  123. self.opts.append('--no-insert-check')
  124. self.tx_file_ops('set_count') # initialize tx_count here so we can resume anywhere
  125. def gen_msg_fns():
  126. fmap = dict(filedir_map)
  127. for coin in self.coins:
  128. if coin == 'xmr':
  129. continue
  130. sdir = os.path.join('test','ref',fmap[coin])
  131. for fn in os.listdir(sdir):
  132. if fn.endswith(f'[{coin.upper()}].rawmsg.json'):
  133. yield os.path.join(sdir,fn)
  134. self.ref_msgfiles = tuple(gen_msg_fns())
  135. self.good_msg_count = 0
  136. self.bad_msg_count = 0
  137. def __del__(self):
  138. if sys.platform == 'win32' or self.tr is None:
  139. return
  140. if self.simulate or not self.live:
  141. LEDControl.delete_dummy_control_files()
  142. def start_daemons(self):
  143. self.spawn('',msg_only=True)
  144. start_test_daemons(*self.network_ids)
  145. return 'ok'
  146. def stop_daemons(self):
  147. self.spawn('',msg_only=True)
  148. stop_test_daemons(*self.network_ids)
  149. return 'ok'
  150. def gen_key(self):
  151. t = self.spawn( 'mmgen-autosign', self.opts + ['gen_key'] )
  152. t.expect_getend('Wrote key file ')
  153. return t
  154. def create_dfl_wallet(self):
  155. t = self.spawn( 'mmgen-walletconv', [
  156. f'--outdir={cfg.data_dir}',
  157. '--usr-randchars=0', '--quiet', '--hash-preset=1', '--label=foo',
  158. 'test/ref/98831F3A.hex'
  159. ]
  160. )
  161. t.passphrase_new('new MMGen wallet','abc')
  162. t.written_to_file('MMGen wallet')
  163. return t
  164. def run_setup_dfl_wallet(self):
  165. return self.run_setup(mn_type='default',use_dfl_wallet=True)
  166. def run_setup_bip39(self):
  167. return self.run_setup(mn_type='bip39')
  168. def run_setup(self,mn_type=None,mn_file=None,use_dfl_wallet=False):
  169. mn_desc = mn_type or 'default'
  170. mn_type = mn_type or 'mmgen'
  171. t = self.spawn(
  172. 'mmgen-autosign',
  173. self.opts +
  174. ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}']) +
  175. ['setup'] )
  176. if use_dfl_wallet:
  177. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'y' )
  178. t.passphrase( 'MMGen wallet', 'abc' )
  179. else:
  180. if use_dfl_wallet is not None: # None => no dfl wallet present
  181. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'n' )
  182. mn_file = mn_file or { 'mmgen': dfl_words_file, 'bip39': dfl_bip39_file }[mn_type]
  183. mn = read_from_file(mn_file).strip().split()
  184. from mmgen.mn_entry import mn_entry
  185. entry_mode = 'full'
  186. mne = mn_entry( cfg, mn_type, entry_mode )
  187. t.expect('words: ',{ 12:'1', 18:'2', 24:'3' }[len(mn)])
  188. t.expect('OK? (Y/n): ','\n')
  189. t.expect('Type a number.*: ',str(mne.entry_modes.index(entry_mode)+1),regex=True)
  190. stealth_mnemonic_entry(t,mne,mn,entry_mode)
  191. t.written_to_file('Autosign wallet')
  192. return t
  193. def copy_tx_files(self):
  194. self.spawn('',msg_only=True)
  195. return self.tx_file_ops('copy')
  196. def remove_signed_txfiles(self):
  197. self.tx_file_ops('remove_signed')
  198. return 'skip'
  199. def remove_signed_txfiles_btc(self):
  200. self.tx_file_ops('remove_signed',txfile_coins=['btc'])
  201. return 'skip'
  202. def tx_file_ops(self,op,txfile_coins=[]):
  203. assert op in ('copy','set_count','remove_signed')
  204. fdata = [e for e in filedir_map if e[0] in (txfile_coins or self.txfile_coins)]
  205. from .ct_ref import CmdTestRef
  206. tfns = [CmdTestRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  207. [CmdTestRef.sources['ref_tx_file'][c][0] for c,d in fdata] + \
  208. ['25EFA3[2.34].testnet.rawtx'] # TX with 2 non-MMGen outputs
  209. self.tx_count = len([fn for fn in tfns if fn])
  210. if op == 'set_count':
  211. return
  212. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata+[('btc','')],tfns)]
  213. for f,fn in zip(tfs,tfns):
  214. if fn: # use empty fn to skip file
  215. if cfg.debug_utf8:
  216. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  217. fn = fn[:-len(ext)] + '-α' + ext
  218. target = joinpath(self.mountpoint,'tx',fn)
  219. if not op == 'remove_signed':
  220. shutil.copyfile(f,target)
  221. try:
  222. os.unlink(target.replace('.rawtx','.sigtx'))
  223. except:
  224. pass
  225. return 'ok'
  226. def create_bad_txfiles(self):
  227. return self.bad_txfiles('create')
  228. def remove_bad_txfiles(self):
  229. return self.bad_txfiles('remove')
  230. def bad_txfiles(self,op):
  231. if self.live:
  232. do_mount(self.mountpoint)
  233. # create or delete 2 bad tx files
  234. self.spawn('',msg_only=True)
  235. fns = [joinpath(self.mountpoint,'tx',f'bad{n}.rawtx') for n in (1,2)]
  236. if op == 'create':
  237. for fn in fns:
  238. with open(fn,'w') as fp:
  239. fp.write('bad tx data\n')
  240. self.bad_tx_count = 2
  241. elif op == 'remove':
  242. for fn in fns:
  243. try:
  244. os.unlink(fn)
  245. except:
  246. pass
  247. self.bad_tx_count = 0
  248. return 'ok'
  249. def copy_msgfiles(self):
  250. return self.msgfile_ops('copy')
  251. def remove_signed_msgfiles(self):
  252. return self.msgfile_ops('remove_signed')
  253. def create_invalid_msgfile(self):
  254. return self.msgfile_ops('create_invalid')
  255. def remove_invalid_msgfile(self):
  256. return self.msgfile_ops('remove_invalid')
  257. def msgfile_ops(self,op):
  258. self.spawn('',msg_only=True)
  259. destdir = joinpath(self.mountpoint,'msg')
  260. os.makedirs(destdir,exist_ok=True)
  261. if op.endswith('_invalid'):
  262. fn = os.path.join(destdir,'DEADBE[BTC].rawmsg.json')
  263. if op == 'create_invalid':
  264. with open(fn,'w') as fp:
  265. fp.write('bad data\n')
  266. self.bad_msg_count += 1
  267. elif op == 'remove_invalid':
  268. os.unlink(fn)
  269. self.bad_msg_count -= 1
  270. else:
  271. for fn in self.ref_msgfiles:
  272. if op == 'copy':
  273. if os.path.basename(fn) == 'ED405C[BTC].rawmsg.json': # contains bad Seed ID
  274. self.bad_msg_count += 1
  275. else:
  276. self.good_msg_count += 1
  277. imsg(f'Copying: {fn} -> {destdir}')
  278. shutil.copy2(fn,destdir)
  279. elif op == 'remove_signed':
  280. os.unlink(os.path.join( destdir, os.path.basename(fn).replace('rawmsg','sigmsg') ))
  281. return 'ok'
  282. def do_sign(self,args,have_msg=False,tx_name='transaction'):
  283. t = self.spawn('mmgen-autosign', self.opts + args )
  284. t.expect(
  285. f'{self.tx_count} {tx_name}{suf(self.tx_count)} signed' if self.tx_count else
  286. 'No unsigned transactions' )
  287. if self.bad_tx_count:
  288. t.expect(f'{self.bad_tx_count} {tx_name}{suf(self.bad_tx_count)} failed to sign')
  289. t.req_exit_val = 1
  290. if have_msg:
  291. t.expect(
  292. f'{self.good_msg_count} message file{suf(self.good_msg_count)}{{0,1}} signed'
  293. if self.good_msg_count else
  294. 'No unsigned message files', regex=True )
  295. if self.bad_msg_count:
  296. t.expect(
  297. f'{self.bad_msg_count} message file{suf(self.bad_msg_count)}{{0,1}} failed to sign',
  298. regex = True )
  299. t.req_exit_val = 1
  300. if 'wait' in args:
  301. t.expect('Waiting')
  302. imsg(purple('\nKilling wait loop!'))
  303. t.kill(2)
  304. t.req_exit_val = 1
  305. else:
  306. t.read()
  307. imsg('')
  308. return t
  309. class CmdTestAutosign(CmdTestAutosignBase):
  310. 'autosigning transactions for all supported coins'
  311. coins = ['btc','bch','ltc','eth']
  312. daemon_coins = ['btc','bch','ltc']
  313. txfile_coins = ['btc','bch','ltc','eth','mm1','etc']
  314. live = False
  315. simulate = False
  316. bad_tx_count = 0
  317. cmd_group = (
  318. ('start_daemons', 'starting daemons'),
  319. ('copy_tx_files', 'copying transaction files'),
  320. ('gen_key', 'generating key'),
  321. ('create_dfl_wallet', 'creating default MMGen wallet'),
  322. ('run_setup_dfl_wallet', 'running ‘autosign setup’ (with default wallet)'),
  323. ('sign_quiet', 'signing transactions (--quiet)'),
  324. ('remove_signed_txfiles', 'removing signed transaction files'),
  325. ('run_setup_bip39', 'running ‘autosign setup’ (BIP39 mnemonic)'),
  326. ('create_bad_txfiles', 'creating bad transaction files'),
  327. ('sign_full_summary', 'signing transactions (--full-summary)'),
  328. ('remove_signed_txfiles_btc','removing transaction files (BTC only)'),
  329. ('remove_bad_txfiles', 'removing bad transaction files'),
  330. ('sign_led', 'signing transactions (--led - BTC files only)'),
  331. ('remove_signed_txfiles', 'removing signed transaction files'),
  332. ('sign_stealth_led', 'signing transactions (--stealth-led)'),
  333. ('remove_signed_txfiles', 'removing signed transaction files'),
  334. ('copy_msgfiles', 'copying message files'),
  335. ('sign_quiet_msg', 'signing transactions and messages (--quiet)'),
  336. ('remove_signed_txfiles', 'removing signed transaction files'),
  337. ('create_bad_txfiles', 'creating bad transaction files'),
  338. ('remove_signed_msgfiles', 'removing signed message files'),
  339. ('create_invalid_msgfile', 'creating invalid message file'),
  340. ('sign_full_summary_msg', 'signing transactions and messages (--full-summary)'),
  341. ('remove_invalid_msgfile', 'removing invalid message file'),
  342. ('remove_bad_txfiles', 'removing bad transaction files'),
  343. ('sign_no_unsigned_msg', 'signing transactions and messages (nothing to sign)'),
  344. ('stop_daemons', 'stopping daemons'),
  345. )
  346. def sign_quiet(self):
  347. return self.do_sign(['--quiet','wait'])
  348. def sign_full_summary(self):
  349. return self.do_sign(['--full-summary','wait'])
  350. def sign_led(self):
  351. return self.do_sign(['--quiet','--led'])
  352. def sign_stealth_led(self):
  353. return self.do_sign(['--quiet','--stealth-led','wait'])
  354. def sign_quiet_msg(self):
  355. return self.do_sign(['--quiet','wait'],have_msg=True)
  356. def sign_full_summary_msg(self):
  357. return self.do_sign(['--full-summary','wait'],have_msg=True)
  358. def sign_no_unsigned_msg(self):
  359. self.tx_count = 0
  360. self.good_msg_count = 0
  361. self.bad_msg_count = 0
  362. return self.do_sign(['--quiet','wait'],have_msg=True)
  363. class CmdTestAutosignBTC(CmdTestAutosign):
  364. 'autosigning BTC transactions'
  365. coins = ['btc']
  366. daemon_coins = ['btc']
  367. txfile_coins = ['btc']
  368. class CmdTestAutosignLive(CmdTestAutosignBTC):
  369. 'live autosigning BTC transactions'
  370. live = True
  371. cmd_group = (
  372. ('start_daemons', 'starting daemons'),
  373. ('copy_tx_files', 'copying transaction files'),
  374. ('gen_key', 'generating key'),
  375. ('run_setup_mmgen', 'running ‘autosign setup’ (MMGen native mnemonic)'),
  376. ('sign_live', 'signing transactions'),
  377. ('create_bad_txfiles', 'creating bad transaction files'),
  378. ('sign_live_led', 'signing transactions (--led)'),
  379. ('remove_bad_txfiles', 'removing bad transaction files'),
  380. ('sign_live_stealth_led','signing transactions (--stealth-led)'),
  381. ('stop_daemons', 'stopping daemons'),
  382. )
  383. def run_setup_mmgen(self):
  384. return self.run_setup(mn_type='mmgen',use_dfl_wallet=None)
  385. def sign_live(self):
  386. return self.do_sign_live([])
  387. def sign_live_led(self):
  388. return self.do_sign_live(['--led'])
  389. def sign_live_stealth_led(self):
  390. return self.do_sign_live(['--stealth-led'])
  391. def do_sign_live(self,led_opts):
  392. def prompt_remove():
  393. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  394. input()
  395. def prompt_insert_sign(t):
  396. omsg(blue(insert_msg))
  397. t.expect(f'{self.tx_count} transactions signed')
  398. if self.bad_tx_count:
  399. t.expect(f'{self.bad_tx_count} transactions failed to sign')
  400. t.expect('Waiting')
  401. if led_opts:
  402. opts_msg = "'" + ' '.join(led_opts) + "'"
  403. info_msg = f"Running 'mmgen-autosign wait' with {led_opts[0]}. " + {
  404. '--led': "The LED should start blinking slowly now",
  405. '--stealth-led': "You should see no LED activity now"
  406. }[led_opts[0]]
  407. insert_msg = 'Insert removable device and watch for fast LED activity during signing'
  408. else:
  409. opts_msg = 'no LED'
  410. info_msg = "Running 'mmgen-autosign wait'"
  411. insert_msg = 'Insert removable device '
  412. omsg(purple(f'Running autosign test with {opts_msg}'))
  413. do_umount(self.mountpoint)
  414. prompt_remove()
  415. omsg(green(info_msg))
  416. t = self.spawn(
  417. 'mmgen-autosign',
  418. self.opts + led_opts + ['--quiet','--no-summary','wait'])
  419. if not cfg.exact_output:
  420. omsg('')
  421. prompt_insert_sign(t)
  422. do_mount(self.mountpoint) # race condition due to device insertion detection
  423. self.remove_signed_txfiles()
  424. do_umount(self.mountpoint)
  425. imsg(purple('\nKilling wait loop!'))
  426. t.kill(2) # 2 = SIGINT
  427. t.req_exit_val = 1
  428. if self.simulate and led_opts:
  429. t.expect("Stopping LED")
  430. return t
  431. class CmdTestAutosignLiveSimulate(CmdTestAutosignLive):
  432. 'live autosigning BTC transactions with simulated LED support'
  433. simulate = True