ts_xmrwallet.py 25 KB

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