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()
50 def check_certificates():
51 config = SimpleConfig()
52 mydir = os.path.join(config.path, "certs")
53 certs = os.listdir(mydir)
56 p = os.path.join(mydir,c)
62 def cert_verify_hostname(s):
63 # hostname verification (disabled)
64 from backports.ssl_match_hostname import match_hostname, CertificateError
66 match_hostname(s.getpeercert(True), host)
67 print_error("hostname matches", host)
68 except CertificateError, ce:
69 print_error("hostname did not match", host)
73 class Interface(threading.Thread):
76 def __init__(self, config=None):
79 config = SimpleConfig()
81 threading.Thread.__init__(self)
84 self.connect_event = threading.Event()
86 self.subscriptions = {}
87 self.lock = threading.Lock()
90 self.bytes_received = 0
91 self.is_connected = False
92 self.poll_interval = 1
96 self.unanswered_requests = {}
97 self.pending_transactions_for_notifications= []
100 s = config.get('server')
101 host, port, protocol = s.split(':')
104 if protocol not in 'ghst':
105 raise BaseException('Unknown protocol: %s'%protocol)
109 self.protocol = protocol
110 self.use_ssl = ( protocol in 'sg' )
111 self.proxy = self.parse_proxy_options(config.get('proxy'))
113 self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
114 self.server = host + ':%d:%s'%(port, protocol)
120 def queue_json_response(self, c):
123 # print_error( "<--",c )
126 error = c.get('error')
129 print_error("received error:", c)
130 if msg_id is not None:
132 method, params, callback = self.unanswered_requests.pop(msg_id)
133 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
137 if msg_id is not None:
139 method, params, callback = self.unanswered_requests.pop(msg_id)
140 result = c.get('result')
144 method = c.get('method')
145 params = c.get('params')
147 if method == 'blockchain.numblocks.subscribe':
151 elif method == 'blockchain.headers.subscribe':
155 elif method == 'blockchain.address.subscribe':
161 for k,v in self.subscriptions.items():
162 if (method, params) in v:
166 print_error( "received unexpected notification", method, params)
167 print_error( self.subscriptions )
171 callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
174 def on_version(self, i, result):
175 self.server_version = result
178 def start_http(self):
179 self.session_id = None
180 self.is_connected = True
181 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
185 print_error("http init session failed")
186 self.is_connected = False
190 print_error('http session:',self.session_id)
191 self.is_connected = True
193 self.is_connected = False
196 self.is_connected = True
197 while self.is_connected:
201 time.sleep(self.poll_interval)
202 except socket.gaierror:
207 traceback.print_exc(file=sys.stdout)
210 self.is_connected = False
217 def send_http(self, messages, callback):
218 import urllib2, json, time, cookielib
219 print_error( "send_http", messages )
222 socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
223 socks.wrapmodule(urllib2)
225 cj = cookielib.CookieJar()
226 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
227 urllib2.install_opener(opener)
234 if type(params) != type([]): params = [params]
235 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
236 self.unanswered_requests[self.message_id] = method, params, callback
240 data_json = json.dumps(data)
246 headers = {'content-type': 'application/json'}
248 headers['cookie'] = 'SESSION=%s'%self.session_id
251 req = urllib2.Request(self.connection_msg, data_json, headers)
252 response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
256 for index, cookie in enumerate(cj):
257 if cookie.name=='SESSION':
258 self.session_id = cookie.value
260 response = response_stream.read()
261 self.bytes_received += len(response)
263 response = json.loads( response )
264 if type(response) is not type([]):
265 self.queue_json_response(response)
267 for item in response:
268 self.queue_json_response(item)
271 self.poll_interval = 1
273 if self.poll_interval < 15:
274 self.poll_interval += 1
275 #print self.poll_interval, response
277 self.rtime = time.time() - t1
278 self.is_connected = True
285 self.connection_msg = self.host + ':%d' % self.port
287 if self.proxy is not None:
289 socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
290 socket.socket = socks.socksocket
291 # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
292 def getaddrinfo(*args):
293 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
294 socket.getaddrinfo = getaddrinfo
297 cert_path = os.path.join( self.config.get('path'), 'certs', self.host)
299 if not os.path.exists(cert_path):
301 # get server certificate.
302 # Do not use ssl.get_server_certificate because it does not work with proxy
303 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
305 s.connect((self.host, self.port))
307 # print_error("failed to connect", self.host, self.port)
310 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
311 dercert = s.getpeercert(True)
313 cert = ssl.DER_cert_to_PEM_cert(dercert)
314 temporary_path = cert_path + '.temp'
315 with open(temporary_path,"w") as f:
322 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
324 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
327 s.connect(( self.host.encode('ascii'), int(self.port)))
329 print_error("failed to connect", self.host, self.port)
334 s = ssl.wrap_socket(s,
335 ssl_version=ssl.PROTOCOL_SSLv3,
336 cert_reqs=ssl.CERT_REQUIRED,
337 ca_certs= (temporary_path if is_new else cert_path),
338 do_handshake_on_connect=True)
339 except ssl.SSLError, e:
340 print_error("SSL error:", self.host, e)
344 os.rename(temporary_path, cert_path + '.rej')
346 from OpenSSL import crypto as c
347 with open(cert_path) as f:
349 _cert = c.load_certificate(c.FILETYPE_PEM, cert)
350 if _cert.has_expired():
351 print_error("certificate has expired:", cert_path)
354 print_msg("wrong certificate", self.host)
358 print_error("wrap_socket failed", self.host)
359 traceback.print_exc(file=sys.stdout)
363 print_error("saving certificate for", self.host)
364 os.rename(temporary_path, cert_path)
369 self.is_connected = True
370 print_error("connected to", self.host, self.port)
375 #if self.use_ssl: self.s.do_handshake()
377 while self.is_connected:
380 msg = self.s.recv(1024)
381 except socket.timeout:
385 except socket.error, err:
386 if err.errno in [11, 10035]:
387 print_error("socket errno", err.errno)
391 traceback.print_exc(file=sys.stdout)
395 # ping the server with server.version, as a real ping does not exist yet
396 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
400 self.bytes_received += len(msg)
402 self.is_connected = False
410 self.queue_json_response(c)
413 traceback.print_exc(file=sys.stdout)
415 self.is_connected = False
418 def send_tcp(self, messages, callback):
419 """return the ids of the requests that we sent"""
424 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
425 self.unanswered_requests[self.message_id] = method, params, callback
426 ids.append(self.message_id)
428 # print "-->", request
430 out += request + '\n'
433 sent = self.s.send( out )
435 except socket.error,e:
436 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
437 print_error( "EAGAIN: retrying")
441 traceback.print_exc(file=sys.stdout)
442 # this happens when we get disconnected
443 print_error( "Not connected, cannot send" )
451 def start_interface(self):
453 if self.protocol in 'st':
455 elif self.protocol in 'gh':
458 self.connect_event.set()
462 def stop_subscriptions(self):
463 for callback in self.subscriptions.keys():
465 self.subscriptions = {}
468 def send(self, messages, callback):
471 for message in messages:
473 if m[-10:] == '.subscribe':
478 if self.subscriptions.get(callback) is None:
479 self.subscriptions[callback] = []
481 if message not in self.subscriptions[callback]:
482 self.subscriptions[callback].append(message)
484 if not self.is_connected:
487 if self.protocol in 'st':
489 out = self.send_tcp(messages, callback)
491 # do not use lock, http is synchronous
492 out = self.send_http(messages, callback)
497 def parse_proxy_options(self, s):
498 if type(s) == type({}): return s # fixme: type should be fixed
499 if type(s) != type(""): return None
500 if s.lower() == 'none': return None
501 proxy = { "mode":"socks5", "host":"localhost" }
504 if proxy_modes.count(args[n]) == 1:
505 proxy["mode"] = args[n]
508 proxy["host"] = args[n]
511 proxy["port"] = args[n]
513 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
519 if self.is_connected and self.protocol in 'st' and self.s:
520 self.s.shutdown(socket.SHUT_RDWR)
524 def is_up_to_date(self):
525 return self.unanswered_requests == {}
528 def synchronous_get(self, requests, timeout=100000000):
529 # todo: use generators, unanswered_requests should be a list of arrays...
530 queue = Queue.Queue()
531 ids = self.send(requests, lambda i,r: queue.put(r))
535 r = queue.get(True, timeout)
539 res[_id] = r.get('result')
546 def start(self, queue):
548 threading.Thread.start(self)
552 self.start_interface()
553 if self.is_connected:
554 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
556 self.run_tcp() if self.protocol in 'st' else self.run_http()
560 def change_status(self):
561 #print "change status", self.server, self.is_connected
566 if __name__ == "__main__":