simplify interface: use callbacks
[electrum-nvc.git] / lib / interface.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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
20 import random, socket, ast, re, ssl, errno
21 import threading, traceback, sys, time, json, Queue
22
23 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
24 from util import print_error, print_msg
25
26
27 DEFAULT_TIMEOUT = 5
28 proxy_modes = ['socks4', 'socks5', 'http']
29
30
31 def pick_random_server():
32     return random.choice( filter_protocol(DEFAULT_SERVERS,'s') )
33
34
35 class Interface(threading.Thread):
36
37
38     def init_server(self, host, port, proxy=None, use_ssl=True):
39         self.host = host
40         self.port = port
41         self.proxy = proxy
42         self.use_ssl = use_ssl
43         self.poll_interval = 1
44
45         #json
46         self.message_id = 0
47         self.unanswered_requests = {}
48         self.pending_transactions_for_notifications= []
49
50
51     def queue_json_response(self, c):
52
53         # uncomment to debug
54         # print_error( "<--",c )
55
56         msg_id = c.get('id')
57         error = c.get('error')
58         
59         if error:
60             print_error("received error:", c)
61             if msg_id is not None:
62                 with self.lock: 
63                     method, params, callback = self.unanswered_requests.pop(msg_id)
64                 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
65
66             return
67
68         if msg_id is not None:
69             with self.lock: 
70                 method, params, callback = self.unanswered_requests.pop(msg_id)
71             result = c.get('result')
72
73         else:
74             # notification
75             method = c.get('method')
76             params = c.get('params')
77
78             if method == 'blockchain.numblocks.subscribe':
79                 result = params[0]
80                 params = []
81
82             elif method == 'blockchain.headers.subscribe':
83                 result = params[0]
84                 params = []
85
86             elif method == 'blockchain.address.subscribe':
87                 addr = params[0]
88                 result = params[1]
89                 params = [addr]
90
91             with self.lock:
92                 for k,v in self.subscriptions.items():
93                     if (method, params) in v:
94                         callback = k
95                         break
96                 else:
97                     print_error( "received unexpected notification", method, params)
98                     print_error( self.subscriptions )
99                     return
100
101
102         callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
103
104
105     def on_version(self, i, result):
106         self.server_version = result
107
108
109     def init_http(self, host, port, proxy=None, use_ssl=True):
110         self.init_server(host, port, proxy, use_ssl)
111         self.session_id = None
112         self.is_connected = True
113         self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
114         try:
115             self.poll()
116         except:
117             print_error("http init session failed")
118             self.is_connected = False
119             return
120
121         if self.session_id:
122             print_error('http session:',self.session_id)
123             self.is_connected = True
124         else:
125             self.is_connected = False
126
127     def run_http(self):
128         self.is_connected = True
129         while self.is_connected:
130             try:
131                 if self.session_id:
132                     self.poll()
133                 time.sleep(self.poll_interval)
134             except socket.gaierror:
135                 break
136             except socket.error:
137                 break
138             except:
139                 traceback.print_exc(file=sys.stdout)
140                 break
141             
142         self.is_connected = False
143
144                 
145     def poll(self):
146         self.send([])
147
148
149     def send_http(self, messages, callback):
150         import urllib2, json, time, cookielib
151         print_error( "send_http", messages )
152         
153         if self.proxy:
154             import socks
155             socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
156             socks.wrapmodule(urllib2)
157
158         cj = cookielib.CookieJar()
159         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
160         urllib2.install_opener(opener)
161
162         t1 = time.time()
163
164         data = []
165         for m in messages:
166             method, params = m
167             if type(params) != type([]): params = [params]
168             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
169             self.unanswered_requests[self.message_id] = method, params, callback
170             self.message_id += 1
171
172         if data:
173             data_json = json.dumps(data)
174         else:
175             # poll with GET
176             data_json = None 
177
178             
179         headers = {'content-type': 'application/json'}
180         if self.session_id:
181             headers['cookie'] = 'SESSION=%s'%self.session_id
182
183         try:
184             req = urllib2.Request(self.connection_msg, data_json, headers)
185             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
186         except:
187             return
188
189         for index, cookie in enumerate(cj):
190             if cookie.name=='SESSION':
191                 self.session_id = cookie.value
192
193         response = response_stream.read()
194         self.bytes_received += len(response)
195         if response: 
196             response = json.loads( response )
197             if type(response) is not type([]):
198                 self.queue_json_response(response)
199             else:
200                 for item in response:
201                     self.queue_json_response(item)
202
203         if response: 
204             self.poll_interval = 1
205         else:
206             if self.poll_interval < 15: 
207                 self.poll_interval += 1
208         #print self.poll_interval, response
209
210         self.rtime = time.time() - t1
211         self.is_connected = True
212
213
214
215
216     def init_tcp(self, host, port, proxy=None, use_ssl=True):
217         self.init_server(host, port, proxy, use_ssl)
218
219         global proxy_modes
220         self.connection_msg = "%s:%d"%(self.host,self.port)
221         if self.proxy is None:
222             s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
223         else:
224             self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
225             import socks
226             s = socks.socksocket()
227             s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
228
229         if self.use_ssl:
230             s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, do_handshake_on_connect=True)
231             
232         s.settimeout(2)
233         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
234
235         try:
236             s.connect(( self.host.encode('ascii'), int(self.port)))
237         except:
238             #traceback.print_exc(file=sys.stdout)
239             print_error("failed to connect", host, port)
240             self.is_connected = False
241             self.s = None
242             return
243
244         s.settimeout(60)
245         self.s = s
246         self.is_connected = True
247
248     def run_tcp(self):
249         try:
250             #if self.use_ssl: self.s.do_handshake()
251             out = ''
252             while self.is_connected:
253                 try: 
254                     timeout = False
255                     msg = self.s.recv(1024)
256                 except socket.timeout:
257                     timeout = True
258                 except ssl.SSLError:
259                     timeout = True
260                 except socket.error, err:
261                     if err.errno in [11, 10035]:
262                         print_error("socket errno", err.errno)
263                         time.sleep(0.1)
264                         continue
265                     else:
266                         traceback.print_exc(file=sys.stdout)
267                         raise
268
269                 if timeout:
270                     # ping the server with server.version, as a real ping does not exist yet
271                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
272                     continue
273
274                 out += msg
275                 self.bytes_received += len(msg)
276                 if msg == '': 
277                     self.is_connected = False
278
279                 while True:
280                     s = out.find('\n')
281                     if s==-1: break
282                     c = out[0:s]
283                     out = out[s+1:]
284                     c = json.loads(c)
285                     self.queue_json_response(c)
286
287         except:
288             traceback.print_exc(file=sys.stdout)
289
290         self.is_connected = False
291
292
293     def send_tcp(self, messages, callback):
294         """return the ids of the requests that we sent"""
295         out = ''
296         ids = []
297         for m in messages:
298             method, params = m 
299             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
300             self.unanswered_requests[self.message_id] = method, params, callback
301             ids.append(self.message_id)
302             # uncomment to debug
303             # print "-->", request
304             self.message_id += 1
305             out += request + '\n'
306         while out:
307             try:
308                 sent = self.s.send( out )
309                 out = out[sent:]
310             except socket.error,e:
311                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
312                     print_error( "EAGAIN: retrying")
313                     time.sleep(0.1)
314                     continue
315                 else:
316                     traceback.print_exc(file=sys.stdout)
317                     # this happens when we get disconnected
318                     print_error( "Not connected, cannot send" )
319                     return None
320         return ids
321
322
323
324     def __init__(self, config=None):
325         #self.server = random.choice(filter_protocol(DEFAULT_SERVERS, 's'))
326         self.proxy = None
327
328         if config is None:
329             from simple_config import SimpleConfig
330             config = SimpleConfig()
331
332         threading.Thread.__init__(self)
333         self.daemon = True
334         self.config = config
335         self.connect_event = threading.Event()
336
337         self.subscriptions = {}
338         self.lock = threading.Lock()
339
340         self.servers = {} # actual list from IRC
341         self.rtime = 0
342         self.bytes_received = 0
343         self.is_connected = False
344
345         # init with None server, in case we are offline 
346         self.init_server(None, None)
347
348
349
350
351     def init_interface(self):
352         if self.config.get('server'):
353             self.init_with_server(self.config)
354         else:
355             if self.config.get('auto_cycle') is None:
356                 self.config.set_key('auto_cycle', True, False)
357
358         if not self.is_connected: 
359             self.connect_event.set()
360             return
361
362         self.connect_event.set()
363
364
365     def init_with_server(self, config):
366             
367         s = config.get('server')
368         host, port, protocol = s.split(':')
369         port = int(port)
370
371         self.protocol = protocol
372         proxy = self.parse_proxy_options(config.get('proxy'))
373         self.server = host + ':%d:%s'%(port, protocol)
374
375         #print protocol, host, port
376         if protocol in 'st':
377             self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
378         elif protocol in 'gh':
379             self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
380         else:
381             raise BaseException('Unknown protocol: %s'%protocol)
382
383
384     def send(self, messages, callback):
385
386         sub = []
387         for message in messages:
388             m, v = message
389             if m[-10:] == '.subscribe':
390                 sub.append(message)
391
392         if sub:
393             with self.lock:
394                 if self.subscriptions.get(callback) is None: 
395                     self.subscriptions[callback] = []
396                 for message in sub:
397                     if message not in self.subscriptions[callback]:
398                         self.subscriptions[callback].append(message)
399
400         if not self.is_connected: 
401             return
402
403         if self.protocol in 'st':
404             with self.lock:
405                 out = self.send_tcp(messages, callback)
406         else:
407             # do not use lock, http is synchronous
408             out = self.send_http(messages, callback)
409
410         return out
411
412
413     def parse_proxy_options(self, s):
414         if type(s) == type({}): return s  # fixme: type should be fixed
415         if type(s) != type(""): return None  
416         if s.lower() == 'none': return None
417         proxy = { "mode":"socks5", "host":"localhost" }
418         args = s.split(':')
419         n = 0
420         if proxy_modes.count(args[n]) == 1:
421             proxy["mode"] = args[n]
422             n += 1
423         if len(args) > n:
424             proxy["host"] = args[n]
425             n += 1
426         if len(args) > n:
427             proxy["port"] = args[n]
428         else:
429             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
430         return proxy
431
432
433     def set_server(self, server, proxy=None):
434         "todo: remove this"
435         # raise an error if the format isnt correct
436         a,b,c = server.split(':')
437         b = int(b)
438         assert c in 'stgh'
439         # set the server
440         if server != self.server or proxy != self.proxy:
441             print "changing server:", server, proxy
442             self.server = server
443             self.proxy = proxy
444             if self.is_connected and self.protocol in 'st' and self.s:
445                 self.s.shutdown(socket.SHUT_RDWR)
446                 self.s.close()
447             self.is_connected = False  # this exits the polling loop
448             self.trigger_callback('disconnecting') # for actively disconnecting
449
450
451     def stop(self):
452         if self.is_connected and self.protocol in 'st' and self.s:
453             self.s.shutdown(socket.SHUT_RDWR)
454             self.s.close()
455
456
457     def is_up_to_date(self):
458         return self.unanswered_requests == {}
459
460
461     def synchronous_get(self, requests, timeout=100000000):
462         # todo: use generators, unanswered_requests should be a list of arrays...
463         q = Queue.Queue()
464         ids = self.send(requests, lambda i,r: queue.put(r))
465         id2 = ids[:]
466         res = {}
467         while ids:
468             r = queue.get(True, timeout)
469             _id = r.get('id')
470             if _id in ids:
471                 ids.remove(_id)
472                 res[_id] = r.get('result')
473         out = []
474         for _id in id2:
475             out.append(res[_id])
476         return out
477
478
479     def start(self, queue):
480         self.queue = queue
481         threading.Thread.start(self)
482
483
484     def run(self):
485         self.init_interface()
486         if self.is_connected:
487             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
488             self.change_status()
489             self.run_tcp() if self.protocol in 'st' else self.run_http()
490         self.change_status()
491         
492
493     def change_status(self):
494         #print "change status", self.server, self.is_connected
495         self.queue.put(self)
496