Browse Source

Refactoring of daemon:

* gui and daemon are in the same process
 * commands that require network are sent to the daemon
 * open only one gui window per wallet
283
ThomasV 9 years ago
parent
commit
92e0744470
  1. 384
      electrum
  2. 2
      gui/android.py
  3. 4
      gui/gtk.py
  4. 2
      gui/jsonrpc.py
  5. 103
      gui/qt/__init__.py
  6. 5
      gui/qt/main_window.py
  7. 2
      gui/stdio.py
  8. 2
      gui/text.py
  9. 1
      lib/__init__.py
  10. 8
      lib/commands.py
  11. 254
      lib/daemon.py

384
electrum

@ -25,6 +25,13 @@ import sys
import time
import traceback
import threading
import socket
import Queue
from collections import defaultdict
DAEMON_SOCKET = 'daemon.sock'
script_dir = os.path.dirname(os.path.realpath(__file__))
is_bundle = getattr(sys, 'frozen', False)
is_local = not is_bundle and os.path.exists(os.path.join(script_dir, "setup-release.py"))
@ -72,7 +79,6 @@ if is_bundle or is_local or is_android:
from electrum import util
from electrum import SimpleConfig, Network, Wallet, WalletStorage, NetworkProxy
from electrum.util import print_msg, print_error, print_stderr, print_json, set_verbosity, InvalidPassword
from electrum.daemon import get_daemon
from electrum.plugins import init_plugins, run_hook, always_hook
from electrum.commands import get_parser, known_commands, Commands, config_variables
@ -91,90 +97,17 @@ def prompt_password(prompt, confirm=True):
def run_gui(config):
url = config.get('url')
if url:
if os.path.exists(url):
# assume this is a payment request
url = "bitcoin:?r=file://"+ os.path.join(os.getcwd(), url)
if not re.match('^bitcoin:', url):
print_stderr('unknown command:', url)
sys.exit(1)
def init_gui(config, network_proxy):
gui_name = config.get('gui', 'qt')
if gui_name in ['lite', 'classic']:
gui_name = 'qt'
gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui'])
gui = gui.ElectrumGui(config, network_proxy)
return gui
try:
gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui'])
except ImportError:
traceback.print_exc(file=sys.stdout)
sys.exit()
# network interface
if not config.get('offline'):
s = get_daemon(config, False)
if s:
print_msg("Connected to daemon")
network = NetworkProxy(s, config)
network.start()
else:
network = None
gui = gui.ElectrumGui(config, network)
gui.main(url)
if network:
network.stop()
# sleep to let socket threads timeout
time.sleep(0.3)
sys.exit(0)
def run_daemon(config):
cmd = config.get('subcommand')
if cmd not in ['start', 'stop', 'status']:
print_msg("syntax: electrum daemon <start|status|stop>")
sys.exit(1)
s = get_daemon(config, False)
if cmd == 'start':
if s:
print_msg("Daemon already running")
sys.exit(1)
get_daemon(config, True)
sys.exit(0)
elif cmd in ['status','stop']:
if not s:
print_msg("Daemon not running")
sys.exit(1)
network = NetworkProxy(s, config)
network.start()
if cmd == 'status':
p = network.get_parameters()
print_json({
'path': network.config.path,
'server': p[0],
'blockchain_height': network.get_local_height(),
'server_height': network.get_server_height(),
'nodes': network.get_interfaces(),
'connected': network.is_connected(),
'auto_connect': p[4],
})
elif cmd == 'stop':
network.stop_daemon()
print_msg("Daemon stopped")
network.stop()
else:
print "unknown command \"%s\""% arg
sys.exit(0)
def run_cmdline(config):
def init_cmdline(config):
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
@ -196,11 +129,6 @@ def run_cmdline(config):
if cmdname == 'listrequests' and config.get('status'):
cmd.requires_network = True
# arguments passed to function
args = map(lambda x: config.get(x), cmd.params)
# options
args += map(lambda x: config.get(x), cmd.options)
# instanciate wallet for command-line
storage = WalletStorage(config.get_wallet_path())
@ -292,25 +220,6 @@ def run_cmdline(config):
else:
password = None
# start network threads
if cmd.requires_network and not config.get('offline'):
s = get_daemon(config, False)
if not s:
print_msg("Network daemon is not running. Try 'electrum daemon start'\nIf you want to run this command offline, use the -o flag.")
sys.exit(1)
network = NetworkProxy(s, config)
network.start()
while network.status == 'unknown':
time.sleep(0.1)
if not network.is_connected():
print_msg("daemon is not connected")
sys.exit(1)
if wallet:
wallet.start_threads(network)
wallet.update()
else:
network = None
# run the command
if cmd.name == 'deseed':
if not wallet.seed:
@ -330,37 +239,189 @@ def run_cmdline(config):
print_msg("Done.")
else:
print_msg("Action canceled.")
sys.exit(0)
elif cmd.name == 'password':
new_password = prompt_password('New password:')
wallet.update_password(password, new_password)
sys.exit(0)
return cmd, password
def run_command(config, network, password):
cmdname = config.get('cmd')
cmd = known_commands[cmdname]
# instanciate wallet for command-line
storage = WalletStorage(config.get_wallet_path())
# create wallet instance
wallet = Wallet(storage) if cmd.requires_wallet else None
# arguments passed to function
args = map(lambda x: config.get(x), cmd.params)
# options
args += map(lambda x: config.get(x), cmd.options)
cmd_runner = Commands(config, wallet, network)
cmd_runner.password = password
func = getattr(cmd_runner, cmd.name)
result = func(*args)
if wallet:
wallet.stop_threads()
return result
class ClientThread(util.DaemonThread):
def __init__(self, server, s):
util.DaemonThread.__init__(self)
self.server = server
self.client_pipe = util.SocketPipe(s)
self.response_queue = Queue.Queue()
self.server.add_client(self)
self.subscriptions = defaultdict(list)
self.network = self.server.network
def run(self):
config_options = self.client_pipe.get()
password = config_options.get('password')
config = SimpleConfig(config_options)
cmd = config.get('cmd')
if cmd == 'gui':
self.server.gui.new_window(config)
response = "ok"
elif cmd == 'daemon':
sub = config.get('subcommand')
assert sub in ['start', 'stop', 'status']
if sub == 'start':
response = "Daemon already running"
elif sub == 'status':
p = self.network.get_parameters()
response = {
'path': self.network.config.path,
'server': p[0],
'blockchain_height': self.network.get_local_height(),
'server_height': self.network.get_server_height(),
'nodes': self.network.get_interfaces(),
'connected': self.network.is_connected(),
'auto_connect': p[4],
}
elif sub == 'stop':
self.server.stop()
response = "Daemon stopped"
else:
try:
response = run_command(config, self.network, password)
except BaseException as e:
err = traceback.format_exc()
response = {'error':err}
# send response and exit
self.client_pipe.send(response)
self.server.remove_client(self)
class NetworkServer(util.DaemonThread):
def __init__(self, config, network_proxy):
util.DaemonThread.__init__(self)
self.debug = False
self.config = config
self.pipe = util.QueuePipe()
self.network_proxy = network_proxy
self.network = self.network_proxy.network
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
def add_client(self, client):
for key in ['fee', 'status', 'banner', 'updated', 'servers', 'interfaces']:
value = self.network.get_status_value(key)
client.response_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
print_error("new client:", len(self.clients))
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def run(self):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
daemon_socket = os.path.join(self.config.path, DAEMON_SOCKET)
if os.path.exists(daemon_socket):
os.remove(daemon_socket)
daemon_timeout = self.config.get('daemon_timeout', None)
s.bind(daemon_socket)
s.listen(5)
s.settimeout(0.1)
while self.is_running():
try:
connection, address = s.accept()
except socket.timeout:
continue
client = ClientThread(self, connection)
client.start()
print_error("Daemon exiting")
else:
cmd_runner = Commands(config, wallet, network)
func = getattr(cmd_runner, cmd.name)
cmd_runner.password = password
try:
result = func(*args)
except Exception:
traceback.print_exc(file=sys.stderr)
sys.exit(1)
if type(result) == str:
print_msg(result)
elif result is not None:
print_json(result)
# shutdown wallet and network
if cmd.requires_network and not config.get('offline'):
if wallet:
wallet.stop_threads()
network.stop()
def get_daemon(config, start_daemon):
daemon_socket = os.path.join(config.path, DAEMON_SOCKET)
daemon_started = False
while True:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(daemon_socket)
return s
except socket.error:
if not start_daemon:
return False
elif not daemon_started:
daemon_started = True
else:
time.sleep(0.1)
except:
# do not use daemon if AF_UNIX is not available (windows)
return False
def check_www_dir(rdir):
# rewrite index.html every time
import urllib, urlparse, shutil, os
if not os.path.exists(rdir):
os.mkdir(rdir)
index = os.path.join(rdir, 'index.html')
src = os.path.join(os.path.dirname(__file__), 'www', 'index.html')
shutil.copy(src, index)
files = [
"https://code.jquery.com/jquery-1.9.1.min.js",
"https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.js",
"https://code.jquery.com/ui/1.10.3/jquery-ui.js",
"https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
]
for URL in files:
path = urlparse.urlsplit(URL).path
filename = os.path.basename(path)
path = os.path.join(rdir, filename)
if not os.path.exists(path):
print_error("downloading ", URL)
urllib.urlretrieve(URL, path)
if __name__ == '__main__':
# make sure that certificates are here
assert os.path.exists(requests.utils.DEFAULT_CA_BUNDLE_PATH)
# on osx, delete Process Serial Number arg generated for apps launched in Finder
sys.argv = filter(lambda x: not x.startswith('-psn'), sys.argv)
@ -385,8 +446,8 @@ if __name__ == '__main__':
elif arg == '?':
sys.argv[i] = prompt_password('Enter argument (will not echo):', False)
# parse cmd line
parser = get_parser(run_gui, run_daemon, run_cmdline)
# parse command line
parser = get_parser()
args = parser.parse_args()
# config is an object passed to the various constructors (wallet, interface, gui)
@ -408,16 +469,81 @@ if __name__ == '__main__':
config_options['electrum_path'] = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data')
set_verbosity(config_options.get('verbose'))
config = SimpleConfig(config_options)
assert os.path.exists(requests.utils.DEFAULT_CA_BUNDLE_PATH)
config = SimpleConfig(config_options)
cmd_name = config.get('cmd')
gui_name = config.get('gui', 'qt') if args.cmd == 'gui' else 'cmdline'
# check url
url = config.get('url')
if url:
if os.path.exists(url):
# assume this is a payment request
url = "bitcoin:?r=file://"+ os.path.join(os.getcwd(), url)
if not re.match('^bitcoin:', url):
print_stderr('unknown command:', url)
sys.exit(1)
# initialize plugins.
if not is_android:
gui_name = config.get('gui', 'qt') if cmd_name == 'gui' else 'cmdline'
init_plugins(config, is_bundle or is_local or is_android, gui_name)
# call function attached to parser
args.func(config)
sys.exit(0)
# get password if needed
if cmd_name not in ['gui', 'daemon']:
cmd, password = init_cmdline(config)
if not cmd.requires_network or config.get('offline'):
result = run_command(config, None, password)
print_json(result)
sys.exit(1)
# check if daemon is running
s = get_daemon(config, False)
if s:
p = util.SocketPipe(s)
p.send(config_options)
result = p.get()
s.close()
if type(result) in [str, unicode]:
print_msg(result)
elif result is not None:
if result.get('error'):
print_stderr(result.get('error'))
else:
print_json(result)
sys.exit(0)
# daemon is not running
if cmd_name == 'gui':
network_proxy = NetworkProxy(None, config)
network_proxy.start()
server = NetworkServer(config, network_proxy)
server.start()
server.gui = init_gui(config, network_proxy)
server.gui.main()
elif cmd_name == 'daemon':
subcommand = config.get('subcommand')
if subcommand in ['status', 'stop']:
print_msg("Daemon not running")
sys.exit(1)
elif subcommand == 'start':
p = os.fork()
if p == 0:
network_proxy = NetworkProxy(None, config)
network_proxy.start()
server = NetworkServer(config, network_proxy)
if config.get('websocket_server'):
import websockets
websockets.WebSocketServer(config, server).start()
if config.get('requests_dir'):
check_www_dir(config.get('requests_dir'))
server.start()
server.join()
else:
print_stderr("starting daemon (PID %d)"%p)
sys.exit(0)
else:
print_msg("syntax: electrum daemon <start|status|stop>")
sys.exit(1)
else:
print_msg("Network daemon is not running. Try 'electrum daemon start'\nIf you want to run this command offline, use the -o flag.")
sys.exit(1)

