ct_shared.py 9.8 KB

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