Update default servers with pruning flag
[electrum-nvc.git] / lib / interface.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19
20 import random, socket, ast, re, ssl
21 import threading, traceback, sys, time, json, Queue
22
23 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
24 from util import print_error
25
26
27 DEFAULT_TIMEOUT = 5
28 DEFAULT_SERVERS = [ 
29     'electrum.bitcoin.cz:p:50001:t',
30     'electrum.novit.ro:p:50001:t', 
31     'electrum.be::50001:t',
32     'electrum.bysh.me::50001:t',
33     'electrum.pdmc.net:p:50001:t',
34     'electrum.no-ip.org::50001:t',
35     'ecdsa.org:p:50001:t'
36     ]
37
38 proxy_modes = ['socks4', 'socks5', 'http']
39
40
41 def pick_random_server():
42     return random.choice( DEFAULT_SERVERS )
43
44
45
46
47 class Interface(threading.Thread):
48
49     def register_callback(self, event, callback):
50         with self.lock:
51             if not self.callbacks.get(event):
52                 self.callbacks[event] = []
53             self.callbacks[event].append(callback)
54
55     def trigger_callback(self, event):
56         with self.lock:
57             callbacks = self.callbacks.get(event,[])[:]
58         if callbacks:
59             [callback() for callback in callbacks]
60
61     def init_server(self, host, port, proxy=None, use_ssl=True):
62         self.host = host
63         self.port = port
64         self.proxy = proxy
65         self.use_ssl = use_ssl
66         self.poll_interval = 1
67
68         #json
69         self.message_id = 0
70         self.unanswered_requests = {}
71
72
73
74     def queue_json_response(self, c):
75
76         # uncomment to debug
77         # print_error( "<--",c )
78
79         msg_id = c.get('id')
80         error = c.get('error')
81         
82         if error:
83             print_error("received error:", c)
84             if msg_id is not None:
85                 with self.lock: 
86                     method, params, channel = self.unanswered_requests.pop(msg_id)
87                 response_queue = self.responses[channel]
88                 response_queue.put({'method':method, 'params':params, 'error':error, 'id':msg_id})
89
90             return
91
92         if msg_id is not None:
93             with self.lock: 
94                 method, params, channel = self.unanswered_requests.pop(msg_id)
95             result = c.get('result')
96
97             if method == 'server.version':
98                 self.server_version = result
99
100             elif method == 'server.peers.subscribe':
101                 servers = {}
102                 for item in result:
103                     s = []
104                     host = item[1]
105                     ports = []
106                     version = None
107                     pruning = False
108                     if len(item) > 2:
109                         for v in item[2]:
110                             if re.match("[stgh]\d+", v):
111                                 ports.append((v[0], v[1:]))
112                             elif re.match("v(.?)+", v):
113                                 version = v[1:]
114                             elif v == 'p':
115                                 pruning = True
116                     try: 
117                         is_recent = float(version)>=float(PROTOCOL_VERSION)
118                     except:
119                         is_recent = False
120                     if ports and is_recent:
121                         servers[host] = {'ports':ports, 'pruning':pruning}
122                 self.servers = servers
123                 self.trigger_callback('peers')
124
125         else:
126             # notification: find the channel(s)
127             method = c.get('method')
128             params = c.get('params')
129
130             if method == 'blockchain.numblocks.subscribe':
131                 result = params[0]
132                 params = []
133
134             elif method == 'blockchain.headers.subscribe':
135                 result = params[0]
136                 params = []
137
138             elif method == 'blockchain.address.subscribe':
139                 addr = params[0]
140                 result = params[1]
141                 params = [addr]
142
143             with self.lock:
144                 for k,v in self.subscriptions.items():
145                     if (method, params) in v:
146                         channel = k
147                         break
148                 else:
149                     print_error( "received unexpected notification", method, params)
150                     print_error( self.subscriptions )
151                     return
152                 
153         response_queue = self.responses[channel]
154         response_queue.put({'method':method, 'params':params, 'result':result, 'id':msg_id})
155
156
157
158     def get_response(self, channel='default', block=True, timeout=10000000000):
159         return self.responses[channel].get(block, timeout)
160
161     def register_channel(self, channel):
162         with self.lock:
163             self.responses[channel] = Queue.Queue()
164
165     def poke(self, channel):
166         self.responses[channel].put(None)
167
168
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
174
175     def run_http(self):
176         self.is_connected = True
177         while self.is_connected:
178             try:
179                 if self.session_id:
180                     self.poll()
181                 time.sleep(self.poll_interval)
182             except socket.gaierror:
183                 break
184             except socket.error:
185                 break
186             except:
187                 traceback.print_exc(file=sys.stdout)
188                 break
189             
190         self.is_connected = False
191
192                 
193     def poll(self):
194         self.send([])
195
196
197     def send_http(self, messages, channel='default'):
198         import urllib2, json, time, cookielib
199         
200         if self.proxy:
201             import socks
202             socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
203             socks.wrapmodule(urllib2)
204
205         cj = cookielib.CookieJar()
206         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
207         urllib2.install_opener(opener)
208
209         t1 = time.time()
210
211         data = []
212         for m in messages:
213             method, params = m
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
217             self.message_id += 1
218
219         if data:
220             data_json = json.dumps(data)
221         else:
222             # poll with GET
223             data_json = None 
224
225             
226         headers = {'content-type': 'application/json'}
227         if self.session_id:
228             headers['cookie'] = 'SESSION=%s'%self.session_id
229
230         req = urllib2.Request(self.connection_msg, data_json, headers)
231         response_stream = urllib2.urlopen(req)
232
233         for index, cookie in enumerate(cj):
234             if cookie.name=='SESSION':
235                 self.session_id = cookie.value
236
237         response = response_stream.read()
238         self.bytes_received += len(response)
239         if response: 
240             response = json.loads( response )
241             if type(response) is not type([]):
242                 self.queue_json_response(response)
243             else:
244                 for item in response:
245                     self.queue_json_response(item)
246
247         if response: 
248             self.poll_interval = 1
249         else:
250             if self.poll_interval < 15: 
251                 self.poll_interval += 1
252         #print self.poll_interval, response
253
254         self.rtime = time.time() - t1
255         self.is_connected = True
256
257
258
259
260     def init_tcp(self, host, port, proxy=None, use_ssl=True):
261         self.init_server(host, port, proxy, use_ssl)
262
263         global proxy_modes
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 )
267         else:
268             self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
269             import socks
270             s = socks.socksocket()
271             s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
272
273         if self.use_ssl:
274             s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23)
275             
276         s.settimeout(2)
277         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
278
279         try:
280             s.connect(( self.host.encode('ascii'), int(self.port)))
281             s.settimeout(60)
282             self.s = s
283             self.is_connected = True
284         except:
285             self.is_connected = False
286             self.s = None
287
288
289     def run_tcp(self):
290         try:
291             out = ''
292             while self.is_connected:
293
294                 try: 
295                     timeout = False
296                     msg = self.s.recv(1024)
297                 except socket.timeout:
298                     timeout = True
299                 except ssl.SSLError:
300                     timeout = True
301
302                 if 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])])
305                     continue
306
307                 out += msg
308                 self.bytes_received += len(msg)
309                 if msg == '': 
310                     self.is_connected = False
311
312                 while True:
313                     s = out.find('\n')
314                     if s==-1: break
315                     c = out[0:s]
316                     out = out[s+1:]
317                     c = json.loads(c)
318                     self.queue_json_response(c)
319
320         except:
321             traceback.print_exc(file=sys.stdout)
322
323         self.is_connected = False
324
325
326     def send_tcp(self, messages, channel='default'):
327         """return the ids of the requests that we sent"""
328         out = ''
329         ids = []
330         for m in messages:
331             method, params = m 
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)
335             # uncomment to debug
336             # print "-->",request
337             self.message_id += 1
338             out += request + '\n'
339         while out:
340             try:
341                 sent = self.s.send( out )
342                 out = out[sent:]
343             except:
344                 # this happens when we get disconnected
345                 print_error( "Not connected, cannot send" )
346                 return None
347         return ids
348
349
350
351     def __init__(self, config=None, loop=False):
352         self.server = None
353         self.proxy = None
354
355         if config is None:
356             from simple_config import SimpleConfig
357             config = SimpleConfig()
358
359         threading.Thread.__init__(self)
360         self.daemon = True
361         self.loop = loop
362         self.config = config
363         self.connect_event = threading.Event()
364
365         self.subscriptions = {}
366         self.responses = {}
367         self.responses['default'] = Queue.Queue()
368
369         self.callbacks = {}
370         self.lock = threading.Lock()
371
372         self.servers = {} # actual list from IRC
373         self.rtime = 0
374         self.bytes_received = 0
375
376
377
378     def init_interface(self):
379         if self.config.get('server'):
380             self.init_with_server(self.config)
381         else:
382             print "Using random server..."
383             servers = DEFAULT_SERVERS[:]
384             while servers:
385                 server = random.choice( servers )
386                 servers.remove(server)
387                 self.config.set_key('server', server, False)
388                 self.init_with_server(self.config)
389                 if self.is_connected: break
390
391             if not servers:
392                 print 'no server available'
393                 self.is_connected = False
394                 self.connect_event.set() # to finish start
395                 self.server = 'ecdsa.org:50001:t'
396                 self.proxy = None
397                 return
398
399         self.connect_event.set()
400         if self.is_connected:
401             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])])
402             self.trigger_callback('connected')
403         else:
404             self.trigger_callback('notconnected')
405             #print_error("Failed to connect " + self.connection_msg)
406
407
408     def init_with_server(self, config):
409             
410         s = config.get('server')
411         host, port, protocol = s.split(':')
412         port = int(port)
413
414         self.protocol = protocol
415         proxy = self.parse_proxy_options(config.get('proxy'))
416         self.server = host + ':%d:%s'%(port, protocol)
417
418         #print protocol, host, port
419         if protocol in 'st':
420             self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
421         elif protocol in 'gh':
422             self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
423         else:
424             raise BaseException('Unknown protocol: %s'%protocol)
425
426
427     def send(self, messages, channel='default'):
428
429         sub = []
430         for message in messages:
431             m, v = message
432             if m[-10:] == '.subscribe':
433                 sub.append(message)
434
435         if sub:
436             with self.lock:
437                 if self.subscriptions.get(channel) is None: 
438                     self.subscriptions[channel] = []
439                 for message in sub:
440                     if message not in self.subscriptions[channel]:
441                         self.subscriptions[channel].append(message)
442
443         if self.protocol in 'st':
444             with self.lock:
445                 out = self.send_tcp(messages, channel)
446         else:
447             # do not use lock, http is synchronous
448             out = self.send_http(messages, channel)
449
450         return out
451
452     def resend_subscriptions(self):
453         for channel, messages in self.subscriptions.items():
454             if messages:
455                 self.send(messages, channel)
456
457
458
459     def parse_proxy_options(self, s):
460         if type(s) == type({}): return s  # fixme: type should be fixed
461         if type(s) != type(""): return None  
462         if s.lower() == 'none': return None
463         proxy = { "mode":"socks5", "host":"localhost" }
464         args = s.split(':')
465         n = 0
466         if proxy_modes.count(args[n]) == 1:
467             proxy["mode"] = args[n]
468             n += 1
469         if len(args) > n:
470             proxy["host"] = args[n]
471             n += 1
472         if len(args) > n:
473             proxy["port"] = args[n]
474         else:
475             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
476         return proxy
477
478
479     def set_server(self, server, proxy=None):
480         # raise an error if the format isnt correct
481         a,b,c = server.split(':')
482         b = int(b)
483         assert c in 'stgh'
484         # set the server
485         if server != self.server or proxy != self.proxy:
486             print "changing server:", server, proxy
487             self.server = server
488             self.proxy = proxy
489             if self.protocol in 'st' and self.s:
490                 self.s.shutdown(socket.SHUT_RDWR)
491                 self.s.close()
492             self.is_connected = False  # this exits the polling loop
493             self.trigger_callback('disconnecting') # for actively disconnecting
494
495     def stop(self):
496         if self.protocol in 'st' and self.s:
497             self.s.shutdown(socket.SHUT_RDWR)
498             self.s.close()
499
500
501     def get_servers_list(self):
502         plist = {}
503         if not self.servers:
504             servers_list = {}
505             for x in DEFAULT_SERVERS:
506                 h,pruning,port,protocol = x.split(':')
507                 servers_list[h] = {'ports':[(protocol,port)], 'pruning':pruning}
508         else:
509             servers_list = self.servers
510         
511         for _host, v in servers_list.items():
512             pp = v['ports']
513             z = {}
514             for item2 in pp:
515                 _protocol, _port = item2
516                 z[_protocol] = _port
517             plist[_host] = z
518                 
519         return plist, servers_list
520
521
522     def is_empty(self, channel):
523         q = self.responses.get(channel)
524         if q: 
525             return q.empty()
526         else:
527             return True
528
529
530     def get_pending_requests(self, channel):
531         result = []
532         with self.lock:
533             for k, v in self.unanswered_requests.items():
534                 a, b, c = v
535                 if c == channel: result.append(k)
536         return result
537
538     def is_up_to_date(self, channel):
539         return self.is_empty(channel) and not self.get_pending_requests(channel)
540
541
542     def synchronous_get(self, requests, timeout=100000000):
543         # todo: use generators, unanswered_requests should be a list of arrays...
544         ids = self.send(requests)
545         id2 = ids[:]
546         res = {}
547         while ids:
548             r = self.responses['default'].get(True, timeout)
549             _id = r.get('id')
550             if _id in ids:
551                 ids.remove(_id)
552                 res[_id] = r.get('result')
553         out = []
554         for _id in id2:
555             out.append(res[_id])
556         return out
557
558
559     def start(self):
560         threading.Thread.start(self)
561         # wait until connection is established
562         self.connect_event.wait()
563
564     def run(self):
565         while True:
566             self.init_interface()
567             if self.is_connected:
568                 self.resend_subscriptions()
569                 self.run_tcp() if self.protocol in 'st' else self.run_http()
570
571             self.trigger_callback('disconnected')
572
573             if not self.loop: break
574             time.sleep(5)
575
576
577