ts_xmrwallet.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 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. ts_xmrwallet.py: xmrwallet tests for the test.py test suite
  20. """
  21. import sys,os,atexit,asyncio
  22. from subprocess import run,PIPE
  23. from mmgen.globalvars import g
  24. from mmgen.opts import opt
  25. from mmgen.obj import MMGenRange,XMRAmt
  26. from mmgen.addr 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 = ('coin',)
  36. tmpdir_nums = [29]
  37. dfl_random_txs = 3
  38. cmd_group = (
  39. ('gen_kafiles', 'generating key-address files'),
  40. ('create_wallets', 'creating Monero wallets'),
  41. ('set_dest_miner', 'opening miner wallet'),
  42. ('mine_blocks', 'mining blocks'),
  43. ('fund_alice', 'sending funds'),
  44. ('mine_blocks_tx', 'mining blocks'),
  45. ('sync_wallets', 'syncing all wallets'),
  46. ('sync_wallets_selected', 'syncing selected wallets'),
  47. ('sweep_to_address_proxy', 'sweeping to new address (via TX relay + proxy)'),
  48. ('mine_blocks', 'mining blocks'),
  49. ('sweep_to_account', 'sweeping to new account'),
  50. ('mine_blocks', 'mining blocks'),
  51. ('sweep_to_address_noproxy', 'sweeping to new address (via TX relay)'),
  52. ('mine_blocks', 'mining blocks'),
  53. )
  54. def __init__(self,trunner,cfgs,spawn):
  55. TestSuiteBase.__init__(self,trunner,cfgs,spawn)
  56. if trunner == None:
  57. return
  58. from mmgen.protocol import init_proto
  59. self.proto = init_proto('XMR',network='testnet')
  60. self.datadir_base = os.path.join('test','daemons','xmrtest')
  61. self.long_opts = ['--testnet=1', '--monero-wallet-rpc-password=passw0rd']
  62. self.init_users()
  63. self.init_daemon_args()
  64. for v in self.users.values():
  65. run(['mkdir','-p',v.udir])
  66. self.init_proxy()
  67. if not opt.no_daemon_autostart:
  68. self.start_daemons()
  69. self.start_wallet_daemons()
  70. if not opt.no_daemon_stop:
  71. atexit.register(self.stop_daemons)
  72. atexit.register(self.stop_wallet_daemons)
  73. self.balance = None
  74. # init methods
  75. def init_proxy(self):
  76. def port_in_use(port):
  77. import socket
  78. try: socket.create_connection(('localhost',port)).close()
  79. except: return False
  80. else: return True
  81. def start_proxy():
  82. if not opt.no_daemon_autostart:
  83. run(a+b2)
  84. omsg(f'SSH SOCKS server started, listening at localhost:{self.socks_port}')
  85. def kill_proxy():
  86. omsg(f'Killing SSH SOCKS server at localhost:{self.socks_port}')
  87. cmd = [ 'pkill', '-f', ' '.join(a + b2) ]
  88. run(cmd)
  89. self.use_proxy = False
  90. self.socks_port = 9060
  91. a = ['ssh','-x','-o','ExitOnForwardFailure=True','-D',f'localhost:{self.socks_port}']
  92. b0 = ['-o','PasswordAuthentication=False']
  93. b1 = ['localhost','true']
  94. b2 = ['-fN','-E','txrelay-proxy.debug','localhost']
  95. if port_in_use(self.socks_port):
  96. omsg(f'Port {self.socks_port} already in use. Assuming SSH SOCKS server is running')
  97. self.use_proxy = True
  98. else:
  99. cp = run(a+b0+b1,stdout=PIPE,stderr=PIPE)
  100. err = cp.stderr.decode()
  101. if err:
  102. omsg(err)
  103. if cp.returncode == 0:
  104. start_proxy()
  105. self.use_proxy = True
  106. elif 'onnection refused' in err:
  107. die(2,fmt("""
  108. The SSH daemon must be running and listening on localhost in order to test
  109. XMR TX relaying via SOCKS proxy. If sshd is not running, please start it.
  110. Otherwise, add the line 'ListenAddress 127.0.0.1' to your sshd_config, and
  111. then restart the daemon.
  112. """,indent=' '))
  113. elif 'ermission denied' in err:
  114. msg(fmt(f"""
  115. In order to test XMR TX relaying via SOCKS proxy, it’s desirable to enable
  116. SSH to localhost without a password, which is not currently supported by
  117. your configuration. Your possible courses of action:
  118. 1. Continue by answering 'y' at this prompt, and enter your system password
  119. at the following prompt;
  120. 2. Exit the test here, add your user SSH public key to your user
  121. 'authorized_keys' file, and restart the test; or
  122. 3. Exit the test here, start the SSH SOCKS proxy manually by entering the
  123. following command, and restart the test:
  124. {' '.join(a+b2)}
  125. """,indent=' ',strip_char='\t'))
  126. if keypress_confirm('Continue?'):
  127. start_proxy()
  128. self.use_proxy = True
  129. else:
  130. die(1,'Exiting at user request')
  131. else:
  132. die(2,fmt(f"""
  133. Please start the SSH SOCKS proxy by entering the following command:
  134. {' '.join(a+b2)}
  135. Then restart the test.
  136. """,indent=' '))
  137. if not opt.no_daemon_stop:
  138. atexit.register(kill_proxy)
  139. def init_users(self):
  140. from mmgen.daemon import CoinDaemon,MoneroWalletDaemon
  141. from mmgen.rpc import MoneroRPCClient,MoneroRPCClientRaw,MoneroWalletRPCClient
  142. self.users = {}
  143. n = self.tmpdir_nums[0]
  144. ud = namedtuple('user_data',[
  145. 'sid',
  146. 'mmwords',
  147. 'udir',
  148. 'datadir',
  149. 'kal_range',
  150. 'kafile',
  151. 'walletfile_fs',
  152. 'addrfile_fs',
  153. 'md',
  154. 'md_rpc',
  155. 'md_json_rpc',
  156. 'wd',
  157. 'wd_rpc',
  158. ])
  159. for user,sid,shift,kal_range in ( # kal_range must be None, a single digit, or a single hyphenated range
  160. ('miner', '98831F3A', 130, '1'),
  161. ('bob', '1378FC64', 140, None),
  162. ('alice', 'FE3C6545', 150, '1-4'),
  163. ):
  164. udir = os.path.join('test',f'tmp{n}',user)
  165. datadir = os.path.join(self.datadir_base,user)
  166. md = CoinDaemon(
  167. proto = self.proto,
  168. test_suite = True,
  169. port_shift = shift,
  170. opts = ['online'],
  171. datadir = datadir
  172. )
  173. md_rpc = MoneroRPCClientRaw(
  174. host = md.host,
  175. port = md.rpc_port,
  176. user = None,
  177. passwd = None,
  178. test_connection = False,
  179. )
  180. md_json_rpc = MoneroRPCClient(
  181. host = md.host,
  182. port = md.rpc_port,
  183. user = None,
  184. passwd = None,
  185. test_connection = False,
  186. )
  187. wd = MoneroWalletDaemon(
  188. user = 'foo',
  189. passwd = 'bar',
  190. wallet_dir = udir,
  191. test_suite = True,
  192. port_shift = shift,
  193. datadir = os.path.join('test','daemons'),
  194. daemon_addr = f'127.0.0.1:{md.rpc_port}',
  195. testnet = True
  196. )
  197. wd_rpc = MoneroWalletRPCClient(
  198. host = wd.host,
  199. port = wd.rpc_port,
  200. user = wd.user,
  201. passwd = wd.passwd,
  202. test_connection = False,
  203. )
  204. self.users[user] = ud(
  205. sid = sid,
  206. mmwords = f'test/ref/{sid}.mmwords',
  207. udir = udir,
  208. datadir = datadir,
  209. kal_range = kal_range,
  210. kafile = f'{udir}/{sid}-XMR-M[{kal_range}].testnet.akeys',
  211. walletfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet.testnet',
  212. addrfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet.testnet.address.txt',
  213. md = md,
  214. md_rpc = md_rpc,
  215. md_json_rpc = md_json_rpc,
  216. wd = wd,
  217. wd_rpc = wd_rpc,
  218. )
  219. def init_daemon_args(self):
  220. common_args = ['--p2p-bind-ip=127.0.0.1','--fixed-difficulty=1'] # ,'--rpc-ssl-allow-any-cert']
  221. for u in self.users:
  222. other_ports = [self.users[u2].md.p2p_port for u2 in self.users if u2 != u]
  223. node_args = [f'--add-exclusive-node=127.0.0.1:{p}' for p in other_ports]
  224. self.users[u].md.usr_coind_args = common_args + node_args
  225. # cmd_group methods
  226. def gen_kafiles(self):
  227. for user,data in self.users.items():
  228. if not data.kal_range:
  229. continue
  230. run(['mkdir','-p',data.udir])
  231. run(f'rm -f {data.kafile}',shell=True)
  232. t = self.spawn(
  233. 'mmgen-keygen', [
  234. '--testnet=1','-q', '--accept-defaults', '--coin=xmr',
  235. f'--outdir={data.udir}', data.mmwords, data.kal_range
  236. ],
  237. extra_desc = f'({capfirst(user)})' )
  238. t.read()
  239. t.ok()
  240. t.skip_ok = True
  241. return t
  242. def create_wallets(self):
  243. for user,data in self.users.items():
  244. if not data.kal_range:
  245. continue
  246. run('rm -f {}*'.format( data.walletfile_fs.format('*') ),shell=True)
  247. dir_opt = [f'--outdir={data.udir}']
  248. t = self.spawn(
  249. 'mmgen-xmrwallet',
  250. self.long_opts + dir_opt + [ 'create', data.kafile, data.kal_range ],
  251. extra_desc = f'({capfirst(user)})' )
  252. t.expect('Check key-to-address validity? (y/N): ','n')
  253. for i in MMGenRange(data.kal_range).items:
  254. t.expect('Address: ')
  255. t.read()
  256. t.ok()
  257. t.skip_ok = True
  258. return t
  259. async def set_dest_miner(self):
  260. self.do_msg()
  261. self.set_dest('miner',1,0,lambda x: x > 20,'unlocked balance > 20')
  262. await self.open_wallet_user('miner',1)
  263. return 'ok'
  264. async def fund_alice(self):
  265. self.do_msg()
  266. await self.transfer(
  267. 'miner',
  268. 1234567891234,
  269. read_from_file(self.users['alice'].addrfile_fs.format(1)),
  270. )
  271. self.set_dest('alice',1,0,lambda x: x > 1,'unlocked balance > 1')
  272. return 'ok'
  273. def sync_wallets_selected(self):
  274. return self.sync_wallets(wallets='1,3-4')
  275. def sync_wallets(self,wallets=None):
  276. data = self.users['alice']
  277. dir_opt = [f'--outdir={data.udir}']
  278. cmd_opts = [f'--daemon=localhost:{data.md.rpc_port}']
  279. t = self.spawn(
  280. 'mmgen-xmrwallet',
  281. self.long_opts + dir_opt + cmd_opts + [ 'sync', data.kafile ] + ([wallets] if wallets else []) )
  282. t.expect('Check key-to-address validity? (y/N): ','n')
  283. wlist = AddrIdxList(wallets) if wallets else MMGenRange(data.kal_range).items
  284. for n,wnum in enumerate(wlist):
  285. t.expect('Syncing wallet {}/{} ({})'.format(
  286. n+1,
  287. len(wlist),
  288. os.path.basename(data.walletfile_fs.format(wnum)),
  289. ))
  290. t.expect('Chain height: ')
  291. t.expect('Wallet height: ')
  292. t.expect('Balance: ')
  293. t.read()
  294. return t
  295. def _sweep_user(self,user,spec,tx_relay_daemon=None):
  296. data = self.users[user]
  297. dir_opt = [f'--outdir={data.udir}']
  298. cmd_opts = list_gen(
  299. [f'--daemon=localhost:{data.md.rpc_port}'],
  300. [f'--tx-relay-daemon={tx_relay_daemon}', tx_relay_daemon]
  301. )
  302. t = self.spawn(
  303. 'mmgen-xmrwallet',
  304. self.long_opts + dir_opt + cmd_opts + [ 'sweep', data.kafile, spec ],
  305. extra_desc = f'({capfirst(user)})' )
  306. t.expect('Check key-to-address validity? (y/N): ','n')
  307. t.expect(
  308. 'Create new {} .* \(y/N\): '.format('account' if ',' in spec else 'address'),
  309. 'y', regex=True )
  310. t.expect('Relay sweep transaction? (y/N): ','y')
  311. t.read()
  312. return t
  313. def sweep_to_address_proxy(self):
  314. ret = self._sweep_user(
  315. 'alice',
  316. '1:0',
  317. tx_relay_daemon = 'localhost:{}:127.0.0.1:{}'.format( # proxy must be IP, not 'localhost'
  318. self.users['bob'].md.rpc_port,
  319. self.socks_port
  320. ) if self.use_proxy else None
  321. )
  322. self.set_dest('alice',1,0,lambda x: x > 1,'unlocked balance > 1')
  323. return ret
  324. def sweep_to_account(self):
  325. ret = self._sweep_user('alice','1:0,2')
  326. self.set_dest('alice',2,1,lambda x: x > 1,'unlocked balance > 1')
  327. return ret
  328. def sweep_to_address_noproxy(self):
  329. ret = self._sweep_user(
  330. 'alice',
  331. '2:1',
  332. tx_relay_daemon = 'localhost:{}'.format(self.users['bob'].md.rpc_port)
  333. )
  334. self.set_dest('alice',2,1,lambda x: x > 1,'unlocked balance > 1')
  335. return ret
  336. # wallet methods
  337. async def open_wallet_user(self,user,wnum):
  338. data = self.users[user]
  339. silence()
  340. kal = KeyAddrList(self.proto,data.kafile,skip_key_address_validity_check=True)
  341. end_silence()
  342. return await data.wd_rpc.call(
  343. 'open_wallet',
  344. filename = os.path.basename(data.walletfile_fs.format(wnum)),
  345. password = kal.entry(wnum).wallet_passwd )
  346. async def close_wallet_user(self,user):
  347. ret = await self.users[user].wd_rpc.call('close_wallet')
  348. return 'ok'
  349. # mining methods
  350. async def start_mining(self):
  351. data = self.users['miner']
  352. addr = read_from_file(data.addrfile_fs.format(1)) # mine to wallet #1, account 0
  353. for i in range(20):
  354. ret = await data.md_rpc.call(
  355. 'start_mining',
  356. do_background_mining = False, # run mining in background or foreground
  357. ignore_battery = True, # ignore battery state (on laptop)
  358. miner_address = addr, # account address to mine to
  359. threads_count = 3 ) # number of mining threads to run
  360. status = self.get_status(ret)
  361. if status == 'OK':
  362. return True
  363. elif status == 'BUSY':
  364. await asyncio.sleep(5)
  365. omsg('Daemon busy. Attempting to start mining...')
  366. else:
  367. die(2,f'Monerod returned status {status}')
  368. else:
  369. die(2,'Max retries exceeded')
  370. async def stop_mining(self):
  371. ret = await self.users['miner'].md_rpc.call('stop_mining')
  372. return self.get_status(ret)
  373. async def mine_blocks(self,random_txs=None):
  374. """
  375. - open destination wallet
  376. - optionally create and broadcast random TXs
  377. - start mining
  378. - mine until funds appear in wallet
  379. - stop mining
  380. - close wallet
  381. """
  382. async def get_height():
  383. u = self.users['miner']
  384. for i in range(20):
  385. try:
  386. return (await u.md_json_rpc.call('get_last_block_header'))['block_header']['height']
  387. except Exception as e:
  388. if 'onnection refused' in str(e):
  389. omsg(f'{e}\nMonerod appears to have crashed. Attempting to restart...')
  390. await asyncio.sleep(5)
  391. u.md.restart()
  392. await asyncio.sleep(5)
  393. await self.start_mining()
  394. else:
  395. raise
  396. else:
  397. die(2,'Restart attempt limit exceeded')
  398. async def send_random_txs():
  399. from mmgen.tool import tool_api
  400. t = tool_api()
  401. t.init_coin('XMR','testnet')
  402. t.usr_randchars = 0
  403. imsg_r(f'Sending random transactions: ')
  404. for i in range(random_txs):
  405. await self.transfer(
  406. 'miner',
  407. 123456789,
  408. t.randpair()[1],
  409. )
  410. imsg_r(f'{i+1} ')
  411. oqmsg_r('+')
  412. await asyncio.sleep(0.5)
  413. imsg('')
  414. def print_balance(dest,ub):
  415. imsg('Total balance in {}’s wallet #{}, account {}: {}'.format(
  416. capfirst(dest.user),
  417. dest.wnum,
  418. dest.account,
  419. ub.hl()
  420. ))
  421. async def get_balance(dest):
  422. data = self.users[dest.user]
  423. await data.wd_rpc.call('refresh')
  424. ret = await data.wd_rpc.call('get_accounts')
  425. return XMRAmt(ret['subaddress_accounts'][dest.account]['unlocked_balance'],from_unit='atomic')
  426. self.do_msg(extra_desc=f'+{random_txs} random TXs' if random_txs else None)
  427. if self.dest.user != 'miner':
  428. await self.open_wallet_user(self.dest.user,self.dest.wnum)
  429. if random_txs:
  430. await send_random_txs()
  431. await self.start_mining()
  432. h = await get_height()
  433. imsg_r(f'Chain height: {h} ')
  434. while True:
  435. ub = await get_balance(self.dest)
  436. if self.dest.test(ub):
  437. imsg('')
  438. oqmsg_r('+')
  439. print_balance(self.dest,ub)
  440. break
  441. # else:
  442. # imsg(f'Test {self.dest.test_desc!r} failed')
  443. await asyncio.sleep(2)
  444. h = await get_height()
  445. imsg_r(f'{h} ')
  446. oqmsg_r('+')
  447. await self.stop_mining()
  448. if self.dest.user != 'miner':
  449. await self.close_wallet_user(self.dest.user)
  450. return 'ok'
  451. async def mine_blocks_tx(self):
  452. return await self.mine_blocks(random_txs=self.dfl_random_txs)
  453. # util methods
  454. def get_status(self,ret):
  455. if ret['status'] != 'OK':
  456. imsg( 'RPC status: {}'.format(ret['status']) )
  457. return ret['status']
  458. def do_msg(self,extra_desc=None):
  459. self.spawn(
  460. '',
  461. msg_only = True,
  462. extra_desc = f'({extra_desc})' if extra_desc else None
  463. )
  464. def set_dest(self,user,wnum,account,test,test_desc):
  465. self.dest = namedtuple(
  466. 'dest_info',['user','wnum','account','test','test_desc'])(user,wnum,account,test,test_desc)
  467. async def transfer(self,user,amt,addr):
  468. return await self.users[user].wd_rpc.call('transfer',destinations=[{'amount':amt,'address':addr}])
  469. # daemon start/stop methods
  470. def start_daemons(self):
  471. self.stop_daemons()
  472. for v in self.users.values():
  473. run(['mkdir','-p',v.datadir])
  474. v.md.start()
  475. def stop_daemons(self):
  476. for v in self.users.values():
  477. if v.md.state != 'stopped':
  478. v.md.stop()
  479. run(['rm','-rf',self.datadir_base])
  480. def start_wallet_daemons(self):
  481. for v in self.users.values():
  482. if v.kal_range:
  483. v.wd.start()
  484. def stop_wallet_daemons(self):
  485. for v in self.users.values():
  486. if v.kal_range and v.wd.state != 'stopped':
  487. v.wd.stop()