ts_autosign.py 7.9 KB

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