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':
113 if re.match("[stgh]\d+", v):
114 ports.append((v[0], v[1:]))
115 elif re.match("v(.?)+", v):
120 is_recent = float(version)>=float(PROTOCOL_VERSION)
123 if ports and is_recent:
124 servers[host] = {'ports':ports, 'pruning':pruning}
125 self.servers = servers
126 self.trigger_callback('peers')
129 # notification: find the channel(s)
130 method = c.get('method')
131 params = c.get('params')
133 if method == 'blockchain.numblocks.subscribe':
137 elif method == 'blockchain.headers.subscribe':
141 elif method == 'blockchain.address.subscribe':
147 for k,v in self.subscriptions.items():
148 if (method, params) in v:
152 print_error( "received unexpected notification", method, params)
153 print_error( self.subscriptions )
156 response_queue = self.responses[channel]
157 response_queue.put({'method':method, 'params':params, 'result':result, 'id':msg_id})
161 def get_response(self, channel='default', block=True, timeout=10000000000):
162 return self.responses[channel].get(block, timeout)
164 def register_channel(self, channel):
166 self.responses[channel] = Queue.Queue()
168 def poke(self, channel):
169 self.responses[channel].put(None)
172 def init_http(self, host, port, proxy=None, use_ssl=True):
173 self.init_server(host, port, proxy, use_ssl)
174 self.session_id = None
175 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
176 self.is_connected = True
179 self.is_connected = True
180 while self.is_connected:
184 time.sleep(self.poll_interval)
185 except socket.gaierror:
190 traceback.print_exc(file=sys.stdout)
193 self.is_connected = False
200 def send_http(self, messages, channel='default'):
201 import urllib2, json, time, cookielib
205 socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
206 socks.wrapmodule(urllib2)
208 cj = cookielib.CookieJar()
209 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
210 urllib2.install_opener(opener)
217 if type(params) != type([]): params = [params]
218 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
219 self.unanswered_requests[self.message_id] = method, params, channel
223 data_json = json.dumps(data)
229 headers = {'content-type': 'application/json'}
231 headers['cookie'] = 'SESSION=%s'%self.session_id
233 req = urllib2.Request(self.connection_msg, data_json, headers)
234 response_stream = urllib2.urlopen(req)
236 for index, cookie in enumerate(cj):
237 if cookie.name=='SESSION':
238 self.session_id = cookie.value
240 response = response_stream.read()
241 self.bytes_received += len(response)
243 response = json.loads( response )
244 if type(response) is not type([]):
245 self.queue_json_response(response)
247 for item in response:
248 self.queue_json_response(item)
251 self.poll_interval = 1
253 if self.poll_interval < 15:
254 self.poll_interval += 1
255 #print self.poll_interval, response
257 self.rtime = time.time() - t1
258 self.is_connected = True
263 def init_tcp(self, host, port, proxy=None, use_ssl=True):
264 self.init_server(host, port, proxy, use_ssl)
267 self.connection_msg = "%s:%d"%(self.host,self.port)
268 if self.proxy is None:
269 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
271 self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
273 s = socks.socksocket()
274 s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
277 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23)
280 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
283 s.connect(( self.host.encode('ascii'), int(self.port)))
286 self.is_connected = True
288 self.is_connected = False
295 while self.is_connected:
299 msg = self.s.recv(1024)
300 except socket.timeout:
306 # ping the server with server.version, as a real ping does not exist yet
307 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
311 self.bytes_received += len(msg)
313 self.is_connected = False
321 self.queue_json_response(c)
324 traceback.print_exc(file=sys.stdout)
326 self.is_connected = False
329 def send_tcp(self, messages, channel='default'):
330 """return the ids of the requests that we sent"""
335 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
336 self.unanswered_requests[self.message_id] = method, params, channel
337 ids.append(self.message_id)
339 # print "-->",request
341 out += request + '\n'
344 sent = self.s.send( out )
347 # this happens when we get disconnected
348 print_error( "Not connected, cannot send" )
354 def __init__(self, config=None, loop=False):
359 from simple_config import SimpleConfig
360 config = SimpleConfig()
362 threading.Thread.__init__(self)
366 self.connect_event = threading.Event()
368 self.subscriptions = {}
370 self.responses['default'] = Queue.Queue()
373 self.lock = threading.Lock()
375 self.servers = {} # actual list from IRC
377 self.bytes_received = 0
381 def init_interface(self):
382 if self.config.get('server'):
383 self.init_with_server(self.config)
385 print "Using random server..."
386 servers = DEFAULT_SERVERS[:]
388 server = random.choice( servers )
389 servers.remove(server)
390 self.config.set_key('server', server, False)
391 self.init_with_server(self.config)
392 if self.is_connected: break
395 print 'no server available'
396 self.is_connected = False
397 self.connect_event.set() # to finish start
398 self.server = 'ecdsa.org:50001:t'
402 self.connect_event.set()
403 if self.is_connected:
404 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
405 self.trigger_callback('connected')
407 self.trigger_callback('notconnected')
408 #print_error("Failed to connect " + self.connection_msg)
411 def init_with_server(self, config):
413 s = config.get('server')
414 host, port, protocol = s.split(':')
417 self.protocol = protocol
418 proxy = self.parse_proxy_options(config.get('proxy'))
419 self.server = host + ':%d:%s'%(port, protocol)
421 #print protocol, host, port
423 self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
424 elif protocol in 'gh':
425 self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
427 raise BaseException('Unknown protocol: %s'%protocol)
430 def send(self, messages, channel='default'):
433 for message in messages:
435 if m[-10:] == '.subscribe':
440 if self.subscriptions.get(channel) is None:
441 self.subscriptions[channel] = []
443 if message not in self.subscriptions[channel]:
444 self.subscriptions[channel].append(message)
446 if self.protocol in 'st':
448 out = self.send_tcp(messages, channel)
450 # do not use lock, http is synchronous
451 out = self.send_http(messages, channel)
455 def resend_subscriptions(self):
456 for channel, messages in self.subscriptions.items():
458 self.send(messages, channel)
462 def parse_proxy_options(self, s):
463 if type(s) == type({}): return s # fixme: type should be fixed
464 if type(s) != type(""): return None
465 if s.lower() == 'none': return None
466 proxy = { "mode":"socks5", "host":"localhost" }
469 if proxy_modes.count(args[n]) == 1:
470 proxy["mode"] = args[n]
473 proxy["host"] = args[n]
476 proxy["port"] = args[n]
478 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
482 def set_server(self, server, proxy=None):
483 # raise an error if the format isnt correct
484 a,b,c = server.split(':')
488 if server != self.server or proxy != self.proxy:
489 print "changing server:", server, proxy
492 if self.protocol in 'st' and self.s:
493 self.s.shutdown(socket.SHUT_RDWR)
495 self.is_connected = False # this exits the polling loop
496 self.trigger_callback('disconnecting') # for actively disconnecting
499 def get_servers_list(self):
503 for x in DEFAULT_SERVERS:
504 h,port,protocol = x.split(':')
505 servers_list[h] = {'ports':[(protocol,port)]}
507 servers_list = self.servers
509 for _host, v in servers_list.items():
513 _protocol, _port = item2
517 return plist, servers_list
520 def is_empty(self, channel):
521 q = self.responses.get(channel)
528 def get_pending_requests(self, channel):
531 for k, v in self.unanswered_requests.items():
533 if c == channel: result.append(k)
536 def is_up_to_date(self, channel):
537 return self.is_empty(channel) and not self.get_pending_requests(channel)
540 def synchronous_get(self, requests, timeout=100000000):
541 # todo: use generators, unanswered_requests should be a list of arrays...
542 ids = self.send(requests)
546 r = self.responses['default'].get(True, timeout)
550 res[_id] = r.get('result')
558 threading.Thread.start(self)
559 # wait until connection is established
560 self.connect_event.wait()
564 self.init_interface()
565 if self.is_connected:
566 self.resend_subscriptions()
567 self.run_tcp() if self.protocol in 'st' else self.run_http()
569 self.trigger_callback('disconnected')
571 if not self.loop: break