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