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
21 import threading, traceback, sys, time, json, Queue
23 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
24 from util import print_error
29 #'electrum.bitcoins.sk:50001:t',
30 #'uncle-enzo.info:50001:t',
31 #'electrum.bitcoin.cz:50001:t',
32 #'electrum.bitfoo.org:50001:t',
33 'electrum.novit.ro:50001:t',
34 'electrum.be:50001:t',
36 'electrum.bysh.me:50001:t',
37 'electrum.pdmc.net:50001:t',
41 proxy_modes = ['socks4', 'socks5', 'http']
44 def pick_random_server():
45 return random.choice( DEFAULT_SERVERS )
50 class Interface(threading.Thread):
52 def register_callback(self, event, callback):
54 if not self.callbacks.get(event):
55 self.callbacks[event] = []
56 self.callbacks[event].append(callback)
58 def trigger_callback(self, event):
60 callbacks = self.callbacks.get(event,[])[:]
62 [callback() for callback in callbacks]
64 def init_server(self, host, port, proxy=None, use_ssl=True):
68 self.use_ssl = use_ssl
69 self.poll_interval = 1
73 self.unanswered_requests = {}
77 def queue_json_response(self, c):
80 # print_error( "<--",c )
83 error = c.get('error')
86 print_error("received error:", c)
87 if msg_id is not None:
89 method, params, channel = self.unanswered_requests.pop(msg_id)
90 response_queue = self.responses[channel]
91 response_queue.put({'method':method, 'params':params, 'error':error, 'id':msg_id})
95 if msg_id is not None:
97 method, params, channel = self.unanswered_requests.pop(msg_id)
98 result = c.get('result')
100 if method == 'server.version':
101 self.server_version = result
103 elif method == 'server.peers.subscribe':
112 if re.match("[stgh]\d+", v):
113 ports.append((v[0], v[1:]))
114 if re.match("v(.?)+", v):
117 is_recent = float(version)>=float(PROTOCOL_VERSION)
120 if ports and is_recent:
121 servers.append((host, ports))
122 self.servers = servers
123 self.trigger_callback('peers')
126 # notification: find the channel(s)
127 method = c.get('method')
128 params = c.get('params')
130 if method == 'blockchain.numblocks.subscribe':
134 elif method == 'blockchain.headers.subscribe':
138 elif method == 'blockchain.address.subscribe':
144 for k,v in self.subscriptions.items():
145 if (method, params) in v:
149 print_error( "received unexpected notification", method, params)
150 print_error( self.subscriptions )
153 response_queue = self.responses[channel]
154 response_queue.put({'method':method, 'params':params, 'result':result, 'id':msg_id})
158 def get_response(self, channel='default', block=True, timeout=10000000000):
159 return self.responses[channel].get(block, timeout)
161 def register_channel(self, channel):
163 self.responses[channel] = Queue.Queue()
165 def poke(self, channel):
166 self.responses[channel].put(None)
169 def init_http(self, host, port, proxy=None, use_ssl=True):
170 self.init_server(host, port, proxy, use_ssl)
171 self.session_id = None
172 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
173 self.is_connected = True
176 self.is_connected = True
177 while self.is_connected:
181 time.sleep(self.poll_interval)
182 except socket.gaierror:
187 traceback.print_exc(file=sys.stdout)
190 self.is_connected = False
197 def send_http(self, messages, channel='default'):
198 import urllib2, json, time, cookielib
202 socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
203 socks.wrapmodule(urllib2)
205 cj = cookielib.CookieJar()
206 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
207 urllib2.install_opener(opener)
214 if type(params) != type([]): params = [params]
215 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
216 self.unanswered_requests[self.message_id] = method, params, channel
220 data_json = json.dumps(data)
226 headers = {'content-type': 'application/json'}
228 headers['cookie'] = 'SESSION=%s'%self.session_id
230 req = urllib2.Request(self.connection_msg, data_json, headers)
231 response_stream = urllib2.urlopen(req)
233 for index, cookie in enumerate(cj):
234 if cookie.name=='SESSION':
235 self.session_id = cookie.value
237 response = response_stream.read()
238 self.bytes_received += len(response)
240 response = json.loads( response )
241 if type(response) is not type([]):
242 self.queue_json_response(response)
244 for item in response:
245 self.queue_json_response(item)
248 self.poll_interval = 1
250 if self.poll_interval < 15:
251 self.poll_interval += 1
252 #print self.poll_interval, response
254 self.rtime = time.time() - t1
255 self.is_connected = True
260 def init_tcp(self, host, port, proxy=None, use_ssl=True):
261 self.init_server(host, port, proxy, use_ssl)
264 self.connection_msg = "%s:%d"%(self.host,self.port)
265 if self.proxy is None:
266 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
268 self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
270 s = socks.socksocket()
271 s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
274 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23)
277 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
280 s.connect(( self.host.encode('ascii'), int(self.port)))
283 self.is_connected = True
285 self.is_connected = False
292 while self.is_connected:
296 msg = self.s.recv(1024)
297 except socket.timeout:
303 # ping the server with server.version, as a real ping does not exist yet
304 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
308 self.bytes_received += len(msg)
310 self.is_connected = False
318 self.queue_json_response(c)
321 traceback.print_exc(file=sys.stdout)
323 self.is_connected = False
326 def send_tcp(self, messages, channel='default'):
327 """return the ids of the requests that we sent"""
332 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
333 self.unanswered_requests[self.message_id] = method, params, channel
334 ids.append(self.message_id)
336 # print "-->",request
338 out += request + '\n'
341 sent = self.s.send( out )
344 # this happens when we get disconnected
345 print_error( "Not connected, cannot send" )
351 def __init__(self, config=None, loop=False):
354 from simple_config import SimpleConfig
355 config = SimpleConfig()
357 threading.Thread.__init__(self)
361 self.connect_event = threading.Event()
363 self.subscriptions = {}
365 self.responses['default'] = Queue.Queue()
368 self.lock = threading.Lock()
370 self.servers = [] # actual list from IRC
372 self.bytes_received = 0
376 def init_interface(self):
377 if self.config.get('server'):
378 self.init_with_server(self.config)
380 print "Using random server..."
381 servers = DEFAULT_SERVERS[:]
383 server = random.choice( servers )
384 servers.remove(server)
385 self.config.set_key('server', server, False)
386 self.init_with_server(self.config)
387 if self.is_connected: break
390 print 'no server available'
391 self.is_connected = False
392 self.connect_event.set() # to finish start
393 self.server = 'ecdsa.org:50001:t'
397 self.connect_event.set()
398 if self.is_connected:
399 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
400 self.trigger_callback('connected')
402 self.trigger_callback('notconnected')
403 #print_error("Failed to connect " + self.connection_msg)
406 def init_with_server(self, config):
408 s = config.get('server')
409 host, port, protocol = s.split(':')
412 self.protocol = protocol
413 proxy = self.parse_proxy_options(config.get('proxy'))
414 self.server = host + ':%d:%s'%(port, protocol)
416 #print protocol, host, port
418 self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
419 elif protocol in 'gh':
420 self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
422 raise BaseException('Unknown protocol: %s'%protocol)
425 def send(self, messages, channel='default'):
428 for message in messages:
430 if m[-10:] == '.subscribe':
435 if self.subscriptions.get(channel) is None:
436 self.subscriptions[channel] = []
438 if message not in self.subscriptions[channel]:
439 self.subscriptions[channel].append(message)
441 if self.protocol in 'st':
443 out = self.send_tcp(messages, channel)
445 # do not use lock, http is synchronous
446 out = self.send_http(messages, channel)
450 def resend_subscriptions(self):
451 for channel, messages in self.subscriptions.items():
453 self.send(messages, channel)
457 def parse_proxy_options(self, s):
458 if type(s) == type({}): return s # fixme: type should be fixed
459 if type(s) != type(""): return None
460 if s.lower() == 'none': return None
461 proxy = { "mode":"socks5", "host":"localhost" }
464 if proxy_modes.count(args[n]) == 1:
465 proxy["mode"] = args[n]
468 proxy["host"] = args[n]
471 proxy["port"] = args[n]
473 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
477 def set_server(self, server, proxy=None):
478 # raise an error if the format isnt correct
479 a,b,c = server.split(':')
483 if server != self.server or proxy != self.proxy:
484 print "changing server:", server, proxy
487 if self.protocol in 'st' and self.s:
488 self.s.shutdown(socket.SHUT_RDWR)
490 self.is_connected = False # this exits the polling loop
491 self.trigger_callback('disconnecting') # for actively disconnecting
494 def get_servers_list(self):
498 for x in DEFAULT_SERVERS:
499 h,port,protocol = x.split(':')
500 servers_list.append( (h,[(protocol,port)] ) )
502 servers_list = self.servers
504 for item in servers_list:
508 _protocol, _port = item2
512 return plist, servers_list
515 def is_empty(self, channel):
516 q = self.responses.get(channel)
523 def get_pending_requests(self, channel):
526 for k, v in self.unanswered_requests.items():
528 if c == channel: result.append(k)
531 def is_up_to_date(self, channel):
532 return self.is_empty(channel) and not self.get_pending_requests(channel)
535 def synchronous_get(self, requests, timeout=100000000):
536 # todo: use generators, unanswered_requests should be a list of arrays...
537 ids = self.send(requests)
541 r = self.responses['default'].get(True, timeout)
545 res[_id] = r.get('result')
553 threading.Thread.start(self)
554 # wait until connection is established
555 self.connect_event.wait()
559 self.init_interface()
560 if self.is_connected:
561 self.resend_subscriptions()
562 self.run_tcp() if self.protocol in 'st' else self.run_http()
564 self.trigger_callback('disconnected')
566 if not self.loop: break