ts_autosign.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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 test.common import *
  26. from test.test_py_d.common import *
  27. from test.test_py_d.ts_base import *
  28. from test.test_py_d.ts_shared import *
  29. class TestSuiteAutosign(TestSuiteBase):
  30. 'autosigning with BTC, BCH, LTC, ETH and ETC'
  31. networks = ('btc',)
  32. tmpdir_nums = [18]
  33. cmd_group = (
  34. ('autosign', 'transaction autosigning (BTC,BCH,LTC,ETH,ETC)'),
  35. )
  36. def autosign_live(self):
  37. return self.autosign_minimal(live=True)
  38. def autosign_minimal(self,live=False):
  39. return self.autosign(
  40. coins=['btc','eth'],
  41. txfiles=['btc','eth','mm1','etc'],
  42. txcount=8,
  43. live=live)
  44. # tests everything except device detection, mount/unmount
  45. def autosign( self,
  46. coins=['btc','bch','ltc','eth'],
  47. txfiles=['btc','bch','ltc','eth','mm1','etc'],
  48. txcount=12,
  49. live=False):
  50. if self.skip_for_win(): return 'skip'
  51. def make_wallet(opts):
  52. t = self.spawn('mmgen-autosign',opts+['gen_key'],extra_desc='(gen_key)')
  53. t.expect_getend('Wrote key file ')
  54. t.ok()
  55. t = self.spawn('mmgen-autosign',opts+['setup'],extra_desc='(setup)')
  56. t.expect('words: ','3')
  57. t.expect('OK? (Y/n): ','\n')
  58. mn_file = dfl_words_file
  59. mn = read_from_file(mn_file).strip().split()
  60. mn = ['foo'] + mn[:5] + ['realiz','realized'] + mn[5:]
  61. stealth_mnemonic_entry(t,mn,fmt='words')
  62. wf = t.written_to_file('Autosign wallet')
  63. t.ok()
  64. def copy_files(mountpoint,remove_signed_only=False,include_bad_tx=True):
  65. fdata_in = (('btc',''),
  66. ('bch',''),
  67. ('ltc','litecoin'),
  68. ('eth','ethereum'),
  69. ('mm1','ethereum'),
  70. ('etc','ethereum_classic'))
  71. fdata = [e for e in fdata_in if e[0] in txfiles]
  72. from test.test_py_d.ts_ref import TestSuiteRef
  73. tfns = [TestSuiteRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  74. [TestSuiteRef.sources['ref_tx_file'][c][0] for c,d in fdata] + \
  75. ['25EFA3[2.34].testnet.rawtx'] # TX with 2 non-MMGen outputs
  76. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata+[('btc','')],tfns)]
  77. for f,fn in zip(tfs,tfns):
  78. if fn: # use empty fn to skip file
  79. if g.debug_utf8:
  80. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  81. fn = fn[:-len(ext)] + '-α' + ext
  82. target = joinpath(mountpoint,'tx',fn)
  83. remove_signed_only or shutil.copyfile(f,target)
  84. try: os.unlink(target.replace('.rawtx','.sigtx'))
  85. except: pass
  86. # make 2 bad tx files
  87. for n in (1,2):
  88. bad_tx = joinpath(mountpoint,'tx','bad{}.rawtx'.format(n))
  89. if include_bad_tx and not remove_signed_only:
  90. open(bad_tx,'w').write('bad tx data')
  91. if not include_bad_tx:
  92. try: os.unlink(bad_tx)
  93. except: pass
  94. def do_autosign_live(opts,mountpoint,led_opts=[],gen_wallet=True):
  95. def do_mount():
  96. try: run(['mount',mountpoint],check=True)
  97. except: pass
  98. def do_unmount():
  99. try: run(['umount',mountpoint],check=True)
  100. except: pass
  101. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  102. input()
  103. if gen_wallet: make_wallet(opts)
  104. else: do_mount()
  105. copy_files(mountpoint,include_bad_tx=not led_opts)
  106. desc = '(sign)'
  107. m1 = "Running 'mmgen-autosign wait'"
  108. m2 = 'Insert removable device '
  109. if led_opts:
  110. if led_opts == ['--led']:
  111. m1 = "Running 'mmgen-autosign wait' with --led. The LED should start blinking slowly now"
  112. elif led_opts == ['--stealth-led']:
  113. m1 = "Running 'mmgen-autosign wait' with --stealth-led. You should see no LED activity now"
  114. m2 = 'Insert removable device and watch for fast LED activity during signing'
  115. desc = '(sign - {})'.format(led_opts[0])
  116. def do_loop():
  117. omsg(blue(m2))
  118. t.expect('{} transactions signed'.format(txcount))
  119. if not led_opts:
  120. t.expect('2 transactions failed to sign')
  121. t.expect('Waiting')
  122. do_unmount()
  123. omsg(green(m1))
  124. t = self.spawn('mmgen-autosign',opts+led_opts+['wait'],extra_desc=desc)
  125. if not opt.exact_output: omsg('')
  126. do_loop()
  127. do_mount() # race condition due to device insertion detection
  128. copy_files(mountpoint,remove_signed_only=True,include_bad_tx=not led_opts)
  129. do_unmount()
  130. do_loop()
  131. t.kill(2) # 2 = SIGINT
  132. t.req_exit_val = 1
  133. return t
  134. def do_autosign(opts,mountpoint):
  135. make_wallet(opts)
  136. copy_files(mountpoint,include_bad_tx=True)
  137. t = self.spawn('mmgen-autosign',opts+['--full-summary','wait'],extra_desc='(sign - full summary)')
  138. t.expect('{} transactions signed'.format(txcount))
  139. t.expect('2 transactions failed to sign')
  140. t.expect('Waiting')
  141. t.kill(2)
  142. t.req_exit_val = 1
  143. imsg('')
  144. t.ok()
  145. copy_files(mountpoint,remove_signed_only=True)
  146. t = self.spawn('mmgen-autosign',opts+['wait'],extra_desc='(sign)')
  147. t.expect('{} transactions signed'.format(txcount))
  148. t.expect('2 transactions failed to sign')
  149. t.expect('Waiting')
  150. t.kill(2)
  151. t.req_exit_val = 1
  152. imsg('')
  153. return t
  154. network_ids = [c+'_tn' for c in coins] + coins
  155. start_test_daemons(*network_ids)
  156. if live:
  157. mountpoint = '/mnt/tx'
  158. if not os.path.ismount(mountpoint):
  159. try:
  160. run(['mount',mountpoint],check=True)
  161. imsg("Mounted '{}'".format(mountpoint))
  162. except:
  163. ydie(1,"Could not mount '{}'! Exiting".format(mountpoint))
  164. txdir = joinpath(mountpoint,'tx')
  165. if not os.path.isdir(txdir):
  166. ydie(1,"Directory '{}' does not exist! Exiting".format(mountpoint))
  167. opts = ['--coins='+','.join(coins)]
  168. led_files = { 'opi': ('/sys/class/leds/orangepi:red:status/brightness',),
  169. 'rpi': ('/sys/class/leds/led0/brightness','/sys/class/leds/led0/trigger') }
  170. for k in ('opi','rpi'):
  171. if os.path.exists(led_files[k][0]):
  172. led_support = k
  173. break
  174. else:
  175. led_support = None
  176. if led_support:
  177. for fn in (led_files[led_support]):
  178. run(['sudo','chmod','0666',fn],check=True)
  179. omsg(purple('Running autosign test with no LED'))
  180. do_autosign_live(opts,mountpoint)
  181. omsg(purple("Running autosign test with '--led'"))
  182. do_autosign_live(opts,mountpoint,led_opts=['--led'],gen_wallet=False)
  183. omsg(purple("Running autosign test with '--stealth-led'"))
  184. ret = do_autosign_live(opts,mountpoint,led_opts=['--stealth-led'],gen_wallet=False)
  185. else:
  186. ret = do_autosign_live(opts,mountpoint)
  187. else:
  188. mountpoint = self.tmpdir
  189. opts = ['--no-insert-check','--mountpoint='+mountpoint,'--coins='+','.join(coins)]
  190. try: os.mkdir(joinpath(mountpoint,'tx'))
  191. except: pass
  192. ret = do_autosign(opts,mountpoint)
  193. stop_test_daemons(*network_ids)
  194. return ret
  195. class TestSuiteAutosignMinimal(TestSuiteAutosign):
  196. 'autosigning with BTC, ETH and ETC'
  197. cmd_group = (
  198. ('autosign_minimal', 'transaction autosigning (BTC,ETH,ETC)'),
  199. )
  200. class TestSuiteAutosignLive(TestSuiteAutosignMinimal):
  201. 'live autosigning operations with device insertion/removal and LED check'
  202. cmd_group = (
  203. ('autosign_live', 'transaction autosigning (BTC,ETH,ETC - test device insertion/removal + LED)'),
  204. )