3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2014 Thomas Voegtlin
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.
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.
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/>.
28 from network import Network
29 from util import print_msg
32 class NetworkProxy(threading.Thread):
34 # sends requests, runs callbacks
36 def __init__(self, config):
37 threading.Thread.__init__(self)
40 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
42 self.daemon_port = config.get('daemon_port', 8000)
43 self.socket.connect(('', self.daemon_port))
45 self.unanswered_requests = {}
46 self.subscriptions = {}
48 self.lock = threading.Lock()
51 def parse_json(self, message):
52 s = message.find('\n')
55 j = json.loads( message[0:s] )
56 return j, message[s+1:]
60 # read responses and trigger callbacks
64 data = self.socket.recv(1024)
72 response, message = self.parse_json(message)
73 if response is not None:
74 self.process(response)
78 print "NetworkProxy: exiting"
81 def process(self, response):
83 if self.debug: print "<--", response
85 msg_id = response.get('id')
87 method, params, callback = self.unanswered_requests.pop(msg_id)
89 result = response.get('result')
90 callback(None, {'method':method, 'params':params, 'result':result, 'id':msg_id})
93 def subscribe(self, messages, callback):
94 # detect if it is a subscription
96 if self.subscriptions.get(callback) is None:
97 self.subscriptions[callback] = []
98 for message in messages:
99 if message not in self.subscriptions[callback]:
100 self.subscriptions[callback].append(message)
102 self.do_send( messages, callback )
105 def do_send(self, messages, callback):
106 """return the ids of the requests that we sent"""
111 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
112 self.unanswered_requests[self.message_id] = method, params, callback
113 ids.append(self.message_id)
114 if self.debug: print "-->", request
116 out += request + '\n'
118 sent = self.socket.send( out )
123 def synchronous_get(self, requests, timeout=100000000):
124 queue = Queue.Queue()
125 ids = self.do_send(requests, lambda i,x: queue.put(x))
129 r = queue.get(True, timeout)
133 res[_id] = r.get('result')
140 def get_servers(self):
141 return self.synchronous_get([('network.get_servers',[])])[0]
143 def get_header(self, height):
144 return self.synchronous_get([('network.get_header',[height])])[0]
146 def get_local_height(self):
147 return self.synchronous_get([('network.get_local_height',[])])[0]
149 def is_connected(self):
150 return self.synchronous_get([('network.is_connected',[])])[0]
152 def is_up_to_date(self):
153 return self.synchronous_get([('network.is_up_to_date',[])])[0]
155 def main_server(self):
156 return self.synchronous_get([('network.main_server',[])])[0]
159 return self.synchronous_get([('daemon.shutdown',[])])[0]
162 def trigger_callback(self, cb):
170 class ClientThread(threading.Thread):
171 # read messages from client (socket), and sends them to Network
172 # responses are sent back on the same socket
174 def __init__(self, server, network, socket):
175 threading.Thread.__init__(self)
179 self.s.settimeout(0.1)
180 self.network = network
181 self.queue = Queue.Queue()
182 self.unanswered_requests = {}
189 self.send_responses()
191 data = self.s.recv(1024)
192 except socket.timeout:
200 cmd, message = self.parse_json(message)
205 #print "client thread terminating"
208 def parse_json(self, message):
209 n = message.find('\n')
212 j = json.loads( message[0:n] )
213 return j, message[n+1:]
216 def process(self, request):
217 if self.debug: print "<--", request
218 method = request['method']
219 params = request['params']
222 if method.startswith('network.'):
225 f = getattr(self.network, method[8:])
226 except AttributeError:
227 out['error'] = "unknown method"
229 out['result'] = f(*params)
230 except BaseException as e:
235 if method == 'daemon.shutdown':
236 self.server.running = False
237 self.queue.put({'id':_id, 'result':True})
243 my_id = self.unanswered_requests.pop(_id)
247 new_id = self.network.interface.send([(method, params)], cb) [0]
248 self.unanswered_requests[new_id] = _id
251 def send_responses(self):
254 r = self.queue.get_nowait()
257 out = json.dumps(r) + '\n'
261 if self.debug: print "-->", r
268 def __init__(self, config):
269 network = Network(config)
270 if not network.start(wait=True):
271 print_msg("Not connected, aborting.")
273 self.network = network
274 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
275 self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
276 self.daemon_port = config.get('daemon_port', 8000)
277 self.server.bind(('', self.daemon_port))
278 self.server.listen(5)
279 self.server.settimeout(1)
281 self.timeout = config.get('daemon_timeout', 60)
289 connection, address = self.server.accept()
290 except socket.timeout:
291 if time.time() - t > self.timeout:
295 client = ClientThread(self, self.network, connection)
300 if __name__ == '__main__':
302 config = simple_config.SimpleConfig({'verbose':True, 'server':'ecdsa.net:50002:s'})
303 server = NetworkServer(config)
306 except KeyboardInterrupt:
307 print "Ctrl C - Stopping server"