daemon.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. daemon.py: Daemon control interface for the MMGen suite
  20. """
  21. import shutil
  22. from subprocess import run,PIPE
  23. from collections import namedtuple
  24. from .exception import *
  25. from .common import *
  26. class Daemon(MMGenObject):
  27. debug = False
  28. wait = True
  29. use_pidfile = True
  30. cfg_file = None
  31. new_console_mswin = False
  32. ps_pid_mswin = False
  33. lockfile = None
  34. avail_flags = ()
  35. _flags = []
  36. def subclass_init(self): pass
  37. def exec_cmd_thread(self,cmd,check):
  38. import threading
  39. tname = ('exec_cmd','exec_cmd_win_console')[self.platform == 'win' and self.new_console_mswin]
  40. t = threading.Thread(target=getattr(self,tname),args=(cmd,check))
  41. t.daemon = True
  42. t.start()
  43. Msg_r(' \b') # blocks w/o this...crazy
  44. def exec_cmd_win_console(self,cmd,check):
  45. from subprocess import Popen,CREATE_NEW_CONSOLE,STARTUPINFO,STARTF_USESHOWWINDOW,SW_HIDE
  46. si = STARTUPINFO(dwFlags=STARTF_USESHOWWINDOW,wShowWindow=SW_HIDE)
  47. p = Popen(cmd,creationflags=CREATE_NEW_CONSOLE,startupinfo=si)
  48. p.wait()
  49. def exec_cmd(self,cmd,check):
  50. cp = run(cmd,check=False,stdout=PIPE,stderr=PIPE)
  51. if self.debug:
  52. print(cp)
  53. if check and cp.returncode != 0:
  54. raise MMGenCalledProcessError(cp)
  55. return cp
  56. def run_cmd(self,cmd,silent=False,check=True,is_daemon=False):
  57. if is_daemon and not silent:
  58. msg('Starting {} {}'.format(self.net_desc,self.desc))
  59. if self.debug:
  60. msg('\nExecuting: {}'.format(' '.join(cmd)))
  61. if self.platform == 'win' and is_daemon:
  62. cp = self.exec_cmd_thread(cmd,check)
  63. else:
  64. cp = self.exec_cmd(cmd,check)
  65. if cp:
  66. out = cp.stdout.decode().rstrip()
  67. err = cp.stderr.decode().rstrip()
  68. if out and (self.debug or not silent):
  69. msg(out)
  70. if err and (self.debug or (cp.returncode and not silent)):
  71. msg(err)
  72. return cp
  73. @property
  74. def pid(self):
  75. if self.ps_pid_mswin and self.platform == 'win':
  76. # TODO: assumes only one running instance of given daemon
  77. cp = self.run_cmd(['ps','-Wl'],silent=True,check=False)
  78. for line in cp.stdout.decode().splitlines():
  79. if self.exec_fn_mswin in line:
  80. return line.split()[3] # use Windows, not Cygwin, PID
  81. die(2,'PID for {!r} not found in ps output'.format(ss))
  82. elif self.use_pidfile:
  83. return open(self.pidfile).read().strip()
  84. else:
  85. return '(unknown)'
  86. def cmd(self,action,*args,**kwargs):
  87. return getattr(self,action)(*args,**kwargs)
  88. def do_start(self,silent=False):
  89. if not silent:
  90. msg('Starting {} {}'.format(self.net_desc,self.desc))
  91. return self.run_cmd(self.start_cmd,silent=True,is_daemon=True)
  92. def do_stop(self,silent=False):
  93. if not silent:
  94. msg('Stopping {} {}'.format(self.net_desc,self.desc))
  95. return self.run_cmd(self.stop_cmd,silent=True)
  96. def cli(self,*cmds,silent=False,check=True):
  97. return self.run_cmd(self.cli_cmd(*cmds),silent=silent,check=check)
  98. def start(self,silent=False):
  99. if self.state == 'ready':
  100. if not silent:
  101. m = '{} {} already running with pid {}'
  102. msg(m.format(self.net_desc,self.desc,self.pid))
  103. return
  104. self.wait_for_state('stopped')
  105. os.makedirs(self.datadir,exist_ok=True)
  106. if self.cfg_file and not 'keep_cfg_file' in self.flags:
  107. open('{}/{}'.format(self.datadir,self.cfg_file),'w').write(self.cfg_file_hdr)
  108. if self.use_pidfile and os.path.exists(self.pidfile):
  109. # Parity just overwrites the data in an existing pidfile without zeroing it first,
  110. # leading to interesting consequences.
  111. os.unlink(self.pidfile)
  112. for i in range(20):
  113. try: ret = self.do_start(silent=silent)
  114. except FileNotFoundError as e:
  115. die(e.errno,e.strerror)
  116. except: pass
  117. else: break
  118. time.sleep(1)
  119. else:
  120. die(2,'Unable to start daemon')
  121. if self.wait:
  122. self.wait_for_state('ready')
  123. return ret
  124. def stop(self,silent=False):
  125. if self.state == 'ready':
  126. ret = self.do_stop(silent=silent)
  127. if self.wait:
  128. self.wait_for_state('stopped')
  129. return ret
  130. else:
  131. if not silent:
  132. msg('{} {} not running'.format(self.net_desc,self.desc))
  133. def restart(self,silent=False):
  134. self.stop(silent=silent)
  135. return self.start(silent=silent)
  136. def test_socket(self,host,port,timeout=10):
  137. import socket
  138. try: socket.create_connection((host,port),timeout=timeout).close()
  139. except: return False
  140. else: return True
  141. def wait_for_state(self,req_state):
  142. for i in range(300):
  143. if self.state == req_state:
  144. return True
  145. time.sleep(0.2)
  146. else:
  147. m = 'Wait for state {!r} timeout exceeded for daemon {} {} (port {})'
  148. die(2,m.format(req_state,self.daemon_id.upper(),self.network,self.rpc_port))
  149. @classmethod
  150. def check_implement(cls):
  151. m = 'required method {}() missing in class {}'
  152. for subcls in cls.__subclasses__():
  153. for k in cls.subclasses_must_implement:
  154. assert k in subcls.__dict__, m.format(k,subcls.__name__)
  155. @property
  156. def flags(self):
  157. return self._flags
  158. def add_flag(self,val):
  159. if val not in self.avail_flags:
  160. m = '{!r}: unrecognized flag (available options: {})'
  161. die(1,m.format(val,self.avail_flags))
  162. if val in self._flags:
  163. die(1,'Flag {!r} already set'.format(val))
  164. self._flags.append(val)
  165. def remove_flag(self,val):
  166. if val not in self.avail_flags:
  167. m = '{!r}: unrecognized flag (available options: {})'
  168. die(1,m.format(val,self.avail_flags))
  169. if val not in self._flags:
  170. die(1,'Flag {!r} not set, so cannot be removed'.format(val))
  171. self._flags.remove(val)
  172. def remove_datadir(self):
  173. if self.state == 'stopped':
  174. import shutil
  175. shutil.rmtree(self.datadir,ignore_errors=True)
  176. else:
  177. msg(f'Cannot remove {self.datadir!r} - daemon is not stopped')
  178. class MoneroWalletDaemon(Daemon):
  179. desc = 'RPC daemon'
  180. net_desc = 'Monero wallet'
  181. daemon_id = 'xmr'
  182. network = 'wallet RPC'
  183. new_console_mswin = True
  184. exec_fn_mswin = 'monero-wallet-rpc.exe'
  185. ps_pid_mswin = True
  186. def __init__(self,wallet_dir,test_suite=False,host=None,user=None,passwd=None):
  187. self.platform = g.platform
  188. self.wallet_dir = wallet_dir
  189. if test_suite:
  190. self.datadir = os.path.join('test','monero-wallet-rpc')
  191. self.rpc_port = 13142
  192. else:
  193. self.datadir = 'monero-wallet-rpc'
  194. self.rpc_port = 13131
  195. self.daemon_port = CoinDaemon('xmr',test_suite=test_suite).rpc_port
  196. self.pidfile = os.path.join(self.datadir,'monero-wallet-rpc.pid')
  197. self.logfile = os.path.join(self.datadir,'monero-wallet-rpc.log')
  198. if self.platform == 'win':
  199. self.use_pidfile = False
  200. self.host = host or g.monero_wallet_rpc_host
  201. self.user = user or g.monero_wallet_rpc_user
  202. self.passwd = passwd or g.monero_wallet_rpc_password
  203. assert self.host
  204. assert self.user
  205. if not self.passwd:
  206. die(1,
  207. 'You must set your Monero wallet RPC password.\n' +
  208. 'This can be done on the command line, with the --monero-wallet-rpc-password\n' +
  209. "option (insecure, not recommended), or by setting 'monero_wallet_rpc_password'\n" +
  210. "in the MMGen config file." )
  211. @property
  212. def start_cmd(self):
  213. cmd = [
  214. 'monero-wallet-rpc',
  215. '--daemon-port={}'.format(self.daemon_port),
  216. '--rpc-bind-port={}'.format(self.rpc_port),
  217. '--wallet-dir='+self.wallet_dir,
  218. '--log-file='+self.logfile,
  219. '--rpc-login={}:{}'.format(self.user,self.passwd) ]
  220. if self.platform == 'linux':
  221. cmd += ['--pidfile={}'.format(self.pidfile)]
  222. cmd += [] if 'no_daemonize' in self.flags else ['--detach']
  223. return cmd
  224. @property
  225. def state(self):
  226. return 'ready' if self.test_socket('localhost',self.rpc_port) else 'stopped'
  227. if not self.test_socket(self.host,self.rpc_port):
  228. return 'stopped'
  229. from .rpc import MoneroWalletRPCClient
  230. try:
  231. MoneroWalletRPCClient(
  232. self.host,
  233. self.rpc_port,
  234. self.user,
  235. self.passwd).call('get_version')
  236. return 'ready'
  237. except:
  238. return 'stopped'
  239. @property
  240. def stop_cmd(self):
  241. return ['kill','-Wf',self.pid] if self.platform == 'win' else ['kill',self.pid]
  242. class CoinDaemon(Daemon):
  243. cfg_file_hdr = ''
  244. subclasses_must_implement = ('state','stop_cmd')
  245. avail_flags = ('no_daemonize','keep_cfg_file')
  246. network_ids = ('btc','btc_tn','btc_rt','bch','bch_tn','bch_rt','ltc','ltc_tn','ltc_rt','xmr','eth','etc')
  247. cd = namedtuple('daemon_data',
  248. ['coin','cls_pfx','coind_exec','cli_exec','cfg_file','testnet_dir','dfl_rpc','dfl_rpc_tn','dfl_rpc_rt'])
  249. daemon_ids = { # for BCH we use non-standard RPC ports
  250. 'btc': cd('Bitcoin', 'Bitcoin', 'bitcoind', 'bitcoin-cli', 'bitcoin.conf', 'testnet3',8332,18332,18444),
  251. 'bch': cd('Bcash', 'Bitcoin', 'bitcoind-abc','bitcoin-cli', 'bitcoin.conf', 'testnet3',8442,18442,18553),
  252. 'ltc': cd('Litecoin', 'Bitcoin', 'litecoind', 'litecoin-cli','litecoin.conf','testnet4',9332,19332,19444),
  253. 'xmr': cd('Monero', 'Monero', 'monerod', 'monerod', 'bitmonero.conf',None, 18081,None,None),
  254. 'eth': cd('Ethereum', 'Ethereum','parity', 'parity', 'parity.conf', None, 8545, None,None),
  255. 'etc': cd('Ethereum Classic','Ethereum','parity', 'parity', 'parity.conf', None, 8545, None,None)
  256. }
  257. testnet_arg = []
  258. coind_args = []
  259. daemonize_args = []
  260. cli_args = []
  261. shared_args = []
  262. coind_cmd = []
  263. coin_specific_coind_args = []
  264. coin_specific_cli_args = []
  265. coin_specific_shared_args = []
  266. usr_coind_args = []
  267. usr_cli_args = []
  268. usr_shared_args = []
  269. def __new__(cls,network_id,test_suite=False,flags=None):
  270. network_id = network_id.lower()
  271. assert network_id in cls.network_ids, '{!r}: invalid network ID'.format(network_id)
  272. if network_id.endswith('_rt'):
  273. network = 'regtest'
  274. daemon_id = network_id[:-3]
  275. elif network_id.endswith('_tn'):
  276. network = 'testnet'
  277. daemon_id = network_id[:-3]
  278. else:
  279. network = 'mainnet'
  280. daemon_id = network_id
  281. me = Daemon.__new__(globals()[cls.daemon_ids[daemon_id].cls_pfx+'Daemon'])
  282. me.network_id = network_id
  283. me.network = network
  284. me.daemon_id = daemon_id
  285. me.desc = 'daemon'
  286. if network == 'regtest':
  287. me.desc = 'regtest daemon'
  288. if test_suite:
  289. rel_datadir = os.path.join(
  290. 'test',
  291. 'data_dir{}'.format('-α' if g.debug_utf8 else ''),
  292. 'regtest',
  293. daemon_id )
  294. else:
  295. me.datadir = os.path.join(g.data_dir_root,'regtest',daemon_id)
  296. elif test_suite:
  297. me.desc = 'test suite daemon'
  298. rel_datadir = os.path.join('test','daemons',daemon_id)
  299. else:
  300. from .protocol import init_proto
  301. me.datadir = init_proto(daemon_id,False).daemon_data_dir
  302. if test_suite:
  303. me.datadir = os.path.abspath(os.path.join(os.getcwd(),rel_datadir))
  304. me.port_shift = 1237 if test_suite else 0
  305. me.platform = g.platform
  306. return me
  307. def __init__(self,network_id,test_suite=False,flags=None):
  308. if flags:
  309. if type(flags) not in (list,tuple):
  310. m = '{!r}: illegal value for flags (must be list or tuple)'
  311. die(1,m.format(flags))
  312. for flag in flags:
  313. self.add_flag(flag)
  314. self.pidfile = '{}/{}-daemon.pid'.format(self.datadir,self.network)
  315. for k in self.daemon_ids[self.daemon_id]._fields:
  316. setattr(self,k,getattr(self.daemon_ids[self.daemon_id],k))
  317. self.rpc_port = {
  318. 'mainnet': self.dfl_rpc,
  319. 'testnet': self.dfl_rpc_tn,
  320. 'regtest': self.dfl_rpc_rt,
  321. }[self.network] + self.port_shift
  322. self.net_desc = '{} {}'.format(self.coin,self.network)
  323. self.subclass_init()
  324. @property
  325. def start_cmd(self):
  326. return ([self.coind_exec]
  327. + self.testnet_arg
  328. + self.coind_args
  329. + self.shared_args
  330. + self.coin_specific_coind_args
  331. + self.coin_specific_shared_args
  332. + self.usr_coind_args
  333. + self.usr_shared_args
  334. + self.daemonize_args
  335. + self.coind_cmd )
  336. def cli_cmd(self,*cmds):
  337. return ([self.cli_exec]
  338. + self.testnet_arg
  339. + self.cli_args
  340. + self.shared_args
  341. + self.coin_specific_cli_args
  342. + self.coin_specific_shared_args
  343. + self.usr_cli_args
  344. + self.usr_shared_args
  345. + list(cmds))
  346. class BitcoinDaemon(CoinDaemon):
  347. cfg_file_hdr = '# BitcoinDaemon config file\n'
  348. def subclass_init(self):
  349. if self.platform == 'win' and self.daemon_id == 'bch':
  350. self.use_pidfile = False
  351. if self.network == 'testnet':
  352. self.testnet_arg = ['--testnet']
  353. self.shared_args = [
  354. '--datadir={}'.format(self.datadir),
  355. '--rpcport={}'.format(self.rpc_port) ]
  356. self.coind_args = [
  357. '--listen=0',
  358. '--keypool=1',
  359. '--rpcallowip=127.0.0.1',
  360. '--rpcbind=127.0.0.1:{}'.format(self.rpc_port) ]
  361. if self.use_pidfile:
  362. self.coind_args += ['--pid='+self.pidfile]
  363. if self.platform == 'linux' and not 'no_daemonize' in self.flags:
  364. self.daemonize_args = ['--daemon']
  365. if self.daemon_id == 'bch':
  366. self.coin_specific_coind_args = ['--usecashaddr=0']
  367. elif self.daemon_id == 'ltc':
  368. self.coin_specific_coind_args = ['--mempoolreplacement=1']
  369. if self.network == 'testnet':
  370. self.lockfile = os.path.join(self.datadir,self.testnet_dir,'.cookie')
  371. elif self.network == 'mainnet':
  372. self.lockfile = os.path.join(self.datadir,'.cookie')
  373. @property
  374. def state(self):
  375. cp = self.cli('getblockcount',silent=True,check=False)
  376. err = cp.stderr.decode()
  377. if ("error: couldn't connect" in err
  378. or "error: Could not connect" in err
  379. or "does not exist" in err ):
  380. # regtest has no cookie file, so test will always fail
  381. if self.lockfile and os.path.exists(self.lockfile):
  382. return 'busy'
  383. else:
  384. return 'stopped'
  385. elif cp.returncode == 0:
  386. return 'ready'
  387. else:
  388. return 'busy'
  389. @property
  390. def stop_cmd(self):
  391. return self.cli_cmd('stop')
  392. class MoneroDaemon(CoinDaemon):
  393. exec_fn_mswin = 'monerod.exe'
  394. ps_pid_mswin = True
  395. new_console_mswin = True
  396. host = 'localhost' # FIXME
  397. def subclass_init(self):
  398. if self.platform == 'win':
  399. self.use_pidfile = False
  400. @property
  401. def shared_args(self):
  402. return ['--zmq-rpc-bind-port={}'.format(self.rpc_port+1),'--rpc-bind-port={}'.format(self.rpc_port)]
  403. @property
  404. def coind_args(self):
  405. cmd = [
  406. '--bg-mining-enable',
  407. '--data-dir={}'.format(self.datadir),
  408. '--offline' ]
  409. if self.platform == 'linux':
  410. cmd += ['--pidfile={}'.format(self.pidfile)]
  411. cmd += [] if 'no_daemonize' in self.flags else ['--detach']
  412. return cmd
  413. @property
  414. def state(self):
  415. if not self.test_socket(self.host,self.rpc_port):
  416. return 'stopped'
  417. cp = self.run_cmd(
  418. [self.coind_exec]
  419. + self.shared_args
  420. + ['status'],
  421. silent=True,
  422. check=False )
  423. return 'stopped' if 'Error:' in cp.stdout.decode() else 'ready'
  424. @property
  425. def stop_cmd(self):
  426. if self.platform == 'win':
  427. return ['kill','-Wf',self.pid]
  428. else:
  429. return [self.coind_exec] + self.shared_args + ['exit']
  430. class EthereumDaemon(CoinDaemon):
  431. exec_fn_mswin = 'parity.exe'
  432. ps_pid_mswin = True
  433. def subclass_init(self):
  434. # defaults:
  435. # linux: $HOME/.local/share/io.parity.ethereum/chains/DevelopmentChain
  436. # win: $LOCALAPPDATA/Parity/Ethereum/chains/DevelopmentChain
  437. self.chaindir = os.path.join(self.datadir,'devchain')
  438. shutil.rmtree(self.chaindir,ignore_errors=True)
  439. if self.platform == 'linux' and not 'no_daemonize' in self.flags:
  440. self.daemonize_args = ['daemon',self.pidfile]
  441. @property
  442. def coind_cmd(self):
  443. return []
  444. @property
  445. def coind_args(self):
  446. return ['--ports-shift={}'.format(self.port_shift),
  447. '--base-path={}'.format(self.chaindir),
  448. '--config=dev',
  449. '--log-file={}'.format(os.path.join(self.datadir,'parity.log')) ]
  450. @property
  451. def state(self):
  452. return 'ready' if self.test_socket('localhost',self.rpc_port) else 'stopped'
  453. # the following code does not work
  454. from mmgen.protocol import init_coin
  455. init_coin('eth')
  456. async def do():
  457. print(g.rpc)
  458. ret = await g.rpc.call('eth_chainId')
  459. print(ret)
  460. return ('stopped','ready')[ret == '0x11']
  461. try:
  462. return run_session(do()) # socket exception is not propagated
  463. except:# SocketError:
  464. return 'stopped'
  465. @property
  466. def stop_cmd(self):
  467. return ['kill','-Wf',self.pid] if self.platform == 'win' else ['kill',self.pid]
  468. CoinDaemon.check_implement()