ts_xmr_autosign.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2023 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
  9. # https://gitlab.com/mmgen/mmgen
  10. """
  11. test.test_py_d.ts_xmr_autosign: xmr autosigning tests for the test.py test suite
  12. """
  13. from .ts_xmrwallet import *
  14. from pathlib import Path
  15. from .ts_autosign import TestSuiteAutosignBase
  16. def make_burn_addr():
  17. from mmgen.tool.coin import tool_cmd
  18. return tool_cmd(
  19. cfg = cfg,
  20. cmdname = 'privhex2addr',
  21. proto = cfg._proto,
  22. mmtype = 'monero' ).privhex2addr('beadcafe'*8)
  23. class TestSuiteXMRAutosign(TestSuiteXMRWallet,TestSuiteAutosignBase):
  24. """
  25. Monero autosigning operations
  26. """
  27. tmpdir_nums = [39]
  28. # ts_xmrwallet attrs:
  29. user_data = (
  30. ('miner', '98831F3A', False, 130, '1', []),
  31. ('alice', 'FE3C6545', True, 150, '1-2', []),
  32. )
  33. # ts_autosign attrs:
  34. coins = ['xmr']
  35. daemon_coins = []
  36. txfile_coins = []
  37. live = False
  38. simulate = False
  39. bad_tx_count = 0
  40. tx_relay_user = 'miner'
  41. cmd_group = (
  42. ('daemon_version', 'checking daemon version'),
  43. ('create_tmp_wallets', 'creating temporary online wallets for Alice'),
  44. ('new_account_alice', 'adding an account to Alice’s tmp wallet'),
  45. ('new_address_alice', 'adding an address to Alice’s tmp wallet'),
  46. ('new_address_alice_label', 'adding an address to Alice’s tmp wallet (with label)'),
  47. ('dump_tmp_wallets', 'dumping Alice’s tmp wallets'),
  48. ('delete_tmp_wallets', 'deleting Alice’s tmp wallets'),
  49. ('clean', 'cleaning signable file directories'),
  50. ('autosign_setup', 'autosign setup with Alice’s seed'),
  51. ('create_watchonly_wallets', 'creating online (watch-only) wallets for Alice'),
  52. ('delete_tmp_dump_files', 'deleting Alice’s dump files'),
  53. ('gen_kafiles', 'generating key-address files for Miner'),
  54. ('create_wallets_miner', 'creating Monero wallets for Miner'),
  55. ('mine_initial_coins', 'mining initial coins'),
  56. ('fund_alice', 'sending funds to Alice'),
  57. ('create_transfer_tx1', 'creating a transfer TX'),
  58. ('sign_transfer_tx1', 'signing the transfer TX'),
  59. ('submit_transfer_tx1', 'submitting the transfer TX'),
  60. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  61. ('sign_transfer_tx2', 'signing the transfer TX (for relaying via proxy)'),
  62. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  63. ('sync_chkbal1', 'syncing Alice’s wallets and checking balance'),
  64. ('dump_wallets', 'dumping Alice’s wallets'),
  65. ('delete_wallets', 'deleting Alice’s wallets'),
  66. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  67. ('delete_dump_files', 'deleting Alice’s dump files'),
  68. ('export_outputs', 'exporting outputs from Alice’s watch-only wallets'),
  69. ('export_key_images', 'exporting signed key images from Alice’s offline wallets'),
  70. ('import_key_images', 'importing signed key images into Alice’s online wallets'),
  71. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  72. ('txlist', 'listing Alice’s submitted transactions'),
  73. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  74. )
  75. def __init__(self,trunner,cfgs,spawn):
  76. TestSuiteXMRWallet.__init__(self,trunner,cfgs,spawn)
  77. TestSuiteAutosignBase.__init__(self,trunner,cfgs,spawn)
  78. if trunner == None:
  79. return
  80. from mmgen.cfg import Config
  81. self.cfg = Config({
  82. 'coin': 'XMR',
  83. 'outdir': self.users['alice'].udir,
  84. 'wallet_dir': self.users['alice'].udir,
  85. 'wallet_rpc_password': 'passwOrd',
  86. })
  87. self.burn_addr = make_burn_addr()
  88. self.opts.append('--xmrwallets={}'.format( self.users['alice'].kal_range )) # mmgen-autosign opts
  89. self.autosign_opts = [f'--autosign-mountpoint={self.mountpoint}'] # mmgen-xmrwallet opts
  90. self.tx_count = 1
  91. def create_tmp_wallets(self):
  92. self.spawn('',msg_only=True)
  93. data = self.users['alice']
  94. from mmgen.wallet import Wallet
  95. from mmgen.xmrwallet import MoneroWalletOps,xmrwallet_uargs
  96. silence()
  97. kal = KeyAddrList(
  98. cfg = self.cfg,
  99. proto = self.proto,
  100. addr_idxs = '1-2',
  101. seed = Wallet(cfg,data.mmwords).seed )
  102. kal.file.write(ask_overwrite=False)
  103. fn = get_file_with_ext(data.udir,'akeys')
  104. m = MoneroWalletOps.create(
  105. self.cfg,
  106. xmrwallet_uargs(fn, '1-2', None))
  107. async_run(m.main())
  108. async_run(m.stop_wallet_daemon())
  109. end_silence()
  110. return 'ok'
  111. def _new_addr_alice(self,*args):
  112. data = self.users['alice']
  113. return self.new_addr_alice(
  114. *args,
  115. kafile = get_file_with_ext(data.udir,'akeys') )
  116. def new_account_alice(self):
  117. return self._new_addr_alice(
  118. '2',
  119. 'start',
  120. fr'Creating new account.*Index:\s+{self.na_idx}\s')
  121. def new_address_alice(self):
  122. return self._new_addr_alice(
  123. '2:1',
  124. 'continue',
  125. fr'Account index:\s+1\s+Creating new address' )
  126. def new_address_alice_label(self):
  127. return self._new_addr_alice(
  128. '2:1,Alice’s new address',
  129. 'stop',
  130. fr'Account index:\s+1\s+Creating new address.*Alice’s new address' )
  131. def dump_tmp_wallets(self):
  132. return self._dump_wallets(autosign=False)
  133. def dump_wallets(self):
  134. return self._dump_wallets(autosign=True)
  135. def _dump_wallets(self,autosign):
  136. data = self.users['alice']
  137. t = self.spawn(
  138. 'mmgen-xmrwallet',
  139. self.extra_opts
  140. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  141. + (self.autosign_opts if autosign else [])
  142. + ['dump']
  143. + ([] if autosign else [get_file_with_ext(data.udir,'akeys')]) )
  144. t.expect('2 wallets dumped')
  145. return t
  146. def _delete_files(self,*ext_list):
  147. data = self.users['alice']
  148. self.spawn('',msg_only=True)
  149. for ext in ext_list:
  150. get_file_with_ext(data.udir,ext,no_dot=True,delete_all=True)
  151. return 'ok'
  152. def delete_tmp_wallets(self):
  153. return self._delete_files( 'MoneroWallet', 'MoneroWallet.keys', '.akeys' )
  154. def delete_wallets(self):
  155. return self._delete_files( 'MoneroWatchOnlyWallet', '.keys', '.address.txt' )
  156. def delete_tmp_dump_files(self):
  157. return self._delete_files( '.dump' )
  158. def delete_dump_files(self):
  159. return self._delete_files( '.dump' )
  160. def autosign_setup(self):
  161. Path(self.autosign_xmr_dir).mkdir(parents=True,exist_ok=True)
  162. Path(self.autosign_xmr_dir,'old.vkeys').touch()
  163. t = self.run_setup(
  164. mn_type = 'mmgen',
  165. mn_file = self.users['alice'].mmwords,
  166. use_dfl_wallet = None )
  167. t.expect('Continue with Monero setup? (Y/n): ','y')
  168. t.written_to_file('View keys')
  169. return t
  170. def create_watchonly_wallets(self):
  171. return self.create_wallets( 'alice', op='restore' )
  172. def restore_wallets(self):
  173. return self.create_wallets( 'alice', op='restore' )
  174. def _create_transfer_tx(self,amt):
  175. return self.do_op('transfer','alice',f'1:0:{self.burn_addr},{amt}',no_relay=True,do_ret=True)
  176. def create_transfer_tx1(self):
  177. return self._create_transfer_tx('0.124')
  178. def create_transfer_tx2(self):
  179. get_file_with_ext(self.asi.xmr_tx_dir,'rawtx',delete_all=True)
  180. get_file_with_ext(self.asi.xmr_tx_dir,'sigtx',delete_all=True)
  181. return self._create_transfer_tx('0.257')
  182. def _sign_transfer_tx(self):
  183. return self.do_sign(['--full-summary'],tx_name='Monero transaction')
  184. def sign_transfer_tx1(self):
  185. return self._sign_transfer_tx()
  186. def sign_transfer_tx2(self):
  187. return self._sign_transfer_tx()
  188. def _xmr_autosign_op(self,op,desc,dtype=None,ext=None,wallet_arg=None,add_opts=[]):
  189. data = self.users['alice']
  190. args = (
  191. self.extra_opts
  192. + self.autosign_opts
  193. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  194. + add_opts
  195. + [ op ]
  196. + ([get_file_with_ext(self.asi.xmr_tx_dir,ext)] if ext else [])
  197. + ([wallet_arg] if wallet_arg else [])
  198. )
  199. t = self.spawn( 'mmgen-xmrwallet', args, extra_desc=f'({desc}, Alice)' )
  200. if dtype:
  201. t.written_to_file(dtype.capitalize())
  202. return t
  203. def _sync_chkbal(self,bal_chk_func):
  204. return self.sync_wallets(
  205. 'alice',
  206. op = 'sync',
  207. wallets = '1',
  208. bal_chk_func = bal_chk_func )
  209. def sync_chkbal1(self):
  210. return self._sync_chkbal( lambda n,b,ub: b == ub and 0.8 < b < 0.86 )
  211. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  212. sync_chkbal2 = sync_chkbal1
  213. def _mine_chk(self,desc):
  214. bal_type = {'locked':'b','unlocked':'ub'}[desc]
  215. return self.mine_chk(
  216. 'alice', 1, 0,
  217. lambda x: 0 < getattr(x,bal_type) < 1.234567891234,
  218. f'{desc} balance 0 < 1.234567891234' )
  219. def submit_transfer_tx1(self):
  220. return self._submit_transfer_tx( ext='sigtx' )
  221. def submit_transfer_tx2(self):
  222. return self._submit_transfer_tx( relay_parm=self.tx_relay_daemon_parm )
  223. def _submit_transfer_tx(self,relay_parm=None,ext=None,op='submit',check_bal=True):
  224. data = self.users['alice']
  225. t = self._xmr_autosign_op(
  226. op = op,
  227. desc = 'submitting TX',
  228. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  229. ext = ext )
  230. t.expect( f'{op.capitalize()} transaction? (y/N): ', 'y' )
  231. t.written_to_file('Submitted transaction')
  232. if check_bal:
  233. t.ok()
  234. return self._mine_chk('unlocked')
  235. else:
  236. return t
  237. def _export_outputs(self,wallet_arg,add_opts=[]):
  238. return self._xmr_autosign_op(
  239. op = 'export-outputs',
  240. desc = 'exporting outputs',
  241. dtype = 'wallet outputs',
  242. wallet_arg = wallet_arg,
  243. add_opts = add_opts )
  244. def export_outputs(self):
  245. return self._export_outputs('1-2')
  246. def _export_key_images(self,tx_count):
  247. self.tx_count = tx_count
  248. return self.do_sign(['--full-summary'],tx_name='Monero wallet outputs file')
  249. def export_key_images(self):
  250. return self._export_key_images(2)
  251. def _import_key_images(self,wallet_arg):
  252. return self._xmr_autosign_op(
  253. op = 'import-key-images',
  254. desc = 'importing key images',
  255. wallet_arg = wallet_arg )
  256. def import_key_images(self):
  257. return self._import_key_images(None)
  258. def create_fake_tx_files(self):
  259. imsg('Creating fake transaction files')
  260. self.asi.msg_dir.mkdir(exist_ok=True)
  261. self.asi.xmr_dir.mkdir(exist_ok=True)
  262. self.asi.xmr_tx_dir.mkdir(exist_ok=True)
  263. self.asi.xmr_outputs_dir.mkdir(exist_ok=True)
  264. for fn in (
  265. 'a.rawtx', 'a.sigtx',
  266. 'b.rawtx', 'b.sigtx',
  267. 'c.rawtx',
  268. 'd.sigtx',
  269. ):
  270. (self.asi.tx_dir / fn).touch()
  271. for fn in (
  272. 'a.rawmsg.json', 'a.sigmsg.json',
  273. 'b.rawmsg.json',
  274. 'c.sigmsg.json',
  275. 'd.rawmsg.json', 'd.sigmsg.json',
  276. ):
  277. (self.asi.msg_dir / fn).touch()
  278. for fn in (
  279. 'a.rawtx', 'a.sigtx', 'a.subtx',
  280. 'b.rawtx', 'b.sigtx',
  281. 'c.subtx',
  282. 'd.rawtx', 'd.subtx',
  283. 'e.rawtx',
  284. 'f.sigtx','f.subtx',
  285. ):
  286. (self.asi.xmr_tx_dir / fn).touch()
  287. for fn in (
  288. 'a.raw', 'a.sig',
  289. 'b.raw',
  290. 'c.sig',
  291. ):
  292. (self.asi.xmr_outputs_dir / fn).touch()
  293. return 'ok'
  294. def _gen_listing(self):
  295. for k in ('tx_dir','msg_dir','xmr_tx_dir','xmr_outputs_dir'):
  296. d = getattr(self.asi,k)
  297. if d.is_dir():
  298. yield '{:12} {}'.format(
  299. str(Path(*d.parts[4:])) + ':',
  300. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  301. def clean(self):
  302. self.create_fake_tx_files()
  303. before = '\n'.join(self._gen_listing())
  304. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  305. out = t.read()
  306. after = '\n'.join(self._gen_listing())
  307. chk = """
  308. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  309. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  310. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  311. xmr/outputs:
  312. """
  313. shutil.rmtree(self.asi.mountpoint)
  314. self.asi.tx_dir.mkdir(parents=True)
  315. imsg(f'\nBefore cleaning:\n{before}')
  316. imsg(f'\nAfter cleaning:\n{after}')
  317. assert '13 files shredded' in out
  318. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  319. return t
  320. def txlist(self):
  321. t = self.spawn( 'mmgen-xmrwallet', self.autosign_opts + ['txlist'] )
  322. t.match_expect_list([
  323. 'SUBMITTED',
  324. 'Network','Submitted',
  325. 'Transfer 1:0','-> ext',
  326. 'Transfer 1:0','-> ext'
  327. ])
  328. return t
  329. def check_tx_dirs(self):
  330. before = '\n'.join(self._gen_listing())
  331. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  332. t.read()
  333. after = '\n'.join(self._gen_listing())
  334. imsg(f'\nBefore cleaning:\n{before}')
  335. imsg(f'\nAfter cleaning:\n{after}')
  336. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  337. assert re.search( pat, after, re.DOTALL ), f'regex search for {pat} failed'
  338. return t