ts_xmrwallet.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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.test_py_d.ts_xmrwallet: xmrwallet tests for the test.py test suite
  20. """
  21. import sys,os,atexit,asyncio,shutil
  22. from subprocess import run,PIPE
  23. from mmgen.cfg import gc
  24. from mmgen.obj import MMGenRange
  25. from mmgen.amt import XMRAmt
  26. from mmgen.addrlist import KeyAddrList,AddrIdxList
  27. from ..include.common import *
  28. from .common import *
  29. from .ts_base import *
  30. class TestSuiteXMRWallet(TestSuiteBase):
  31. """
  32. Monero wallet operations
  33. """
  34. networks = ('xmr',)
  35. passthru_opts = ()
  36. tmpdir_nums = [29]
  37. dfl_random_txs = 3
  38. color = True
  39. socks_port = 49237
  40. cmd_group = (
  41. ('daemon_version', 'checking daemon version'),
  42. ('gen_kafiles', 'generating key-address files'),
  43. ('create_wallets_miner', 'creating Monero wallets (Miner)'),
  44. ('set_label_miner', 'setting an address label (Miner, primary account)'),
  45. ('mine_initial_coins', 'mining initial coins'),
  46. ('create_wallets_alice', 'creating Monero wallets (Alice)'),
  47. ('fund_alice', 'sending funds'),
  48. ('sync_wallets_all', 'syncing all wallets'),
  49. ('new_account_alice', 'creating a new account (Alice)'),
  50. ('new_account_alice_label', 'creating a new account (Alice, with label)'),
  51. ('new_address_alice', 'creating a new address (Alice)'),
  52. ('new_address_alice_label', 'creating a new address (Alice, with label)'),
  53. ('remove_label_alice', 'removing an address label (Alice, subaddress)'),
  54. ('set_label_alice', 'setting an address label (Alice, subaddress)'),
  55. ('sync_wallets_selected', 'syncing selected wallets'),
  56. ('sweep_to_address_proxy', 'sweeping to new address (via TX relay + proxy)'),
  57. ('sweep_to_account', 'sweeping to new account'),
  58. ('sweep_to_address_noproxy', 'sweeping to new address (via TX relay, no proxy)'),
  59. ('transfer_to_miner_proxy', 'transferring funds to Miner (via TX relay + proxy)'),
  60. ('transfer_to_miner_noproxy', 'transferring funds to Miner (via TX relay, no proxy)'),
  61. ('transfer_to_miner_create1', 'transferring funds to Miner (create TX)'),
  62. ('transfer_to_miner_send1', 'transferring funds to Miner (send TX via proxy)'),
  63. ('transfer_to_miner_create2', 'transferring funds to Miner (create TX)'),
  64. ('transfer_to_miner_send2', 'transferring funds to Miner (send TX, no proxy)'),
  65. ('sweep_create_and_send', 'sweeping to new account (create TX + send TX, in stages)'),
  66. ('list_wallets_all', 'listing wallets'),
  67. )
  68. def __init__(self,trunner,cfgs,spawn):
  69. TestSuiteBase.__init__(self,trunner,cfgs,spawn)
  70. if trunner == None:
  71. return
  72. from mmgen.protocol import init_proto
  73. self.proto = init_proto( cfg, 'XMR', network='mainnet' )
  74. self.datadir_base = os.path.join('test','daemons','xmrtest')
  75. self.extra_opts = ['--wallet-rpc-password=passw0rd']
  76. self.init_users()
  77. self.init_daemon_args()
  78. for v in self.users.values():
  79. run(['mkdir','-p',v.udir])
  80. self.init_proxy()
  81. self.tx_relay_daemon_parm = 'localhost:{}'.format( self.users['bob'].md.rpc_port )
  82. self.tx_relay_daemon_proxy_parm = (
  83. self.tx_relay_daemon_parm + f':127.0.0.1:{self.socks_port}' ) # must be IP, not 'localhost'
  84. if not cfg.no_daemon_stop:
  85. atexit.register(self.stop_daemons)
  86. atexit.register(self.stop_miner_wallet_daemon)
  87. if not cfg.no_daemon_autostart:
  88. self.stop_daemons()
  89. shutil.rmtree(self.datadir_base,ignore_errors=True)
  90. os.makedirs(self.datadir_base)
  91. self.start_daemons()
  92. self.balance = None
  93. # init methods
  94. @classmethod
  95. def init_proxy(cls,external_call=False):
  96. def port_in_use(port):
  97. import socket
  98. try: socket.create_connection(('localhost',port)).close()
  99. except: return False
  100. else: return True
  101. def start_proxy():
  102. if external_call or not cfg.no_daemon_autostart:
  103. run(a+b2)
  104. omsg(f'SSH SOCKS server started, listening at localhost:{cls.socks_port}')
  105. def kill_proxy():
  106. if gc.platform == 'linux':
  107. omsg(f'Killing SSH SOCKS server at localhost:{cls.socks_port}')
  108. cmd = [ 'pkill', '-f', ' '.join(a + b2) ]
  109. run(cmd)
  110. a = ['ssh','-x','-o','ExitOnForwardFailure=True','-D',f'localhost:{cls.socks_port}']
  111. b0 = ['-o','PasswordAuthentication=False']
  112. b1 = ['localhost','true']
  113. b2 = ['-fN','-E','txrelay-proxy.debug','localhost']
  114. if port_in_use(cls.socks_port):
  115. omsg(f'Port {cls.socks_port} already in use. Assuming SSH SOCKS server is running')
  116. else:
  117. cp = run(a+b0+b1,stdout=PIPE,stderr=PIPE)
  118. err = cp.stderr.decode()
  119. if err:
  120. omsg(err)
  121. if cp.returncode == 0:
  122. start_proxy()
  123. elif 'onnection refused' in err:
  124. die(2,fmt("""
  125. The SSH daemon must be running and listening on localhost in order to test
  126. XMR TX relaying via SOCKS proxy. If sshd is not running, please start it.
  127. Otherwise, add the line 'ListenAddress 127.0.0.1' to your sshd_config, and
  128. then restart the daemon.
  129. """,indent=' '))
  130. elif 'ermission denied' in err:
  131. msg(fmt(f"""
  132. In order to test XMR TX relaying via SOCKS proxy, it’s desirable to enable
  133. SSH to localhost without a password, which is not currently supported by
  134. your configuration. Your possible courses of action:
  135. 1. Continue by answering 'y' at this prompt, and enter your system password
  136. at the following prompt;
  137. 2. Exit the test here, add your user SSH public key to your user
  138. 'authorized_keys' file, and restart the test; or
  139. 3. Exit the test here, start the SSH SOCKS proxy manually by entering the
  140. following command, and restart the test:
  141. {' '.join(a+b2)}
  142. """,indent=' ',strip_char='\t'))
  143. from mmgen.ui import keypress_confirm
  144. if keypress_confirm(cfg,'Continue?'):
  145. start_proxy()
  146. else:
  147. die(1,'Exiting at user request')
  148. else:
  149. die(2,fmt(f"""
  150. Please start the SSH SOCKS proxy by entering the following command:
  151. {' '.join(a+b2)}
  152. Then restart the test.
  153. """,indent=' '))
  154. if not (external_call or cfg.no_daemon_stop):
  155. atexit.register(kill_proxy)
  156. return True
  157. def init_users(self):
  158. from mmgen.daemon import CoinDaemon
  159. from mmgen.proto.xmr.daemon import MoneroWalletDaemon
  160. from mmgen.proto.xmr.rpc import MoneroRPCClient,MoneroWalletRPCClient
  161. self.users = {}
  162. n = self.tmpdir_nums[0]
  163. ud = namedtuple('user_data',[
  164. 'sid',
  165. 'mmwords',
  166. 'udir',
  167. 'datadir',
  168. 'kal_range',
  169. 'kafile',
  170. 'walletfile_fs',
  171. 'addrfile_fs',
  172. 'md',
  173. 'md_rpc',
  174. 'wd',
  175. 'wd_rpc',
  176. 'add_coind_args',
  177. ])
  178. # kal_range must be None, a single digit, or a single hyphenated range
  179. for user,sid,shift,kal_range,add_coind_args in (
  180. ('miner', '98831F3A', 130, '1-2', []),
  181. ('bob', '1378FC64', 140, None, ['--restricted-rpc']),
  182. ('alice', 'FE3C6545', 150, '1-4', []),
  183. ):
  184. udir = os.path.join('test','tmp',str(n),user)
  185. datadir = os.path.join(self.datadir_base,user)
  186. md = CoinDaemon(
  187. cfg = cfg,
  188. proto = self.proto,
  189. test_suite = True,
  190. port_shift = shift,
  191. opts = ['online'],
  192. datadir = datadir
  193. )
  194. md_rpc = MoneroRPCClient(
  195. cfg = cfg,
  196. proto = self.proto,
  197. host = md.host,
  198. port = md.rpc_port,
  199. user = None,
  200. passwd = None,
  201. test_connection = False,
  202. daemon = md,
  203. )
  204. wd = MoneroWalletDaemon(
  205. cfg = cfg,
  206. proto = self.proto,
  207. test_suite = True,
  208. wallet_dir = udir,
  209. user = 'foo',
  210. passwd = 'bar',
  211. port_shift = shift,
  212. datadir = os.path.join('test','daemons'),
  213. daemon_addr = f'127.0.0.1:{md.rpc_port}',
  214. )
  215. wd_rpc = MoneroWalletRPCClient(
  216. cfg = cfg,
  217. daemon = wd,
  218. test_connection = False,
  219. )
  220. self.users[user] = ud(
  221. sid = sid,
  222. mmwords = f'test/ref/{sid}.mmwords',
  223. udir = udir,
  224. datadir = datadir,
  225. kal_range = kal_range,
  226. kafile = f'{udir}/{sid}-XMR-M[{kal_range}].akeys',
  227. walletfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet',
  228. addrfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet.address.txt',
  229. md = md,
  230. md_rpc = md_rpc,
  231. wd = wd,
  232. wd_rpc = wd_rpc,
  233. add_coind_args = add_coind_args,
  234. )
  235. def init_daemon_args(self):
  236. common_args = ['--p2p-bind-ip=127.0.0.1','--fixed-difficulty=1','--regtest'] # ,'--rpc-ssl-allow-any-cert']
  237. for u in self.users:
  238. other_ports = [self.users[u2].md.p2p_port for u2 in self.users if u2 != u]
  239. node_args = [f'--add-exclusive-node=127.0.0.1:{p}' for p in other_ports]
  240. self.users[u].md.usr_coind_args = (
  241. common_args +
  242. node_args +
  243. self.users[u].add_coind_args )
  244. # cmd_group methods
  245. def daemon_version(self):
  246. rpc_port = self.users['miner'].md.rpc_port
  247. return self.spawn( 'mmgen-tool', ['--coin=xmr', f'--rpc-port={rpc_port}', 'daemon_version'] )
  248. def gen_kafiles(self):
  249. for user,data in self.users.items():
  250. if not data.kal_range:
  251. continue
  252. run(['mkdir','-p',data.udir])
  253. run(f'rm -f {data.kafile}',shell=True)
  254. t = self.spawn(
  255. 'mmgen-keygen', [
  256. '-q', '--accept-defaults', '--coin=xmr',
  257. f'--outdir={data.udir}', data.mmwords, data.kal_range
  258. ],
  259. extra_desc = f'({capfirst(user)})' )
  260. t.read()
  261. t.ok()
  262. t.skip_ok = True
  263. return t
  264. def create_wallets_miner(self): return self.create_wallets('miner')
  265. def create_wallets_alice(self): return self.create_wallets('alice')
  266. def create_wallets(self,user,wallet=None):
  267. assert wallet is None or is_int(wallet), 'wallet arg'
  268. data = self.users[user]
  269. run(
  270. 'rm -f {}*'.format( data.walletfile_fs.format(wallet or '*') ),
  271. shell = True
  272. )
  273. dir_opt = [f'--wallet-dir={data.udir}']
  274. t = self.spawn(
  275. 'mmgen-xmrwallet',
  276. self.extra_opts + dir_opt + [ 'create', data.kafile, (wallet or data.kal_range) ] )
  277. for i in MMGenRange(wallet or data.kal_range).items:
  278. write_data_to_file(
  279. cfg,
  280. self.users[user].addrfile_fs.format(i),
  281. t.expect_getend('Address: '),
  282. quiet = True
  283. )
  284. return t
  285. def new_addr_alice(self,spec,cfg,expect):
  286. data = self.users['alice']
  287. t = self.spawn(
  288. 'mmgen-xmrwallet',
  289. self.extra_opts +
  290. [f'--wallet-dir={data.udir}'] +
  291. [f'--daemon=localhost:{data.md.rpc_port}'] +
  292. (['--no-start-wallet-daemon'] if cfg in ('continue','stop') else []) +
  293. (['--no-stop-wallet-daemon'] if cfg in ('start','continue') else []) +
  294. [ 'new', data.kafile, spec ] )
  295. res = strip_ansi_escapes(t.read()).replace('\r','')
  296. m = re.search(expect,res,re.DOTALL)
  297. assert m, m
  298. return t
  299. na_idx = 1
  300. def new_account_alice(self):
  301. return self.new_addr_alice(
  302. '4',
  303. 'start',
  304. fr'Creating new account.*Index:\s+{self.na_idx}\s')
  305. def new_account_alice_label(self):
  306. return self.new_addr_alice(
  307. '4,Alice’s new account',
  308. 'continue',
  309. fr'Creating new account.*Index:\s+{self.na_idx+1}\s.*Alice’s new account')
  310. def new_address_alice(self):
  311. return self.new_addr_alice(
  312. '4:2',
  313. 'continue',
  314. fr'Account index:\s+2\s+Creating new address' )
  315. def new_address_alice_label(self):
  316. return self.new_addr_alice(
  317. '4:2,Alice’s new address',
  318. 'stop',
  319. fr'Account index:\s+2\s+Creating new address.*Alice’s new address' )
  320. async def mine_initial_coins(self):
  321. await self.open_wallet_user('miner',1)
  322. return await self.mine_chk('miner',1,0,lambda x: x > 20,'unlocked balance > 20')
  323. async def fund_alice(self):
  324. await self.transfer(
  325. 'miner',
  326. 1234567891234,
  327. read_from_file(self.users['alice'].addrfile_fs.format(1)),
  328. )
  329. bal = '1.234567891234'
  330. return await self.mine_chk(
  331. 'alice',1,0,
  332. lambda x: str(x) == bal,f'unlocked balance == {bal}',
  333. random_txs = self.dfl_random_txs
  334. )
  335. def set_label_miner(self):
  336. return self.set_label_user( 'miner', '1:0:0,"Miner’s new primary account label [1:0:0]"' )
  337. def remove_label_alice(self):
  338. return self.set_label_user( 'alice', '4:2:2,""' )
  339. def set_label_alice(self):
  340. return self.set_label_user( 'alice', '4:2:2,"Alice’s new subaddress label [4:2:2]"' )
  341. def set_label_user(self,user,label_spec):
  342. data = self.users[user]
  343. cmd_opts = [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  344. t = self.spawn(
  345. 'mmgen-xmrwallet',
  346. self.extra_opts + cmd_opts + ['label', data.kafile, label_spec]
  347. )
  348. t.expect('(y/N): ','y')
  349. t.expect(['successfully set','successfully removed'])
  350. return t
  351. def sync_wallets_all(self):
  352. return self.sync_wallets('alice',add_opts=['--rescan-blockchain'])
  353. def sync_wallets_selected(self):
  354. return self.sync_wallets('alice',wallets='1-2,4')
  355. def list_wallets_all(self):
  356. return self.sync_wallets('alice',op='list')
  357. def sync_wallets(self,user,op='sync',wallets=None,add_opts=None):
  358. data = self.users[user]
  359. cmd_opts = list_gen(
  360. [f'--wallet-dir={data.udir}'],
  361. [f'--daemon=localhost:{data.md.rpc_port}'],
  362. )
  363. t = self.spawn(
  364. 'mmgen-xmrwallet',
  365. self.extra_opts + cmd_opts + (add_opts or []) + [ op, data.kafile ] + ([wallets] if wallets else []) )
  366. wlist = AddrIdxList(wallets) if wallets else MMGenRange(data.kal_range).items
  367. for n,wnum in enumerate(wlist):
  368. t.expect('Syncing wallet {}/{} ({})'.format(
  369. n+1,
  370. len(wlist),
  371. os.path.basename(data.walletfile_fs.format(wnum)),
  372. ))
  373. t.expect('Chain height: ')
  374. t.expect('Wallet height: ')
  375. t.expect('Balance: ')
  376. return t
  377. def do_op(self, op, user, arg2,
  378. tx_relay_parm = None,
  379. no_relay = False,
  380. return_amt = False,
  381. reuse_acct = False,
  382. add_desc = None,
  383. do_ret = False ):
  384. data = self.users[user]
  385. cmd_opts = list_gen(
  386. [f'--wallet-dir={data.udir}'],
  387. [f'--outdir={data.udir}'],
  388. [f'--daemon=localhost:{data.md.rpc_port}'],
  389. [f'--tx-relay-daemon={tx_relay_parm}', tx_relay_parm],
  390. ['--no-relay', no_relay]
  391. )
  392. add_desc = (', ' + add_desc) if add_desc else ''
  393. t = self.spawn(
  394. 'mmgen-xmrwallet',
  395. self.extra_opts + cmd_opts + [ op, data.kafile, arg2 ],
  396. extra_desc = f'({capfirst(user)}{add_desc})' )
  397. if op == 'sweep':
  398. t.expect(
  399. r'Create new {} .* \(y/N\): '.format(('address','account')[',' in arg2]),
  400. ('y','n')[reuse_acct],
  401. regex=True )
  402. if reuse_acct:
  403. t.expect( r'to last existing account .* \(y/N\): ','y', regex=True )
  404. if return_amt:
  405. amt = XMRAmt(strip_ansi_escapes(t.expect_getend('Amount: ')).replace('XMR','').strip())
  406. t.expect('Save MoneroMMGenTX data? (y/N): ','y')
  407. t.written_to_file('MoneroMMGenTX data')
  408. if not no_relay:
  409. t.expect(f'Relay {op} transaction? (y/N): ','y')
  410. get_file_with_ext(self.users[user].udir,'sigtx',delete_all=True)
  411. t.read()
  412. return t if do_ret else amt if return_amt else t.ok()
  413. def sweep_to_address_proxy(self):
  414. self.do_op('sweep','alice','1:0',self.tx_relay_daemon_proxy_parm)
  415. return self.mine_chk('alice',1,0,lambda x: x > 1,'unlocked balance > 1')
  416. def sweep_to_account(self):
  417. self.do_op('sweep','alice','1:0,2')
  418. return self.mine_chk('alice',2,1,lambda x: x > 1,'unlocked balance > 1')
  419. def sweep_to_address_noproxy(self):
  420. self.do_op('sweep','alice','2:1',self.tx_relay_daemon_parm)
  421. return self.mine_chk('alice',2,1,lambda x: x > 0.9,'unlocked balance > 0.9')
  422. async def transfer_to_miner_proxy(self):
  423. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  424. amt = '0.135'
  425. self.do_op('transfer','alice',f'2:1:{addr},{amt}',self.tx_relay_daemon_proxy_parm)
  426. await self.stop_wallet_user('miner')
  427. await self.open_wallet_user('miner',2)
  428. await self.mine_chk('miner',2,0,lambda x: str(x) == amt,f'unlocked balance == {amt}')
  429. ok()
  430. return await self.mine_chk('alice',2,1,lambda x: x > 0.9,'unlocked balance > 0.9')
  431. async def transfer_to_miner_noproxy(self):
  432. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  433. self.do_op('transfer','alice',f'2:1:{addr},0.0995',self.tx_relay_daemon_parm)
  434. await self.mine_chk('miner',2,0,lambda x: str(x) == '0.2345','unlocked balance == 0.2345')
  435. ok()
  436. return await self.mine_chk('alice',2,1,lambda x: x > 0.9,'unlocked balance > 0.9')
  437. def transfer_to_miner_create(self,amt):
  438. get_file_with_ext(self.users['alice'].udir,'sigtx',delete_all=True)
  439. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  440. return self.do_op('transfer','alice',f'2:1:{addr},{amt}',no_relay=True,do_ret=True)
  441. def transfer_to_miner_create1(self):
  442. return self.transfer_to_miner_create('0.0111')
  443. def transfer_to_miner_create2(self):
  444. return self.transfer_to_miner_create('0.0012')
  445. def relay_tx(self,relay_opt=None,add_desc=None):
  446. user = 'alice'
  447. data = self.users[user]
  448. fn = get_file_with_ext(data.udir,'sigtx')
  449. add_desc = (', ' + add_desc) if add_desc else ''
  450. t = self.spawn(
  451. 'mmgen-xmrwallet',
  452. self.extra_opts
  453. + ([relay_opt] if relay_opt else [])
  454. + [ 'relay', fn ],
  455. extra_desc = f'(relaying TX, {capfirst(user)}{add_desc})' )
  456. t.expect('Relay transaction? ','y')
  457. t.read()
  458. t.ok()
  459. async def transfer_to_miner_send1(self):
  460. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_proxy_parm}',add_desc='via proxy')
  461. await self.mine_chk('miner',2,0,lambda x: str(x) == '0.2456','unlocked balance == 0.2456')
  462. ok()
  463. return await self.mine_chk('alice',2,1,lambda x: x > 0.9,'unlocked balance > 0.9')
  464. async def transfer_to_miner_send2(self):
  465. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_parm}',add_desc='no proxy')
  466. await self.mine_chk('miner',2,0,lambda x: str(x) == '0.2468','unlocked balance == 0.2468')
  467. ok()
  468. return await self.mine_chk('alice',2,1,lambda x: x > 0.9,'unlocked balance > 0.9')
  469. async def sweep_create_and_send(self):
  470. bal = XMRAmt('0')
  471. min_bal = XMRAmt('0.9')
  472. for i in range(4):
  473. if i: ok()
  474. get_file_with_ext(self.users['alice'].udir,'sigtx',delete_all=True)
  475. send_amt = self.do_op(
  476. 'sweep','alice','2:1,3', # '2:1,3'
  477. no_relay = True,
  478. reuse_acct = True,
  479. add_desc = f'TX #{i+1}',
  480. return_amt = True )
  481. ok()
  482. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_parm}',add_desc=f'send amt: {send_amt} XMR')
  483. await self.mine_chk('alice',2,1,lambda x: 'chk_bal_chg','balance has changed')
  484. ok()
  485. bal += await self.mine_chk('alice',3,0,lambda x,y=bal: x > y, f'bal > {bal}',return_amt=True)
  486. if bal >= min_bal:
  487. return 'ok'
  488. return False
  489. # wallet methods
  490. async def open_wallet_user(self,user,wnum):
  491. data = self.users[user]
  492. silence()
  493. kal = KeyAddrList( cfg, self.proto, data.kafile, key_address_validity_check=False )
  494. end_silence()
  495. self.users[user].wd.start(silent=not (cfg.exact_output or cfg.verbose))
  496. return data.wd_rpc.call(
  497. 'open_wallet',
  498. filename = os.path.basename(data.walletfile_fs.format(wnum)),
  499. password = kal.entry(wnum).wallet_passwd )
  500. async def stop_wallet_user(self,user):
  501. await self.users[user].wd_rpc.stop_daemon(silent=not (cfg.exact_output or cfg.verbose))
  502. return 'ok'
  503. # mining methods
  504. async def start_mining(self):
  505. data = self.users['miner']
  506. addr = read_from_file(data.addrfile_fs.format(1)) # mine to wallet #1, account 0
  507. for i in range(20):
  508. ret = data.md_rpc.call_raw(
  509. 'start_mining',
  510. do_background_mining = False, # run mining in background or foreground
  511. ignore_battery = True, # ignore battery state (on laptop)
  512. miner_address = addr, # account address to mine to
  513. threads_count = 3 ) # number of mining threads to run
  514. status = self.get_status(ret)
  515. if status == 'OK':
  516. return True
  517. elif status == 'BUSY':
  518. await asyncio.sleep(5)
  519. omsg('Daemon busy. Attempting to start mining...')
  520. else:
  521. die(2,f'Monerod returned status {status}')
  522. else:
  523. die(2,'Max retries exceeded')
  524. async def stop_mining(self):
  525. ret = self.users['miner'].md_rpc.call_raw('stop_mining')
  526. return self.get_status(ret)
  527. async def mine_chk(self,user,wnum,account,test,test_desc,random_txs=None,return_amt=False):
  528. """
  529. - open destination wallet
  530. - optionally create and broadcast random TXs
  531. - start mining
  532. - mine until funds appear in wallet
  533. - stop mining
  534. - close wallet
  535. """
  536. async def get_height():
  537. u = self.users['miner']
  538. for i in range(20):
  539. try:
  540. return u.md_rpc.call('get_last_block_header')['block_header']['height']
  541. except Exception as e:
  542. if 'onnection refused' in str(e):
  543. omsg(f'{e}\nMonerod appears to have crashed. Attempting to restart...')
  544. await asyncio.sleep(5)
  545. u.md.restart()
  546. await asyncio.sleep(5)
  547. await self.start_mining()
  548. else:
  549. raise
  550. else:
  551. die(2,'Restart attempt limit exceeded')
  552. async def send_random_txs():
  553. from mmgen.tool.api import tool_api
  554. t = tool_api(cfg)
  555. t.init_coin('XMR','mainnet')
  556. t.usr_randchars = 0
  557. imsg_r(f'Sending random transactions: ')
  558. for i in range(random_txs):
  559. await self.transfer(
  560. 'miner',
  561. 123456789,
  562. t.randpair()[1],
  563. )
  564. imsg_r(f'{i+1} ')
  565. oqmsg_r('+')
  566. await asyncio.sleep(0.5)
  567. imsg('')
  568. def print_balance(dest,ub):
  569. imsg('Total balance in {}’s wallet {}, account #{}: {}'.format(
  570. capfirst(dest.user),
  571. dest.wnum,
  572. dest.account,
  573. ub.hl()
  574. ))
  575. async def get_balance(dest,count):
  576. data = self.users[dest.user]
  577. data.wd_rpc.call('refresh')
  578. if count and not count % 20:
  579. data.wd_rpc.call('rescan_blockchain')
  580. ret = data.wd_rpc.call('get_accounts')
  581. return XMRAmt(ret['subaddress_accounts'][dest.account]['unlocked_balance'],from_unit='atomic')
  582. # start execution:
  583. self.do_msg(extra_desc =
  584. (f'sending {random_txs} random TXs, ' if random_txs else '') +
  585. f'mining, checking wallet {user}:{wnum}:{account}' )
  586. dest = namedtuple(
  587. 'dest_info',['user','wnum','account','test','test_desc'])(user,wnum,account,test,test_desc)
  588. if dest.user != 'miner':
  589. await self.open_wallet_user(dest.user,dest.wnum)
  590. ub_start = await get_balance(dest,0)
  591. chk_bal_chg = dest.test(ub_start) == 'chk_bal_chg'
  592. if random_txs:
  593. await send_random_txs()
  594. await self.start_mining()
  595. h = await get_height()
  596. imsg_r(f'Chain height: {h} ')
  597. for count in range(500):
  598. ub = await get_balance(dest,count)
  599. if h > 300 and (dest.test(ub) is True or ( chk_bal_chg and ub != ub_start )):
  600. imsg('')
  601. oqmsg_r('+')
  602. print_balance(dest,ub)
  603. break
  604. await asyncio.sleep(2)
  605. h = await get_height()
  606. imsg_r(f'{h} ')
  607. oqmsg_r('+')
  608. else:
  609. die(2,'Timeout exceeded, balance {ub!r}')
  610. await self.stop_mining()
  611. if user != 'miner':
  612. await self.stop_wallet_user(dest.user)
  613. return ub if return_amt else 'ok'
  614. # util methods
  615. def get_status(self,ret):
  616. if ret['status'] != 'OK':
  617. imsg( 'RPC status: {}'.format( ret['status'] ))
  618. return ret['status']
  619. def do_msg(self,extra_desc=None):
  620. self.spawn(
  621. '',
  622. msg_only = True,
  623. extra_desc = f'({extra_desc})' if extra_desc else None
  624. )
  625. async def transfer(self,user,amt,addr):
  626. return self.users[user].wd_rpc.call('transfer',destinations=[{'amount':amt,'address':addr}])
  627. # daemon start/stop methods
  628. def start_daemons(self):
  629. for v in self.users.values():
  630. run(['mkdir','-p',v.datadir])
  631. v.md.start()
  632. def stop_daemons(self):
  633. for v in self.users.values():
  634. if '--restricted-rpc' in v.md.start_cmd:
  635. v.md.stop()
  636. else:
  637. async_run(v.md_rpc.stop_daemon())
  638. def stop_miner_wallet_daemon(self):
  639. async_run(self.users['miner'].wd_rpc.stop_daemon())