ts_autosign.py 14 KB

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