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