xmr_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. test.cmdtest_d.xmr_autosign: xmr autosigning tests for the cmdtest.py test suite
  12. """
  13. import re, asyncio
  14. from mmgen.color import blue, cyan, brown
  15. from ..include.common import imsg, silence, end_silence
  16. from .include.common import get_file_with_ext
  17. from .xmrwallet import CmdTestXMRWallet
  18. from .autosign import CmdTestAutosignThreaded
  19. def make_burn_addr(cfg):
  20. from mmgen.tool.coin import tool_cmd
  21. return tool_cmd(
  22. cfg = cfg,
  23. cmdname = 'privhex2addr',
  24. proto = cfg._proto,
  25. mmtype = 'monero').privhex2addr('beadcafe'*8)
  26. class CmdTestXMRAutosign(CmdTestXMRWallet, CmdTestAutosignThreaded):
  27. """
  28. Monero autosigning operations
  29. """
  30. tmpdir_nums = [39]
  31. # xmrwallet attrs:
  32. tx_relay_user = 'miner'
  33. # user sid autosign shift kal_range add_coind_args
  34. user_data = (
  35. ('miner', '98831F3A', False, 130, '1', []),
  36. ('alice', 'FE3C6545', True, 150, '1-2', []),
  37. )
  38. # autosign attrs:
  39. coins = ['xmr']
  40. cmd_group = (
  41. ('daemon_version', 'checking daemon version'),
  42. ('gen_kafile_miner', 'generating key-address file for Miner'),
  43. ('create_wallet_miner', 'creating Monero wallet for Miner'),
  44. ('mine_initial_coins', 'mining initial coins'),
  45. ('create_tmp_wallets', 'creating temporary online wallets for Alice'),
  46. ('new_account_alice', 'adding an account to Alice’s tmp wallet'),
  47. ('new_address_alice', 'adding an address to Alice’s tmp wallet'),
  48. ('new_address_alice_label', 'adding an address to Alice’s tmp wallet (with label)'),
  49. ('dump_tmp_wallets', 'dumping Alice’s tmp wallets'),
  50. ('delete_tmp_wallets', 'deleting Alice’s tmp wallets'),
  51. ('autosign_setup', 'autosign setup with Alice’s seed'),
  52. ('autosign_xmr_setup', 'autosign setup (creation of Monero signing wallets)'),
  53. ('create_watchonly_wallets', 'creating watch-only wallets from Alice’s wallet dumps'),
  54. ('delete_tmp_dump_files', 'deleting Alice’s dump files'),
  55. ('fund_alice1', 'sending funds to Alice (wallet #1)'),
  56. ('check_bal_alice1', 'mining, checking balance (wallet #1)'),
  57. ('fund_alice2', 'sending funds to Alice (wallet #2)'),
  58. ('check_bal_alice2', 'mining, checking balance (wallet #2)'),
  59. ('wait_loop_start', 'starting autosign wait loop'),
  60. ('export_outputs1', 'exporting outputs from Alice’s watch-only wallet #1'),
  61. ('create_transfer_tx1', 'creating a transfer TX'),
  62. ('submit_transfer_tx1', 'submitting the transfer TX'),
  63. ('resubmit_transfer_tx1', 'resubmitting the transfer TX'),
  64. ('export_outputs2', 'exporting outputs from Alice’s watch-only wallet #1'),
  65. ('import_key_images1', 'importing signed key images into Alice’s online wallets'),
  66. ('sync_chkbal1', 'syncing Alice’s wallet #1'),
  67. ('abort_tx1', 'aborting the current transaction (error)'),
  68. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  69. ('abort_tx2', 'aborting the current transaction (OK, unsigned)'),
  70. ('create_transfer_tx2a', 'creating the transfer TX again'),
  71. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  72. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  73. ('dump_wallets', 'dumping Alice’s wallets'),
  74. ('delete_wallets', 'deleting Alice’s wallets'),
  75. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  76. ('delete_dump_files', 'deleting Alice’s dump files'),
  77. ('export_outputs3', 'exporting outputs from Alice’s watch-only wallets'),
  78. ('import_key_images2', 'importing signed key images into Alice’s online wallets'),
  79. ('sync_chkbal3', 'syncing Alice’s wallets and checking balance'),
  80. ('wait_loop_kill', 'stopping autosign wait loop'),
  81. ('stop_daemons', 'stopping all wallet and coin daemons'),
  82. ('view', 'viewing Alice’s wallet in offline mode (wallet #1)'),
  83. ('listview', 'list-viewing Alice’s wallet in offline mode (wallet #2)'),
  84. ('txlist', 'listing Alice’s submitted transactions'),
  85. ('txview', 'viewing Alice’s submitted transactions'),
  86. ('txview_all', 'viewing all raw, signed and submitted transactions'),
  87. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  88. )
  89. def __init__(self, cfg, trunner, cfgs, spawn):
  90. CmdTestAutosignThreaded.__init__(self, cfg, trunner, cfgs, spawn)
  91. CmdTestXMRWallet.__init__(self, cfg, trunner, cfgs, spawn)
  92. if trunner is None:
  93. return
  94. from mmgen.cfg import Config
  95. self.alice_cfg = Config({
  96. 'coin': 'XMR',
  97. 'outdir': self.users['alice'].udir,
  98. 'wallet_dir': self.users['alice'].udir,
  99. 'wallet_rpc_password': 'passwOrd',
  100. 'test_suite': True,
  101. })
  102. self.burn_addr = make_burn_addr(cfg)
  103. self.opts.append('--xmrwallets={}'.format(self.users['alice'].kal_range)) # mmgen-autosign opts
  104. self.autosign_opts = ['--autosign'] # mmgen-xmrwallet opts
  105. self.spawn_env['MMGEN_TEST_SUITE_XMR_AUTOSIGN'] = '1'
  106. def create_tmp_wallets(self):
  107. self.spawn(msg_only=True)
  108. data = self.users['alice']
  109. from mmgen.wallet import Wallet
  110. from mmgen.xmrwallet import op
  111. from mmgen.addrlist import KeyAddrList
  112. silence()
  113. kal = KeyAddrList(
  114. cfg = self.alice_cfg,
  115. proto = self.proto,
  116. addr_idxs = '1-2',
  117. seed = Wallet(self.alice_cfg, fn=data.mmwords).seed,
  118. skip_chksum_msg = True,
  119. key_address_validity_check = False)
  120. kal.file.write(ask_overwrite=False)
  121. fn = get_file_with_ext(data.udir, 'akeys')
  122. m = op('create', self.alice_cfg, fn, '1-2')
  123. asyncio.run(m.main())
  124. asyncio.run(m.stop_wallet_daemon())
  125. end_silence()
  126. return 'ok'
  127. def _new_addr_alice(self, *args):
  128. data = self.users['alice']
  129. return self.new_addr_alice(
  130. *args,
  131. kafile = get_file_with_ext(data.udir, 'akeys'))
  132. def new_account_alice(self):
  133. return self._new_addr_alice(
  134. '2',
  135. 'start',
  136. r'Creating new account for wallet .*2.* with label .*‘xmrwallet new account .*y/N\): ')
  137. def new_address_alice(self):
  138. return self._new_addr_alice(
  139. '2:1',
  140. 'continue',
  141. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘xmrwallet new address .*y/N\): ')
  142. def new_address_alice_label(self):
  143. return self._new_addr_alice(
  144. '2:1,Alice’s new address',
  145. 'stop',
  146. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘Alice’s new address .*y/N\): ')
  147. def dump_tmp_wallets(self):
  148. return self._dump_wallets(autosign=False)
  149. def dump_wallets(self):
  150. return self._dump_wallets(autosign=True)
  151. def _dump_wallets(self, autosign):
  152. data = self.users['alice']
  153. self.insert_device_online()
  154. t = self.spawn(
  155. 'mmgen-xmrwallet',
  156. self.extra_opts
  157. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  158. + (self.autosign_opts if autosign else [])
  159. + ['dump']
  160. + ([] if autosign else [get_file_with_ext(data.udir, 'akeys')]))
  161. t.expect('2 wallets dumped')
  162. t.read()
  163. self.remove_device_online()
  164. return t
  165. def _delete_files(self, *ext_list):
  166. data = self.users['alice']
  167. self.spawn(msg_only=True)
  168. for ext in ext_list:
  169. get_file_with_ext(data.udir, ext, no_dot=True, delete_all=True)
  170. return 'ok'
  171. def delete_tmp_wallets(self):
  172. return self._delete_files('MoneroWallet', 'MoneroWallet.keys', '.akeys')
  173. def delete_wallets(self):
  174. return self._delete_files('MoneroWatchOnlyWallet', '.keys', '.address.txt')
  175. def delete_tmp_dump_files(self):
  176. return self._delete_files('.dump')
  177. def gen_kafile_miner(self):
  178. return self.gen_kafiles(['miner'])
  179. def create_wallet_miner(self):
  180. return self.create_wallets_miner()
  181. def delete_dump_files(self):
  182. return self._delete_files('.dump')
  183. async def fund_alice1(self):
  184. return await self.fund_alice(wallet=1)
  185. async def check_bal_alice1(self):
  186. return await self.check_bal_alice(wallet=1)
  187. async def fund_alice2(self):
  188. return await self.fund_alice(wallet=2)
  189. async def check_bal_alice2(self):
  190. return await self.check_bal_alice(wallet=2)
  191. def autosign_setup(self):
  192. return self.run_setup(
  193. mn_type = 'mmgen',
  194. mn_file = self.users['alice'].mmwords,
  195. use_dfl_wallet = None,
  196. expect_args = ['Continue with Monero setup? (Y/n): ', 'n'])
  197. def autosign_xmr_setup(self):
  198. self.insert_device_online()
  199. self.do_mount_online()
  200. self.asi_online.xmr_dir.mkdir(exist_ok=True)
  201. (self.asi_online.xmr_dir / 'old.vkeys').touch()
  202. self.do_umount_online()
  203. self.remove_device_online()
  204. self.insert_device()
  205. t = self.spawn('mmgen-autosign', self.opts + ['xmr_setup'], no_passthru_opts=True)
  206. t.written_to_file('View keys')
  207. t.read()
  208. self.remove_device()
  209. return t
  210. def create_watchonly_wallets(self):
  211. return self._create_wallets('restore')
  212. def restore_wallets(self):
  213. return self._create_wallets('restore')
  214. def _create_wallets(self, op='create'):
  215. self.insert_device_online()
  216. t = self.create_wallets('alice', op=op)
  217. t.read() # required!
  218. self.remove_device_online()
  219. return t
  220. def _create_transfer_tx(self, amt, add_opts=[]):
  221. self.insert_device_online()
  222. t = self.do_op(
  223. 'transfer',
  224. 'alice',
  225. f'1:0:{self.burn_addr},{amt}',
  226. no_relay = True,
  227. do_ret = True,
  228. add_opts = add_opts)
  229. t.read() # required!
  230. self.remove_device_online()
  231. return t
  232. def create_transfer_tx1(self):
  233. return self._create_transfer_tx('0.124', add_opts=['--priority=2'])
  234. def create_transfer_tx2(self):
  235. return self._create_transfer_tx('0.257')
  236. create_transfer_tx2a = create_transfer_tx2
  237. def _abort_tx(self, expect, send=None, exit_val=None):
  238. self.insert_device_online()
  239. t = self.spawn('mmgen-xmrwallet', ['--autosign', 'abort'], exit_val=exit_val)
  240. t.expect(expect)
  241. if send:
  242. t.send(send)
  243. t.read() # required!
  244. self.remove_device_online()
  245. return t
  246. def abort_tx1(self):
  247. return self._abort_tx('No unsent transactions present', exit_val=2)
  248. def abort_tx2(self):
  249. return self._abort_tx('(y/N): ', 'y')
  250. def _xmr_autosign_op(
  251. self,
  252. op,
  253. desc = None,
  254. signable_desc = None,
  255. ext = None,
  256. wallet_arg = None,
  257. add_opts = [],
  258. wait_signed = False):
  259. if wait_signed:
  260. self._wait_signed(signable_desc)
  261. data = self.users['alice']
  262. args = (
  263. self.extra_opts
  264. + self.autosign_opts
  265. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  266. + add_opts
  267. + [op]
  268. + ([get_file_with_ext(self.asi.xmr_tx_dir, ext)] if ext else [])
  269. + ([wallet_arg] if wallet_arg else []))
  270. desc_pfx = f'{desc}, ' if desc else ''
  271. self.insert_device_online() # device must be removed by calling method
  272. return self.spawn('mmgen-xmrwallet', args, extra_desc=f'({desc_pfx}Alice)')
  273. def _sync_chkbal(self, wallet_arg, bal_chk_func):
  274. return self.sync_wallets(
  275. 'alice',
  276. op = 'sync',
  277. wallets = wallet_arg,
  278. bal_chk_func = bal_chk_func)
  279. def sync_chkbal1(self):
  280. return self._sync_chkbal('1', lambda n, b, ub: b == ub and 1 < b < 1.12)
  281. # 1.234567891234 - 0.124 = 1.110567891234 (minus fees)
  282. def sync_chkbal2(self):
  283. return self._sync_chkbal('1', lambda n, b, ub: b == ub and 0.8 < b < 0.86)
  284. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  285. def sync_chkbal3(self):
  286. return self._sync_chkbal(
  287. '1-2',
  288. lambda n, b, ub: b == ub and ((n == 1 and 0.8 < b < 0.86) or (n == 2 and b > 1.23)))
  289. async def submit_transfer_tx1(self):
  290. return await self._submit_transfer_tx()
  291. async def resubmit_transfer_tx1(self):
  292. return await self._submit_transfer_tx(
  293. relay_parm = self.tx_relay_daemon_proxy_parm,
  294. op = 'resubmit',
  295. check_bal = False)
  296. async def submit_transfer_tx2(self):
  297. return await self._submit_transfer_tx(relay_parm=self.tx_relay_daemon_parm)
  298. async def _submit_transfer_tx(self, relay_parm=None, ext=None, op='submit', check_bal=True):
  299. t = self._xmr_autosign_op(
  300. op = op,
  301. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  302. ext = ext,
  303. signable_desc = 'transaction',
  304. wait_signed = op == 'submit')
  305. t.expect(f'{op.capitalize()} transaction? (y/N): ', 'y')
  306. t.written_to_file('Submitted transaction')
  307. t.read()
  308. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  309. if check_bal:
  310. t.ok()
  311. return await self.mine_chk(
  312. 'alice', 1, 0,
  313. lambda x: 0 < x.ub < 1.234567891234,
  314. 'unlocked balance 0 < 1.234567891234')
  315. else:
  316. return t
  317. def _export_outputs(self, wallet_arg, op, add_opts=[]):
  318. t = self._xmr_autosign_op(
  319. op = op,
  320. wallet_arg = wallet_arg,
  321. add_opts = add_opts)
  322. t.written_to_file('Wallet outputs')
  323. t.read()
  324. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  325. return t
  326. def export_outputs1(self):
  327. return self._export_outputs('1', op='export-outputs')
  328. def export_outputs2(self): # NB: --rescan-spent does not work with testnet/stagenet
  329. return self._export_outputs('1', op='export-outputs-sign', add_opts=['--rescan-blockchain'])
  330. def export_outputs3(self):
  331. return self._export_outputs('1-2', op='export-outputs-sign')
  332. def _import_key_images(self, wallet_arg):
  333. t = self._xmr_autosign_op(
  334. op = 'import-key-images',
  335. wallet_arg = wallet_arg,
  336. signable_desc = 'wallet outputs',
  337. wait_signed = True)
  338. t.read()
  339. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  340. return t
  341. def import_key_images1(self):
  342. return self._import_key_images(None)
  343. def import_key_images2(self):
  344. return self._import_key_images(None)
  345. def txlist(self):
  346. self.insert_device_online()
  347. t = self.spawn('mmgen-xmrwallet', self.autosign_opts + ['txlist'])
  348. t.match_expect_list([
  349. 'SUBMITTED',
  350. 'Network', 'Submitted',
  351. 'transfer 1:0', '-> ext',
  352. 'transfer 1:0', '-> ext'
  353. ])
  354. t.read()
  355. self.remove_device_online()
  356. return t
  357. def txview(self):
  358. self.insert_device_online()
  359. t = self.spawn('mmgen-xmrwallet', self.autosign_opts + ['txview'])
  360. t.read()
  361. self.remove_device_online()
  362. return t
  363. def txview_all(self):
  364. self.spawn(msg_only=True)
  365. self.insert_device()
  366. self.do_mount()
  367. imsg(blue('Opening transaction directory: ') + cyan(f'{self.asi.xmr_tx_dir}'))
  368. for fn in self.asi.xmr_tx_dir.iterdir():
  369. imsg('\n' + brown(f'Viewing ‘{fn.name}’'))
  370. self.spawn('mmgen-xmrwallet', ['txview', str(fn)], no_msg=True).read()
  371. imsg('')
  372. self.do_umount()
  373. self.remove_device()
  374. return 'ok'
  375. def check_tx_dirs(self):
  376. self.insert_device()
  377. self.do_mount()
  378. before = '\n'.join(self._gen_listing())
  379. self.do_umount()
  380. self.remove_device()
  381. self.insert_device()
  382. t = self.spawn('mmgen-autosign', self.opts + ['clean'])
  383. t.read()
  384. self.remove_device()
  385. self.insert_device()
  386. self.do_mount()
  387. after = '\n'.join(self._gen_listing())
  388. self.do_umount()
  389. self.remove_device()
  390. imsg(f'\nBefore cleaning:\n{before}')
  391. imsg(f'\nAfter cleaning:\n{after}')
  392. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  393. assert re.search(pat, after, re.DOTALL), f'regex search for {pat} failed'
  394. return t
  395. def view(self):
  396. return self.sync_wallets('alice', op='view', wallets='1')
  397. def listview(self):
  398. return self.sync_wallets('alice', op='listview', wallets='2')