2 # Copyright(C) 2011 thomasv@gitorious
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as
6 # published by the Free Software Foundation, either version 3 of the
7 # License, or (at your option) any later version.
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public
15 # License along with this program. If not, see
16 # <http://www.gnu.org/licenses/agpl.html>.
20 * server should check and return bitcoind status..
21 * improve txpoint sorting
22 * command to check cache
24 mempool transactions do not need to be added to the database; it slows it down
28 import time, json, socket, operator, thread, ast, sys,re
32 from json import dumps, loads
35 # we need to import electrum
36 sys.path.append('../client/')
37 from wallet import Wallet
38 from interface import Interface
41 config = ConfigParser.ConfigParser()
42 # set some defaults, which will be overwritten by the config file
43 config.add_section('server')
44 config.set('server','banner', 'Welcome to Electrum!')
45 config.set('server', 'host', 'localhost')
46 config.set('server', 'port', '50000')
47 config.set('server', 'password', '')
48 config.set('server', 'irc', 'yes')
49 config.set('server', 'ircname', 'Electrum server')
50 config.add_section('database')
51 config.set('database', 'type', 'psycopg2')
52 config.set('database', 'database', 'abe')
55 f = open('/etc/electrum.conf','r')
59 print "Could not read electrum.conf. I will use the default values."
62 f = open('/etc/electrum.banner','r')
63 config.set('server','banner', f.read())
69 password = config.get('server','password')
75 sessions_sub_numblocks = {} # sessions that have subscribed to the service
77 m_sessions = [{}] # served by http
81 wallets = {} # for ultra-light clients such as bccapi
83 from Queue import Queue
85 output_queue = Queue()
86 address_queue = Queue()
92 class Direct_Interface(Interface):
96 def handler(self, method, params = ''):
97 cmds = {'session.new':new_session,
98 'session.poll':poll_session,
99 'session.update':update_session,
100 'transaction.broadcast':send_tx,
101 'address.get_history':store.get_history
104 return func( params )
109 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
110 respdata = urllib.urlopen(bitcoind_url, postdata).read()
112 if r['error'] != None:
113 out = "error: transaction rejected by memorypool\n"+tx
120 def random_string(N):
121 import random, string
122 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
126 def cmd_stop(_,__,pw):
132 return 'wrong password'
134 def cmd_load(_,__,pw):
136 return repr( len(sessions) )
138 return 'wrong password'
141 def clear_cache(_,__,pw):
146 return 'wrong password'
148 def get_cache(_,__,pw,addr):
150 return store.tx_cache.get(addr)
152 return 'wrong password'
157 def modified_addresses(session):
160 addresses = session['addresses']
161 session['last_time'] = time.time()
164 for addr in addresses:
165 if store.tx_cache.get( addr ) is not None: k += 1
166 status = get_address_status( addr )
167 msg_id, last_status = addresses.get( addr )
168 if last_status != status:
169 addresses[addr] = msg_id, status
172 t2 = time.time() - t1
173 #if t2 > 10: print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
174 return ret, addresses
177 def poll_session(session_id):
179 session = sessions.get(session_id)
181 print time.asctime(), "session not found", session_id
184 ret, addresses = modified_addresses(session)
185 if ret: sessions[session_id]['addresses'] = addresses
186 return repr( (block_number,ret))
189 def poll_session_json(session_id, message_id):
190 session = m_sessions[0].get(session_id)
192 raise BaseException("session not found %s"%session_id)
195 ret, addresses = modified_addresses(session)
197 m_sessions[0][session_id]['addresses'] = addresses
199 msg_id, status = addresses[addr]
200 out.append( { 'id':msg_id, 'result':status } )
202 msg_id, last_nb = session.get('numblocks')
204 if last_nb != block_number:
205 m_sessions[0][session_id]['numblocks'] = msg_id, block_number
206 out.append( {'id':msg_id, 'result':block_number} )
211 def do_update_address(addr):
212 # an address was involved in a transaction; we check if it was subscribed to in a session
213 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
215 for session_id in sessions.keys():
216 session = sessions[session_id]
217 if session.get('type') != 'persistent': continue
218 addresses = session['addresses'].keys()
220 if addr in addresses:
221 status = get_address_status( addr )
222 message_id, last_status = session['addresses'][addr]
223 if last_status != status:
224 #print "sending new status for %s:"%addr, status
225 send_status(session_id,message_id,addr,status)
226 sessions[session_id]['addresses'][addr] = (message_id,status)
228 def get_address_status(addr):
229 # get address status, i.e. the last block for that address.
230 tx_points = store.get_history(addr)
234 lastpoint = tx_points[-1]
235 status = lastpoint['blk_hash']
236 # this is a temporary hack; move it up once old clients have disappeared
237 if status == 'mempool': # and session['version'] != "old":
238 status = status + ':%d'% len(tx_points)
242 def send_numblocks(session_id):
243 message_id = sessions_sub_numblocks[session_id]
244 out = json.dumps( {'id':message_id, 'result':block_number} )
245 output_queue.put((session_id, out))
247 def send_status(session_id, message_id, address, status):
248 out = json.dumps( { 'id':message_id, 'result':status } )
249 output_queue.put((session_id, out))
251 def address_get_history_json(_,message_id,address):
252 return store.get_history(address)
254 def subscribe_to_numblocks(session_id, message_id):
255 sessions_sub_numblocks[session_id] = message_id
256 send_numblocks(session_id)
258 def subscribe_to_numblocks_json(session_id, message_id):
260 m_sessions[0][session_id]['numblocks'] = message_id,block_number
263 def subscribe_to_address(session_id, message_id, address):
264 status = get_address_status(address)
265 sessions[session_id]['addresses'][address] = (message_id, status)
266 sessions[session_id]['last_time'] = time.time()
267 send_status(session_id, message_id, address, status)
269 def add_address_to_session_json(session_id, message_id, address):
271 sessions = m_sessions[0]
272 status = get_address_status(address)
273 sessions[session_id]['addresses'][address] = (message_id, status)
274 sessions[session_id]['last_time'] = time.time()
275 m_sessions[0] = sessions
278 def add_address_to_session(session_id, address):
279 status = get_address_status(address)
280 sessions[session_id]['addresses'][addr] = ("", status)
281 sessions[session_id]['last_time'] = time.time()
284 def new_session(version, addresses):
285 session_id = random_string(10)
286 sessions[session_id] = { 'addresses':{}, 'version':version }
288 sessions[session_id]['addresses'][a] = ('','')
289 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
290 sessions[session_id]['last_time'] = time.time()
294 def client_version_json(session_id, _, version):
296 sessions = m_sessions[0]
297 sessions[session_id]['version'] = version
298 m_sessions[0] = sessions
300 def create_session_json(_, __):
301 sessions = m_sessions[0]
302 session_id = random_string(10)
303 print "creating session", session_id
304 sessions[session_id] = { 'addresses':{}, 'numblocks':('','') }
305 sessions[session_id]['last_time'] = time.time()
306 m_sessions[0] = sessions
311 def get_banner(_,__):
312 return config.get('server','banner').replace('\\n','\n')
314 def update_session(session_id,addresses):
315 """deprecated in 0.42"""
316 sessions[session_id]['addresses'] = {}
318 sessions[session_id]['addresses'][a] = ''
319 sessions[session_id]['last_time'] = time.time()
322 def native_server_thread():
323 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
324 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
325 s.bind((config.get('server','host'), config.getint('server','port')))
328 conn, addr = s.accept()
330 thread.start_new_thread(native_client_thread, (addr, conn,))
332 # can't start new thread if there is no memory..
333 traceback.print_exc(file=sys.stdout)
336 def native_client_thread(ipaddr,conn):
337 #print "client thread", ipaddr
347 msg = msg.split('#', 1)[0]
350 cmd, data = ast.literal_eval(msg)
352 print "syntax error", repr(msg), ipaddr
356 out = do_command(cmd, data, ipaddr)
358 #print ipaddr, cmd, len(out)
362 print "error, could not send"
369 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
371 # used by the native handler
372 def do_command(cmd, data, ipaddr):
375 out = "%d"%block_number
377 elif cmd in ['session','new_session']:
380 addresses = ast.literal_eval(data)
383 version, addresses = ast.literal_eval(data)
384 if version[0]=="0": version = "v" + version
388 print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
389 out = new_session(version, addresses)
391 elif cmd=='address.subscribe':
393 session_id, addr = ast.literal_eval(data)
397 out = add_address_to_session(session_id,addr)
399 elif cmd=='update_session':
401 session_id, addresses = ast.literal_eval(data)
405 print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
406 out = update_session(session_id,addresses)
408 elif cmd == 'bccapi_login':
411 v, k = ast.literal_eval(data)
412 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
413 print master_public_key
414 wallet_id = random_string(10)
415 w = Wallet( Direct_Interface() )
416 w.master_public_key = master_public_key.decode('hex')
418 wallets[wallet_id] = w
420 print "wallets", wallets
422 elif cmd == 'bccapi_getAccountInfo':
423 from wallet import int_to_hex
424 v, wallet_id = ast.literal_eval(data)
425 w = wallets.get(wallet_id)
427 num = len(w.addresses)
428 c, u = w.get_balance()
429 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
430 out = out.decode('hex')
435 elif cmd == 'bccapi_getAccountStatement':
436 from wallet import int_to_hex
437 v, wallet_id = ast.literal_eval(data)
438 w = wallets.get(wallet_id)
440 num = len(w.addresses)
441 c, u = w.get_balance()
442 total_records = num_records = 0
443 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 ) + int_to_hex( total_records ) + int_to_hex( num_records )
444 out = out.decode('hex')
449 elif cmd == 'bccapi_getSendCoinForm':
452 elif cmd == 'bccapi_submitTransaction':
456 out = poll_session(data)
461 out = repr( store.get_history( address ) )
468 print timestr(), "sent tx:", ipaddr, out
474 out = repr(peer_list.values())
483 ####################################################################
485 def tcp_server_thread():
486 thread.start_new_thread(process_input_queue, ())
487 thread.start_new_thread(process_output_queue, ())
489 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
490 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
491 s.bind((config.get('server','host'), 50001))
494 conn, addr = s.accept()
496 thread.start_new_thread(tcp_client_thread, (addr, conn,))
498 # can't start new thread if there is no memory..
499 traceback.print_exc(file=sys.stdout)
502 def close_session(session_id):
503 #print "lost connection", session_id
504 sessions.pop(session_id)
505 if session_id in sessions_sub_numblocks:
506 sessions_sub_numblocks.pop(session_id)
509 # one thread per client. put requests in a queue.
510 def tcp_client_thread(ipaddr,conn):
511 """ use a persistent connection. put commands in a queue."""
513 print timestr(), "TCP session", ipaddr
516 session_id = random_string(10)
517 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
528 close_session(session_id)
541 close_session(session_id)
546 print "json error", repr(c)
549 message_id = c.get('id')
550 method = c.get('method')
551 params = c.get('params')
553 print "syntax error", repr(c), ipaddr
557 input_queue.put((session_id, message_id, method, params))
561 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
562 def process_input_queue():
564 session_id, message_id, method, data = input_queue.get()
565 if session_id not in sessions.keys():
568 if method == 'address.subscribe':
570 subscribe_to_address(session_id,message_id,address)
571 elif method == 'numblocks.subscribe':
572 subscribe_to_numblocks(session_id,message_id)
573 elif method == 'client.version':
574 sessions[session_id]['version'] = data[0]
575 elif method == 'server.banner':
576 out = { 'result':config.get('server','banner').replace('\\n','\n') }
577 elif method == 'server.peers':
578 out = { 'result':peer_list.values() }
579 elif method == 'address.get_history':
581 out = { 'result':store.get_history( address ) }
582 elif method == 'transaction.broadcast':
583 postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
584 txo = urllib.urlopen(bitcoind_url, postdata).read()
585 print "sent tx:", txo
586 out = json.loads(txo)
588 print "unknown command", method
590 out['id'] = message_id
591 out = json.dumps( out )
592 output_queue.put((session_id, out))
594 # this is a separate thread
595 def process_output_queue():
597 session_id, out = output_queue.get()
598 session = sessions.get(session_id)
601 conn = session.get('conn')
604 close_session(session_id)
609 ####################################################################
614 def clean_session_thread():
618 for k,s in sessions.items():
619 if s.get('type') == 'persistent': continue
623 print "lost session", k
628 NICK = 'E_'+random_string(10)
632 s.connect(('irc.freenode.net', 6667))
633 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
634 s.send('NICK '+NICK+'\n')
635 s.send('JOIN #electrum\n')
636 sf = s.makefile('r', 0)
640 line = line.rstrip('\r\n')
643 s.send('PONG '+line[1]+'\n')
644 elif '353' in line: # answer to /names
645 k = line.index('353')
646 for item in line[k+1:]:
647 if item[0:2] == 'E_':
648 s.send('WHO %s\n'%item)
649 elif '352' in line: # answer to /who
650 # warning: this is a horrible hack which apparently works
651 k = line.index('352')
653 ip = socket.gethostbyname(ip)
656 peer_list[name] = (ip,host)
657 if time.time() - t > 5*60:
658 s.send('NAMES #electrum\n')
662 traceback.print_exc(file=sys.stdout)
668 def get_peers_json(_,__):
669 return peer_list.values()
671 def http_server_thread(store):
672 # see http://code.google.com/p/jsonrpclib/
673 from SocketServer import ThreadingMixIn
674 from StratumJSONRPCServer import StratumJSONRPCServer
675 class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass
676 server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081))
677 server.register_function(get_peers_json, 'server.peers')
678 server.register_function(cmd_stop, 'stop')
679 server.register_function(cmd_load, 'load')
680 server.register_function(clear_cache, 'clear_cache')
681 server.register_function(get_cache, 'get_cache')
682 server.register_function(get_banner, 'server.banner')
683 server.register_function(lambda a,b,c: send_tx(c), 'transaction.broadcast')
684 server.register_function(address_get_history_json, 'address.get_history')
685 server.register_function(add_address_to_session_json, 'address.subscribe')
686 server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe')
687 server.register_function(client_version_json, 'client.version')
688 server.register_function(create_session_json, 'session.create') # internal message (not part of protocol)
689 server.register_function(poll_session_json, 'session.poll') # internal message (not part of protocol)
690 server.serve_forever()
696 if __name__ == '__main__':
700 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
703 out = server.load(password)
705 out = server.server.peers()
707 out = server.stop(password)
708 elif cmd == 'clear_cache':
709 out = server.clear_cache(password)
710 elif cmd == 'get_cache':
711 out = server.get_cache(password,sys.argv[2])
713 out = server.address.get_history(sys.argv[2])
715 out = server.transaction.broadcast(sys.argv[2])
717 out = server.numblocks.subscribe()
719 out = "Unknown command: '%s'" % cmd
726 store = db.MyStore(config,address_queue)
729 # supported protocols
730 thread.start_new_thread(native_server_thread, ())
731 thread.start_new_thread(tcp_server_thread, ())
732 thread.start_new_thread(http_server_thread, (store,))
733 thread.start_new_thread(clean_session_thread, ())
735 if (config.get('server','irc') == 'yes' ):
736 thread.start_new_thread(irc_thread, ())
738 print "starting Electrum server"
742 block_number = store.main_iteration()
744 if block_number != old_block_number:
745 old_block_number = block_number
746 for session_id in sessions_sub_numblocks.keys():
747 send_numblocks(session_id)
751 addr = address_queue.get(False)
754 do_update_address(addr)
757 print "server stopped"