xmr_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 port_shift kal_range add_coind_args
  34. user_data = (
  35. ('miner', '98831F3A', False, 130, '1', []),
  36. ('alice', 'FE3C6545', True, 150, '1-2', []))
  37. # autosign attrs:
  38. coins = ['xmr']
  39. cmd_group = (
  40. ('daemon_version', 'checking daemon version'),
  41. ('gen_kafile_miner', 'generating key-address file for Miner'),
  42. ('create_wallet_miner', 'creating Monero wallet for Miner'),
  43. ('mine_initial_coins', 'mining initial coins'),
  44. ('create_tmp_wallets', 'creating temporary online wallets for Alice'),
  45. ('new_account_alice', 'adding an account to Alice’s tmp wallet'),
  46. ('new_address_alice', 'adding an address to Alice’s tmp wallet'),
  47. ('new_address_alice_label', 'adding an address to Alice’s tmp wallet (with label)'),
  48. ('dump_tmp_wallets', 'dumping Alice’s tmp wallets'),
  49. ('delete_tmp_wallets', 'deleting Alice’s tmp wallets'),
  50. ('autosign_setup', 'autosign setup with Alice’s seed'),
  51. ('autosign_xmr_setup', 'autosign setup (creation of Monero signing wallets)'),
  52. ('create_watchonly_wallets', 'creating watch-only wallets from Alice’s wallet dumps'),
  53. ('delete_tmp_dump_files', 'deleting Alice’s dump files'),
  54. ('fund_alice1', 'sending funds to Alice (wallet #1)'),
  55. ('check_bal_alice1', 'mining, checking balance (wallet #1)'),
  56. ('fund_alice2', 'sending funds to Alice (wallet #2)'),
  57. ('check_bal_alice2', 'mining, checking balance (wallet #2)'),
  58. ('wait_loop_start', 'starting autosign wait loop'),
  59. ('export_outputs1', 'exporting outputs from Alice’s watch-only wallet #1'),
  60. ('create_transfer_tx1', 'creating a transfer TX'),
  61. ('submit_transfer_tx1', 'submitting the transfer TX'),
  62. ('resubmit_transfer_tx1', 'resubmitting the transfer TX'),
  63. ('export_outputs2', 'exporting outputs from Alice’s watch-only wallet #1'),
  64. ('import_key_images1', 'importing signed key images into Alice’s online wallets'),
  65. ('sync_chkbal1', 'syncing Alice’s wallet #1'),
  66. ('abort_tx1', 'aborting the current transaction (error)'),
  67. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  68. ('abort_tx2', 'aborting the current transaction (OK, unsigned)'),
  69. ('create_transfer_tx2a', 'creating the transfer TX again'),
  70. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  71. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  72. ('dump_wallets', 'dumping Alice’s wallets'),
  73. ('delete_wallets', 'deleting Alice’s wallets'),
  74. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  75. ('delete_dump_files', 'deleting Alice’s dump files'),
  76. ('export_outputs3', 'exporting outputs from Alice’s watch-only wallets'),
  77. ('import_key_images2', 'importing signed key images into Alice’s online wallets'),
  78. ('sync_chkbal3', 'syncing Alice’s wallets and checking balance'),
  79. ('wait_loop_kill', 'stopping autosign wait loop'),
  80. ('stop_daemons', 'stopping all wallet and coin daemons'),
  81. ('view', 'viewing Alice’s wallet in offline mode (wallet #1)'),
  82. ('listview', 'list-viewing Alice’s wallet in offline mode (wallet #2)'),
  83. ('txlist', 'listing Alice’s submitted transactions'),
  84. ('txview', 'viewing Alice’s submitted transactions'),
  85. ('txview_all', 'viewing all raw, signed and submitted transactions'),
  86. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  87. )
  88. def __init__(self, cfg, trunner, cfgs, spawn):
  89. CmdTestAutosignThreaded.__init__(self, cfg, trunner, cfgs, spawn)
  90. CmdTestXMRWallet.__init__(self, cfg, trunner, cfgs, spawn)
  91. if trunner is None:
  92. return
  93. from mmgen.cfg import Config
  94. self.alice_cfg = Config({
  95. 'coin': 'XMR',
  96. 'outdir': self.users['alice'].udir,
  97. 'wallet_dir': self.users['alice'].udir,
  98. 'wallet_rpc_password': 'passwOrd',
  99. 'test_suite': True,
  100. })
  101. self.burn_addr = make_burn_addr(cfg)
  102. self.opts.append('--xmrwallets={}'.format(self.users['alice'].kal_range)) # mmgen-autosign opts
  103. self.autosign_opts = ['--autosign'] # mmgen-xmrwallet opts
  104. self.spawn_env['MMGEN_TEST_SUITE_XMR_AUTOSIGN'] = '1'
  105. def create_tmp_wallets(self):
  106. self.spawn(msg_only=True)
  107. data = self.users['alice']
  108. from mmgen.wallet import Wallet
  109. from mmgen.xmrwallet import op
  110. from mmgen.addrlist import KeyAddrList
  111. silence()
  112. kal = KeyAddrList(
  113. cfg = self.alice_cfg,
  114. proto = self.proto,
  115. addr_idxs = '1-2',
  116. seed = Wallet(self.alice_cfg, fn=data.mmwords).seed,
  117. skip_chksum_msg = True,
  118. key_address_validity_check = False)
  119. kal.file.write(ask_overwrite=False)
  120. fn = get_file_with_ext(data.udir, 'akeys')
  121. m = op('create', self.alice_cfg, fn, '1-2')
  122. asyncio.run(m.main())
  123. asyncio.run(m.stop_wallet_daemon())
  124. end_silence()
  125. return 'ok'
  126. def _new_addr_alice(self, *args):
  127. data = self.users['alice']
  128. return self.new_addr_alice(
  129. *args,
  130. kafile = get_file_with_ext(data.udir, 'akeys'))
  131. def new_account_alice(self):
  132. return self._new_addr_alice(
  133. '2',
  134. 'start',
  135. r'Creating new account for wallet .*2.* with label .*‘xmrwallet new account .*y/N\): ')
  136. def new_address_alice(self):
  137. return self._new_addr_alice(
  138. '2:1',
  139. 'continue',
  140. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘xmrwallet new address .*y/N\): ')
  141. def new_address_alice_label(self):
  142. return self._new_addr_alice(
  143. '2:1,Alice’s new address',
  144. 'stop',
  145. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘Alice’s new address .*y/N\): ')
  146. def dump_tmp_wallets(self):
  147. return self._dump_wallets(autosign=False)
  148. def dump_wallets(self):
  149. return self._dump_wallets(autosign=True)
  150. def _dump_wallets(self, autosign):
  151. data = self.users['alice']
  152. self.insert_device_online()
  153. t = self.spawn(
  154. 'mmgen-xmrwallet',
  155. self.extra_opts
  156. + [f'--wallet-dir={data.udir}']
  157. + [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}']
  266. + [f'--daemon=localhost:{data.md.rpc_port}']
  267. + add_opts
  268. + [op]
  269. + ([get_file_with_ext(self.asi.xmr_tx_dir, ext)] if ext else [])
  270. + ([wallet_arg] if wallet_arg else []))
  271. desc_pfx = f'{desc}, ' if desc else ''
  272. self.insert_device_online() # device must be removed by calling method
  273. return self.spawn('mmgen-xmrwallet', args, extra_desc=f'({desc_pfx}Alice)')
  274. def _sync_chkbal(self, wallet_arg, bal_chk_func):
  275. return self.sync_wallets(
  276. 'alice',
  277. op = 'sync',
  278. wallets = wallet_arg,
  279. bal_chk_func = bal_chk_func)
  280. def sync_chkbal1(self):
  281. return self._sync_chkbal('1', lambda n, b, ub: b == ub and 1 < b < 1.12)
  282. # 1.234567891234 - 0.124 = 1.110567891234 (minus fees)
  283. def sync_chkbal2(self):
  284. return self._sync_chkbal('1', lambda n, b, ub: b == ub and 0.8 < b < 0.86)
  285. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  286. def sync_chkbal3(self):
  287. return self._sync_chkbal(
  288. '1-2',
  289. lambda n, b, ub: b == ub and ((n == 1 and 0.8 < b < 0.86) or (n == 2 and b > 1.23)))
  290. async def submit_transfer_tx1(self):
  291. return await self._submit_transfer_tx()
  292. async def resubmit_transfer_tx1(self):
  293. return await self._submit_transfer_tx(
  294. relay_parm = self.tx_relay_daemon_proxy_parm,
  295. op = 'resubmit',
  296. check_bal = False)
  297. async def submit_transfer_tx2(self):
  298. return await self._submit_transfer_tx(relay_parm=self.tx_relay_daemon_parm)
  299. async def _submit_transfer_tx(self, relay_parm=None, ext=None, op='submit', check_bal=True):
  300. t = self._xmr_autosign_op(
  301. op = op,
  302. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  303. ext = ext,
  304. signable_desc = 'transaction',
  305. wait_signed = op == 'submit')
  306. t.expect(f'{op.capitalize()} transaction? (y/N): ', 'y')
  307. t.written_to_file('Submitted transaction')
  308. t.read()
  309. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  310. if check_bal:
  311. t.ok()
  312. return await self.mine_chk(
  313. 'alice', 1, 0,
  314. lambda x: 0 < x.ub < 1.234567891234,
  315. 'unlocked balance 0 < 1.234567891234')
  316. else:
  317. return t
  318. def _export_outputs(self, wallet_arg, op, add_opts=[]):
  319. t = self._xmr_autosign_op(
  320. op = op,
  321. wallet_arg = wallet_arg,
  322. add_opts = add_opts)
  323. t.written_to_file('Wallet outputs')
  324. t.read()
  325. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  326. return t
  327. def export_outputs1(self):
  328. return self._export_outputs('1', op='export-outputs')
  329. def export_outputs2(self): # NB: --rescan-spent does not work with testnet/stagenet
  330. return self._export_outputs('1', op='export-outputs-sign', add_opts=['--rescan-blockchain'])
  331. def export_outputs3(self):
  332. return self._export_outputs('1-2', op='export-outputs-sign')
  333. def _import_key_images(self, wallet_arg):
  334. t = self._xmr_autosign_op(
  335. op = 'import-key-images',
  336. wallet_arg = wallet_arg,
  337. signable_desc = 'wallet outputs',
  338. wait_signed = True)
  339. t.read()
  340. self.remove_device_online() # device was inserted by _xmr_autosign_op()
  341. return t
  342. def import_key_images1(self):
  343. return self._import_key_images(None)
  344. def import_key_images2(self):
  345. return self._import_key_images(None)
  346. def txlist(self):
  347. self.insert_device_online()
  348. t = self.spawn('mmgen-xmrwallet', self.autosign_opts + ['txlist'])
  349. t.match_expect_list([
  350. 'SUBMITTED',
  351. 'Network', 'Submitted',
  352. 'transfer 1:0', '-> ext',
  353. 'transfer 1:0', '-> ext'
  354. ])
  355. t.read()
  356. self.remove_device_online()
  357. return t
  358. def txview(self):
  359. self.insert_device_online()
  360. t = self.spawn('mmgen-xmrwallet', self.autosign_opts + ['txview'])
  361. t.read()
  362. self.remove_device_online()
  363. return t
  364. def txview_all(self):
  365. self.spawn(msg_only=True)
  366. self.insert_device()
  367. self.do_mount()
  368. imsg(blue('Opening transaction directory: ') + cyan(f'{self.asi.xmr_tx_dir}'))
  369. for fn in self.asi.xmr_tx_dir.iterdir():
  370. imsg('\n' + brown(f'Viewing ‘{fn.name}’'))
  371. self.spawn('mmgen-xmrwallet', ['txview', str(fn)], no_msg=True).read()
  372. imsg('')
  373. self.do_umount()
  374. self.remove_device()
  375. return 'ok'
  376. def check_tx_dirs(self):
  377. self.insert_device()
  378. self.do_mount()
  379. before = '\n'.join(self._gen_listing())
  380. self.do_umount()
  381. self.remove_device()
  382. self.insert_device()
  383. t = self.spawn('mmgen-autosign', self.opts + ['clean'])
  384. t.read()
  385. self.remove_device()
  386. self.insert_device()
  387. self.do_mount()
  388. after = '\n'.join(self._gen_listing())
  389. self.do_umount()
  390. self.remove_device()
  391. imsg(f'\nBefore cleaning:\n{before}')
  392. imsg(f'\nAfter cleaning:\n{after}')
  393. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  394. assert re.search(pat, after, re.DOTALL), f'regex search for {pat} failed'
  395. return t
  396. def view(self):
  397. return self.sync_wallets('alice', op='view', wallets='1')
  398. def listview(self):
  399. return self.sync_wallets('alice', op='listview', wallets='2')