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, socket, ast, re, ssl, errno, os
21 import threading, traceback, sys, time, json, Queue
24 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
25 from util import print_error, print_msg
29 proxy_modes = ['socks4', 'socks5', 'http']
32 class Interface(threading.Thread):
35 def init_server(self, host, port, proxy=None, use_ssl=True):
39 self.use_ssl = use_ssl
40 self.poll_interval = 1
44 self.unanswered_requests = {}
45 self.pending_transactions_for_notifications= []
48 def queue_json_response(self, c):
51 # print_error( "<--",c )
54 error = c.get('error')
57 print_error("received error:", c)
58 if msg_id is not None:
60 method, params, callback = self.unanswered_requests.pop(msg_id)
61 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
65 if msg_id is not None:
67 method, params, callback = self.unanswered_requests.pop(msg_id)
68 result = c.get('result')
72 method = c.get('method')
73 params = c.get('params')
75 if method == 'blockchain.numblocks.subscribe':
79 elif method == 'blockchain.headers.subscribe':
83 elif method == 'blockchain.address.subscribe':
89 for k,v in self.subscriptions.items():
90 if (method, params) in v:
94 print_error( "received unexpected notification", method, params)
95 print_error( self.subscriptions )
99 callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
102 def on_version(self, i, result):
103 self.server_version = result
106 def init_http(self, host, port, proxy=None, use_ssl=True):
107 self.init_server(host, port, proxy, use_ssl)
108 self.session_id = None
109 self.is_connected = True
110 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
114 print_error("http init session failed")
115 self.is_connected = False
119 print_error('http session:',self.session_id)
120 self.is_connected = True
122 self.is_connected = False
125 self.is_connected = True
126 while self.is_connected:
130 time.sleep(self.poll_interval)
131 except socket.gaierror:
136 traceback.print_exc(file=sys.stdout)
139 self.is_connected = False
146 def send_http(self, messages, callback):
147 import urllib2, json, time, cookielib
148 print_error( "send_http", messages )
151 socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
152 socks.wrapmodule(urllib2)
154 cj = cookielib.CookieJar()
155 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
156 urllib2.install_opener(opener)
163 if type(params) != type([]): params = [params]
164 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
165 self.unanswered_requests[self.message_id] = method, params, callback
169 data_json = json.dumps(data)
175 headers = {'content-type': 'application/json'}
177 headers['cookie'] = 'SESSION=%s'%self.session_id
180 req = urllib2.Request(self.connection_msg, data_json, headers)
181 response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
185 for index, cookie in enumerate(cj):
186 if cookie.name=='SESSION':
187 self.session_id = cookie.value
189 response = response_stream.read()
190 self.bytes_received += len(response)
192 response = json.loads( response )
193 if type(response) is not type([]):
194 self.queue_json_response(response)
196 for item in response:
197 self.queue_json_response(item)
200 self.poll_interval = 1
202 if self.poll_interval < 15:
203 self.poll_interval += 1
204 #print self.poll_interval, response
206 self.rtime = time.time() - t1
207 self.is_connected = True
212 def init_tcp(self, host, port, proxy=None, use_ssl=True):
215 cert_path = os.path.join( self.config.get('path'), 'certs', host)
216 if not os.path.exists(cert_path):
217 dir_path = os.path.join( self.config.get('path'), 'certs')
218 if not os.path.exists(dir_path):
221 cert = ssl.get_server_certificate((host, port))
223 print_error("failed to connect", host, port)
226 with open(cert_path,"w") as f:
229 self.init_server(host, port, proxy, use_ssl)
232 self.connection_msg = "%s:%d"%(self.host,self.port)
234 if self.proxy is None:
235 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
237 self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
238 s = socks.socksocket()
239 s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
244 s = ssl.wrap_socket(s,
245 ssl_version=ssl.PROTOCOL_SSLv3,
246 cert_reqs=ssl.CERT_REQUIRED,
248 do_handshake_on_connect=True)
250 print_error("wrap_socket failed", host)
254 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
257 s.connect(( self.host.encode('ascii'), int(self.port)))
258 except ssl.SSLError, e:
259 print_error("SSL error:", host, e)
262 #traceback.print_exc(file=sys.stdout)
263 print_error("failed to connect", host, port)
266 # hostname verification (disabled)
267 if self.use_ssl and False:
268 from backports.ssl_match_hostname import match_hostname, CertificateError
270 match_hostname(s.getpeercert(), host)
271 print_error("hostname matches", host)
272 except CertificateError, ce:
273 print_error("hostname does not match", host, s.getpeercert())
278 self.is_connected = True
279 print_error("connected to", host, port)
284 #if self.use_ssl: self.s.do_handshake()
286 while self.is_connected:
289 msg = self.s.recv(1024)
290 except socket.timeout:
294 except socket.error, err:
295 if err.errno in [11, 10035]:
296 print_error("socket errno", err.errno)
300 traceback.print_exc(file=sys.stdout)
304 # ping the server with server.version, as a real ping does not exist yet
305 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
309 self.bytes_received += len(msg)
311 self.is_connected = False
319 self.queue_json_response(c)
322 traceback.print_exc(file=sys.stdout)
324 self.is_connected = False
327 def send_tcp(self, messages, callback):
328 """return the ids of the requests that we sent"""
333 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
334 self.unanswered_requests[self.message_id] = method, params, callback
335 ids.append(self.message_id)
337 # print "-->", request
339 out += request + '\n'
342 sent = self.s.send( out )
344 except socket.error,e:
345 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
346 print_error( "EAGAIN: retrying")
350 traceback.print_exc(file=sys.stdout)
351 # this happens when we get disconnected
352 print_error( "Not connected, cannot send" )
358 def __init__(self, config=None):
359 #self.server = random.choice(filter_protocol(DEFAULT_SERVERS, 's'))
363 from simple_config import SimpleConfig
364 config = SimpleConfig()
366 threading.Thread.__init__(self)
369 self.connect_event = threading.Event()
371 self.subscriptions = {}
372 self.lock = threading.Lock()
374 self.servers = {} # actual list from IRC
376 self.bytes_received = 0
377 self.is_connected = False
379 # init with None server, in case we are offline
380 self.init_server(None, None)
385 def init_interface(self):
386 if self.config.get('server'):
387 self.init_with_server(self.config)
389 if self.config.get('auto_cycle') is None:
390 self.config.set_key('auto_cycle', True, False)
392 if not self.is_connected:
393 self.connect_event.set()
396 self.connect_event.set()
399 def init_with_server(self, config):
401 s = config.get('server')
402 host, port, protocol = s.split(':')
405 self.protocol = protocol
406 proxy = self.parse_proxy_options(config.get('proxy'))
407 self.server = host + ':%d:%s'%(port, protocol)
409 #print protocol, host, port
411 self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
412 elif protocol in 'gh':
413 self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
415 raise BaseException('Unknown protocol: %s'%protocol)
418 def stop_subscriptions(self):
419 for callback in self.subscriptions.keys():
421 self.subscriptions = {}
424 def send(self, messages, callback):
427 for message in messages:
429 if m[-10:] == '.subscribe':
434 if self.subscriptions.get(callback) is None:
435 self.subscriptions[callback] = []
437 if message not in self.subscriptions[callback]:
438 self.subscriptions[callback].append(message)
440 if not self.is_connected:
443 if self.protocol in 'st':
445 out = self.send_tcp(messages, callback)
447 # do not use lock, http is synchronous
448 out = self.send_http(messages, callback)
453 def parse_proxy_options(self, s):
454 if type(s) == type({}): return s # fixme: type should be fixed
455 if type(s) != type(""): return None
456 if s.lower() == 'none': return None
457 proxy = { "mode":"socks5", "host":"localhost" }
460 if proxy_modes.count(args[n]) == 1:
461 proxy["mode"] = args[n]
464 proxy["host"] = args[n]
467 proxy["port"] = args[n]
469 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
475 if self.is_connected and self.protocol in 'st' and self.s:
476 self.s.shutdown(socket.SHUT_RDWR)
480 def is_up_to_date(self):
481 return self.unanswered_requests == {}
484 def synchronous_get(self, requests, timeout=100000000):
485 # todo: use generators, unanswered_requests should be a list of arrays...
486 queue = Queue.Queue()
487 ids = self.send(requests, lambda i,r: queue.put(r))
491 r = queue.get(True, timeout)
495 res[_id] = r.get('result')
502 def start(self, queue):
504 threading.Thread.start(self)
508 self.init_interface()
509 if self.is_connected:
510 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
512 self.run_tcp() if self.protocol in 'st' else self.run_http()
516 def change_status(self):
517 #print "change status", self.server, self.is_connected
522 if __name__ == "__main__":
525 i = Interface({'server':'btc.it-zone.org:50002:s', 'path':'/extra/key/wallet', 'verbose':True})