# along with this program. If not, see <http://www.gnu.org/licenses/>.
-import random, socket, ast, re
+import random, ast, re, errno, os
import threading, traceback, sys, time, json, Queue
+import socks
+import socket
+import ssl
-from version import ELECTRUM_VERSION
-from util import print_error
+from version import ELECTRUM_VERSION, PROTOCOL_VERSION
+from util import print_error, print_msg
+from simple_config import SimpleConfig
DEFAULT_TIMEOUT = 5
-DEFAULT_SERVERS = [
- 'electrum.novit.ro:50001:t',
- 'electrum.pdmc.net:50001:t',
- 'ecdsa.org:50001:t',
- 'electrum.bitcoins.sk:50001:t',
- 'uncle-enzo.info:50001:t',
- 'electrum.bytesized-hosting.com:50001:t',
- 'electrum.bitcoin.cz:50001:t',
- 'electrum.bitfoo.org:50001:t'
- ]
-
proxy_modes = ['socks4', 'socks5', 'http']
-def pick_random_server():
- return random.choice( DEFAULT_SERVERS )
-
+def check_cert(host, cert):
+ from OpenSSL import crypto as c
+ _cert = c.load_certificate(c.FILETYPE_PEM, cert)
+
+ m = "host: %s\n"%host
+ m += "has_expired: %s\n"% _cert.has_expired()
+ m += "pubkey: %s bits\n" % _cert.get_pubkey().bits()
+ m += "serial number: %s\n"% _cert.get_serial_number()
+ #m += "issuer: %s\n"% _cert.get_issuer()
+ #m += "algo: %s\n"% _cert.get_signature_algorithm()
+ m += "version: %s\n"% _cert.get_version()
+ print_msg(m)
+
+
+def cert_has_expired(cert_path):
+ try:
+ import OpenSSL
+ except:
+ print_error("Warning: cannot import OpenSSL")
+ return False
+ from OpenSSL import crypto as c
+ with open(cert_path) as f:
+ cert = f.read()
+ _cert = c.load_certificate(c.FILETYPE_PEM, cert)
+ return _cert.has_expired()
+
+
+def check_certificates():
+ config = SimpleConfig()
+ mydir = os.path.join(config.path, "certs")
+ certs = os.listdir(mydir)
+ for c in certs:
+ print c
+ p = os.path.join(mydir,c)
+ with open(p) as f:
+ cert = f.read()
+ check_cert(c, cert)
+
+
+def cert_verify_hostname(s):
+ # hostname verification (disabled)
+ from backports.ssl_match_hostname import match_hostname, CertificateError
+ try:
+ match_hostname(s.getpeercert(True), host)
+ print_error("hostname matches", host)
+ except CertificateError, ce:
+ print_error("hostname did not match", host)
class Interface(threading.Thread):
- def register_callback(self, event, callback):
- with self.lock:
- self.callbacks[event] = callback
- def trigger_callback(self, event):
- with self.lock:
- callback = self.callbacks.get(event)
- if callback:
- callback()
-
+ def __init__(self, server, config = None):
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.config = config if config is not None else SimpleConfig()
+ self.connect_event = threading.Event()
- def init_server(self, host, port, proxy=None, use_ssl=True):
- self.host = host
- self.port = port
- self.proxy = proxy
- self.use_ssl = use_ssl
+ self.subscriptions = {}
+ self.lock = threading.Lock()
- self.servers = [] # actual list from IRC
self.rtime = 0
self.bytes_received = 0
-
- self.is_connected = True
+ self.is_connected = False
self.poll_interval = 1
+ self.debug = False # dump network messages. can be changed at runtime using the console
+
#json
self.message_id = 0
self.unanswered_requests = {}
+ self.pending_transactions_for_notifications= []
+
+ # parse server
+ self.server = server
+ host, port, protocol = self.server.split(':')
+ port = int(port)
+
+ if protocol not in 'ghst':
+ raise BaseException('Unknown protocol: %s'%protocol)
+
+ self.host = host
+ self.port = port
+ self.protocol = protocol
+ self.use_ssl = ( protocol in 'sg' )
+ self.proxy = self.parse_proxy_options(self.config.get('proxy'))
+ if self.proxy:
+ self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
+
+
def queue_json_response(self, c):
# uncomment to debug
- # print "<--",c
+ if self.debug:
+ print_error( "<--",c )
msg_id = c.get('id')
error = c.get('error')
if error:
- print "received error:", c
+ print_error("received error:", c)
+ if msg_id is not None:
+ with self.lock:
+ method, params, callback = self.unanswered_requests.pop(msg_id)
+ callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
+
return
if msg_id is not None:
with self.lock:
- method, params, channel = self.unanswered_requests.pop(msg_id)
+ method, params, callback = self.unanswered_requests.pop(msg_id)
result = c.get('result')
+
else:
- # notification. we should find the channel(s)..
+ # notification
method = c.get('method')
params = c.get('params')
- with self.lock:
- for k,v in self.subscriptions.items():
- if (method, params) in v:
- channel = k
- else:
- raise
if method == 'blockchain.numblocks.subscribe':
result = params[0]
params = []
+ elif method == 'blockchain.headers.subscribe':
+ result = params[0]
+ params = []
+
elif method == 'blockchain.address.subscribe':
addr = params[0]
result = params[1]
params = [addr]
-
- response_queue = self.responses[channel]
- response_queue.put({'method':method, 'params':params, 'result':result, 'id':msg_id})
-
+ with self.lock:
+ for k,v in self.subscriptions.items():
+ if (method, params) in v:
+ callback = k
+ break
+ else:
+ print_error( "received unexpected notification", method, params)
+ print_error( self.subscriptions )
+ return
- def get_response(self, channel='default', block=True, timeout=10000000000):
- return self.responses[channel].get(block, timeout)
+ callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
- def register_channel(self, channel):
- with self.lock:
- self.responses[channel] = Queue.Queue()
- def poke(self, channel):
- self.responses[channel].put(None)
+ def on_version(self, i, result):
+ self.server_version = result
- def init_http(self, host, port, proxy=None, use_ssl=True):
- self.init_server(host, port, proxy, use_ssl)
+ def start_http(self):
self.session_id = None
+ self.is_connected = True
self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
+ try:
+ self.poll()
+ except:
+ print_error("http init session failed")
+ self.is_connected = False
+ return
+ if self.session_id:
+ print_error('http session:',self.session_id)
+ self.is_connected = True
+ else:
+ self.is_connected = False
def run_http(self):
self.is_connected = True
def poll(self):
- self.send([])
+ self.send([], None)
- def send_http(self, messages, channel='default'):
+ def send_http(self, messages, callback):
import urllib2, json, time, cookielib
+ print_error( "send_http", messages )
if self.proxy:
- import socks
- socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]), self.proxy["host"], int(self.proxy["port"]) )
+ socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
socks.wrapmodule(urllib2)
cj = cookielib.CookieJar()
method, params = m
if type(params) != type([]): params = [params]
data.append( { 'method':method, 'id':self.message_id, 'params':params } )
- self.unanswered_requests[self.message_id] = method, params, channel
+ self.unanswered_requests[self.message_id] = method, params, callback
self.message_id += 1
if data:
if self.session_id:
headers['cookie'] = 'SESSION=%s'%self.session_id
- req = urllib2.Request(self.connection_msg, data_json, headers)
- response_stream = urllib2.urlopen(req)
+ try:
+ req = urllib2.Request(self.connection_msg, data_json, headers)
+ response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
+ except:
+ return
for index, cookie in enumerate(cj):
if cookie.name=='SESSION':
- def init_tcp(self, host, port, proxy=None, use_ssl=True):
- self.init_server(host, port, proxy, use_ssl)
+ def start_tcp(self):
- import ssl
- global proxy_modes
- self.connection_msg = "%s:%d"%(self.host,self.port)
- if self.proxy is None:
- s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
- else:
- self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
- import socks
- s = socks.socksocket()
- s.setproxy(proxy_modes.index(self.proxy["mode"]), self.proxy["host"], int(self.proxy["port"]) )
+ self.connection_msg = self.host + ':%d' % self.port
+
+ if self.proxy is not None:
+
+ socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
+ socket.socket = socks.socksocket
+ # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
+ def getaddrinfo(*args):
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
+ socket.getaddrinfo = getaddrinfo
if self.use_ssl:
- s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23)
-
+ cert_path = os.path.join( self.config.path, 'certs', self.host)
+
+ if not os.path.exists(cert_path):
+ is_new = True
+ # get server certificate.
+ # Do not use ssl.get_server_certificate because it does not work with proxy
+ s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
+ try:
+ s.connect((self.host, self.port))
+ except:
+ # print_error("failed to connect", self.host, self.port)
+ return
+
+ try:
+ s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
+ except ssl.SSLError, e:
+ print_error("SSL error:", self.host, e)
+ return
+ dercert = s.getpeercert(True)
+ s.close()
+ cert = ssl.DER_cert_to_PEM_cert(dercert)
+ temporary_path = cert_path + '.temp'
+ with open(temporary_path,"w") as f:
+ f.write(cert)
+
+ else:
+ is_new = False
+
+
+ s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.settimeout(2)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
try:
s.connect(( self.host.encode('ascii'), int(self.port)))
- s.settimeout(60)
- self.s = s
- self.is_connected = True
except:
- self.is_connected = False
- self.s = None
+ print_error("failed to connect", self.host, self.port)
+ return
+
+ if self.use_ssl:
+ try:
+ s = ssl.wrap_socket(s,
+ ssl_version=ssl.PROTOCOL_SSLv3,
+ cert_reqs=ssl.CERT_REQUIRED,
+ ca_certs= (temporary_path if is_new else cert_path),
+ do_handshake_on_connect=True)
+ except ssl.SSLError, e:
+ print_error("SSL error:", self.host, e)
+ if e.errno != 1:
+ return
+ if is_new:
+ os.rename(temporary_path, cert_path + '.rej')
+ else:
+ if cert_has_expired(cert_path):
+ print_error("certificate has expired:", cert_path)
+ os.unlink(cert_path)
+ else:
+ print_msg("wrong certificate", self.host)
+ return
+ except:
+ print_error("wrap_socket failed", self.host)
+ traceback.print_exc(file=sys.stdout)
+ return
+
+ if is_new:
+ print_error("saving certificate for", self.host)
+ os.rename(temporary_path, cert_path)
+
+ s.settimeout(60)
+ self.s = s
+ self.is_connected = True
+ print_error("connected to", self.host, self.port)
def run_tcp(self):
try:
+ #if self.use_ssl: self.s.do_handshake()
out = ''
while self.is_connected:
- try: msg = self.s.recv(1024)
+ try:
+ timeout = False
+ msg = self.s.recv(1024)
except socket.timeout:
- print "timeout"
+ timeout = True
+ except ssl.SSLError:
+ timeout = True
+ except socket.error, err:
+ if err.errno in [11, 10035]:
+ print_error("socket errno", err.errno)
+ time.sleep(0.1)
+ continue
+ else:
+ traceback.print_exc(file=sys.stdout)
+ raise
+
+ if timeout:
# ping the server with server.version, as a real ping does not exist yet
- self.send([('server.version', [ELECTRUM_VERSION])])
+ self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
continue
+
out += msg
self.bytes_received += len(msg)
if msg == '':
self.is_connected = False
- def send_tcp(self, messages, channel='default'):
+ def send_tcp(self, messages, callback):
"""return the ids of the requests that we sent"""
out = ''
ids = []
for m in messages:
method, params = m
request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
- self.unanswered_requests[self.message_id] = method, params, channel
+ self.unanswered_requests[self.message_id] = method, params, callback
ids.append(self.message_id)
- # uncomment to debug
- # print "-->",request
+ if self.debug:
+ print "-->", request
self.message_id += 1
out += request + '\n'
while out:
- sent = self.s.send( out )
- out = out[sent:]
+ try:
+ sent = self.s.send( out )
+ out = out[sent:]
+ except socket.error,e:
+ if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
+ print_error( "EAGAIN: retrying")
+ time.sleep(0.1)
+ continue
+ else:
+ traceback.print_exc(file=sys.stdout)
+ # this happens when we get disconnected
+ print_error( "Not connected, cannot send" )
+ return None
return ids
- def __init__(self, config=None, loop=False):
-
- if config is None:
- from simple_config import SimpleConfig
- config = SimpleConfig()
-
- threading.Thread.__init__(self)
- self.daemon = True
- self.loop = loop
- self.config = config
- self.connect_event = threading.Event()
-
- self.subscriptions = {}
- self.responses = {}
- self.responses['default'] = Queue.Queue()
-
- self.callbacks = {}
- self.lock = threading.Lock()
+ def start_interface(self):
- def init_interface(self):
- if self.config.get('server'):
- self.init_with_server(self.config)
- else:
- print "Using random server..."
- servers = DEFAULT_SERVERS
- while servers:
- server = random.choice( servers )
- servers.remove(server)
- self.config.set_key('server', server, False)
- self.init_with_server(self.config)
- if self.is_connected: break
-
- if not servers:
- raise BaseException('no server available')
+ if self.protocol in 'st':
+ self.start_tcp()
+ elif self.protocol in 'gh':
+ self.start_http()
self.connect_event.set()
- if self.is_connected:
- self.send([('server.version', [ELECTRUM_VERSION])])
- self.trigger_callback('connected')
- else:
- self.trigger_callback('notconnected')
- #print_error("Failed to connect " + self.connection_msg)
- def init_with_server(self, config):
-
- s = config.get('server')
- host, port, protocol = s.split(':')
- port = int(port)
- self.protocol = protocol
- proxy = self.parse_proxy_options(config.get('proxy'))
- self.server = host + ':%d:%s'%(port, protocol)
-
- #print protocol, host, port
- if protocol in 'st':
- self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
- elif protocol in 'gh':
- self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
- else:
- raise BaseException('Unknown protocol: %s'%protocol)
+ def stop_subscriptions(self):
+ for callback in self.subscriptions.keys():
+ callback(self, None)
+ self.subscriptions = {}
- def send(self, messages, channel='default'):
+ def send(self, messages, callback):
sub = []
for message in messages:
if sub:
with self.lock:
- if self.subscriptions.get(channel) is None:
- self.subscriptions[channel] = []
- self.subscriptions[channel] += sub
+ if self.subscriptions.get(callback) is None:
+ self.subscriptions[callback] = []
+ for message in sub:
+ if message not in self.subscriptions[callback]:
+ self.subscriptions[callback].append(message)
+
+ if not self.is_connected:
+ print_error("interface: trying to send while not connected")
+ return
if self.protocol in 'st':
with self.lock:
- out = self.send_tcp(messages, channel)
+ out = self.send_tcp(messages, callback)
else:
# do not use lock, http is synchronous
- out = self.send_http(messages, channel)
+ out = self.send_http(messages, callback)
return out
- def resend_subscriptions(self):
- for channel, messages in self.subscriptions.items():
- if messages:
- self.send(messages, channel)
-
-
def parse_proxy_options(self, s):
if type(s) == type({}): return s # fixme: type should be fixed
return proxy
- def set_server(self, server, proxy=None):
- # raise an error if the format isnt correct
- a,b,c = server.split(':')
- b = int(b)
- assert c in 'stgh'
- # set the server
- if server != self.server or proxy != self.proxy:
- print "changing server:", server, proxy
- self.server = server
- self.proxy = proxy
- if self.protocol in 'st':
- self.s.shutdown(socket.SHUT_RDWR)
- self.s.close()
- self.is_connected = False # this exits the polling loop
-
-
- def is_empty(self, channel):
- q = self.responses.get(channel)
- if q:
- return q.empty()
- else:
- return True
-
-
- def get_pending_requests(self, channel):
- result = []
- with self.lock:
- for k, v in self.unanswered_requests.items():
- a, b, c = v
- if c == channel: result.append(k)
- return result
-
- def is_up_to_date(self, channel):
- return self.is_empty(channel) and not self.get_pending_requests(channel)
-
-
- def synchronous_get(self, requests, timeout=100000000):
- # todo: use generators, unanswered_requests should be a list of arrays...
- ids = self.send(requests)
- id2 = ids[:]
- res = {}
- while ids:
- r = self.responses['default'].get(True, timeout)
- _id = r.get('id')
- if _id in ids:
- ids.remove(_id)
- res[_id] = r.get('result')
- out = []
- for _id in id2:
- out.append(res[_id])
- return out
+
+ def stop(self):
+ if self.is_connected and self.protocol in 'st' and self.s:
+ self.s.shutdown(socket.SHUT_RDWR)
+ self.s.close()
+
+
+ def is_up_to_date(self):
+ return self.unanswered_requests == {}
- def start(self):
+
+ def start(self, queue = None, wait = False):
+ self.queue = queue if queue else Queue.Queue()
threading.Thread.start(self)
- # wait until connection is established
- self.connect_event.wait()
+ if wait:
+ self.connect_event.wait()
- def run(self):
- while True:
- self.init_interface()
- self.resend_subscriptions()
+ def run(self):
+ self.start_interface()
+ if self.is_connected:
+ self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
+ self.change_status()
self.run_tcp() if self.protocol in 'st' else self.run_http()
- self.trigger_callback('disconnected')
- if not self.loop: break
+ self.change_status()
+
+
+ def change_status(self):
+ #print "change status", self.server, self.is_connected
+ self.queue.put(self)
- time.sleep(5)
+if __name__ == "__main__":
+ check_certificates()