ec76bc6d9a503fa37abbd93ff4e3897da9000122
[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, ast, re, errno, os
21 import threading, traceback, sys, time, json, Queue
22 import socks
23 import socket
24 import ssl
25
26 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
27 from util import print_error, print_msg
28
29
30 DEFAULT_TIMEOUT = 5
31 proxy_modes = ['socks4', 'socks5', 'http']
32
33
34 class Interface(threading.Thread):
35
36
37     def __init__(self, config=None):
38
39         if config is None:
40             from simple_config import SimpleConfig
41             config = SimpleConfig()
42
43         threading.Thread.__init__(self)
44         self.daemon = True
45         self.config = config
46         self.connect_event = threading.Event()
47
48         self.subscriptions = {}
49         self.lock = threading.Lock()
50
51         self.rtime = 0
52         self.bytes_received = 0
53         self.is_connected = False
54         self.poll_interval = 1
55
56         #json
57         self.message_id = 0
58         self.unanswered_requests = {}
59         self.pending_transactions_for_notifications= []
60
61         # parse server
62         s = config.get('server')
63         host, port, protocol = s.split(':')
64         port = int(port)
65             
66         if protocol not in 'ghst':
67             raise BaseException('Unknown protocol: %s'%protocol)
68
69         self.host = host
70         self.port = port
71         self.protocol = protocol
72         self.use_ssl = ( protocol in 'sg' )
73         self.proxy = self.parse_proxy_options(config.get('proxy'))
74         if self.proxy:
75             self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
76         self.server = host + ':%d:%s'%(port, protocol)
77
78
79
80     def queue_json_response(self, c):
81
82         # uncomment to debug
83         # print_error( "<--",c )
84
85         msg_id = c.get('id')
86         error = c.get('error')
87         
88         if error:
89             print_error("received error:", c)
90             if msg_id is not None:
91                 with self.lock: 
92                     method, params, callback = self.unanswered_requests.pop(msg_id)
93                 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
94
95             return
96
97         if msg_id is not None:
98             with self.lock: 
99                 method, params, callback = self.unanswered_requests.pop(msg_id)
100             result = c.get('result')
101
102         else:
103             # notification
104             method = c.get('method')
105             params = c.get('params')
106
107             if method == 'blockchain.numblocks.subscribe':
108                 result = params[0]
109                 params = []
110
111             elif method == 'blockchain.headers.subscribe':
112                 result = params[0]
113                 params = []
114
115             elif method == 'blockchain.address.subscribe':
116                 addr = params[0]
117                 result = params[1]
118                 params = [addr]
119
120             with self.lock:
121                 for k,v in self.subscriptions.items():
122                     if (method, params) in v:
123                         callback = k
124                         break
125                 else:
126                     print_error( "received unexpected notification", method, params)
127                     print_error( self.subscriptions )
128                     return
129
130
131         callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
132
133
134     def on_version(self, i, result):
135         self.server_version = result
136
137
138     def init_http(self, host, port, proxy=None, use_ssl=True):
139         self.session_id = None
140         self.is_connected = True
141         self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
142         try:
143             self.poll()
144         except:
145             print_error("http init session failed")
146             self.is_connected = False
147             return
148
149         if self.session_id:
150             print_error('http session:',self.session_id)
151             self.is_connected = True
152         else:
153             self.is_connected = False
154
155     def run_http(self):
156         self.is_connected = True
157         while self.is_connected:
158             try:
159                 if self.session_id:
160                     self.poll()
161                 time.sleep(self.poll_interval)
162             except socket.gaierror:
163                 break
164             except socket.error:
165                 break
166             except:
167                 traceback.print_exc(file=sys.stdout)
168                 break
169             
170         self.is_connected = False
171
172                 
173     def poll(self):
174         self.send([])
175
176
177     def send_http(self, messages, callback):
178         import urllib2, json, time, cookielib
179         print_error( "send_http", messages )
180         
181         if self.proxy:
182             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
183             socks.wrapmodule(urllib2)
184
185         cj = cookielib.CookieJar()
186         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
187         urllib2.install_opener(opener)
188
189         t1 = time.time()
190
191         data = []
192         for m in messages:
193             method, params = m
194             if type(params) != type([]): params = [params]
195             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
196             self.unanswered_requests[self.message_id] = method, params, callback
197             self.message_id += 1
198
199         if data:
200             data_json = json.dumps(data)
201         else:
202             # poll with GET
203             data_json = None 
204
205             
206         headers = {'content-type': 'application/json'}
207         if self.session_id:
208             headers['cookie'] = 'SESSION=%s'%self.session_id
209
210         try:
211             req = urllib2.Request(self.connection_msg, data_json, headers)
212             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
213         except:
214             return
215
216         for index, cookie in enumerate(cj):
217             if cookie.name=='SESSION':
218                 self.session_id = cookie.value
219
220         response = response_stream.read()
221         self.bytes_received += len(response)
222         if response: 
223             response = json.loads( response )
224             if type(response) is not type([]):
225                 self.queue_json_response(response)
226             else:
227                 for item in response:
228                     self.queue_json_response(item)
229
230         if response: 
231             self.poll_interval = 1
232         else:
233             if self.poll_interval < 15: 
234                 self.poll_interval += 1
235         #print self.poll_interval, response
236
237         self.rtime = time.time() - t1
238         self.is_connected = True
239
240
241
242
243     def start_tcp(self):
244
245         if self.proxy is not None:
246
247             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
248             socket.socket = socks.socksocket
249             # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
250             def getaddrinfo(*args):
251                 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
252             socket.getaddrinfo = getaddrinfo
253
254         if self.use_ssl:
255             cert_path = os.path.join( self.config.get('path'), 'certs', self.host)
256
257             if not os.path.exists(cert_path):
258                 # get server certificate.
259                 # Do not use ssl.get_server_certificate because it does not work with proxy
260                 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
261                 try:
262                     s.connect((self.host, self.port))
263                 except:
264                     print_error("failed to connect", self.host, self.port)
265                     return
266
267                 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
268                 dercert = s.getpeercert(True)
269                 s.close()
270                 cert = ssl.DER_cert_to_PEM_cert(dercert)
271
272                 #from OpenSSL import crypto as c
273                 #_cert = c.load_certificate(c.FILETYPE_PEM, cert)
274                 #notAfter = _cert.get_notAfter() 
275                 #notBefore = _cert.get_notBefore() 
276                 #now = time.time()
277                 #if now > time.mktime( time.strptime(notAfter[:-1] + "GMT", "%Y%m%d%H%M%S%Z") ):
278                 #    print "deprecated cert", host, notAfter
279                 #    return
280                 #if now < time.mktime( time.strptime(notBefore[:-1] + "GMT", "%Y%m%d%H%M%S%Z") ):
281                 #    print "notbefore", host, notBefore
282                 #    return
283
284                 with open(cert_path,"w") as f:
285                     print_error("saving certificate for",self.host)
286                     f.write(cert)
287
288
289         s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
290         s.settimeout(2)
291         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
292
293         try:
294             s.connect(( self.host.encode('ascii'), int(self.port)))
295         except:
296             print_error("failed to connect", self.host, self.port)
297             return
298
299         if self.use_ssl:
300             try:
301                 s = ssl.wrap_socket(s,
302                                     ssl_version=ssl.PROTOCOL_SSLv3,
303                                     cert_reqs=ssl.CERT_REQUIRED,
304                                     ca_certs=cert_path,
305                                     do_handshake_on_connect=True)
306             except ssl.SSLError, e:
307                 print_error("SSL error:", self.host, e)
308                 if e.errno == 1:
309                     # delete the certificate so we will download a new one
310                     os.unlink(cert_path)
311                 return
312             except:
313                 traceback.print_exc(file=sys.stdout)
314                 print_error("wrap_socket failed", self.host)
315                 return
316
317             # hostname verification (disabled)
318             #from backports.ssl_match_hostname import match_hostname, CertificateError
319             #try:
320             #    match_hostname(s.getpeercert(), self.host)
321             #    print_error("hostname matches", self.host)
322             #except CertificateError, ce:
323             #    print_error("hostname does not match", self.host, s.getpeercert())
324             #    return
325
326         s.settimeout(60)
327         self.s = s
328         self.is_connected = True
329         print_error("connected to", self.host, self.port)
330
331
332     def run_tcp(self):
333         try:
334             #if self.use_ssl: self.s.do_handshake()
335             out = ''
336             while self.is_connected:
337                 try: 
338                     timeout = False
339                     msg = self.s.recv(1024)
340                 except socket.timeout:
341                     timeout = True
342                 except ssl.SSLError:
343                     timeout = True
344                 except socket.error, err:
345                     if err.errno in [11, 10035]:
346                         print_error("socket errno", err.errno)
347                         time.sleep(0.1)
348                         continue
349                     else:
350                         traceback.print_exc(file=sys.stdout)
351                         raise
352
353                 if timeout:
354                     # ping the server with server.version, as a real ping does not exist yet
355                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
356                     continue
357
358                 out += msg
359                 self.bytes_received += len(msg)
360                 if msg == '': 
361                     self.is_connected = False
362
363                 while True:
364                     s = out.find('\n')
365                     if s==-1: break
366                     c = out[0:s]
367                     out = out[s+1:]
368                     c = json.loads(c)
369                     self.queue_json_response(c)
370
371         except:
372             traceback.print_exc(file=sys.stdout)
373
374         self.is_connected = False
375
376
377     def send_tcp(self, messages, callback):
378         """return the ids of the requests that we sent"""
379         out = ''
380         ids = []
381         for m in messages:
382             method, params = m 
383             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
384             self.unanswered_requests[self.message_id] = method, params, callback
385             ids.append(self.message_id)
386             # uncomment to debug
387             # print "-->", request
388             self.message_id += 1
389             out += request + '\n'
390         while out:
391             try:
392                 sent = self.s.send( out )
393                 out = out[sent:]
394             except socket.error,e:
395                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
396                     print_error( "EAGAIN: retrying")
397                     time.sleep(0.1)
398                     continue
399                 else:
400                     traceback.print_exc(file=sys.stdout)
401                     # this happens when we get disconnected
402                     print_error( "Not connected, cannot send" )
403                     return None
404         return ids
405
406
407
408
409
410     def start_interface(self):
411
412         if self.protocol in 'st':
413             self.start_tcp()
414         elif self.protocol in 'gh':
415             self.start_http()
416
417         self.connect_event.set()
418
419
420
421     def stop_subscriptions(self):
422         for callback in self.subscriptions.keys():
423             callback(self, None)
424         self.subscriptions = {}
425
426
427     def send(self, messages, callback):
428
429         sub = []
430         for message in messages:
431             m, v = message
432             if m[-10:] == '.subscribe':
433                 sub.append(message)
434
435         if sub:
436             with self.lock:
437                 if self.subscriptions.get(callback) is None: 
438                     self.subscriptions[callback] = []
439                 for message in sub:
440                     if message not in self.subscriptions[callback]:
441                         self.subscriptions[callback].append(message)
442
443         if not self.is_connected: 
444             return
445
446         if self.protocol in 'st':
447             with self.lock:
448                 out = self.send_tcp(messages, callback)
449         else:
450             # do not use lock, http is synchronous
451             out = self.send_http(messages, callback)
452
453         return out
454
455
456     def parse_proxy_options(self, s):
457         if type(s) == type({}): return s  # fixme: type should be fixed
458         if type(s) != type(""): return None  
459         if s.lower() == 'none': return None
460         proxy = { "mode":"socks5", "host":"localhost" }
461         args = s.split(':')
462         n = 0
463         if proxy_modes.count(args[n]) == 1:
464             proxy["mode"] = args[n]
465             n += 1
466         if len(args) > n:
467             proxy["host"] = args[n]
468             n += 1
469         if len(args) > n:
470             proxy["port"] = args[n]
471         else:
472             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
473         return proxy
474
475
476
477     def stop(self):
478         if self.is_connected and self.protocol in 'st' and self.s:
479             self.s.shutdown(socket.SHUT_RDWR)
480             self.s.close()
481
482
483     def is_up_to_date(self):
484         return self.unanswered_requests == {}
485
486
487     def synchronous_get(self, requests, timeout=100000000):
488         # todo: use generators, unanswered_requests should be a list of arrays...
489         queue = Queue.Queue()
490         ids = self.send(requests, lambda i,r: queue.put(r))
491         id2 = ids[:]
492         res = {}
493         while ids:
494             r = queue.get(True, timeout)
495             _id = r.get('id')
496             if _id in ids:
497                 ids.remove(_id)
498                 res[_id] = r.get('result')
499         out = []
500         for _id in id2:
501             out.append(res[_id])
502         return out
503
504
505     def start(self, queue):
506         self.queue = queue
507         threading.Thread.start(self)
508
509
510     def run(self):
511         self.start_interface()
512         if self.is_connected:
513             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
514             self.change_status()
515             self.run_tcp() if self.protocol in 'st' else self.run_http()
516         self.change_status()
517         
518
519     def change_status(self):
520         #print "change status", self.server, self.is_connected
521         self.queue.put(self)
522
523
524
525 if __name__ == "__main__":
526     
527     q = Queue.Queue()
528     i = Interface({'server':'btc.it-zone.org:50002:s', 'path':'/extra/key/wallet', 'verbose':True})
529     i.start(q)
530     time.sleep(1)
531     exit()
532
533