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
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.socket.connect(('', 8000))
44 self.unanswered_requests = {}
45 self.subscriptions = {}
47 self.lock = threading.Lock()
50 def parse_json(self, message):
51 s = message.find('\n')
54 j = json.loads( message[0:s] )
55 return j, message[s+1:]
59 # read responses and trigger callbacks
63 data = self.socket.recv(1024)
71 response, message = self.parse_json(message)
72 if response is not None:
73 self.process(response)
77 print "NetworkProxy: exiting"
80 def process(self, response):
82 #print "<--", response
84 msg_id = response.get('id')
86 method, params, callback = self.unanswered_requests.pop(msg_id)
88 result = response.get('result')
89 callback(None, {'method':method, 'params':params, 'result':result, 'id':msg_id})
92 def subscribe(self, messages, callback):
93 # detect if it is a subscription
95 if self.subscriptions.get(callback) is None:
96 self.subscriptions[callback] = []
97 for message in messages:
98 if message not in self.subscriptions[callback]:
99 self.subscriptions[callback].append(message)
101 self.do_send( messages, callback )
104 def do_send(self, messages, callback):
105 """return the ids of the requests that we sent"""
110 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
111 self.unanswered_requests[self.message_id] = method, params, callback
112 ids.append(self.message_id)
113 # print "-->", request
115 out += request + '\n'
117 sent = self.socket.send( out )
122 def synchronous_get(self, requests, timeout=100000000):
123 queue = Queue.Queue()
124 ids = self.do_send(requests, lambda i,x: queue.put(x))
128 r = queue.get(True, timeout)
132 res[_id] = r.get('result')
139 def get_servers(self):
140 return self.synchronous_get([('network.get_servers',[])])[0]
142 def get_header(self, height):
143 return self.synchronous_get([('network.get_header',[height])])[0]
145 def get_local_height(self):
146 return self.synchronous_get([('network.get_local_height',[])])[0]
148 def is_connected(self):
149 return self.synchronous_get([('network.is_connected',[])])[0]
151 def is_up_to_date(self):
152 return self.synchronous_get([('network.is_up_to_date',[])])[0]
154 def main_server(self):
155 return self.synchronous_get([('network.main_server',[])])[0]
158 return self.synchronous_get([('daemon.shutdown',[])])[0]
161 def trigger_callback(self, cb):
169 class ClientThread(threading.Thread):
170 # read messages from client (socket), and sends them to Network
171 # responses are sent back on the same socket
173 def __init__(self, server, network, socket):
174 threading.Thread.__init__(self)
178 self.s.settimeout(0.1)
179 self.network = network
180 self.queue = Queue.Queue()
181 self.unanswered_requests = {}
187 self.send_responses()
189 data = self.s.recv(1024)
190 except socket.timeout:
198 cmd, message = self.parse_json(message)
203 #print "client thread terminating"
206 def parse_json(self, message):
207 n = message.find('\n')
210 j = json.loads( message[0:n] )
211 return j, message[n+1:]
214 def process(self, request):
215 #print "<--", request
216 method = request['method']
217 params = request['params']
220 if method.startswith('network.'):
223 f = getattr(self.network, method[8:])
224 except AttributeError:
225 out['error'] = "unknown method"
227 out['result'] = f(*params)
228 except BaseException as e:
232 if method == 'daemon.shutdown':
233 self.server.running = False
234 self.queue.put({'id':_id, 'result':True})
240 my_id = self.unanswered_requests.pop(_id)
244 new_id = self.network.interface.send([(method, params)], cb) [0]
245 self.unanswered_requests[new_id] = _id
248 def send_responses(self):
251 r = self.queue.get_nowait()
254 out = json.dumps(r) + '\n'
265 def __init__(self, config):
266 network = Network(config)
267 if not network.start(wait=True):
268 print_msg("Not connected, aborting.")
270 self.network = network
271 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
272 self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
273 self.server.bind(('', 8000))
274 self.server.listen(5)
275 self.server.settimeout(1)
285 connection, address = self.server.accept()
286 except socket.timeout:
287 if time.time() - t > self.timeout:
291 client = ClientThread(self, self.network, connection)
296 def start_daemon(config):
298 if (pid == 0): # The first child.
303 if (pid2 == 0): # Second child
304 server = NetworkServer(config)
307 except KeyboardInterrupt:
308 print "Ctrl C - Stopping server"
313 # should use a signal
318 if __name__ == '__main__':
320 config = simple_config.SimpleConfig({'verbose':True, 'server':'ecdsa.net:50002:s'})
321 server = NetworkServer(config)
324 except KeyboardInterrupt:
325 print "Ctrl C - Stopping server"