2
gui/android.py

@ -964,7 +964,7 @@ class ElectrumGui:
wallet.start_threads(network)
def main(self, url):
def main(self):
s = 'main'
while True:
add_menu(s)

4
gui/gtk.py

@ -1289,7 +1289,7 @@ class ElectrumGui():
self.config = config
def main(self, url=None):
def main(self):
storage = WalletStorage(self.config.get_wallet_path())
if not storage.file_exists:
@ -1334,7 +1334,7 @@ class ElectrumGui():
self.restore_wallet(wallet)
w = ElectrumWindow(self.wallet, self.config, self.network)
if url: w.set_url(url)
#if url: w.set_url(url)
Gtk.main()
def restore_or_create(self):

2
gui/jsonrpc.py

@ -60,7 +60,7 @@ class ElectrumGui:
for cmdname in known_commands:
self.server.register_function(getattr(self.cmd_runner, cmdname), cmdname)
def main(self, url):
def main(self):
self.wallet.start_threads(self.network)
while True:
try:

103
gui/qt/__init__.py

@ -62,17 +62,21 @@ class OpenFileEventFilter(QObject):
return False
class ElectrumGui:
def __init__(self, config, network, app=None):
def __init__(self, config, network):
set_language(config.get('language'))
self.network = network
self.config = config
self.windows = []
self.windows = {}
self.efilter = OpenFileEventFilter(self.windows)
if app is None:
self.app = QApplication(sys.argv)
self.app = QApplication(sys.argv)
self.app.installEventFilter(self.efilter)
self.timer = Timer()
self.app.connect(self.app, QtCore.SIGNAL('new_window'), self.start_new_window)
def build_tray_menu(self):
m = QMenu()
@ -102,48 +106,27 @@ class ElectrumGui:
def close(self):
self.current_window.close()
def go_full(self):
self.config.set_key('lite_mode', False, True)
self.lite_window.hide()
self.main_window.show()
self.main_window.raise_()
self.current_window = self.main_window
def go_lite(self):
self.config.set_key('lite_mode', True, True)
self.main_window.hide()
self.lite_window.show()
self.lite_window.raise_()
self.current_window = self.lite_window
def init_lite(self):
import lite_window
if not self.check_qt_version():
if self.config.get('lite_mode') is True:
msg = "Electrum was unable to load the 'Lite GUI' because it needs Qt version >= 4.7.\nChanging your config to use the 'Classic' GUI"
QMessageBox.warning(None, "Could not start Lite GUI.", msg)
self.config.set_key('lite_mode', False, True)
sys.exit(0)
self.lite_window = None
return
def new_window(self, config):
self.app.emit(SIGNAL('new_window'), config)
actuator = lite_window.MiniActuator(self.main_window)
actuator.load_theme()
self.lite_window = lite_window.MiniWindow(actuator, self.go_full, self.config)
driver = lite_window.MiniDriver(self.main_window, self.lite_window)
def start_new_window(self, config):
path = config.get_wallet_path()
if path not in self.windows:
w = ElectrumWindow(config, self.network, self)
w.connect_slots(self.timer)
w.load_wallet_file(path)
w.show()
self.windows[path] = w
w = self.windows[path]
url = config.get('url')
if url:
w.pay_to_URI(url)
return w
def check_qt_version(self):
qtVersion = qVersion()
return int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7
def set_url(self, uri):
self.current_window.pay_to_URI(uri)
def main(self, url):
def main(self):
self.timer.start()
last_wallet = self.config.get('gui_last_wallet')
if last_wallet is not None and self.config.get('wallet_path') is None:
@ -160,14 +143,7 @@ class ElectrumGui:
self.tray.show()
# main window
self.main_window = w = ElectrumWindow(self.config, self.network, self)
self.current_window = self.main_window
w.show()
#lite window
self.init_lite()
w.load_wallet_file(self.config.get_wallet_path())
self.current_window = self.main_window = self.start_new_window(self.config)
# plugins interact with main window
run_hook('init_qt', self)
@ -175,30 +151,19 @@ class ElectrumGui:
# initial configuration
if self.config.get('hide_gui') is True and self.tray.isVisible():
self.main_window.hide()
self.lite_window.hide()
else:
if self.config.get('lite_mode') is True:
self.go_lite()
else:
self.go_full()
s = Timer()
s.start()
self.windows.append(w)
if url:
self.set_url(url)
w.connect_slots(s)
signal.signal(signal.SIGINT, lambda *args: self.app.quit())
# main loop
self.app.exec_()
if self.tray:
self.tray.hide()
# clipboard persistence
# see http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17328.html
# clipboard persistence. see http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17328.html
event = QtCore.QEvent(QtCore.QEvent.Clipboard)
self.app.sendEvent(self.app.clipboard(), event)
w.close_wallet()
for window in self.windows.values():
window.close_wallet()
if self.tray:
self.tray.hide()

