shared.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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.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 .include.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. if 'confirm_chg_non_mmgen' in tweaks:
  94. t.expect('to confirm: ', 'YES\n')
  95. t.do_comment(add_comment)
  96. if return_early:
  97. return t
  98. t.view_tx(view)
  99. if not txdo:
  100. t.expect('(y/N): ', ('n', 'y')[save])
  101. t.written_to_file(file_desc)
  102. return t
  103. def txsign_ui_common(
  104. self,
  105. t,
  106. caller = None,
  107. view = 't',
  108. add_comment = '',
  109. file_desc = 'Signed transaction',
  110. ni = False,
  111. save = True,
  112. do_passwd = False,
  113. passwd = None,
  114. has_label = False):
  115. txdo = (caller or self.test_name)[:4] == 'txdo'
  116. if do_passwd and txdo:
  117. t.passphrase('MMGen wallet', passwd or self.wpasswd)
  118. if not (ni or txdo):
  119. t.view_tx(view)
  120. if do_passwd:
  121. t.passphrase('MMGen wallet', passwd or self.wpasswd)
  122. t.do_comment(add_comment, has_label=has_label)
  123. t.expect('(Y/n): ', ('n', 'y')[save])
  124. t.written_to_file(file_desc)
  125. return t
  126. def txsend_ui_common(
  127. self,
  128. t,
  129. caller = None,
  130. view = 'n',
  131. add_comment = '',
  132. file_desc = 'Sent transaction',
  133. confirm_send = True,
  134. bogus_send = True,
  135. test = False,
  136. quiet = False,
  137. has_label = False):
  138. txdo = (caller or self.test_name)[:4] == 'txdo'
  139. if not txdo:
  140. t.license() # MMGEN_NO_LICENSE is set, so does nothing
  141. t.view_tx(view)
  142. t.do_comment(add_comment, has_label=has_label)
  143. if not test:
  144. self._do_confirm_send(t, quiet=quiet, confirm_send=confirm_send)
  145. if bogus_send:
  146. txid = ''
  147. t.expect('BOGUS transaction NOT sent')
  148. elif test == 'tx_proxy':
  149. t.expect('can be sent')
  150. return True
  151. else:
  152. m = 'TxID: ' if test else 'Transaction sent: '
  153. txid = strip_ansi_escapes(t.expect_getend(m))
  154. assert len(txid) == 64, f'{txid!r}: Incorrect txid length!'
  155. if not test:
  156. t.written_to_file(file_desc)
  157. return txid
  158. def txsign_end(self, t, tnum=None, has_label=False):
  159. t.expect('Signing transaction')
  160. t.do_comment(False, has_label=has_label)
  161. t.expect(r'Save signed transaction.*?\? \(Y/n\): ', 'y', regex=True)
  162. t.written_to_file('Signed transaction' + (' #' + tnum if tnum else ''))
  163. return t
  164. def txsign(
  165. self,
  166. wf,
  167. txfile,
  168. save = True,
  169. has_label = False,
  170. extra_opts = [],
  171. extra_desc = '',
  172. view = 'n',
  173. dfl_wallet = False):
  174. opts = extra_opts + ['-d', self.tmpdir, txfile] + ([wf] if wf else [])
  175. wcls = get_wallet_cls(ext = 'mmdat' if dfl_wallet else get_extension(wf))
  176. t = self.spawn(
  177. 'mmgen-txsign',
  178. opts,
  179. extra_desc,
  180. no_passthru_opts = ['coin'],
  181. exit_val = None if save or (wcls.enc and wcls.type != 'brain') else 1)
  182. t.license()
  183. t.view_tx(view)
  184. if wcls.enc and wcls.type != 'brain':
  185. t.passphrase(wcls.desc, self.wpasswd)
  186. if save:
  187. self.txsign_end(t, has_label=has_label)
  188. else:
  189. t.do_comment(False, has_label=has_label)
  190. t.expect('Save signed transaction? (Y/n): ', 'n')
  191. t.expect('not saved')
  192. return t
  193. def ref_brain_chk(self, bw_file=ref_bw_file):
  194. wf = joinpath(ref_dir, bw_file)
  195. add_args = [f'-l{self.seed_len}', f'-p{ref_bw_hash_preset}']
  196. return self.walletchk(wf, add_args=add_args, sid=self.ref_bw_seed_id)
  197. def walletchk(
  198. self,
  199. wf,
  200. wcls = None,
  201. add_args = [],
  202. sid = None,
  203. extra_desc = '',
  204. dfl_wallet = False):
  205. hp = self.hash_preset if hasattr(self, 'hash_preset') else '1'
  206. wcls = wcls or get_wallet_cls(ext=get_extension(wf))
  207. t = self.spawn(
  208. 'mmgen-walletchk',
  209. ([] if dfl_wallet else ['-i', wcls.fmt_codes[0]])
  210. + self.testnet_opt
  211. + add_args + ['-p', hp]
  212. + ([wf] if wf else []),
  213. extra_desc = extra_desc,
  214. no_passthru_opts = True)
  215. if wcls.type != 'incog_hidden':
  216. t.expect(f"Getting {wcls.desc} from file ‘")
  217. if wcls.enc and wcls.type != 'brain':
  218. t.passphrase(wcls.desc, self.wpasswd)
  219. t.expect(['Passphrase is OK', 'Passphrase.* are correct'], regex=True)
  220. chksum = t.expect_getend(f'Valid {wcls.desc} for Seed ID ')[:8]
  221. if sid:
  222. cmp_or_die(chksum, sid)
  223. return t
  224. def addrgen(
  225. self,
  226. wf,
  227. check_ref = False,
  228. ftype = 'addr',
  229. id_str = None,
  230. extra_opts = [],
  231. mmtype = None,
  232. stdout = False,
  233. dfl_wallet = False,
  234. no_passthru_opts = False):
  235. list_type = ftype[:4]
  236. passgen = list_type == 'pass'
  237. if not mmtype and not passgen:
  238. mmtype = self.segwit_mmtype
  239. t = self.spawn(
  240. f'mmgen-{list_type}gen',
  241. ['-d', self.tmpdir] + extra_opts +
  242. ([], ['--type='+str(mmtype)])[bool(mmtype)] +
  243. ([], ['--stdout'])[stdout] +
  244. ([], [wf])[bool(wf)] +
  245. ([], [id_str])[bool(id_str)] +
  246. [getattr(self, f'{list_type}_idx_list')],
  247. extra_desc = f'({mmtype})' if mmtype in ('segwit', 'bech32') else '',
  248. no_passthru_opts = no_passthru_opts)
  249. t.license()
  250. wcls = get_wallet_cls(ext = 'mmdat' if dfl_wallet else get_extension(wf))
  251. t.passphrase(wcls.desc, self.wpasswd)
  252. t.expect('Passphrase is OK')
  253. desc = ('address', 'password')[passgen]
  254. chksum = strip_ansi_escapes(t.expect_getend(rf'Checksum for {desc} data .*?: ', regex=True))
  255. if check_ref:
  256. chksum_chk = (
  257. self.chk_data[self.test_name] if passgen else
  258. self.chk_data[self.test_name][self.fork][self.proto.testnet])
  259. cmp_or_die(chksum, chksum_chk, desc=f'{ftype}list data checksum')
  260. if passgen:
  261. t.expect('Encrypt password list? (y/N): ', 'N')
  262. if stdout:
  263. t.read()
  264. else:
  265. fn = t.written_to_file('Password list' if passgen else 'Addresses')
  266. cls = PasswordList if passgen else AddrList
  267. silence()
  268. al = cls(cfg, self.proto, infile=fn, skip_chksum_msg=True) # read back the file we’ve written
  269. end_silence()
  270. cmp_or_die(al.chksum, chksum, desc=f'{ftype}list data checksum from file')
  271. return t
  272. def keyaddrgen(self, wf, check_ref=False, extra_opts=[], mmtype=None):
  273. if not mmtype:
  274. mmtype = self.segwit_mmtype
  275. args = ['-d', self.tmpdir, self.usr_rand_arg, wf, self.addr_idx_list]
  276. t = self.spawn('mmgen-keygen',
  277. ([f'--type={mmtype}'] if mmtype else []) + extra_opts + args,
  278. extra_desc = f'({mmtype})' if mmtype in ('segwit', 'bech32') else '')
  279. t.license()
  280. wcls = get_wallet_cls(ext=get_extension(wf))
  281. t.passphrase(wcls.desc, self.wpasswd)
  282. chksum = t.expect_getend(r'Checksum for key-address data .*?: ', regex=True)
  283. if check_ref:
  284. chksum_chk = self.chk_data[self.test_name][self.fork][self.proto.testnet]
  285. cmp_or_die(chksum, chksum_chk, desc='key-address list data checksum')
  286. t.expect('Encrypt key list? (y/N): ', 'y')
  287. t.usr_rand(self.usr_rand_chars)
  288. t.hash_preset('new key-address list', '1')
  289. t.passphrase_new('new key-address list', self.kapasswd)
  290. t.written_to_file('Encrypted secret keys')
  291. return t
  292. def _do_confirm_send(self, t, quiet=False, confirm_send=True, sure=True):
  293. if sure:
  294. t.expect('Are you sure you want to broadcast this')
  295. m = ('YES, I REALLY WANT TO DO THIS', 'YES')[quiet]
  296. t.expect(f'{m!r} to confirm: ', ('', m)[confirm_send]+'\n')