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.bitfoo.org:50001:t',
32 #'webbtc.net:50001:t',
33 'electrum.bitcoin.cz:50001:t',
34 'electrum.novit.ro:50001:t',
35 'electrum.be:50001:t',
36 'electrum.bysh.me:50001:t',
37 'electrum.pdmc.net:50001:t',
38 'electrum.no-ip.org:50001:t',
42 proxy_modes = ['socks4', 'socks5', 'http']
45 def pick_random_server():
46 return random.choice( DEFAULT_SERVERS )
51 class Interface(threading.Thread):
53 def register_callback(self, event, callback):
55 if not self.callbacks.get(event):
56 self.callbacks[event] = []
57 self.callbacks[event].append(callback)
59 def trigger_callback(self, event):
61 callbacks = self.callbacks.get(event,[])[:]
63 [callback() for callback in callbacks]
65 def init_server(self, host, port, proxy=None, use_ssl=True):
69 self.use_ssl = use_ssl
70 self.poll_interval = 1
74 self.unanswered_requests = {}
78 def queue_json_response(self, c):
81 # print_error( "<--",c )
84 error = c.get('error')
87 print_error("received error:", c)
88 if msg_id is not None:
90 method, params, channel = self.unanswered_requests.pop(msg_id)
91 response_queue = self.responses[channel]
92 response_queue.put({'method':method, 'params':params, 'error':error, 'id':msg_id})
96 if msg_id is not None:
98 method, params, channel = self.unanswered_requests.pop(msg_id)
99 result = c.get('result')
101 if method == 'server.version':
102 self.server_version = result
104 elif method == 'server.peers.subscribe':
114 if re.match("[stgh]\d+", v):
115 ports.append((v[0], v[1:]))
116 elif re.match("v(.?)+", v):
121 is_recent = float(version)>=float(PROTOCOL_VERSION)
124 if ports and is_recent:
125 servers[host] = {'ports':ports, 'pruning':pruning}
126 self.servers = servers
127 self.trigger_callback('peers')
130 # notification: find the channel(s)
131 method = c.get('method')
132 params = c.get('params')
134 if method == 'blockchain.numblocks.subscribe':
138 elif method == 'blockchain.headers.subscribe':
142 elif method == 'blockchain.address.subscribe':
148 for k,v in self.subscriptions.items():
149 if (method, params) in v:
153 print_error( "received unexpected notification", method, params)
154 print_error( self.subscriptions )
157 response_queue = self.responses[channel]
158 response_queue.put({'method':method, 'params':params, 'result':result, 'id':msg_id})
162 def get_response(self, channel='default', block=True, timeout=10000000000):
163 return self.responses[channel].get(block, timeout)
165 def register_channel(self, channel):
167 self.responses[channel] = Queue.Queue()
169 def poke(self, channel):
170 self.responses[channel].put(None)
173 def init_http(self, host, port, proxy=None, use_ssl=True):
174 self.init_server(host, port, proxy, use_ssl)
175 self.session_id = None
176 self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
177 self.is_connected = True
180 self.is_connected = True
181 while self.is_connected:
185 time.sleep(self.poll_interval)
186 except socket.gaierror:
191 traceback.print_exc(file=sys.stdout)
194 self.is_connected = False
201 def send_http(self, messages, channel='default'):
202 import urllib2, json, time, cookielib
206 socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
207 socks.wrapmodule(urllib2)
209 cj = cookielib.CookieJar()
210 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
211 urllib2.install_opener(opener)
218 if type(params) != type([]): params = [params]
219 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
220 self.unanswered_requests[self.message_id] = method, params, channel
224 data_json = json.dumps(data)
230 headers = {'content-type': 'application/json'}
232 headers['cookie'] = 'SESSION=%s'%self.session_id
234 req = urllib2.Request(self.connection_msg, data_json, headers)
235 response_stream = urllib2.urlopen(req)
237 for index, cookie in enumerate(cj):
238 if cookie.name=='SESSION':
239 self.session_id = cookie.value
241 response = response_stream.read()
242 self.bytes_received += len(response)
244 response = json.loads( response )
245 if type(response) is not type([]):
246 self.queue_json_response(response)
248 for item in response:
249 self.queue_json_response(item)
252 self.poll_interval = 1
254 if self.poll_interval < 15:
255 self.poll_interval += 1
256 #print self.poll_interval, response
258 self.rtime = time.time() - t1
259 self.is_connected = True
264 def init_tcp(self, host, port, proxy=None, use_ssl=True):
265 self.init_server(host, port, proxy, use_ssl)
268 self.connection_msg = "%s:%d"%(self.host,self.port)
269 if self.proxy is None:
270 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
272 self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
274 s = socks.socksocket()
275 s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
278 s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23)
281 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
284 s.connect(( self.host.encode('ascii'), int(self.port)))
287 self.is_connected = True
289 self.is_connected = False
296 while self.is_connected:
300 msg = self.s.recv(1024)
301 except socket.timeout:
307 # ping the server with server.version, as a real ping does not exist yet
308 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
312 self.bytes_received += len(msg)
314 self.is_connected = False
322 self.queue_json_response(c)
325 traceback.print_exc(file=sys.stdout)
327 self.is_connected = False
330 def send_tcp(self, messages, channel='default'):
331 """return the ids of the requests that we sent"""
336 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
337 self.unanswered_requests[self.message_id] = method, params, channel
338 ids.append(self.message_id)
340 # print "-->",request
342 out += request + '\n'
345 sent = self.s.send( out )
348 # this happens when we get disconnected
349 print_error( "Not connected, cannot send" )
355 def __init__(self, config=None, loop=False):
360 from simple_config import SimpleConfig
361 config = SimpleConfig()
363 threading.Thread.__init__(self)
367 self.connect_event = threading.Event()
369 self.subscriptions = {}
371 self.responses['default'] = Queue.Queue()
374 self.lock = threading.Lock()
376 self.servers = {} # actual list from IRC
378 self.bytes_received = 0
382 def init_interface(self):
383 if self.config.get('server'):
384 self.init_with_server(self.config)
386 print "Using random server..."
387 servers = DEFAULT_SERVERS[:]
389 server = random.choice( servers )
390 servers.remove(server)
391 self.config.set_key('server', server, False)
392 self.init_with_server(self.config)
393 if self.is_connected: break
396 print 'no server available'
397 self.is_connected = False
398 self.connect_event.set() # to finish start
399 self.server = 'ecdsa.org:50001:t'
403 self.connect_event.set()
404 if self.is_connected:
405 self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
406 self.trigger_callback('connected')
408 self.trigger_callback('notconnected')
409 #print_error("Failed to connect " + self.connection_msg)
412 def init_with_server(self, config):
414 s = config.get('server')
415 host, port, protocol = s.split(':')
418 self.protocol = protocol
419 proxy = self.parse_proxy_options(config.get('proxy'))
420 self.server = host + ':%d:%s'%(port, protocol)
422 #print protocol, host, port
424 self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
425 elif protocol in 'gh':
426 self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
428 raise BaseException('Unknown protocol: %s'%protocol)
431 def send(self, messages, channel='default'):
434 for message in messages:
436 if m[-10:] == '.subscribe':
441 if self.subscriptions.get(channel) is None:
442 self.subscriptions[channel] = []
444 if message not in self.subscriptions[channel]:
445 self.subscriptions[channel].append(message)
447 if self.protocol in 'st':
449 out = self.send_tcp(messages, channel)
451 # do not use lock, http is synchronous
452 out = self.send_http(messages, channel)
456 def resend_subscriptions(self):
457 for channel, messages in self.subscriptions.items():
459 self.send(messages, channel)
463 def parse_proxy_options(self, s):
464 if type(s) == type({}): return s # fixme: type should be fixed
465 if type(s) != type(""): return None
466 if s.lower() == 'none': return None
467 proxy = { "mode":"socks5", "host":"localhost" }
470 if proxy_modes.count(args[n]) == 1:
471 proxy["mode"] = args[n]
474 proxy["host"] = args[n]
477 proxy["port"] = args[n]
479 proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
483 def set_server(self, server, proxy=None):
484 # raise an error if the format isnt correct
485 a,b,c = server.split(':')
489 if server != self.server or proxy != self.proxy:
490 print "changing server:", server, proxy
493 if self.protocol in 'st' and self.s:
494 self.s.shutdown(socket.SHUT_RDWR)
496 self.is_connected = False # this exits the polling loop
497 self.trigger_callback('disconnecting') # for actively disconnecting
500 if self.protocol in 'st' and self.s:
501 self.s.shutdown(socket.SHUT_RDWR)
505 def get_servers_list(self):
509 for x in DEFAULT_SERVERS:
510 h,port,protocol = x.split(':')
511 servers_list[h] = {'ports':[(protocol,port)]}
513 servers_list = self.servers
515 for _host, v in servers_list.items():
519 _protocol, _port = item2
523 return plist, servers_list
526 def is_empty(self, channel):
527 q = self.responses.get(channel)
534 def get_pending_requests(self, channel):
537 for k, v in self.unanswered_requests.items():
539 if c == channel: result.append(k)
542 def is_up_to_date(self, channel):
543 return self.is_empty(channel) and not self.get_pending_requests(channel)
546 def synchronous_get(self, requests, timeout=100000000):
547 # todo: use generators, unanswered_requests should be a list of arrays...
548 ids = self.send(requests)
552 r = self.responses['default'].get(True, timeout)
556 res[_id] = r.get('result')
564 threading.Thread.start(self)
565 # wait until connection is established
566 self.connect_event.wait()
570 self.init_interface()
571 if self.is_connected:
572 self.resend_subscriptions()
573 self.run_tcp() if self.protocol in 'st' else self.run_http()
575 self.trigger_callback('disconnected')
577 if not self.loop: break