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
23 from version import ELECTRUM_VERSION
26 DEFAULT_SERVERS = [ 'ecdsa.org:50001:t', 'electrum.novit.ro:50001:t', 'electrum.bitcoins.sk:50001:t'] # list of default servers
30 s = s.replace("'blk_hash'", "'block_hash'")
31 s = s.replace("'pos'", "'index'")
32 s = s.replace("'nTime'", "'timestamp'")
33 s = s.replace("'is_in'", "'is_input'")
34 s = s.replace("'raw_scriptPubKey'","'raw_output_script'")
38 class Interface(threading.Thread):
39 def __init__(self, host, port):
40 threading.Thread.__init__(self)
45 self.servers = [] # actual list from IRC
48 self.is_connected = True
49 self.poll_interval = 1
53 self.responses = Queue.Queue()
54 self.unanswered_requests = {}
57 # push a fake response so that the getting thread exits its loop
58 self.responses.put(None)
60 def queue_json_response(self, c):
64 error = c.get('error')
67 print "received error:", c
70 if msg_id is not None:
71 method, params = self.unanswered_requests.pop(msg_id)
72 result = c.get('result')
75 method = c.get('method')
76 params = c.get('params')
78 if method == 'blockchain.numblocks.subscribe':
82 elif method == 'blockchain.address.subscribe':
87 self.responses.put({'method':method, 'params':params, 'result':result})
91 def subscribe(self, addresses):
93 for addr in addresses:
94 messages.append(('blockchain.address.subscribe', [addr]))
100 class PollingInterface(Interface):
101 """ non-persistent connection. synchronous calls"""
103 def __init__(self, host, port):
104 Interface.__init__(self, host, port)
105 self.session_id = None
107 def get_history(self, address):
108 self.send([('blockchain.address.get_history', [address] )])
112 #if is_new or wallet.remote_url:
113 # self.was_updated = True
114 # is_new = wallet.synchronize()
115 # wallet.update_tx_history()
122 self.is_connected = True
123 while self.is_connected:
127 time.sleep(self.poll_interval)
128 except socket.gaierror:
133 traceback.print_exc(file=sys.stdout)
136 self.is_connected = False
147 class HttpStratumInterface(PollingInterface):
152 def send(self, messages):
153 import urllib2, json, time, cookielib
155 cj = cookielib.CookieJar()
156 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
157 urllib2.install_opener(opener)
164 if type(params) != type([]): params = [params]
165 data.append( { 'method':method, 'id':self.message_id, 'params':params } )
166 self.unanswered_requests[self.message_id] = method, params
170 data_json = json.dumps(data)
175 host = 'http://%s:%d'%( self.host, self.port )
176 headers = {'content-type': 'application/json'}
178 headers['cookie'] = 'SESSION=%s'%self.session_id
180 req = urllib2.Request(host, data_json, headers)
181 response_stream = urllib2.urlopen(req)
183 for index, cookie in enumerate(cj):
184 if cookie.name=='SESSION':
185 self.session_id = cookie.value
187 response = response_stream.read()
189 response = json.loads( response )
190 if type(response) is not type([]):
191 self.queue_json_response(response)
193 for item in response:
194 self.queue_json_response(item)
197 self.poll_interval = 1
199 if self.poll_interval < 15:
200 self.poll_interval += 1
201 #print self.poll_interval, response
203 self.rtime = time.time() - t1
204 self.is_connected = True
209 class TcpStratumInterface(Interface):
210 """json-rpc over persistent TCP connection, asynchronous"""
212 def __init__(self, host, port):
213 Interface.__init__(self, host, port)
214 self.s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
215 self.s.settimeout(5*60)
216 self.s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
218 self.s.connect(( self.host, self.port))
219 self.is_connected = True
220 self.send([('server.version', [ELECTRUM_VERSION])])
222 self.is_connected = False
223 print "not connected"
228 while self.is_connected:
229 try: msg = self.s.recv(1024)
230 except socket.timeout:
231 # ping the server with server.version, as a real ping does not exist yet
232 self.send([('server.version', [ELECTRUM_VERSION])])
236 self.is_connected = False
237 print "disconnected."
245 self.queue_json_response(c)
248 traceback.print_exc(file=sys.stdout)
250 self.is_connected = False
254 def send(self, messages):
258 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
259 self.unanswered_requests[self.message_id] = method, params
262 out += request + '\n'
265 def get_history(self, addr):
266 self.send([('blockchain.address.get_history', [addr])])
272 class WalletSynchronizer(threading.Thread):
274 def __init__(self, wallet, loop=False):
275 threading.Thread.__init__(self)
279 self.start_interface()
282 def handle_response(self, r):
290 if method == 'server.banner':
291 self.wallet.banner = result
292 self.wallet.was_updated = True
294 elif method == 'server.peers.subscribe':
302 if re.match("[th]\d+",v):
303 ports.append((v[0],v[1:]))
305 servers.append( (host, ports) )
306 self.interface.servers = servers
308 elif method == 'blockchain.address.subscribe':
310 self.wallet.receive_status_callback(addr, result)
312 elif method == 'blockchain.address.get_history':
314 self.wallet.receive_history_callback(addr, result)
315 self.wallet.was_updated = True
317 elif method == 'blockchain.transaction.broadcast':
318 self.wallet.tx_result = result
319 self.wallet.tx_event.set()
321 elif method == 'blockchain.numblocks.subscribe':
322 self.wallet.blocks = result
324 elif method == 'server.version':
328 print "unknown message:", method, params, result
331 def start_interface(self):
333 host, port, protocol = self.wallet.server.split(':')
336 self.wallet.pick_random_server()
337 host, port, protocol = self.wallet.server.split(':')
340 #print protocol, host, port
342 InterfaceClass = TcpStratumInterface
343 elif protocol == 'h':
344 InterfaceClass = HttpStratumInterface
346 print "unknown protocol"
347 InterfaceClass = TcpStratumInterface
349 self.interface = InterfaceClass(host, port)
350 self.interface.start()
351 self.wallet.interface = self.interface
353 if self.interface.is_connected:
354 self.wallet.start_session(self.interface)
361 while self.interface.is_connected:
362 new_addresses = self.wallet.synchronize()
364 self.interface.subscribe(new_addresses)
366 if self.wallet.is_up_to_date():
367 if not self.wallet.up_to_date:
368 self.wallet.up_to_date = True
369 self.wallet.was_updated = True
370 self.wallet.up_to_date_event.set()
372 if self.wallet.up_to_date:
373 self.wallet.up_to_date = False
374 self.wallet.was_updated = True
376 if self.wallet.was_updated:
377 self.wallet.gui_callback()
378 self.wallet.was_updated = False
380 response = self.interface.responses.get()
381 self.handle_response(response)
383 print "disconnected, gui callback"
384 self.wallet.gui_callback()
387 self.start_interface()