5
gui/qt/main_window.py

@ -117,8 +117,6 @@ class ElectrumWindow(QMainWindow):
self.gui_object = gui_object
self.tray = gui_object.tray
self.go_lite = gui_object.go_lite
self.lite = None
self.app = gui_object.app
self.invoices = InvoiceStore(self.config)
@ -1900,9 +1898,6 @@ class ElectrumWindow(QMainWindow):
self.search_box.hide()
sb.addPermanentWidget(self.search_box)
if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) )
self.lock_icon = QIcon()
self.password_button = StatusBarButton( self.lock_icon, _("Password"), self.change_password_dialog )
sb.addPermanentWidget( self.password_button )

2
gui/stdio.py

@ -170,7 +170,7 @@ class ElectrumGui:
print(msg)
def main(self,url):
def main(self):
while self.done == 0: self.main_command()
def do_send(self):

2
gui/text.py

@ -268,7 +268,7 @@ class ElectrumGui:
self.show_message(repr(c))
pass
def main(self,url):
def main(self):
tty.setraw(sys.stdin)
while self.tab != -1:

1
lib/__init__.py

@ -11,5 +11,4 @@ import transaction
from transaction import Transaction
from plugins import BasePlugin
from commands import Commands, known_commands
from daemon import NetworkServer
from network_proxy import NetworkProxy

