fix error to create a wallet due to missing pick_random_server decl
[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, errno
21 import threading, traceback, sys, time, json, Queue
22
23 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
24 from util import print_error, print_msg
25
26
27 DEFAULT_TIMEOUT = 5
28 proxy_modes = ['socks4', 'socks5', 'http']
29
30
31 class Interface(threading.Thread):
32
33
34     def init_server(self, host, port, proxy=None, use_ssl=True):
35         self.host = host
36         self.port = port
37         self.proxy = proxy
38         self.use_ssl = use_ssl
39         self.poll_interval = 1
40
41         #json
42         self.message_id = 0
43         self.unanswered_requests = {}
44         self.pending_transactions_for_notifications= []
45
46
47     def queue_json_response(self, c):
48
49         # uncomment to debug
50         # print_error( "<--",c )
51
52         msg_id = c.get('id')
53         error = c.get('error')
54         
55         if error:
56             print_error("received error:", c)
57             if msg_id is not None:
58                 with self.lock: 
59                     method, params, callback = self.unanswered_requests.pop(msg_id)
60                 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
61
62             return
63
64         if msg_id is not None:
65             with self.lock: 
66                 method, params, callback = self.unanswered_requests.pop(msg_id)
67             result = c.get('result')
68
69         else:
70             # notification
71             method = c.get('method')
72             params = c.get('params')
73
74             if method == 'blockchain.numblocks.subscribe':
75                 result = params[0]
76                 params = []
77
78             elif method == 'blockchain.headers.subscribe':
79                 result = params[0]
80                 params = []
81
82             elif method == 'blockchain.address.subscribe':
83                 addr = params[0]
84                 result = params[1]
85                 params = [addr]
86
87             with self.lock:
88                 for k,v in self.subscriptions.items():
89                     if (method, params) in v:
90                         callback = k
91                         break
92                 else:
93                     print_error( "received unexpected notification", method, params)
94                     print_error( self.subscriptions )
95                     return
96
97
98         callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
99
100
101     def on_version(self, i, result):
102         self.server_version = result
103
104
105     def init_http(self, host, port, proxy=None, use_ssl=True):
106         self.init_server(host, port, proxy, use_ssl)
107         self.session_id = None
108         self.is_connected = True
109         self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
110         try:
111             self.poll()
112         except:
113             print_error("http init session failed")
114             self.is_connected = False
115             return
116
117         if self.session_id:
118             print_error('http session:',self.session_id)
119             self.is_connected = True
120         else:
121             self.is_connected = False
122
123     def run_http(self):
124         self.is_connected = True
125         while self.is_connected:
126             try:
127                 if self.session_id:
128                     self.poll()
129                 time.sleep(self.poll_interval)
130             except socket.gaierror:
131                 break
132             except socket.error:
133                 break
134             except:
135                 traceback.print_exc(file=sys.stdout)
136                 break
137             
138         self.is_connected = False
139
140                 
141     def poll(self):
142         self.send([])
143
144
145     def send_http(self, messages, callback):
146         import urllib2, json, time, cookielib
147         print_error( "send_http", messages )
148         
149         if self.proxy:
150             import socks
151             socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
152             socks.wrapmodule(urllib2)
153
154         cj = cookielib.CookieJar()
155         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
156         urllib2.install_opener(opener)
157
158         t1 = time.time()
159
160         data = []
161         for m in messages:
162             method, params = m
163             if type(params) != type([]): params = [params]
164             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
165             self.unanswered_requests[self.message_id] = method, params, callback
166             self.message_id += 1
167
168         if data:
169             data_json = json.dumps(data)
170         else:
171             # poll with GET
172             data_json = None 
173
174             
175         headers = {'content-type': 'application/json'}
176         if self.session_id:
177             headers['cookie'] = 'SESSION=%s'%self.session_id
178
179         try:
180             req = urllib2.Request(self.connection_msg, data_json, headers)
181             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
182         except:
183             return
184
185         for index, cookie in enumerate(cj):
186             if cookie.name=='SESSION':
187                 self.session_id = cookie.value
188
189         response = response_stream.read()
190         self.bytes_received += len(response)
191         if response: 
192             response = json.loads( response )
193             if type(response) is not type([]):
194                 self.queue_json_response(response)
195             else:
196                 for item in response:
197                     self.queue_json_response(item)
198
199         if response: 
200             self.poll_interval = 1
201         else:
202             if self.poll_interval < 15: 
203                 self.poll_interval += 1
204         #print self.poll_interval, response
205
206         self.rtime = time.time() - t1
207         self.is_connected = True
208
209
210
211
212     def init_tcp(self, host, port, proxy=None, use_ssl=True):
213         self.init_server(host, port, proxy, use_ssl)
214
215         global proxy_modes
216         self.connection_msg = "%s:%d"%(self.host,self.port)
217         if self.proxy is None:
218             s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
219         else:
220             self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
221             import socks
222             s = socks.socksocket()
223             s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
224
225         if self.use_ssl:
226             s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, do_handshake_on_connect=True)
227             
228         s.settimeout(2)
229         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
230
231         try:
232             s.connect(( self.host.encode('ascii'), int(self.port)))
233         except:
234             #traceback.print_exc(file=sys.stdout)
235             print_error("failed to connect", host, port)
236             self.is_connected = False
237             self.s = None
238             return
239
240         s.settimeout(60)
241         self.s = s
242         self.is_connected = True
243
244     def run_tcp(self):
245         try:
246             #if self.use_ssl: self.s.do_handshake()
247             out = ''
248             while self.is_connected:
249                 try: 
250                     timeout = False
251                     msg = self.s.recv(1024)
252                 except socket.timeout:
253                     timeout = True
254                 except ssl.SSLError:
255                     timeout = True
256                 except socket.error, err:
257                     if err.errno in [11, 10035]:
258                         print_error("socket errno", err.errno)
259                         time.sleep(0.1)
260                         continue
261                     else:
262                         traceback.print_exc(file=sys.stdout)
263                         raise
264
265                 if timeout:
266                     # ping the server with server.version, as a real ping does not exist yet
267                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
268                     continue
269
270                 out += msg
271                 self.bytes_received += len(msg)
272                 if msg == '': 
273                     self.is_connected = False
274
275                 while True:
276                     s = out.find('\n')
277                     if s==-1: break
278                     c = out[0:s]
279                     out = out[s+1:]
280                     c = json.loads(c)
281                     self.queue_json_response(c)
282
283         except:
284             traceback.print_exc(file=sys.stdout)
285
286         self.is_connected = False
287
288
289     def send_tcp(self, messages, callback):
290         """return the ids of the requests that we sent"""
291         out = ''
292         ids = []
293         for m in messages:
294             method, params = m 
295             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
296             self.unanswered_requests[self.message_id] = method, params, callback
297             ids.append(self.message_id)
298             # uncomment to debug
299             # print "-->", request
300             self.message_id += 1
301             out += request + '\n'
302         while out:
303             try:
304                 sent = self.s.send( out )
305                 out = out[sent:]
306             except socket.error,e:
307                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
308                     print_error( "EAGAIN: retrying")
309                     time.sleep(0.1)
310                     continue
311                 else:
312                     traceback.print_exc(file=sys.stdout)
313                     # this happens when we get disconnected
314                     print_error( "Not connected, cannot send" )
315                     return None
316         return ids
317
318
319
320     def __init__(self, config=None):
321         #self.server = random.choice(filter_protocol(DEFAULT_SERVERS, 's'))
322         self.proxy = None
323
324         if config is None:
325             from simple_config import SimpleConfig
326             config = SimpleConfig()
327
328         threading.Thread.__init__(self)
329         self.daemon = True
330         self.config = config
331         self.connect_event = threading.Event()
332
333         self.subscriptions = {}
334         self.lock = threading.Lock()
335
336         self.servers = {} # actual list from IRC
337         self.rtime = 0
338         self.bytes_received = 0
339         self.is_connected = False
340
341         # init with None server, in case we are offline 
342         self.init_server(None, None)
343
344
345
346
347     def init_interface(self):
348         if self.config.get('server'):
349             self.init_with_server(self.config)
350         else:
351             if self.config.get('auto_cycle') is None:
352                 self.config.set_key('auto_cycle', True, False)
353
354         if not self.is_connected: 
355             self.connect_event.set()
356             return
357
358         self.connect_event.set()
359
360
361     def init_with_server(self, config):
362             
363         s = config.get('server')
364         host, port, protocol = s.split(':')
365         port = int(port)
366
367         self.protocol = protocol
368         proxy = self.parse_proxy_options(config.get('proxy'))
369         self.server = host + ':%d:%s'%(port, protocol)
370
371         #print protocol, host, port
372         if protocol in 'st':
373             self.init_tcp(host, port, proxy, use_ssl=(protocol=='s'))
374         elif protocol in 'gh':
375             self.init_http(host, port, proxy, use_ssl=(protocol=='g'))
376         else:
377             raise BaseException('Unknown protocol: %s'%protocol)
378
379
380     def stop_subscriptions(self):
381         for callback in self.subscriptions.keys():
382             callback(self, None)
383         self.subscriptions = {}
384
385
386     def send(self, messages, callback):
387
388         sub = []
389         for message in messages:
390             m, v = message
391             if m[-10:] == '.subscribe':
392                 sub.append(message)
393
394         if sub:
395             with self.lock:
396                 if self.subscriptions.get(callback) is None: 
397                     self.subscriptions[callback] = []
398                 for message in sub:
399                     if message not in self.subscriptions[callback]:
400                         self.subscriptions[callback].append(message)
401
402         if not self.is_connected: 
403             return
404
405         if self.protocol in 'st':
406             with self.lock:
407                 out = self.send_tcp(messages, callback)
408         else:
409             # do not use lock, http is synchronous
410             out = self.send_http(messages, callback)
411
412         return out
413
414
415     def parse_proxy_options(self, s):
416         if type(s) == type({}): return s  # fixme: type should be fixed
417         if type(s) != type(""): return None  
418         if s.lower() == 'none': return None
419         proxy = { "mode":"socks5", "host":"localhost" }
420         args = s.split(':')
421         n = 0
422         if proxy_modes.count(args[n]) == 1:
423             proxy["mode"] = args[n]
424             n += 1
425         if len(args) > n:
426             proxy["host"] = args[n]
427             n += 1
428         if len(args) > n:
429             proxy["port"] = args[n]
430         else:
431             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
432         return proxy
433
434
435
436     def stop(self):
437         if self.is_connected and self.protocol in 'st' and self.s:
438             self.s.shutdown(socket.SHUT_RDWR)
439             self.s.close()
440
441
442     def is_up_to_date(self):
443         return self.unanswered_requests == {}
444
445
446     def synchronous_get(self, requests, timeout=100000000):
447         # todo: use generators, unanswered_requests should be a list of arrays...
448         queue = Queue.Queue()
449         ids = self.send(requests, lambda i,r: queue.put(r))
450         id2 = ids[:]
451         res = {}
452         while ids:
453             r = queue.get(True, timeout)
454             _id = r.get('id')
455             if _id in ids:
456                 ids.remove(_id)
457                 res[_id] = r.get('result')
458         out = []
459         for _id in id2:
460             out.append(res[_id])
461         return out
462
463
464     def start(self, queue):
465         self.queue = queue
466         threading.Thread.start(self)
467
468
469     def run(self):
470         self.init_interface()
471         if self.is_connected:
472             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
473             self.change_status()
474             self.run_tcp() if self.protocol in 'st' else self.run_http()
475         self.change_status()
476         
477
478     def change_status(self):
479         #print "change status", self.server, self.is_connected
480         self.queue.put(self)
481