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
21 import threading, traceback, sys, time, json, Queue
24 DEFAULT_SERVERS = [ 'ecdsa.org:50001:t', 'electrum.novit.ro:50001:t', 'electrum.bitcoins.sk:50001:t'] # list of default servers
28 s = s.replace("'blk_hash'", "'block_hash'")
29 s = s.replace("'pos'", "'index'")
30 s = s.replace("'nTime'", "'timestamp'")
31 s = s.replace("'is_in'", "'is_input'")
32 s = s.replace("'raw_scriptPubKey'","'raw_output_script'")
36 class Interface(threading.Thread):
37 def __init__(self, host, port):
38 threading.Thread.__init__(self)
43 self.servers = [] # actual list from IRC
46 self.is_connected = True
47 self.poll_interval = 1
51 self.responses = Queue.Queue()
55 # push a fake response so that the getting thread exits its loop
56 self.responses.put(None)
58 def queue_json_response(self, c):
62 error = c.get('error')
65 print "received error:", c
68 if msg_id is not None:
69 method, params = self.methods.pop(msg_id)
70 result = c.get('result')
73 method = c.get('method')
74 params = c.get('params')
76 if method == 'blockchain.numblocks.subscribe':
80 elif method == 'blockchain.address.subscribe':
85 self.responses.put({'method':method, 'params':params, 'result':result})
89 def subscribe(self, addresses):
91 for addr in addresses:
92 messages.append(('blockchain.address.subscribe', [addr]))
96 def get_servers(self, wallet):
97 # loop over default servers
98 # requesting servers could be an independent process
99 addresses = wallet.all_addresses()
100 version = wallet.electrum_version
102 for server in DEFAULT_SERVERS:
103 print "connecting to", server
106 self.start_session(addresses, version)
107 wallet.host = self.host
109 except socket.timeout:
114 traceback.print_exc(file=sys.stdout)
117 def start_session(self, addresses, version):
118 #print "Starting new session: %s:%d"%(self.host,self.port)
119 self.send([('server.version', [version]), ('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
120 self.subscribe(addresses)
123 class PollingInterface(Interface):
124 """ non-persistent connection. synchronous calls"""
126 def __init__(self, host, port):
127 Interface.__init__(self, host, port)
128 self.session_id = None
130 def get_history(self, address):
131 self.send([('blockchain.address.get_history', [address] )])
135 #if is_new or wallet.remote_url:
136 # self.was_updated = True
137 # is_new = wallet.synchronize()
138 # wallet.update_tx_history()
145 self.is_connected = True
146 while self.is_connected:
150 time.sleep(self.poll_interval)
151 except socket.gaierror:
156 traceback.print_exc(file=sys.stdout)
159 self.is_connected = False
170 class HttpStratumInterface(PollingInterface):
175 def send(self, messages):
176 import urllib2, json, time, cookielib
178 cj = cookielib.CookieJar()
179 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
180 urllib2.install_opener(opener)
187 if type(params) != type([]): params = [params]
188 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
189 self.methods[self.message_id] = method, params
193 data_json = json.dumps(data)
198 host = 'http://%s:%d'%( self.host, self.port )
199 headers = {'content-type': 'application/json'}
201 headers['cookie'] = 'SESSION=%s'%self.session_id
203 req = urllib2.Request(host, data_json, headers)
204 response_stream = urllib2.urlopen(req)
206 for index, cookie in enumerate(cj):
207 if cookie.name=='SESSION':
208 self.session_id = cookie.value
210 response = response_stream.read()
212 response = json.loads( response )
213 if type(response) is not type([]):
214 self.queue_json_response(response)
216 for item in response:
217 self.queue_json_response(item)
220 self.poll_interval = 1
222 if self.poll_interval < 15:
223 self.poll_interval += 1
224 #print self.poll_interval, response
226 self.rtime = time.time() - t1
227 self.is_connected = True
232 class TcpStratumInterface(Interface):
233 """json-rpc over persistent TCP connection, asynchronous"""
235 def __init__(self, host, port):
236 Interface.__init__(self, host, port)
237 self.s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
239 self.s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
241 self.s.connect(( self.host, self.port))
242 self.is_connected = True
244 self.is_connected = False
245 print "not connected"
250 while self.is_connected:
251 try: msg = self.s.recv(1024)
252 except socket.timeout:
256 self.is_connected = False
257 print "disconnected."
265 self.queue_json_response(c)
268 traceback.print_exc(file=sys.stdout)
270 self.is_connected = False
274 def send(self, messages):
278 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
279 self.methods[self.message_id] = method, params
282 out += request + '\n'
285 def get_history(self, addr):
286 self.send([('blockchain.address.get_history', [addr])])
292 class WalletSynchronizer(threading.Thread):
294 def __init__(self, wallet, loop=False):
295 threading.Thread.__init__(self)
299 self.start_interface()
302 def handle_response(self, r):
310 if method == 'server.banner':
311 self.wallet.banner = result
312 self.wallet.was_updated = True
314 elif method == 'server.peers.subscribe':
322 if re.match("[th]\d+",v):
323 ports.append((v[0],v[1:]))
325 servers.append( (host, ports) )
326 self.interface.servers = servers
328 elif method == 'blockchain.address.subscribe':
330 self.wallet.receive_status_callback(addr, result)
332 elif method == 'blockchain.address.get_history':
334 self.wallet.receive_history_callback(addr, result)
335 self.wallet.was_updated = True
337 elif method == 'blockchain.transaction.broadcast':
338 self.wallet.tx_result = result
339 self.wallet.tx_event.set()
341 elif method == 'blockchain.numblocks.subscribe':
342 self.wallet.blocks = result
344 elif method == 'server.version':
348 print "unknown message:", method, params, result
351 def start_interface(self):
353 host, port, protocol = self.wallet.server.split(':')
356 self.wallet.pick_random_server()
357 host, port, protocol = self.wallet.server.split(':')
360 #print protocol, host, port
362 InterfaceClass = TcpStratumInterface
363 elif protocol == 'h':
364 InterfaceClass = HttpStratumInterface
366 print "unknown protocol"
367 InterfaceClass = TcpStratumInterface
369 self.interface = InterfaceClass(host, port)
370 self.wallet.interface = self.interface
372 with self.wallet.lock:
373 self.wallet.addresses_waiting_for_status = []
374 self.wallet.addresses_waiting_for_history = []
375 addresses = self.wallet.all_addresses()
376 version = self.wallet.electrum_version
377 for addr in addresses:
378 self.wallet.addresses_waiting_for_status.append(addr)
381 self.interface.start()
382 self.interface.start_session(addresses,version)
384 self.interface.is_connected = False
390 while self.interface.is_connected:
391 new_addresses = self.wallet.synchronize()
393 self.interface.subscribe(new_addresses)
394 for addr in new_addresses:
395 with self.wallet.lock:
396 self.wallet.addresses_waiting_for_status.append(addr)
398 if self.wallet.is_up_to_date():
399 if not self.wallet.up_to_date:
400 self.wallet.up_to_date = True
401 self.wallet.was_updated = True
402 self.wallet.up_to_date_event.set()
404 if self.wallet.up_to_date:
405 self.wallet.up_to_date = False
406 self.wallet.was_updated = True
408 if self.wallet.was_updated:
409 self.wallet.gui_callback()
410 self.wallet.was_updated = False
412 response = self.interface.responses.get()
413 self.handle_response(response)
415 print "disconnected, gui callback"
416 self.wallet.gui_callback()
419 self.start_interface()