8
lib/commands.py

@ -724,7 +724,7 @@ def add_network_options(parser):
from util import profiler
@profiler
def get_parser(run_gui, run_daemon, run_cmdline):
def get_parser():
# parent parser, because set_default_subparser removes global options
parent_parser = argparse.ArgumentParser('parent', add_help=False)
group = parent_parser.add_argument_group('global options')
@ -740,7 +740,7 @@ def get_parser(run_gui, run_daemon, run_cmdline):
# gui
parser_gui = subparsers.add_parser('gui', parents=[parent_parser], description="Run Electrum's Graphical User Interface.", help="Run GUI (default)")
parser_gui.add_argument("url", nargs='?', default=None, help="bitcoin URI (or bip70 file)")
parser_gui.set_defaults(func=run_gui)
#parser_gui.set_defaults(func=run_gui)
parser_gui.add_argument("-g", "--gui", dest="gui", help="select graphical user interface", choices=['qt', 'lite', 'gtk', 'text', 'stdio', 'jsonrpc'])
parser_gui.add_argument("-m", action="store_true", dest="hide_gui", default=False, help="hide GUI on startup")
parser_gui.add_argument("-L", "--lang", dest="language", default=None, help="default language used in GUI")
@ -748,13 +748,13 @@ def get_parser(run_gui, run_daemon, run_cmdline):
# daemon
parser_daemon = subparsers.add_parser('daemon', parents=[parent_parser], help="Run Daemon")
parser_daemon.add_argument("subcommand", choices=['start', 'status', 'stop'])
parser_daemon.set_defaults(func=run_daemon)
#parser_daemon.set_defaults(func=run_daemon)
add_network_options(parser_daemon)
# commands
for cmdname in sorted(known_commands.keys()):
cmd = known_commands[cmdname]
p = subparsers.add_parser(cmdname, parents=[parent_parser], help=cmd.help, description=cmd.description)
p.set_defaults(func=run_cmdline)
#p.set_defaults(func=run_cmdline)
if cmd.requires_password:
p.add_argument("-W", "--password", dest="password", default=None, help="password")
for optname, default in zip(cmd.options, cmd.defaults):

