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])])
221 print "Connected to %s:%d"%(self.host,self.port)
223 self.is_connected = False
224 print "Not connected"
229 while self.is_connected:
230 try: msg = self.s.recv(1024)
231 except socket.timeout:
232 # ping the server with server.version, as a real ping does not exist yet
233 self.send([('server.version', [ELECTRUM_VERSION])])
237 self.is_connected = False
238 print "disconnected."
246 self.queue_json_response(c)
249 traceback.print_exc(file=sys.stdout)
251 self.is_connected = False
255 def send(self, messages):
259 request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
260 self.unanswered_requests[self.message_id] = method, params
263 out += request + '\n'
266 def get_history(self, addr):
267 self.send([('blockchain.address.get_history', [addr])])
273 class WalletSynchronizer(threading.Thread):
275 def __init__(self, wallet, loop=False):
276 threading.Thread.__init__(self)
280 self.start_interface()
283 def handle_response(self, r):
291 if method == 'server.banner':
292 self.wallet.banner = result
293 self.wallet.was_updated = True
295 elif method == 'server.peers.subscribe':
303 if re.match("[th]\d+",v):
304 ports.append((v[0],v[1:]))
306 servers.append( (host, ports) )
307 self.interface.servers = servers
309 elif method == 'blockchain.address.subscribe':
311 self.wallet.receive_status_callback(addr, result)
313 elif method == 'blockchain.address.get_history':
315 self.wallet.receive_history_callback(addr, result)
316 self.wallet.was_updated = True
318 elif method == 'blockchain.transaction.broadcast':
319 self.wallet.tx_result = result
320 self.wallet.tx_event.set()
322 elif method == 'blockchain.numblocks.subscribe':
323 self.wallet.blocks = result
325 elif method == 'server.version':
329 print "unknown message:", method, params, result
332 def start_interface(self):
334 host, port, protocol = self.wallet.server.split(':')
337 self.wallet.pick_random_server()
338 host, port, protocol = self.wallet.server.split(':')
341 #print protocol, host, port
343 InterfaceClass = TcpStratumInterface
344 elif protocol == 'h':
345 InterfaceClass = HttpStratumInterface
347 print "unknown protocol"
348 InterfaceClass = TcpStratumInterface
350 self.interface = InterfaceClass(host, port)
351 self.interface.start()
352 self.wallet.interface = self.interface
354 if self.interface.is_connected:
355 self.wallet.start_session(self.interface)
362 while self.interface.is_connected:
363 new_addresses = self.wallet.synchronize()
365 self.interface.subscribe(new_addresses)
367 if self.wallet.is_up_to_date():
368 if not self.wallet.up_to_date:
369 self.wallet.up_to_date = True
370 self.wallet.was_updated = True
371 self.wallet.up_to_date_event.set()
373 if self.wallet.up_to_date:
374 self.wallet.up_to_date = False
375 self.wallet.was_updated = True
377 if self.wallet.was_updated:
378 self.wallet.gui_callback()
379 self.wallet.was_updated = False
381 response = self.interface.responses.get()
382 self.handle_response(response)
384 self.wallet.gui_callback()
387 self.start_interface()