ts_autosign.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. ts_autosign.py: Autosign tests for the test.py test suite
  20. """
  21. import os,shutil
  22. from subprocess import run
  23. from mmgen.globalvars import g
  24. from mmgen.opts import opt
  25. from ..include.common import *
  26. from .common import *
  27. from .ts_base import *
  28. from .ts_shared import *
  29. from .input import *
  30. from mmgen.led import LEDControl
  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):
  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. txdir = joinpath(mountpoint,'tx')
  56. if not os.path.isdir(txdir):
  57. die(2,f'Directory {txdir} does not exist! Exiting')
  58. def do_mount(mountpoint):
  59. if not os.path.ismount(mountpoint):
  60. try: run(['mount',mountpoint],check=True)
  61. except: pass
  62. def do_umount(mountpoint):
  63. if os.path.ismount(mountpoint):
  64. try: run(['umount',mountpoint],check=True)
  65. except: pass
  66. class TestSuiteAutosignBase(TestSuiteBase):
  67. networks = ('btc',)
  68. tmpdir_nums = [18]
  69. color = True
  70. def __init__(self,trunner,cfgs,spawn):
  71. super().__init__(trunner,cfgs,spawn)
  72. if trunner == None:
  73. return
  74. self.network_ids = [c+'_tn' for c in self.daemon_coins] + self.daemon_coins
  75. if self.simulate and not opt.exact_output:
  76. die(1,red('This command must be run with --exact-output enabled!'))
  77. if self.simulate or not self.live:
  78. os.environ['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  79. LEDControl.create_dummy_control_files()
  80. if self.live:
  81. self.mountpoint = '/mnt/tx'
  82. self.opts = ['--coins='+','.join(self.coins)]
  83. check_mountpoint(self.mountpoint)
  84. init_led(self.simulate)
  85. else:
  86. self.mountpoint = self.tmpdir
  87. try:
  88. os.mkdir(joinpath(self.mountpoint,'tx'))
  89. except:
  90. pass
  91. self.opts = [
  92. '--coins='+','.join(self.coins),
  93. '--mountpoint='+self.mountpoint,
  94. '--no-insert-check' ]
  95. self.tx_file_ops('set_count') # initialize tx_count here so we can resume anywhere
  96. def __del__(self):
  97. if self.simulate or not self.live:
  98. LEDControl.delete_dummy_control_files()
  99. def start_daemons(self):
  100. self.spawn('',msg_only=True)
  101. start_test_daemons(*self.network_ids)
  102. return 'ok'
  103. def stop_daemons(self):
  104. self.spawn('',msg_only=True)
  105. stop_test_daemons(*[i for i in self.network_ids if i != 'btc'])
  106. return 'ok'
  107. def gen_key(self):
  108. t = self.spawn( 'mmgen-autosign', self.opts + ['gen_key'] )
  109. t.expect_getend('Wrote key file ')
  110. return t
  111. def make_wallet_mmgen(self):
  112. return self.make_wallet(mn_type='mmgen')
  113. def make_wallet_bip39(self):
  114. return self.make_wallet(mn_type='bip39')
  115. def make_wallet(self,mn_type=None):
  116. mn_desc = mn_type or 'default'
  117. mn_type = mn_type or 'mmgen'
  118. t = self.spawn(
  119. 'mmgen-autosign',
  120. self.opts +
  121. ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}']) +
  122. ['setup'] )
  123. t.expect('words: ','3')
  124. t.expect('OK? (Y/n): ','\n')
  125. mn_file = { 'mmgen': dfl_words_file, 'bip39': dfl_bip39_file }[mn_type]
  126. mn = read_from_file(mn_file).strip().split()
  127. from mmgen.mn_entry import mn_entry
  128. entry_mode = 'full'
  129. mne = mn_entry(mn_type,entry_mode)
  130. t.expect('Type a number.*: ',str(mne.entry_modes.index(entry_mode)+1),regex=True)
  131. stealth_mnemonic_entry(t,mne,mn,entry_mode)
  132. wf = t.written_to_file('Autosign wallet')
  133. return t
  134. def copy_tx_files(self):
  135. self.spawn('',msg_only=True)
  136. return self.tx_file_ops('copy')
  137. def remove_signed_txfiles(self):
  138. self.tx_file_ops('remove_signed')
  139. return 'skip'
  140. def remove_signed_txfiles_btc(self):
  141. self.tx_file_ops('remove_signed',txfile_coins=['btc'])
  142. return 'skip'
  143. def tx_file_ops(self,op,txfile_coins=[]):
  144. assert op in ('copy','set_count','remove_signed')
  145. fdata = [e for e in filedir_map if e[0] in (txfile_coins or self.txfile_coins)]
  146. from .ts_ref import TestSuiteRef
  147. tfns = [TestSuiteRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  148. [TestSuiteRef.sources['ref_tx_file'][c][0] for c,d in fdata] + \
  149. ['25EFA3[2.34].testnet.rawtx'] # TX with 2 non-MMGen outputs
  150. self.tx_count = len([fn for fn in tfns if fn])
  151. if op == 'set_count':
  152. return
  153. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata+[('btc','')],tfns)]
  154. for f,fn in zip(tfs,tfns):
  155. if fn: # use empty fn to skip file
  156. if g.debug_utf8:
  157. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  158. fn = fn[:-len(ext)] + '-α' + ext
  159. target = joinpath(self.mountpoint,'tx',fn)
  160. if not op == 'remove_signed':
  161. shutil.copyfile(f,target)
  162. try:
  163. os.unlink(target.replace('.rawtx','.sigtx'))
  164. except:
  165. pass
  166. return 'ok'
  167. def create_bad_txfiles(self):
  168. return self.bad_txfiles('create')
  169. def remove_bad_txfiles(self):
  170. return self.bad_txfiles('remove')
  171. def bad_txfiles(self,op):
  172. if self.live:
  173. do_mount(self.mountpoint)
  174. # create or delete 2 bad tx files
  175. self.spawn('',msg_only=True)
  176. fns = [joinpath(self.mountpoint,'tx',f'bad{n}.rawtx') for n in (1,2)]
  177. if op == 'create':
  178. for fn in fns:
  179. with open(fn,'w') as fp:
  180. fp.write('bad tx data\n')
  181. self.bad_tx_count = 2
  182. elif op == 'remove':
  183. for fn in fns:
  184. try: os.unlink(fn)
  185. except: pass
  186. self.bad_tx_count = 0
  187. return 'ok'
  188. class TestSuiteAutosign(TestSuiteAutosignBase):
  189. 'autosigning transactions for all supported coins'
  190. coins = ['btc','bch','ltc','eth']
  191. daemon_coins = ['btc','bch','ltc']
  192. txfile_coins = ['btc','bch','ltc','eth','mm1','etc']
  193. live = False
  194. simulate = False
  195. bad_tx_count = 0
  196. cmd_group = (
  197. ('start_daemons', 'starting daemons'),
  198. ('copy_tx_files', 'copying transaction files'),
  199. ('gen_key', 'generating key'),
  200. ('make_wallet_mmgen', 'making wallet (MMGen native)'),
  201. ('sign_quiet', 'signing transactions (--quiet)'),
  202. ('remove_signed_txfiles', 'removing signed transaction files'),
  203. ('make_wallet_bip39', 'making wallet (BIP39)'),
  204. ('create_bad_txfiles', 'creating bad transaction files'),
  205. ('sign_full_summary', 'signing transactions (--full-summary)'),
  206. ('remove_signed_txfiles_btc','removing transaction files (BTC only)'),
  207. ('remove_bad_txfiles', 'removing bad transaction files'),
  208. ('sign_led', 'signing transactions (--led - BTC files only)'),
  209. ('remove_signed_txfiles', 'removing signed transaction files'),
  210. ('sign_stealth_led', 'signing transactions (--stealth-led)'),
  211. ('stop_daemons', 'stopping daemons'),
  212. )
  213. def do_sign(self,args):
  214. t = self.spawn('mmgen-autosign', self.opts + args )
  215. t.expect(f'{self.tx_count} transactions signed')
  216. if self.bad_tx_count:
  217. t.expect(f'{self.bad_tx_count} transactions failed to sign')
  218. t.req_exit_val = 1
  219. if 'wait' in args:
  220. t.expect('Waiting')
  221. t.kill(2)
  222. t.req_exit_val = 1
  223. else:
  224. t.read()
  225. imsg('')
  226. return t
  227. def sign_quiet(self):
  228. return self.do_sign(['--quiet','wait'])
  229. def sign_full_summary(self):
  230. return self.do_sign(['--full-summary','wait'])
  231. def sign_led(self):
  232. return self.do_sign(['--quiet','--led'])
  233. def sign_stealth_led(self):
  234. return self.do_sign(['--quiet','--stealth-led','wait'])
  235. class TestSuiteAutosignBTC(TestSuiteAutosign):
  236. 'autosigning BTC transactions'
  237. coins = ['btc']
  238. daemon_coins = ['btc']
  239. txfile_coins = ['btc']
  240. class TestSuiteAutosignLive(TestSuiteAutosignBTC):
  241. 'live autosigning BTC transactions'
  242. live = True
  243. cmd_group = (
  244. ('start_daemons', 'starting daemons'),
  245. ('copy_tx_files', 'copying transaction files'),
  246. ('gen_key', 'generating key'),
  247. ('make_wallet_bip39', 'making wallet (BIP39)'),
  248. ('sign_live', 'signing transactions'),
  249. ('create_bad_txfiles', 'creating bad transaction files'),
  250. ('sign_live_led', 'signing transactions (--led)'),
  251. ('remove_bad_txfiles', 'removing bad transaction files'),
  252. ('sign_live_stealth_led','signing transactions (--stealth-led)'),
  253. ('stop_daemons', 'stopping daemons'),
  254. )
  255. def sign_live(self):
  256. return self.do_sign_live([])
  257. def sign_live_led(self):
  258. return self.do_sign_live(['--led'])
  259. def sign_live_stealth_led(self):
  260. return self.do_sign_live(['--stealth-led'])
  261. def do_sign_live(self,led_opts):
  262. def prompt_remove():
  263. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  264. input()
  265. def prompt_insert_sign(t):
  266. omsg(blue(insert_msg))
  267. t.expect(f'{self.tx_count} transactions signed')
  268. if self.bad_tx_count:
  269. t.expect(f'{self.bad_tx_count} transactions failed to sign')
  270. t.expect('Waiting')
  271. if led_opts:
  272. opts_msg = "'" + ' '.join(led_opts) + "'"
  273. info_msg = f"Running 'mmgen-autosign wait' with {led_opts[0]}. " + {
  274. '--led': "The LED should start blinking slowly now",
  275. '--stealth-led': "You should see no LED activity now"
  276. }[led_opts[0]]
  277. insert_msg = 'Insert removable device and watch for fast LED activity during signing'
  278. else:
  279. opts_msg = 'no LED'
  280. info_msg = "Running 'mmgen-autosign wait'"
  281. insert_msg = 'Insert removable device '
  282. omsg(purple(f'Running autosign test with {opts_msg}'))
  283. do_umount(self.mountpoint)
  284. prompt_remove()
  285. omsg(green(info_msg))
  286. t = self.spawn(
  287. 'mmgen-autosign',
  288. self.opts + led_opts + ['--quiet','--no-summary','wait'])
  289. if not opt.exact_output:
  290. omsg('')
  291. prompt_insert_sign(t)
  292. do_mount(self.mountpoint) # race condition due to device insertion detection
  293. self.remove_signed_txfiles()
  294. do_umount(self.mountpoint)
  295. imsg(purple('\nKilling wait loop!'))
  296. t.kill(2) # 2 = SIGINT
  297. t.req_exit_val = 1
  298. if self.simulate and led_opts:
  299. t.expect("Stopping LED")
  300. return t
  301. class TestSuiteAutosignLiveSimulate(TestSuiteAutosignLive):
  302. 'live autosigning BTC transactions with simulated LED support'
  303. simulate = True