ts_autosign.py 14 KB

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