ts_shared.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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_shared: Shared methods for the test.py test suite
  20. """
  21. from mmgen.util import get_extension
  22. from mmgen.wallet import get_wallet_cls
  23. from ..include.common import cmp_or_die,strip_ansi_escapes,joinpath
  24. from .common import ref_bw_file,ref_bw_hash_preset,ref_dir
  25. class TestSuiteShared:
  26. 'shared methods for the test.py test suite'
  27. def txcreate_ui_common(
  28. self,
  29. t,
  30. caller = None,
  31. menu = [],
  32. inputs = '1',
  33. file_desc = 'Unsigned transaction',
  34. input_sels_prompt = 'to spend',
  35. bad_input_sels = False,
  36. interactive_fee = '',
  37. fee_desc = 'transaction fee',
  38. fee_info_pat = None,
  39. add_comment = '',
  40. view = 't',
  41. save = True,
  42. tweaks = [],
  43. used_chg_addr_resp = None,
  44. auto_chg_addr = None):
  45. txdo = (caller or self.test_name)[:4] == 'txdo'
  46. expect_pat = r'\[q\]uit menu, .*?:.'
  47. delete_pat = r'Enter account number .*:.'
  48. confirm_pat = r'Is this what you want.*:.'
  49. if used_chg_addr_resp is not None:
  50. t.expect('reuse harms your privacy.*:.*',used_chg_addr_resp,regex=True)
  51. if auto_chg_addr is not None:
  52. e1 = 'Choose a change address:.*Enter a number> '
  53. e2 = fr'Using .*{auto_chg_addr}.* as.*address'
  54. res = t.expect([e1,e2],regex=True)
  55. if res == 0:
  56. choice = [s.split(')')[0].lstrip() for s in t.p.match[0].split('\n') if auto_chg_addr in s][0]
  57. t.send(f'{choice}\n')
  58. t.expect(e2,regex=True)
  59. t.send('y')
  60. pat = expect_pat
  61. for choice in menu + ['q']:
  62. t.expect(pat,choice,regex=True)
  63. if self.proto.base_proto == 'Ethereum':
  64. pat = confirm_pat if pat == delete_pat else delete_pat if choice == 'D' else expect_pat
  65. if bad_input_sels:
  66. for r in ('x','3-1','9999'):
  67. t.expect(input_sels_prompt+': ',r+'\n')
  68. t.expect(input_sels_prompt+': ',inputs+'\n')
  69. have_est_fee = t.expect([f'{fee_desc}: ','OK? (Y/n): ']) == 1
  70. if have_est_fee and not interactive_fee:
  71. t.send('y')
  72. else:
  73. if have_est_fee:
  74. t.send('n')
  75. t.expect(f'{fee_desc}: ',interactive_fee+'\n')
  76. else:
  77. t.send(interactive_fee+'\n')
  78. if fee_info_pat:
  79. t.expect(fee_info_pat,regex=True)
  80. t.expect('OK? (Y/n): ','y')
  81. t.expect('(Y/n): ','\n') # chg amt OK prompt
  82. if 'confirm_non_mmgen' in tweaks:
  83. t.expect('Continue? (Y/n)','\n')
  84. t.do_comment(add_comment)
  85. t.view_tx(view)
  86. if not txdo:
  87. t.expect('(y/N): ',('n','y')[save])
  88. t.written_to_file(file_desc)
  89. return t
  90. def txsign_ui_common(
  91. self,
  92. t,
  93. caller = None,
  94. view = 't',
  95. add_comment = '',
  96. file_desc = 'Signed transaction',
  97. ni = False,
  98. save = True,
  99. do_passwd = False,
  100. has_label = False):
  101. txdo = (caller or self.test_name)[:4] == 'txdo'
  102. if do_passwd:
  103. t.passphrase('MMGen wallet',self.wpasswd)
  104. if not ni and not txdo:
  105. t.view_tx(view)
  106. t.do_comment(add_comment,has_label=has_label)
  107. t.expect('(Y/n): ',('n','y')[save])
  108. t.written_to_file(file_desc)
  109. return t
  110. def txsend_ui_common(
  111. self,
  112. t,
  113. caller = None,
  114. view = 'n',
  115. add_comment = '',
  116. file_desc = 'Sent transaction',
  117. confirm_send = True,
  118. bogus_send = True,
  119. quiet = False,
  120. has_label = False):
  121. txdo = (caller or self.test_name)[:4] == 'txdo'
  122. if not txdo:
  123. t.license() # MMGEN_NO_LICENSE is set, so does nothing
  124. t.view_tx(view)
  125. t.do_comment(add_comment,has_label=has_label)
  126. self._do_confirm_send(t,quiet=quiet,confirm_send=confirm_send)
  127. if bogus_send:
  128. txid = ''
  129. t.expect('BOGUS transaction NOT sent')
  130. else:
  131. txid = strip_ansi_escapes(t.expect_getend('Transaction sent: '))
  132. assert len(txid) == 64, f'{txid!r}: Incorrect txid length!'
  133. t.written_to_file(file_desc)
  134. return txid
  135. def txsign_end(self,t,tnum=None,has_label=False):
  136. t.expect('Signing transaction')
  137. t.do_comment(False,has_label=has_label)
  138. t.expect(r'Save signed transaction.*?\? \(Y/n\): ','y',regex=True)
  139. t.written_to_file('Signed transaction' + (' #' + tnum if tnum else ''), oo=True)
  140. return t
  141. def txsign(
  142. self,
  143. wf,
  144. txfile,
  145. pf = '',
  146. bumpf = '',
  147. save = True,
  148. has_label = False,
  149. extra_opts = [],
  150. extra_desc = '',
  151. view = 'n',
  152. dfl_wallet = False):
  153. opts = extra_opts + ['-d',self.tmpdir,txfile] + ([wf] if wf else [])
  154. t = self.spawn('mmgen-txsign', opts, extra_desc)
  155. t.license()
  156. t.view_tx(view)
  157. wcls = get_wallet_cls( ext = 'mmdat' if dfl_wallet else get_extension(wf) )
  158. if wcls.enc and wcls.type != 'brain':
  159. t.passphrase(wcls.desc,self.wpasswd)
  160. if save:
  161. self.txsign_end(t,has_label=has_label)
  162. else:
  163. t.do_comment(False,has_label=has_label)
  164. t.expect('Save signed transaction? (Y/n): ','n')
  165. t.expect('not saved')
  166. t.req_exit_val = 1
  167. return t
  168. def ref_brain_chk(self,bw_file=ref_bw_file):
  169. wf = joinpath(ref_dir,bw_file)
  170. add_args = [f'-l{self.seed_len}', f'-p{ref_bw_hash_preset}']
  171. return self.walletchk(wf,pf=None,add_args=add_args,sid=self.ref_bw_seed_id)
  172. def walletchk(
  173. self,
  174. wf,
  175. pf,
  176. wcls = None,
  177. add_args = [],
  178. sid = None,
  179. extra_desc = '',
  180. dfl_wallet = False):
  181. hp = self.hash_preset if hasattr(self,'hash_preset') else '1'
  182. wcls = wcls or get_wallet_cls(ext=get_extension(wf))
  183. t = self.spawn('mmgen-walletchk',
  184. ([] if dfl_wallet else ['-i',wcls.fmt_codes[0]])
  185. + add_args + ['-p',hp]
  186. + ([wf] if wf else []),
  187. extra_desc=extra_desc)
  188. if wcls.type != 'incog_hidden':
  189. t.expect(f"Getting {wcls.desc} from file '")
  190. if wcls.enc and wcls.type != 'brain':
  191. t.passphrase(wcls.desc,self.wpasswd)
  192. t.expect(['Passphrase is OK', 'Passphrase.* are correct'],regex=True)
  193. chk = t.expect_getend(f'Valid {wcls.desc} for Seed ID ')[:8]
  194. if sid:
  195. cmp_or_die(chk,sid)
  196. return t
  197. def addrgen(
  198. self,
  199. wf,
  200. pf = None,
  201. check_ref = False,
  202. ftype = 'addr',
  203. id_str = None,
  204. extra_args = [],
  205. mmtype = None,
  206. stdout = False,
  207. dfl_wallet = False):
  208. passgen = ftype[:4] == 'pass'
  209. if not mmtype and not passgen:
  210. mmtype = self.segwit_mmtype
  211. cmd_pfx = (ftype,'pass')[passgen]
  212. t = self.spawn(
  213. f'mmgen-{cmd_pfx}gen',
  214. ['-d',self.tmpdir] + extra_args +
  215. ([],['--type='+str(mmtype)])[bool(mmtype)] +
  216. ([],['--stdout'])[stdout] +
  217. ([],[wf])[bool(wf)] +
  218. ([],[id_str])[bool(id_str)] +
  219. [getattr(self,f'{cmd_pfx}_idx_list')],
  220. extra_desc=f'({mmtype})' if mmtype in ('segwit','bech32') else '')
  221. t.license()
  222. wcls = get_wallet_cls( ext = 'mmdat' if dfl_wallet else get_extension(wf) )
  223. t.passphrase(wcls.desc,self.wpasswd)
  224. t.expect('Passphrase is OK')
  225. desc = ('address','password')[passgen]
  226. chk = t.expect_getend(rf'Checksum for {desc} data .*?: ',regex=True)
  227. if passgen:
  228. t.expect('Encrypt password list? (y/N): ','N')
  229. t.read() if stdout else t.written_to_file(('Addresses','Password list')[passgen])
  230. if check_ref:
  231. chk_ref = (
  232. self.chk_data[self.test_name] if passgen else
  233. self.chk_data[self.test_name][self.fork][self.proto.testnet])
  234. cmp_or_die(chk,chk_ref,desc=f'{ftype}list data checksum')
  235. return t
  236. def keyaddrgen(self,wf,pf=None,check_ref=False,mmtype=None):
  237. if not mmtype:
  238. mmtype = self.segwit_mmtype
  239. args = ['-d',self.tmpdir,self.usr_rand_arg,wf,self.addr_idx_list]
  240. t = self.spawn('mmgen-keygen',
  241. ([],['--type='+str(mmtype)])[bool(mmtype)] + args,
  242. extra_desc=f'({mmtype})' if mmtype in ('segwit','bech32') else '')
  243. t.license()
  244. wcls = get_wallet_cls(ext=get_extension(wf))
  245. t.passphrase(wcls.desc,self.wpasswd)
  246. chk = t.expect_getend(r'Checksum for key-address data .*?: ',regex=True)
  247. if check_ref:
  248. chk_ref = self.chk_data[self.test_name][self.fork][self.proto.testnet]
  249. cmp_or_die(chk,chk_ref,desc='key-address list data checksum')
  250. t.expect('Encrypt key list? (y/N): ','y')
  251. t.usr_rand(self.usr_rand_chars)
  252. t.hash_preset('new key-address list','1')
  253. t.passphrase_new('new key-address list',self.kapasswd)
  254. t.written_to_file('Encrypted secret keys',oo=True)
  255. return t
  256. def _do_confirm_send(self,t,quiet=False,confirm_send=True,sure=True):
  257. if sure:
  258. t.expect('Are you sure you want to broadcast this')
  259. m = ('YES, I REALLY WANT TO DO THIS','YES')[quiet]
  260. t.expect(f'{m!r} to confirm: ',('',m)[confirm_send]+'\n')