3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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/>.
20 import random, ast, re, errno, os
21 import threading, traceback, sys, time, json, Queue
26 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
27 from util import print_error, print_msg
28 from simple_config import SimpleConfig
32 proxy_modes = ['socks4', 'socks5', 'http']
35 def check_cert(host, cert):
36 from OpenSSL import crypto as c
37 _cert = c.load_certificate(c.FILETYPE_PEM, cert)
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()
49 def cert_has_expired(cert_path):
53 print_error("Warning: cannot import OpenSSL")
55 from OpenSSL import crypto as c
56 with open(cert_path) as f:
58 _cert = c.load_certificate(c.FILETYPE_PEM, cert)
59 return _cert.has_expired()
62 def check_certificates():
63 config = SimpleConfig()
64 mydir = os.path.join(config.path, "certs")
65 certs = os.listdir(mydir)
68 p = os.path.join(mydir,c)
74 def cert_verify_hostname(s):
75 # hostname verification (disabled)
76 from backports.ssl_match_hostname import match_hostname, CertificateError
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)
85 class Interface(threading.Thread):
88 def __init__(self, server, config = None):
90 threading.Thread.__init__(self)
92 self.config = config if config is not None else SimpleConfig()
93 self.connect_event = threading.Event()
95 self.subscriptions = {}
96 self.lock = threading.Lock()
99 self.bytes_received = 0
100 self.is_connected = False
101 self.poll_interval = 1
103 self.debug = False # dump network messages. can be changed at runtime using the console
107 self.unanswered_requests = {}
108 self.pending_transactions_for_notifications= []
113 host, port, protocol = self.server.split(':')
119 if protocol not in 'ghst':
120 raise Exception('Unknown protocol: %s'%protocol)
124 self.protocol = protocol
125 self.use_ssl = ( protocol in 'sg' )
126 self.proxy = self.parse_proxy_options(self.config.get('proxy'))
128 self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
134 def queue_json_response(self, c):
138 print_error( "<--",c )
141 error = c.get('error')
144 print_error("received error:", c)
145 if msg_id is not None:
147 method, params, callback = self.unanswered_requests.pop(msg_id)
148 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
152 if msg_id is not None:
154 method, params, callback = self.unanswered_requests.pop(msg_id)
155 result = c.get('result')
159 method = c.get('method')
160 params = c.get('params')
162 if method == 'blockchain.numblocks.subscribe':
166 elif method == 'blockchain.headers.subscribe':
170 elif method == 'blockchain.address.subscribe':
176 for k,v in self.subscriptions.items():
177 if (method, params) in v:
181 print_error( "received unexpected notification", method, params)
182 print_error( self.subscriptions )
186 callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
189 def on_version(self, i, result):
190 self.server_version = result
193 def start_http(self):
194 self.session_id = None
195 self.is_connected = True
196 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
200 print_error("http init session failed")
201 self.is_connected = False
205 print_error('http session:',self.session_id)
206 self.is_connected = True
208 self.is_connected = False
211 self.is_connected = True
212 while self.is_connected:
216 time.sleep(self.poll_interval)
217 except socket.gaierror:
222 traceback.print_exc(file=sys.stdout)
225 self.is_connected = False
232 def send_http(self, messages, callback):
233 import urllib2, json, time, cookielib
234 print_error( "send_http", messages )
237 socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
238 socks.wrapmodule(urllib2)
240 cj = cookielib.CookieJar()
241 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
242 urllib2.install_opener(opener)
249 if type(params) != type([]): params = [params]
250 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
251 self.unanswered_requests[self.message_id] = method, params, callback
255 data_json = json.dumps(data)
261 headers = {'content-type': 'application/json'}
263 headers['cookie'] = 'SESSION=%s'%self.session_id
266 req = urllib2.Request(self.connection_msg, data_json, headers)
267 response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
271 for index, cookie in enumerate(cj):
272 if cookie.name=='SESSION':
273 self.session_id = cookie.value
275 response = response_stream.read()
276 self.bytes_received += len(response)
278 response = json.loads( response )
279 if type(response) is not type([]):
280 self.queue_json_response(response)
282 for item in response:
283 self.queue_json_response(item)
286 self.poll_interval = 1
288 if self.poll_interval < 15:
289 self.poll_interval += 1
290 #print self.poll_interval, response
292 self.rtime = time.time() - t1
293 self.is_connected = True
300 self.connection_msg = self.host + ':%d' % self.port
302 if self.proxy is not None:
304 socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
305 socket.socket = socks.socksocket
306 # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
307 def getaddrinfo(*args):
308 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
309 socket.getaddrinfo = getaddrinfo
312 cert_path = os.path.join( self.config.path, 'certs', self.host)
314 if not os.path.exists(cert_path):
316 # get server certificate.
317 # Do not use ssl.get_server_certificate because it does not work with proxy
318 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
320 s = socket.socket( res[0], socket.SOCK_STREAM )
327 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
328 except ssl.SSLError, e:
329 print_error("SSL error retrieving SSL certificate:", self.host, e)
337 dercert = s.getpeercert(True)
339 cert = ssl.DER_cert_to_PEM_cert(dercert)
340 # workaround android bug
341 cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert)
342 temporary_path = cert_path + '.temp'
343 with open(temporary_path,"w") as f:
349 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
351 s = socket.socket( res[0], socket.SOCK_STREAM )
353 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
361 print_error("failed to connect", self.host, self.port)
366 s = ssl.wrap_socket(s,
367 ssl_version=ssl.PROTOCOL_SSLv3,
368 cert_reqs=ssl.CERT_REQUIRED,
369 ca_certs= (temporary_path if is_new else cert_path),
370 do_handshake_on_connect=True)
371 except ssl.SSLError, e:
372 print_error("SSL error:", self.host, e)
376 rej = cert_path + '.rej'
377 if os.path.exists(rej):
379 os.rename(temporary_path, rej)
381 if cert_has_expired(cert_path):
382 print_error("certificate has expired:", cert_path)
385 print_msg("wrong certificate", self.host)
388 print_error("wrap_socket failed", self.host)
389 traceback.print_exc(file=sys.stdout)
393 print_error("saving certificate for", self.host)
394 os.rename(temporary_path, cert_path)
398 self.is_connected = True
399 print_error("connected to", self.host, self.port)
404 #if self.use_ssl: self.s.do_handshake()
406 while self.is_connected:
409 msg = self.s.recv(1024)
410 except socket.timeout:
414 except socket.error, err:
415 if err.errno in [11, 10035]:
416 print_error("socket errno", err.errno)
420 traceback.print_exc(file=sys.stdout)
424 # ping the server with server.version, as a real ping does not exist yet
425 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
429 self.bytes_received += len(msg)
431 self.is_connected = False
439 self.queue_json_response(c)
442 traceback.print_exc(file=sys.stdout)
444 self.is_connected = False
447 def send_tcp(self, messages, callback):
448 """return the ids of the requests that we sent"""
453 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
454 self.unanswered_requests[self.message_id] = method, params, callback
455 ids.append(self.message_id)
459 out += request + '\n'
462 sent = self.s.send( out )
464 except socket.error,e:
465 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
466 print_error( "EAGAIN: retrying")
470 traceback.print_exc(file=sys.stdout)
471 # this happens when we get disconnected
472 print_error( "Not connected, cannot send" )
480 def start_interface(self):
482 if self.protocol in 'st':
484 elif self.protocol in 'gh':
487 self.connect_event.set()
491 def stop_subscriptions(self):
492 for callback in self.subscriptions.keys():
494 self.subscriptions = {}
497 def send(self, messages, callback):
500 for message in messages:
502 if m[-10:] == '.subscribe':
507 if self.subscriptions.get(callback) is None:
508 self.subscriptions[callback] = []
510 if message not in self.subscriptions[callback]:
511 self.subscriptions[callback].append(message)
513 if not self.is_connected:
514 print_error("interface: trying to send while not connected")
517 if self.protocol in 'st':
519 out = self.send_tcp(messages, callback)
521 # do not use lock, http is synchronous
522 out = self.send_http(messages, callback)
527 def parse_proxy_options(self, s):
528 if type(s) == type({}): return s # fixme: type should be fixed
529 if type(s) != type(""): return None
530 if s.lower() == 'none': return None
531 proxy = { "mode":"socks5", "host":"localhost" }
534 if proxy_modes.count(args[n]) == 1:
535 proxy["mode"] = args[n]
538 proxy["host"] = args[n]
541 proxy["port"] = args[n]
543 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
549 if self.is_connected and self.protocol in 'st' and self.s:
550 self.s.shutdown(socket.SHUT_RDWR)
554 def is_up_to_date(self):
555 return self.unanswered_requests == {}
559 def start(self, queue = None, wait = False):
562 self.queue = queue if queue else Queue.Queue()
563 threading.Thread.start(self)
565 self.connect_event.wait()
569 self.start_interface()
570 if self.is_connected:
571 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
573 self.run_tcp() if self.protocol in 'st' else self.run_http()
577 def change_status(self):
578 #print "change status", self.server, self.is_connected
583 if __name__ == "__main__":