ct_autosign.py 15 KB

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