electrum-bitcoinprivate/lib/daemon.py

235 lines
6.7 KiB
Python
Raw Normal View History

2014-03-10 08:16:27 -07:00
#!/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 network import Network
2014-07-24 01:59:13 -07:00
from util import print_error, print_stderr
from simple_config import SimpleConfig
2014-03-10 08:16:27 -07:00
2014-07-24 01:59:13 -07:00
"""
The Network object is not aware of clients/subscribers
It only does subscribe/unsubscribe to addresses
Which client has wich address is managed by the daemon
Network also reports status changes
"""
2014-03-10 08:16:27 -07:00
2014-07-24 01:59:13 -07:00
DAEMON_PORT=8001
2014-03-10 08:16:27 -07:00
2014-07-24 01:59:13 -07:00
def parse_json(message):
n = message.find('\n')
if n==-1:
return None, message
try:
j = json.loads( message[0:n] )
except:
j = None
return j, message[n+1:]
2014-03-10 08:16:27 -07:00
class ClientThread(threading.Thread):
# read messages from client (socket), and sends them to Network
# responses are sent back on the same socket
2014-07-24 01:59:13 -07:00
def __init__(self, server, network, s):
2014-03-10 08:16:27 -07:00
threading.Thread.__init__(self)
self.server = server
self.daemon = True
2014-07-24 01:59:13 -07:00
self.s = s
2014-07-24 14:14:47 -07:00
self.s.settimeout(0.1)
2014-03-10 08:16:27 -07:00
self.network = network
self.queue = Queue.Queue()
self.unanswered_requests = {}
2014-03-10 23:12:57 -07:00
self.debug = False
2014-07-24 14:14:47 -07:00
self.server.add_client(self)
2014-03-10 08:16:27 -07:00
def run(self):
2014-07-24 14:14:47 -07:00
2014-03-10 08:16:27 -07:00
message = ''
while True:
self.send_responses()
try:
data = self.s.recv(1024)
except socket.timeout:
continue
2014-07-24 01:59:13 -07:00
except:
data = ''
2014-03-10 08:16:27 -07:00
if not data:
break
message += data
while True:
2014-07-24 01:59:13 -07:00
cmd, message = parse_json(message)
2014-03-10 08:16:27 -07:00
if not cmd:
break
self.process(cmd)
2014-07-24 01:59:13 -07:00
self.server.remove_client(self)
2014-03-10 08:16:27 -07:00
def process(self, request):
2014-07-24 01:59:13 -07:00
if self.debug:
print_error("<--", request)
2014-03-10 08:16:27 -07:00
method = request['method']
params = request['params']
_id = request['id']
if method.startswith('network.'):
out = {'id':_id}
try:
f = getattr(self.network, method[8:])
except AttributeError:
out['error'] = "unknown method"
try:
out['result'] = f(*params)
except BaseException as e:
2014-07-25 00:11:56 -07:00
out['error'] = str(e)
print_error("network error", str(e))
self.queue.put(out)
2014-03-10 23:12:57 -07:00
return
2014-03-10 08:16:27 -07:00
def cb(i,r):
_id = r.get('id')
if _id is not None:
my_id = self.unanswered_requests.pop(_id)
r['id'] = my_id
self.queue.put(r)
2014-07-25 00:11:56 -07:00
try:
new_id = self.network.interface.send([(method, params)], cb) [0]
except Exception as e:
self.queue.put({'id':_id, 'error':str(e)})
print_error("network interface error", str(e))
2014-07-25 00:11:56 -07:00
return
2014-03-10 08:16:27 -07:00
self.unanswered_requests[new_id] = _id
def send_responses(self):
while True:
try:
r = self.queue.get_nowait()
except Queue.Empty:
break
out = json.dumps(r) + '\n'
while out:
n = self.s.send(out)
out = out[n:]
2014-07-24 01:59:13 -07:00
if self.debug:
print_error("-->", r)
2014-03-10 08:16:27 -07:00
class NetworkServer:
def __init__(self, config):
2014-07-24 14:14:47 -07:00
self.network = Network(config)
self.network.trigger_callback = self.trigger_callback
self.network.start()
2014-07-24 01:59:13 -07:00
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2014-06-10 11:44:52 -07:00
self.daemon_port = config.get('daemon_port', DAEMON_PORT)
2014-07-24 01:59:13 -07:00
self.socket.bind(('', self.daemon_port))
self.socket.listen(5)
self.socket.settimeout(1)
2014-03-10 08:16:27 -07:00
self.running = False
2014-07-24 14:14:47 -07:00
# daemon terminates after period of inactivity
2014-03-15 22:28:16 -07:00
self.timeout = config.get('daemon_timeout', 60)
2014-07-24 01:59:13 -07:00
self.lock = threading.RLock()
2014-07-24 14:14:47 -07:00
# each GUI is a client of the daemon
2014-07-24 01:59:13 -07:00
self.clients = []
2014-07-24 14:14:47 -07:00
# daemon needs to know which client subscribed to which address
2014-07-24 01:59:13 -07:00
def add_client(self, client):
2014-07-25 00:11:56 -07:00
for key in ['status','banner','updated','servers','interfaces']:
2014-07-24 14:14:47 -07:00
value = self.get_status_value(key)
client.queue.put({'method':'network.status', 'params':[key, value]})
2014-07-24 01:59:13 -07:00
with self.lock:
self.clients.append(client)
2014-07-24 14:14:47 -07:00
2014-07-24 01:59:13 -07:00
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
2014-07-24 14:14:47 -07:00
def get_status_value(self, key):
if key == 'status':
value = self.network.connection_status
elif key == 'banner':
value = self.network.banner
elif key == 'updated':
value = self.network.get_local_height()
elif key == 'servers':
2014-07-25 00:11:56 -07:00
value = self.network.get_servers()
elif key == 'interfaces':
value = self.network.get_interfaces()
2014-07-24 14:14:47 -07:00
return value
def trigger_callback(self, key):
value = self.get_status_value(key)
print_error("daemon trigger callback", key, len(self.clients))
2014-07-24 01:59:13 -07:00
for client in self.clients:
2014-07-24 14:14:47 -07:00
client.queue.put({'method':'network.status', 'params':[key, value]})
2014-03-10 08:16:27 -07:00
def main_loop(self):
self.running = True
t = time.time()
while self.running:
try:
2014-07-24 01:59:13 -07:00
connection, address = self.socket.accept()
2014-03-10 08:16:27 -07:00
except socket.timeout:
2014-07-24 01:59:13 -07:00
if not self.clients:
if time.time() - t > self.timeout:
break
else:
t = time.time()
2014-03-10 08:16:27 -07:00
continue
2014-07-25 06:16:52 -07:00
t = time.time()
2014-03-10 08:16:27 -07:00
client = ClientThread(self, self.network, connection)
client.start()
2014-07-24 14:14:47 -07:00
print_error("Daemon exiting (timeout)")
2014-03-10 08:16:27 -07:00
if __name__ == '__main__':
2014-07-24 01:59:13 -07:00
import simple_config, util
config = simple_config.SimpleConfig()
util.set_verbosity(True)
2014-03-10 08:16:27 -07:00
server = NetworkServer(config)
try:
server.main_loop()
except KeyboardInterrupt:
print "Ctrl C - Stopping server"
sys.exit(1)