254
lib/daemon.py

@ -1,254 +0,0 @@
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 Thomas Voegtlin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import socket
import time
import sys
import os
import threading
import traceback
import json
import Queue
from collections import defaultdict
import util
from network import Network
from util import print_error, print_stderr, parse_json
from simple_config import SimpleConfig
DAEMON_SOCKET = 'daemon.sock'
def do_start_daemon(config):
import subprocess
args = [sys.executable, __file__, config.path]
logfile = open(os.path.join(config.path, 'daemon.log'),'w')
p = subprocess.Popen(args, stderr=logfile, stdout=logfile, close_fds=(os.name=="posix"))
print_stderr("starting daemon (PID %d)"%p.pid)
def get_daemon(config, start_daemon):
import socket
daemon_socket = os.path.join(config.path, DAEMON_SOCKET)
daemon_started = False
while True:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(daemon_socket)
return s
except socket.error:
if not start_daemon:
return False
elif not daemon_started:
do_start_daemon(config)
daemon_started = True
else:
time.sleep(0.1)
except:
# do not use daemon if AF_UNIX is not available (windows)
return False
class ClientThread(util.DaemonThread):
def __init__(self, server, s):
util.DaemonThread.__init__(self)
self.server = server
self.client_pipe = util.SocketPipe(s)
self.response_queue = Queue.Queue()
self.server.add_client(self)
self.subscriptions = defaultdict(list)
def reading_thread(self):
while self.is_running():
try:
request = self.client_pipe.get()
except util.timeout:
continue
if request is None:
self.running = False
break
method = request.get('method')
params = request.get('params')
if method == 'daemon.stop':
self.server.stop()
continue
if method[-10:] == '.subscribe':
self.subscriptions[method].append(params)
self.server.send_request(self, request)
def run(self):
threading.Thread(target=self.reading_thread).start()
while self.is_running():
try:
response = self.response_queue.get(timeout=0.1)
except Queue.Empty:
continue
try:
self.client_pipe.send(response)
except socket.error:
self.running = False
break
self.server.remove_client(self)
class NetworkServer(util.DaemonThread):
def __init__(self, config):
util.DaemonThread.__init__(self)
self.debug = False
self.config = config
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
self.request_id = 0
self.requests = {}
def add_client(self, client):
for key in ['fee', 'status', 'banner', 'updated', 'servers', 'interfaces']:
value = self.network.get_status_value(key)
client.response_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
print_error("new client:", len(self.clients))
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def send_request(self, client, request):
with self.lock:
self.request_id += 1
self.requests[self.request_id] = (request['id'], client)
request['id'] = self.request_id
if self.debug:
print_error("-->", request)
self.pipe.send(request)
def run(self):
self.network.start()
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if self.debug:
print_error("<--", response)
response_id = response.get('id')
if response_id:
with self.lock:
client_id, client = self.requests.pop(response_id)
response['id'] = client_id
client.response_queue.put(response)
else:
# notification
m = response.get('method')
v = response.get('params')
for client in self.clients:
if m == 'network.status' or v in client.subscriptions.get(m, []):
client.response_queue.put(response)
self.network.stop()
print_error("server exiting")
def daemon_loop(server):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
daemon_socket = os.path.join(server.config.path, DAEMON_SOCKET)
if os.path.exists(daemon_socket):
os.remove(daemon_socket)
daemon_timeout = server.config.get('daemon_timeout', None)
s.bind(daemon_socket)
s.listen(5)
s.settimeout(1)
t = time.time()
while server.running:
try:
connection, address = s.accept()
except socket.timeout:
if daemon_timeout is None:
continue
if not server.clients:
if time.time() - t > daemon_timeout:
print_error("Daemon timeout")
break
else:
t = time.time()
continue
t = time.time()
client = ClientThread(server, connection)
client.start()
server.stop()
# sleep so that other threads can terminate cleanly
time.sleep(0.5)
print_error("Daemon exiting")
def check_www_dir(rdir):
# rewrite index.html every time
import urllib, urlparse, shutil, os
if not os.path.exists(rdir):
os.mkdir(rdir)
index = os.path.join(rdir, 'index.html')
src = os.path.join(os.path.dirname(__file__), 'www', 'index.html')
shutil.copy(src, index)
files = [
"https://code.jquery.com/jquery-1.9.1.min.js",
"https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.js",
"https://code.jquery.com/ui/1.10.3/jquery-ui.js",
"https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
]
for URL in files:
path = urlparse.urlsplit(URL).path
filename = os.path.basename(path)
path = os.path.join(rdir, filename)
if not os.path.exists(path):
print_error("downloading ", URL)
urllib.urlretrieve(URL, path)
if __name__ == '__main__':
import simple_config, util
_config = {}
if len(sys.argv) > 1:
_config['electrum_path'] = sys.argv[1]
config = simple_config.SimpleConfig(_config)
util.set_verbosity(True)
server = NetworkServer(config)
server.start()
if config.get('websocket_server'):
import websockets
websockets.WebSocketServer(config, server).start()
if config.get('requests_dir'):
check_www_dir(config.get('requests_dir'))
try:
daemon_loop(server)
except KeyboardInterrupt:
print "Ctrl C - Stopping daemon"
server.stop()
sys.exit(1)
Loading…
Cancel
Save