ts_xmrwallet.py 27 KB

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