ct_xmr_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2024 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_py_d.ct_xmr_autosign: xmr autosigning tests for the cmdtest.py test suite
  12. """
  13. import os,time,re,shutil
  14. from pathlib import Path
  15. from mmgen.color import yellow,purple,gray
  16. from mmgen.util import fmt,async_run
  17. from ..include.common import (
  18. cfg,
  19. oqmsg,
  20. oqmsg_r,
  21. imsg,
  22. silence,
  23. end_silence
  24. )
  25. from .common import get_file_with_ext
  26. from .ct_xmrwallet import CmdTestXMRWallet
  27. from .ct_autosign import CmdTestAutosignBase
  28. def make_burn_addr():
  29. from mmgen.tool.coin import tool_cmd
  30. return tool_cmd(
  31. cfg = cfg,
  32. cmdname = 'privhex2addr',
  33. proto = cfg._proto,
  34. mmtype = 'monero' ).privhex2addr('beadcafe'*8)
  35. class CmdTestXMRAutosign(CmdTestXMRWallet,CmdTestAutosignBase):
  36. """
  37. Monero autosigning operations
  38. """
  39. tmpdir_nums = [39]
  40. # ct_xmrwallet attrs:
  41. user_data = (
  42. ('miner', '98831F3A', False, 130, '1', []),
  43. ('alice', 'FE3C6545', True, 150, '1-2', []),
  44. )
  45. # ct_autosign attrs:
  46. coins = ['xmr']
  47. daemon_coins = []
  48. txfile_coins = []
  49. live = False
  50. simulate = False
  51. bad_tx_count = 0
  52. tx_relay_user = 'miner'
  53. no_insert_check = False
  54. win_skip = True
  55. cmd_group = (
  56. ('daemon_version', 'checking daemon version'),
  57. ('create_tmp_wallets', 'creating temporary online wallets for Alice'),
  58. ('new_account_alice', 'adding an account to Alice’s tmp wallet'),
  59. ('new_address_alice', 'adding an address to Alice’s tmp wallet'),
  60. ('new_address_alice_label', 'adding an address to Alice’s tmp wallet (with label)'),
  61. ('dump_tmp_wallets', 'dumping Alice’s tmp wallets'),
  62. ('delete_tmp_wallets', 'deleting Alice’s tmp wallets'),
  63. ('autosign_clean', 'cleaning signable file directories'),
  64. ('autosign_setup', 'autosign setup with Alice’s seed'),
  65. ('create_watchonly_wallets', 'creating online (watch-only) wallets for Alice'),
  66. ('delete_tmp_dump_files', 'deleting Alice’s dump files'),
  67. ('gen_kafiles', 'generating key-address files for Miner'),
  68. ('create_wallets_miner', 'creating Monero wallets for Miner'),
  69. ('mine_initial_coins', 'mining initial coins'),
  70. ('fund_alice1', 'sending funds to Alice (wallet #1)'),
  71. ('fund_alice2', 'sending funds to Alice (wallet #2)'),
  72. ('autosign_start_thread', 'starting autosign wait loop'),
  73. ('create_transfer_tx1', 'creating a transfer TX'),
  74. ('submit_transfer_tx1', 'submitting the transfer TX'),
  75. ('resubmit_transfer_tx1', 'resubmitting the transfer TX'),
  76. ('export_outputs1', 'exporting outputs from Alice’s watch-only wallet #1'),
  77. ('import_key_images1', 'importing signed key images into Alice’s online wallets'),
  78. ('sync_chkbal1', 'syncing Alice’s wallet #1'),
  79. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  80. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  81. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  82. ('dump_wallets', 'dumping Alice’s wallets'),
  83. ('delete_wallets', 'deleting Alice’s wallets'),
  84. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  85. ('delete_dump_files', 'deleting Alice’s dump files'),
  86. ('export_outputs2', 'exporting outputs from Alice’s watch-only wallets'),
  87. ('import_key_images2', 'importing signed key images into Alice’s online wallets'),
  88. ('sync_chkbal3', 'syncing Alice’s wallets and checking balance'),
  89. ('txlist', 'listing Alice’s submitted transactions'),
  90. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  91. ('autosign_kill_thread', 'stopping autosign wait loop'),
  92. ('stop_daemons', 'stopping all wallet and coin daemons'),
  93. )
  94. def __init__(self,trunner,cfgs,spawn):
  95. CmdTestXMRWallet.__init__(self,trunner,cfgs,spawn)
  96. CmdTestAutosignBase.__init__(self,trunner,cfgs,spawn)
  97. if trunner is None:
  98. return
  99. from mmgen.cfg import Config
  100. self.cfg = Config({
  101. 'coin': 'XMR',
  102. 'outdir': self.users['alice'].udir,
  103. 'wallet_dir': self.users['alice'].udir,
  104. 'wallet_rpc_password': 'passwOrd',
  105. 'test_suite': True,
  106. })
  107. self.burn_addr = make_burn_addr()
  108. self.opts.append('--xmrwallets={}'.format( self.users['alice'].kal_range )) # mmgen-autosign opts
  109. self.autosign_opts = [f'--autosign-mountpoint={self.mountpoint}'] # mmgen-xmrwallet opts
  110. self.tx_count = 1
  111. self.spawn_env['MMGEN_TEST_SUITE_XMR_AUTOSIGN'] = '1'
  112. def create_tmp_wallets(self):
  113. self.spawn('',msg_only=True)
  114. data = self.users['alice']
  115. from mmgen.wallet import Wallet
  116. from mmgen.xmrwallet import MoneroWalletOps,xmrwallet_uargs
  117. from mmgen.addrlist import KeyAddrList
  118. silence()
  119. kal = KeyAddrList(
  120. cfg = self.cfg,
  121. proto = self.proto,
  122. addr_idxs = '1-2',
  123. seed = Wallet(cfg,data.mmwords).seed,
  124. skip_chksum_msg = True,
  125. key_address_validity_check = False )
  126. kal.file.write(ask_overwrite=False)
  127. fn = get_file_with_ext(data.udir,'akeys')
  128. m = MoneroWalletOps.create(
  129. self.cfg,
  130. xmrwallet_uargs(fn, '1-2', None))
  131. async_run(m.main())
  132. async_run(m.stop_wallet_daemon())
  133. end_silence()
  134. return 'ok'
  135. def _new_addr_alice(self,*args):
  136. data = self.users['alice']
  137. return self.new_addr_alice(
  138. *args,
  139. kafile = get_file_with_ext(data.udir,'akeys') )
  140. def new_account_alice(self):
  141. return self._new_addr_alice(
  142. '2',
  143. 'start',
  144. fr'Creating new account.*Index:\s+{self.na_idx}\s')
  145. def new_address_alice(self):
  146. return self._new_addr_alice(
  147. '2:1',
  148. 'continue',
  149. r'Account index:\s+1\s+Creating new address' )
  150. def new_address_alice_label(self):
  151. return self._new_addr_alice(
  152. '2:1,Alice’s new address',
  153. 'stop',
  154. r'Account index:\s+1\s+Creating new address.*Alice’s new address' )
  155. def dump_tmp_wallets(self):
  156. return self._dump_wallets(autosign=False)
  157. def dump_wallets(self):
  158. return self._dump_wallets(autosign=True)
  159. def _dump_wallets(self,autosign):
  160. data = self.users['alice']
  161. t = self.spawn(
  162. 'mmgen-xmrwallet',
  163. self.extra_opts
  164. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  165. + (self.autosign_opts if autosign else [])
  166. + ['dump']
  167. + ([] if autosign else [get_file_with_ext(data.udir,'akeys')]) )
  168. t.expect('2 wallets dumped')
  169. return t
  170. def _delete_files(self,*ext_list):
  171. data = self.users['alice']
  172. self.spawn('',msg_only=True)
  173. for ext in ext_list:
  174. get_file_with_ext(data.udir,ext,no_dot=True,delete_all=True)
  175. return 'ok'
  176. def delete_tmp_wallets(self):
  177. return self._delete_files( 'MoneroWallet', 'MoneroWallet.keys', '.akeys' )
  178. def delete_wallets(self):
  179. return self._delete_files( 'MoneroWatchOnlyWallet', '.keys', '.address.txt' )
  180. def delete_tmp_dump_files(self):
  181. return self._delete_files( '.dump' )
  182. def delete_dump_files(self):
  183. return self._delete_files( '.dump' )
  184. def fund_alice1(self):
  185. return self.fund_alice(wallet=1,check_bal=False)
  186. def fund_alice2(self):
  187. return self.fund_alice(wallet=2)
  188. def insert_device(self):
  189. self.asi.dev_disk_path.touch()
  190. def autosign_setup(self):
  191. self.insert_device()
  192. Path(self.autosign_xmr_dir).mkdir(parents=True,exist_ok=True)
  193. Path(self.autosign_xmr_dir,'old.vkeys').touch()
  194. t = self.run_setup(
  195. mn_type = 'mmgen',
  196. mn_file = self.users['alice'].mmwords,
  197. use_dfl_wallet = None )
  198. t.expect('Continue with Monero setup? (Y/n): ','y')
  199. t.written_to_file('View keys')
  200. return t
  201. def autosign_start_thread(self):
  202. if self.asi.dev_disk_path.exists():
  203. self.asi.dev_disk_path.unlink()
  204. def run():
  205. t = self.spawn('mmgen-autosign', self.opts + ['wait'], direct_exec=True )
  206. self.write_to_tmpfile('autosign_thread_pid',str(t.ep.pid))
  207. import threading
  208. threading.Thread( target=run, name='Autosign wait loop' ).start()
  209. time.sleep(0.2)
  210. return 'silent'
  211. def autosign_kill_thread(self):
  212. self.spawn('',msg_only=True)
  213. pid = int(self.read_from_tmpfile('autosign_thread_pid'))
  214. self.delete_tmpfile('autosign_thread_pid')
  215. from signal import SIGTERM
  216. imsg(purple(f'Killing autosign wait loop [PID {pid}]'))
  217. try:
  218. os.kill(pid,SIGTERM)
  219. except:
  220. imsg(yellow(f'{pid}: no such process'))
  221. return 'ok'
  222. def create_watchonly_wallets(self):
  223. return self.create_wallets( 'alice', op='restore' )
  224. def restore_wallets(self):
  225. return self.create_wallets( 'alice', op='restore' )
  226. def _create_transfer_tx(self,amt):
  227. t = self.do_op('transfer','alice',f'1:0:{self.burn_addr},{amt}',no_relay=True,do_ret=True)
  228. t.read() # required!
  229. self.insert_device()
  230. return t
  231. def create_transfer_tx1(self):
  232. return self._create_transfer_tx('0.124')
  233. def create_transfer_tx2(self):
  234. get_file_with_ext(self.asi.xmr_tx_dir,'rawtx',delete_all=True)
  235. get_file_with_ext(self.asi.xmr_tx_dir,'sigtx',delete_all=True)
  236. return self._create_transfer_tx('0.257')
  237. def _xmr_autosign_op(
  238. self,
  239. op,
  240. desc = None,
  241. dtype = None,
  242. ext = None,
  243. wallet_arg = None,
  244. add_opts = [],
  245. wait_signed = False):
  246. if wait_signed:
  247. oqmsg_r(gray(f'→ offline wallet{"s" if dtype.endswith("s") else ""} signing {dtype}'))
  248. while True:
  249. oqmsg_r(gray('.'))
  250. if not self.asi.dev_disk_path.exists():
  251. break
  252. time.sleep(0.5)
  253. oqmsg(gray('done'))
  254. data = self.users['alice']
  255. args = (
  256. self.extra_opts
  257. + self.autosign_opts
  258. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  259. + add_opts
  260. + [ op ]
  261. + ([get_file_with_ext(self.asi.xmr_tx_dir,ext)] if ext else [])
  262. + ([wallet_arg] if wallet_arg else [])
  263. )
  264. desc_pfx = f'{desc}, ' if desc else ''
  265. return self.spawn( 'mmgen-xmrwallet', args, extra_desc=f'({desc_pfx}Alice)' )
  266. def _sync_chkbal(self,wallet_arg,bal_chk_func):
  267. return self.sync_wallets(
  268. 'alice',
  269. op = 'sync',
  270. wallets = wallet_arg,
  271. bal_chk_func = bal_chk_func )
  272. def sync_chkbal1(self):
  273. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 1 < b < 1.12 )
  274. # 1.234567891234 - 0.124 = 1.110567891234 (minus fees)
  275. def sync_chkbal2(self):
  276. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 0.8 < b < 0.86 )
  277. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  278. def sync_chkbal3(self):
  279. return self._sync_chkbal(
  280. '1-2',
  281. lambda n,b,ub: b == ub and ((n == 1 and 0.8 < b < 0.86) or (n == 2 and b > 1.23)) )
  282. def _mine_chk(self,desc):
  283. bal_type = {'locked':'b','unlocked':'ub'}[desc]
  284. return self.mine_chk(
  285. 'alice', 1, 0,
  286. lambda x: 0 < getattr(x,bal_type) < 1.234567891234,
  287. f'{desc} balance 0 < 1.234567891234' )
  288. def submit_transfer_tx1(self):
  289. return self._submit_transfer_tx( ext='sigtx' )
  290. def resubmit_transfer_tx1(self):
  291. return self._submit_transfer_tx(
  292. relay_parm = self.tx_relay_daemon_proxy_parm,
  293. op = 'resubmit',
  294. check_bal = False)
  295. def submit_transfer_tx2(self):
  296. return self._submit_transfer_tx( relay_parm=self.tx_relay_daemon_parm )
  297. def _submit_transfer_tx(self,relay_parm=None,ext=None,op='submit',check_bal=True):
  298. t = self._xmr_autosign_op(
  299. op = op,
  300. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  301. ext = ext,
  302. dtype = 'transaction',
  303. wait_signed = op == 'submit' )
  304. t.expect( f'{op.capitalize()} transaction? (y/N): ', 'y' )
  305. t.written_to_file('Submitted transaction')
  306. if check_bal:
  307. t.ok()
  308. return self._mine_chk('unlocked')
  309. else:
  310. return t
  311. def _export_outputs(self,wallet_arg,add_opts=[]):
  312. t = self._xmr_autosign_op(
  313. op = 'export-outputs',
  314. wallet_arg = wallet_arg,
  315. add_opts = add_opts )
  316. t.written_to_file('Wallet outputs')
  317. t.read() # required!
  318. self.insert_device()
  319. return t
  320. def export_outputs1(self):
  321. return self._export_outputs('1',['--rescan-blockchain'])
  322. def export_outputs2(self):
  323. return self._export_outputs('1-2')
  324. def _import_key_images(self,wallet_arg):
  325. return self._xmr_autosign_op(
  326. op = 'import-key-images',
  327. wallet_arg = wallet_arg,
  328. dtype = 'wallet outputs',
  329. wait_signed = True )
  330. def import_key_images1(self):
  331. return self._import_key_images(None)
  332. def import_key_images2(self):
  333. return self._import_key_images(None)
  334. def create_fake_tx_files(self):
  335. imsg('Creating fake transaction files')
  336. self.asi.msg_dir.mkdir(exist_ok=True)
  337. self.asi.xmr_dir.mkdir(exist_ok=True)
  338. self.asi.xmr_tx_dir.mkdir(exist_ok=True)
  339. self.asi.xmr_outputs_dir.mkdir(exist_ok=True)
  340. for fn in (
  341. 'a.rawtx', 'a.sigtx',
  342. 'b.rawtx', 'b.sigtx',
  343. 'c.rawtx',
  344. 'd.sigtx',
  345. ):
  346. (self.asi.tx_dir / fn).touch()
  347. for fn in (
  348. 'a.rawmsg.json', 'a.sigmsg.json',
  349. 'b.rawmsg.json',
  350. 'c.sigmsg.json',
  351. 'd.rawmsg.json', 'd.sigmsg.json',
  352. ):
  353. (self.asi.msg_dir / fn).touch()
  354. for fn in (
  355. 'a.rawtx', 'a.sigtx', 'a.subtx',
  356. 'b.rawtx', 'b.sigtx',
  357. 'c.subtx',
  358. 'd.rawtx', 'd.subtx',
  359. 'e.rawtx',
  360. 'f.sigtx','f.subtx',
  361. ):
  362. (self.asi.xmr_tx_dir / fn).touch()
  363. for fn in (
  364. 'a.raw', 'a.sig',
  365. 'b.raw',
  366. 'c.sig',
  367. ):
  368. (self.asi.xmr_outputs_dir / fn).touch()
  369. return 'ok'
  370. def _gen_listing(self):
  371. for k in ('tx_dir','msg_dir','xmr_tx_dir','xmr_outputs_dir'):
  372. d = getattr(self.asi,k)
  373. if d.is_dir():
  374. yield '{:12} {}'.format(
  375. str(Path(*d.parts[4:])) + ':',
  376. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  377. def autosign_clean(self):
  378. self.create_fake_tx_files()
  379. before = '\n'.join(self._gen_listing())
  380. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  381. out = t.read()
  382. after = '\n'.join(self._gen_listing())
  383. chk = """
  384. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  385. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  386. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  387. xmr/outputs:
  388. """
  389. shutil.rmtree(self.asi.mountpoint)
  390. self.asi.tx_dir.mkdir(parents=True)
  391. imsg(f'\nBefore cleaning:\n{before}')
  392. imsg(f'\nAfter cleaning:\n{after}')
  393. assert '13 files shredded' in out
  394. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  395. return t
  396. def txlist(self):
  397. t = self.spawn( 'mmgen-xmrwallet', self.autosign_opts + ['txlist'] )
  398. t.match_expect_list([
  399. 'SUBMITTED',
  400. 'Network','Submitted',
  401. 'Transfer 1:0','-> ext',
  402. 'Transfer 1:0','-> ext'
  403. ])
  404. return t
  405. def check_tx_dirs(self):
  406. before = '\n'.join(self._gen_listing())
  407. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  408. t.read()
  409. after = '\n'.join(self._gen_listing())
  410. imsg(f'\nBefore cleaning:\n{before}')
  411. imsg(f'\nAfter cleaning:\n{after}')
  412. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  413. assert re.search( pat, after, re.DOTALL ), f'regex search for {pat} failed'
  414. return t