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
29 import psycopg2, binascii
31 from Abe.abe import hash_to_address, decode_check_address
32 from Abe.DataStore import DataStore as Datastore_class
33 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
36 from json import dumps, loads
39 # we need to import electrum
40 sys.path.append('../client/')
41 from wallet import Wallet
42 from interface import Interface
45 config = ConfigParser.ConfigParser()
46 # set some defaults, which will be overwritten by the config file
47 config.add_section('server')
48 config.set('server','banner', 'Welcome to Electrum!')
49 config.set('server', 'host', 'localhost')
50 config.set('server', 'port', 50000)
51 config.set('server', 'password', '')
52 config.set('server', 'irc', 'yes')
53 config.set('server', 'ircname', 'Electrum server')
54 config.add_section('database')
55 config.set('database', 'type', 'psycopg2')
56 config.set('database', 'database', 'abe')
59 f = open('/etc/electrum.conf','r')
63 print "Could not read electrum.conf. I will use the default values."
66 f = open('/etc/electrum.banner','r')
67 config.set('server','banner', f.read())
72 password = config.get('server','password')
73 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
79 sessions_sub_numblocks = {} # sessions that have subscribed to the service
81 m_sessions = [{}] # served by http
83 dblock = thread.allocate_lock()
86 wallets = {} # for ultra-light clients such as bccapi
88 from Queue import Queue
90 output_queue = Queue()
91 address_queue = Queue()
95 class MyStore(Datastore_class):
97 def import_block(self, b, chain_ids=frozenset()):
98 block_id = super(MyStore, self).import_block(b, chain_ids)
99 #print "block", block_id
100 for pos in xrange(len(b['transactions'])):
101 tx = b['transactions'][pos]
103 tx['hash'] = util.double_sha256(tx['tx'])
104 tx_id = store.tx_find_id_and_value(tx)
106 self.update_tx_cache(tx_id)
108 print "error: import_block: no tx_id"
112 def update_tx_cache(self, txid):
113 inrows = self.get_tx_inputs(txid, False)
115 _hash = store.binout(row[6])
116 address = hash_to_address(chr(0), _hash)
117 if self.tx_cache.has_key(address):
118 print "cache: invalidating", address
119 self.tx_cache.pop(address)
120 address_queue.put(address)
122 outrows = self.get_tx_outputs(txid, False)
124 _hash = store.binout(row[6])
125 address = hash_to_address(chr(0), _hash)
126 if self.tx_cache.has_key(address):
127 print "cache: invalidating", address
128 self.tx_cache.pop(address)
129 address_queue.put(address)
131 def safe_sql(self,sql, params=(), lock=True):
133 if lock: dblock.acquire()
134 ret = self.selectall(sql,params)
135 if lock: dblock.release()
138 print "sql error", sql
141 def get_tx_outputs(self, tx_id, lock=True):
142 return self.safe_sql("""SELECT
144 txout.txout_scriptPubKey,
151 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
152 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
153 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
154 WHERE txout.tx_id = %d
155 ORDER BY txout.txout_pos
156 """%(tx_id), (), lock)
158 def get_tx_inputs(self, tx_id, lock=True):
159 return self.safe_sql(""" SELECT
163 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
165 COALESCE(txout.txout_pos, u.txout_pos),
168 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
169 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
170 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
171 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
172 WHERE txin.tx_id = %d
173 ORDER BY txin.txin_pos
174 """%(tx_id,), (), lock)
176 def get_address_out_rows(self, dbhash):
177 return self.safe_sql(""" SELECT
187 FROM chain_candidate cc
188 JOIN block b ON (b.block_id = cc.block_id)
189 JOIN block_tx ON (block_tx.block_id = b.block_id)
190 JOIN tx ON (tx.tx_id = block_tx.tx_id)
191 JOIN txin ON (txin.tx_id = tx.tx_id)
192 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
193 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
194 WHERE pubkey.pubkey_hash = ?
195 AND cc.in_longest = 1""", (dbhash,))
197 def get_address_out_rows_memorypool(self, dbhash):
198 return self.safe_sql(""" SELECT
205 JOIN txin ON (txin.tx_id = tx.tx_id)
206 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
207 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
208 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
210 def get_address_in_rows(self, dbhash):
211 return self.safe_sql(""" SELECT
221 FROM chain_candidate cc
222 JOIN block b ON (b.block_id = cc.block_id)
223 JOIN block_tx ON (block_tx.block_id = b.block_id)
224 JOIN tx ON (tx.tx_id = block_tx.tx_id)
225 JOIN txout ON (txout.tx_id = tx.tx_id)
226 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
227 WHERE pubkey.pubkey_hash = ?
228 AND cc.in_longest = 1""", (dbhash,))
230 def get_address_in_rows_memorypool(self, dbhash):
231 return self.safe_sql( """ SELECT
238 JOIN txout ON (txout.tx_id = tx.tx_id)
239 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
240 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
242 def get_history(self, addr):
244 cached_version = self.tx_cache.get( addr )
245 if cached_version is not None:
246 return cached_version
248 version, binaddr = decode_check_address(addr)
252 dbhash = self.binin(binaddr)
254 rows += self.get_address_out_rows( dbhash )
255 rows += self.get_address_in_rows( dbhash )
262 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
264 print "cannot unpack row", row
266 tx_hash = self.hashout_hex(tx_hash)
269 "height": int(height),
271 "blk_hash": self.hashout_hex(blk_hash),
278 txpoints.append(txpoint)
279 known_tx.append(self.hashout_hex(tx_hash))
282 # todo: sort them really...
283 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
287 rows += self.get_address_in_rows_memorypool( dbhash )
288 rows += self.get_address_out_rows_memorypool( dbhash )
289 address_has_mempool = False
292 is_in, tx_hash, tx_id, pos, value = row
293 tx_hash = self.hashout_hex(tx_hash)
294 if tx_hash in known_tx:
297 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
298 address_has_mempool = True
300 # this means pending transactions are returned by getmemorypool
301 if tx_hash not in self.mempool_keys:
304 #print "mempool", tx_hash
309 "blk_hash": 'mempool',
315 txpoints.append(txpoint)
318 for txpoint in txpoints:
319 tx_id = txpoint['tx_id']
322 inrows = self.get_tx_inputs(tx_id)
324 _hash = self.binout(row[6])
325 address = hash_to_address(chr(0), _hash)
326 txinputs.append(address)
327 txpoint['inputs'] = txinputs
329 outrows = self.get_tx_outputs(tx_id)
331 _hash = self.binout(row[6])
332 address = hash_to_address(chr(0), _hash)
333 txoutputs.append(address)
334 txpoint['outputs'] = txoutputs
336 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
337 if not txpoint['is_in']:
338 # detect if already redeemed...
340 if row[6] == dbhash: break
343 #row = self.get_tx_output(tx_id,dbhash)
344 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
345 # if not redeemed, we add the script
347 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
350 if not address_has_mempool:
351 self.tx_cache[addr] = txpoints
357 class Direct_Interface(Interface):
361 def handler(self, method, params = ''):
362 cmds = {'session.new':new_session,
363 'session.poll':poll_session,
364 'session.update':update_session,
365 'transaction.broadcast':send_tx,
366 'address.get_history':store.get_history
369 return func( params )
374 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
375 respdata = urllib.urlopen(bitcoind_url, postdata).read()
377 if r['error'] != None:
378 out = "error: transaction rejected by memorypool\n"+tx
385 def random_string(N):
386 import random, string
387 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
391 def cmd_stop(_,__,pw):
397 return 'wrong password'
399 def cmd_load(_,__,pw):
401 return repr( len(sessions) )
403 return 'wrong password'
406 def clear_cache(_,__,pw):
411 return 'wrong password'
413 def get_cache(_,__,pw,addr):
415 return store.tx_cache.get(addr)
417 return 'wrong password'
422 def modified_addresses(session):
425 addresses = session['addresses']
426 session['last_time'] = time.time()
429 for addr in addresses:
430 if store.tx_cache.get( addr ) is not None: k += 1
431 status = get_address_status( addr )
432 msg_id, last_status = addresses.get( addr )
433 if last_status != status:
434 addresses[addr] = msg_id, status
437 t2 = time.time() - t1
438 #if t2 > 10: print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
439 return ret, addresses
442 def poll_session(session_id):
444 session = sessions.get(session_id)
446 print time.asctime(), "session not found", session_id
449 ret, addresses = modified_addresses(session)
450 if ret: sessions[session_id]['addresses'] = addresses
451 return repr( (block_number,ret))
454 def poll_session_json(session_id, message_id):
455 session = m_sessions[0].get(session_id)
457 raise BaseException("session not found %s"%session_id)
460 ret, addresses = modified_addresses(session)
462 m_sessions[0][session_id]['addresses'] = addresses
464 msg_id, status = addresses[addr]
465 out.append( { 'id':msg_id, 'result':status } )
467 msg_id, last_nb = session.get('numblocks')
469 if last_nb != block_number:
470 m_sessions[0][session_id]['numblocks'] = msg_id, block_number
471 out.append( {'id':msg_id, 'result':block_number} )
476 def do_update_address(addr):
477 # an address was involved in a transaction; we check if it was subscribed to in a session
478 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
480 for session_id in sessions.keys():
481 session = sessions[session_id]
482 if session.get('type') != 'persistent': continue
483 addresses = session['addresses'].keys()
485 if addr in addresses:
486 status = get_address_status( addr )
487 message_id, last_status = session['addresses'][addr]
488 if last_status != status:
489 #print "sending new status for %s:"%addr, status
490 send_status(session_id,message_id,addr,status)
491 sessions[session_id]['addresses'][addr] = (message_id,status)
493 def get_address_status(addr):
494 # get address status, i.e. the last block for that address.
495 tx_points = store.get_history(addr)
499 lastpoint = tx_points[-1]
500 status = lastpoint['blk_hash']
501 # this is a temporary hack; move it up once old clients have disappeared
502 if status == 'mempool': # and session['version'] != "old":
503 status = status + ':%d'% len(tx_points)
507 def send_numblocks(session_id):
508 message_id = sessions_sub_numblocks[session_id]
509 out = json.dumps( {'id':message_id, 'result':block_number} )
510 output_queue.put((session_id, out))
512 def send_status(session_id, message_id, address, status):
513 out = json.dumps( { 'id':message_id, 'result':status } )
514 output_queue.put((session_id, out))
516 def address_get_history_json(_,message_id,address):
517 return store.get_history(address)
519 def subscribe_to_numblocks(session_id, message_id):
520 sessions_sub_numblocks[session_id] = message_id
521 send_numblocks(session_id)
523 def subscribe_to_numblocks_json(session_id, message_id):
525 m_sessions[0][session_id]['numblocks'] = message_id,block_number
528 def subscribe_to_address(session_id, message_id, address):
529 status = get_address_status(address)
530 sessions[session_id]['addresses'][address] = (message_id, status)
531 sessions[session_id]['last_time'] = time.time()
532 send_status(session_id, message_id, address, status)
534 def add_address_to_session_json(session_id, message_id, address):
536 sessions = m_sessions[0]
537 status = get_address_status(address)
538 sessions[session_id]['addresses'][address] = (message_id, status)
539 sessions[session_id]['last_time'] = time.time()
540 m_sessions[0] = sessions
543 def add_address_to_session(session_id, address):
544 status = get_address_status(address)
545 sessions[session_id]['addresses'][addr] = ("", status)
546 sessions[session_id]['last_time'] = time.time()
549 def new_session(version, addresses):
550 session_id = random_string(10)
551 sessions[session_id] = { 'addresses':{}, 'version':version }
553 sessions[session_id]['addresses'][a] = ('','')
554 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
555 sessions[session_id]['last_time'] = time.time()
559 def client_version_json(session_id, _, version):
561 sessions = m_sessions[0]
562 sessions[session_id]['version'] = version
563 m_sessions[0] = sessions
565 def create_session_json(_, __):
566 sessions = m_sessions[0]
567 session_id = random_string(10)
568 print "creating session", session_id
569 sessions[session_id] = { 'addresses':{}, 'numblocks':('','') }
570 sessions[session_id]['last_time'] = time.time()
571 m_sessions[0] = sessions
576 def get_banner(_,__):
577 return config.get('server','banner').replace('\\n','\n')
579 def update_session(session_id,addresses):
580 """deprecated in 0.42"""
581 sessions[session_id]['addresses'] = {}
583 sessions[session_id]['addresses'][a] = ''
584 sessions[session_id]['last_time'] = time.time()
587 def native_server_thread():
588 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
589 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
590 s.bind((config.get('server','host'), config.getint('server','port')))
593 conn, addr = s.accept()
595 thread.start_new_thread(native_client_thread, (addr, conn,))
597 # can't start new thread if there is no memory..
598 traceback.print_exc(file=sys.stdout)
601 def native_client_thread(ipaddr,conn):
602 #print "client thread", ipaddr
612 msg = msg.split('#', 1)[0]
615 cmd, data = ast.literal_eval(msg)
617 print "syntax error", repr(msg), ipaddr
621 out = do_command(cmd, data, ipaddr)
623 #print ipaddr, cmd, len(out)
627 print "error, could not send"
634 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
636 # used by the native handler
637 def do_command(cmd, data, ipaddr):
640 out = "%d"%block_number
642 elif cmd in ['session','new_session']:
645 addresses = ast.literal_eval(data)
648 version, addresses = ast.literal_eval(data)
649 if version[0]=="0": version = "v" + version
653 print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
654 out = new_session(version, addresses)
656 elif cmd=='address.subscribe':
658 session_id, addr = ast.literal_eval(data)
662 out = add_address_to_session(session_id,addr)
664 elif cmd=='update_session':
666 session_id, addresses = ast.literal_eval(data)
670 print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
671 out = update_session(session_id,addresses)
673 elif cmd == 'bccapi_login':
676 v, k = ast.literal_eval(data)
677 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
678 print master_public_key
679 wallet_id = random_string(10)
680 w = Wallet( Direct_Interface() )
681 w.master_public_key = master_public_key.decode('hex')
683 wallets[wallet_id] = w
685 print "wallets", wallets
687 elif cmd == 'bccapi_getAccountInfo':
688 from wallet import int_to_hex
689 v, wallet_id = ast.literal_eval(data)
690 w = wallets.get(wallet_id)
692 num = len(w.addresses)
693 c, u = w.get_balance()
694 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
695 out = out.decode('hex')
700 elif cmd == 'bccapi_getAccountStatement':
701 from wallet import int_to_hex
702 v, wallet_id = ast.literal_eval(data)
703 w = wallets.get(wallet_id)
705 num = len(w.addresses)
706 c, u = w.get_balance()
707 total_records = num_records = 0
708 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 )
709 out = out.decode('hex')
714 elif cmd == 'bccapi_getSendCoinForm':
717 elif cmd == 'bccapi_submitTransaction':
721 out = poll_session(data)
726 out = repr( store.get_history( address ) )
733 print timestr(), "sent tx:", ipaddr, out
739 out = repr(peer_list.values())
748 ####################################################################
750 def tcp_server_thread():
751 thread.start_new_thread(process_input_queue, ())
752 thread.start_new_thread(process_output_queue, ())
754 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
755 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
756 s.bind((config.get('server','host'), 50001))
759 conn, addr = s.accept()
761 thread.start_new_thread(tcp_client_thread, (addr, conn,))
763 # can't start new thread if there is no memory..
764 traceback.print_exc(file=sys.stdout)
767 def close_session(session_id):
768 #print "lost connection", session_id
769 sessions.pop(session_id)
770 if session_id in sessions_sub_numblocks:
771 sessions_sub_numblocks.pop(session_id)
774 # one thread per client. put requests in a queue.
775 def tcp_client_thread(ipaddr,conn):
776 """ use a persistent connection. put commands in a queue."""
778 print timestr(), "TCP session", ipaddr
781 session_id = random_string(10)
782 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
793 close_session(session_id)
806 close_session(session_id)
811 print "json error", repr(c)
814 message_id = c.get('id')
815 method = c.get('method')
816 params = c.get('params')
818 print "syntax error", repr(c), ipaddr
822 input_queue.put((session_id, message_id, method, params))
826 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
827 def process_input_queue():
829 session_id, message_id, method, data = input_queue.get()
830 if session_id not in sessions.keys():
833 if method == 'address.subscribe':
835 subscribe_to_address(session_id,message_id,address)
836 elif method == 'numblocks.subscribe':
837 subscribe_to_numblocks(session_id,message_id)
838 elif method == 'client.version':
839 sessions[session_id]['version'] = data[0]
840 elif method == 'server.banner':
841 out = { 'result':config.get('server','banner').replace('\\n','\n') }
842 elif method == 'server.peers':
843 out = { 'result':peer_list.values() }
844 elif method == 'address.get_history':
846 out = { 'result':store.get_history( address ) }
847 elif method == 'transaction.broadcast':
848 postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
849 txo = urllib.urlopen(bitcoind_url, postdata).read()
850 print "sent tx:", txo
851 out = json.loads(txo)
853 print "unknown command", method
855 out['id'] = message_id
856 out = json.dumps( out )
857 output_queue.put((session_id, out))
859 # this is a separate thread
860 def process_output_queue():
862 session_id, out = output_queue.get()
863 session = sessions.get(session_id)
866 conn = session.get('conn')
869 close_session(session_id)
874 ####################################################################
877 def memorypool_update(store):
879 ds = BCDataStream.BCDataStream()
880 previous_transactions = store.mempool_keys
881 store.mempool_keys = []
883 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
884 respdata = urllib.urlopen(bitcoind_url, postdata).read()
886 if r['error'] != None:
889 v = r['result'].get('transactions')
892 ds.write(hextx.decode('hex'))
893 tx = deserialize.parse_Transaction(ds)
894 tx['hash'] = util.double_sha256(tx['tx'])
895 tx_hash = store.hashin(tx['hash'])
897 store.mempool_keys.append(tx_hash)
898 if store.tx_find_id_and_value(tx):
901 tx_id = store.import_tx(tx, False)
902 store.update_tx_cache(tx_id)
907 def clean_session_thread():
911 for k,s in sessions.items():
912 if s.get('type') == 'persistent': continue
916 print "lost session", k
921 NICK = 'E_'+random_string(10)
925 s.connect(('irc.freenode.net', 6667))
926 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
927 s.send('NICK '+NICK+'\n')
928 s.send('JOIN #electrum\n')
929 sf = s.makefile('r', 0)
933 line = line.rstrip('\r\n')
936 s.send('PONG '+line[1]+'\n')
937 elif '353' in line: # answer to /names
938 k = line.index('353')
939 for item in line[k+1:]:
940 if item[0:2] == 'E_':
941 s.send('WHO %s\n'%item)
942 elif '352' in line: # answer to /who
943 # warning: this is a horrible hack which apparently works
944 k = line.index('352')
946 ip = socket.gethostbyname(ip)
949 peer_list[name] = (ip,host)
950 if time.time() - t > 5*60:
951 s.send('NAMES #electrum\n')
955 traceback.print_exc(file=sys.stdout)
961 def get_peers_json(_,__):
962 return peer_list.values()
964 def http_server_thread(store):
965 # see http://code.google.com/p/jsonrpclib/
966 from SocketServer import ThreadingMixIn
967 from StratumJSONRPCServer import StratumJSONRPCServer
968 class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass
969 server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081))
970 server.register_function(get_peers_json, 'server.peers')
971 server.register_function(cmd_stop, 'stop')
972 server.register_function(cmd_load, 'load')
973 server.register_function(clear_cache, 'clear_cache')
974 server.register_function(get_cache, 'get_cache')
975 server.register_function(get_banner, 'server.banner')
976 server.register_function(lambda a,b,c: send_tx(c), 'transaction.broadcast')
977 server.register_function(address_get_history_json, 'address.get_history')
978 server.register_function(add_address_to_session_json, 'address.subscribe')
979 server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe')
980 server.register_function(client_version_json, 'client.version')
981 server.register_function(create_session_json, 'session.create') # internal message (not part of protocol)
982 server.register_function(poll_session_json, 'session.poll') # internal message (not part of protocol)
983 server.serve_forever()
989 if __name__ == '__main__':
993 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
996 out = server.load(password)
998 out = server.server.peers()
1000 out = server.stop(password)
1001 elif cmd == 'clear_cache':
1002 out = server.clear_cache(password)
1003 elif cmd == 'get_cache':
1004 out = server.get_cache(password,sys.argv[2])
1006 out = server.address.get_history(sys.argv[2])
1008 out = server.transaction.broadcast(sys.argv[2])
1010 out = server.numblocks.subscribe()
1012 out = "Unknown command: '%s'" % cmd
1017 print "starting Electrum server"
1019 conf = DataStore.CONFIG_DEFAULTS
1020 args, argv = readconf.parse_argv( [], conf)
1021 args.dbtype= config.get('database','type')
1022 if args.dbtype == 'sqlite3':
1023 args.connect_args = { 'database' : config.get('database','database') }
1024 elif args.dbtype == 'MySQLdb':
1025 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
1026 elif args.dbtype == 'psycopg2':
1027 args.connect_args = { 'database' : config.get('database','database') }
1028 store = MyStore(args)
1030 store.mempool_keys = {}
1032 # supported protocols
1033 thread.start_new_thread(native_server_thread, ())
1034 thread.start_new_thread(tcp_server_thread, ())
1035 thread.start_new_thread(http_server_thread, (store,))
1037 thread.start_new_thread(clean_session_thread, ())
1039 if (config.get('server','irc') == 'yes' ):
1040 thread.start_new_thread(irc_thread, ())
1046 memorypool_update(store)
1048 block_number = store.get_block_number(1)
1049 if block_number != old_block_number:
1050 old_block_number = block_number
1051 for session_id in sessions_sub_numblocks.keys():
1052 send_numblocks(session_id)
1055 print "IOError: cannot reach bitcoind"
1058 traceback.print_exc(file=sys.stdout)
1066 addr = address_queue.get(False)
1069 do_update_address(addr)
1073 print "server stopped"