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)
459 print "poll: session found", session_id
461 ret, addresses = modified_addresses(session)
463 m_sessions[0][session_id]['addresses'] = addresses
465 msg_id, status = addresses[addr]
466 out.append( { 'id':msg_id, 'result':status } )
468 msg_id, last_nb = session.get('numblocks')
470 if last_nb != block_number:
471 m_sessions[0][session_id]['numblocks'] = msg_id, block_number
472 out.append( {'id':msg_id, 'result':block_number} )
477 def do_update_address(addr):
478 # an address was involved in a transaction; we check if it was subscribed to in a session
479 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
481 for session_id in sessions.keys():
482 session = sessions[session_id]
483 if session.get('type') != 'persistent': continue
484 addresses = session['addresses'].keys()
486 if addr in addresses:
487 status = get_address_status( addr )
488 message_id, last_status = session['addresses'][addr]
489 if last_status != status:
490 #print "sending new status for %s:"%addr, status
491 send_status(session_id,message_id,addr,status)
492 sessions[session_id]['addresses'][addr] = (message_id,status)
494 def get_address_status(addr):
495 # get address status, i.e. the last block for that address.
496 tx_points = store.get_history(addr)
500 lastpoint = tx_points[-1]
501 status = lastpoint['blk_hash']
502 # this is a temporary hack; move it up once old clients have disappeared
503 if status == 'mempool': # and session['version'] != "old":
504 status = status + ':%d'% len(tx_points)
508 def send_numblocks(session_id):
509 message_id = sessions_sub_numblocks[session_id]
510 out = json.dumps( {'id':message_id, 'result':block_number} )
511 output_queue.put((session_id, out))
513 def send_status(session_id, message_id, address, status):
514 out = json.dumps( { 'id':message_id, 'result':status } )
515 output_queue.put((session_id, out))
517 def address_get_history_json(_,message_id,address):
518 return store.get_history(address)
520 def subscribe_to_numblocks(session_id, message_id):
521 sessions_sub_numblocks[session_id] = message_id
522 send_numblocks(session_id)
524 def subscribe_to_numblocks_json(session_id, message_id):
526 m_sessions[0][session_id]['numblocks'] = message_id,block_number
529 def subscribe_to_address(session_id, message_id, address):
530 status = get_address_status(address)
531 sessions[session_id]['addresses'][address] = (message_id, status)
532 sessions[session_id]['last_time'] = time.time()
533 send_status(session_id, message_id, address, status)
535 def add_address_to_session_json(session_id, message_id, address):
537 sessions = m_sessions[0]
538 status = get_address_status(address)
539 sessions[session_id]['addresses'][address] = (message_id, status)
540 sessions[session_id]['last_time'] = time.time()
541 m_sessions[0] = sessions
544 def add_address_to_session(session_id, address):
545 status = get_address_status(address)
546 sessions[session_id]['addresses'][addr] = ("", status)
547 sessions[session_id]['last_time'] = time.time()
550 def new_session(version, addresses):
551 session_id = random_string(10)
552 sessions[session_id] = { 'addresses':{}, 'version':version }
554 sessions[session_id]['addresses'][a] = ('','')
555 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
556 sessions[session_id]['last_time'] = time.time()
560 def client_version_json(session_id, _, version):
562 sessions = m_sessions[0]
563 sessions[session_id]['version'] = version
564 m_sessions[0] = sessions
566 def create_session_json(_, __):
567 sessions = m_sessions[0]
568 session_id = random_string(10)
569 print "creating session", session_id
570 sessions[session_id] = { 'addresses':{}, 'numblocks':('','') }
571 sessions[session_id]['last_time'] = time.time()
572 m_sessions[0] = sessions
577 def get_banner(_,__):
578 return config.get('server','banner').replace('\\n','\n')
580 def update_session(session_id,addresses):
581 """deprecated in 0.42"""
582 sessions[session_id]['addresses'] = {}
584 sessions[session_id]['addresses'][a] = ''
585 sessions[session_id]['last_time'] = time.time()
588 def native_server_thread():
589 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
590 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
591 s.bind((config.get('server','host'), config.getint('server','port')))
594 conn, addr = s.accept()
596 thread.start_new_thread(native_client_thread, (addr, conn,))
598 # can't start new thread if there is no memory..
599 traceback.print_exc(file=sys.stdout)
602 def native_client_thread(ipaddr,conn):
603 #print "client thread", ipaddr
613 msg = msg.split('#', 1)[0]
616 cmd, data = ast.literal_eval(msg)
618 print "syntax error", repr(msg), ipaddr
622 out = do_command(cmd, data, ipaddr)
624 #print ipaddr, cmd, len(out)
628 print "error, could not send"
635 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
637 # used by the native handler
638 def do_command(cmd, data, ipaddr):
641 out = "%d"%block_number
643 elif cmd in ['session','new_session']:
646 addresses = ast.literal_eval(data)
649 version, addresses = ast.literal_eval(data)
650 if version[0]=="0": version = "v" + version
654 print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
655 out = new_session(version, addresses)
657 elif cmd=='address.subscribe':
659 session_id, addr = ast.literal_eval(data)
663 out = add_address_to_session(session_id,addr)
665 elif cmd=='update_session':
667 session_id, addresses = ast.literal_eval(data)
671 print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
672 out = update_session(session_id,addresses)
674 elif cmd == 'bccapi_login':
677 v, k = ast.literal_eval(data)
678 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
679 print master_public_key
680 wallet_id = random_string(10)
681 w = Wallet( Direct_Interface() )
682 w.master_public_key = master_public_key.decode('hex')
684 wallets[wallet_id] = w
686 print "wallets", wallets
688 elif cmd == 'bccapi_getAccountInfo':
689 from wallet import int_to_hex
690 v, wallet_id = ast.literal_eval(data)
691 w = wallets.get(wallet_id)
693 num = len(w.addresses)
694 c, u = w.get_balance()
695 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
696 out = out.decode('hex')
701 elif cmd == 'bccapi_getAccountStatement':
702 from wallet import int_to_hex
703 v, wallet_id = ast.literal_eval(data)
704 w = wallets.get(wallet_id)
706 num = len(w.addresses)
707 c, u = w.get_balance()
708 total_records = num_records = 0
709 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 )
710 out = out.decode('hex')
715 elif cmd == 'bccapi_getSendCoinForm':
718 elif cmd == 'bccapi_submitTransaction':
722 out = poll_session(data)
727 out = repr( store.get_history( address ) )
734 print timestr(), "sent tx:", ipaddr, out
740 out = repr(peer_list.values())
749 ####################################################################
751 def tcp_server_thread():
752 thread.start_new_thread(process_input_queue, ())
753 thread.start_new_thread(process_output_queue, ())
755 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
756 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
757 s.bind((config.get('server','host'), 50001))
760 conn, addr = s.accept()
762 thread.start_new_thread(tcp_client_thread, (addr, conn,))
764 # can't start new thread if there is no memory..
765 traceback.print_exc(file=sys.stdout)
768 def close_session(session_id):
769 #print "lost connection", session_id
770 sessions.pop(session_id)
771 if session_id in sessions_sub_numblocks:
772 sessions_sub_numblocks.pop(session_id)
775 # one thread per client. put requests in a queue.
776 def tcp_client_thread(ipaddr,conn):
777 """ use a persistent connection. put commands in a queue."""
779 print timestr(), "TCP session", ipaddr
782 session_id = random_string(10)
783 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
794 close_session(session_id)
807 close_session(session_id)
812 print "json error", repr(c)
815 message_id = c.get('id')
816 method = c.get('method')
817 params = c.get('params')
819 print "syntax error", repr(c), ipaddr
823 input_queue.put((session_id, message_id, method, params))
827 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
828 def process_input_queue():
830 session_id, message_id, method, data = input_queue.get()
831 if session_id not in sessions.keys():
834 if method == 'address.subscribe':
836 subscribe_to_address(session_id,message_id,address)
837 elif method == 'numblocks.subscribe':
838 subscribe_to_numblocks(session_id,message_id)
839 elif method == 'client.version':
840 sessions[session_id]['version'] = data[0]
841 elif method == 'server.banner':
842 out = { 'result':config.get('server','banner').replace('\\n','\n') }
843 elif method == 'server.peers':
844 out = { 'result':peer_list.values() }
845 elif method == 'address.get_history':
847 out = { 'result':store.get_history( address ) }
848 elif method == 'transaction.broadcast':
849 postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
850 txo = urllib.urlopen(bitcoind_url, postdata).read()
851 print "sent tx:", txo
852 out = json.loads(txo)
854 print "unknown command", method
856 out['id'] = message_id
857 out = json.dumps( out )
858 output_queue.put((session_id, out))
860 # this is a separate thread
861 def process_output_queue():
863 session_id, out = output_queue.get()
864 session = sessions.get(session_id)
867 conn = session.get('conn')
870 close_session(session_id)
875 ####################################################################
878 def memorypool_update(store):
880 ds = BCDataStream.BCDataStream()
881 previous_transactions = store.mempool_keys
882 store.mempool_keys = []
884 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
885 respdata = urllib.urlopen(bitcoind_url, postdata).read()
887 if r['error'] != None:
890 v = r['result'].get('transactions')
893 ds.write(hextx.decode('hex'))
894 tx = deserialize.parse_Transaction(ds)
895 tx['hash'] = util.double_sha256(tx['tx'])
896 tx_hash = store.hashin(tx['hash'])
898 store.mempool_keys.append(tx_hash)
899 if store.tx_find_id_and_value(tx):
902 tx_id = store.import_tx(tx, False)
903 store.update_tx_cache(tx_id)
908 def clean_session_thread():
912 for k,s in sessions.items():
913 if s.get('type') == 'persistent': continue
917 print "lost session", k
922 NICK = 'E_'+random_string(10)
926 s.connect(('irc.freenode.net', 6667))
927 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
928 s.send('NICK '+NICK+'\n')
929 s.send('JOIN #electrum\n')
930 sf = s.makefile('r', 0)
934 line = line.rstrip('\r\n')
937 s.send('PONG '+line[1]+'\n')
938 elif '353' in line: # answer to /names
939 k = line.index('353')
940 for item in line[k+1:]:
941 if item[0:2] == 'E_':
942 s.send('WHO %s\n'%item)
943 elif '352' in line: # answer to /who
944 # warning: this is a horrible hack which apparently works
945 k = line.index('352')
947 ip = socket.gethostbyname(ip)
950 peer_list[name] = (ip,host)
951 if time.time() - t > 5*60:
952 s.send('NAMES #electrum\n')
956 traceback.print_exc(file=sys.stdout)
962 def get_peers_json(_,__):
963 return peer_list.values()
965 def http_server_thread(store):
966 # see http://code.google.com/p/jsonrpclib/
967 from SocketServer import ThreadingMixIn
968 from StratumJSONRPCServer import StratumJSONRPCServer
969 class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass
970 server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081))
971 server.register_function(get_peers_json, 'server.peers')
972 server.register_function(cmd_stop, 'stop')
973 server.register_function(cmd_load, 'load')
974 server.register_function(clear_cache, 'clear_cache')
975 server.register_function(get_cache, 'get_cache')
976 server.register_function(get_banner, 'server.banner')
977 server.register_function(lambda a,b,c: send_tx(c), 'transaction.broadcast')
978 server.register_function(address_get_history_json, 'address.get_history')
979 server.register_function(add_address_to_session_json, 'address.subscribe')
980 server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe')
981 server.register_function(client_version_json, 'client.version')
982 server.register_function(create_session_json, 'session.create') # internal message (not part of protocol)
983 server.register_function(poll_session_json, 'session.poll') # internal message (not part of protocol)
984 server.serve_forever()
990 if __name__ == '__main__':
994 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
997 out = server.load(password)
999 out = server.server.peers()
1001 out = server.stop(password)
1002 elif cmd == 'clear_cache':
1003 out = server.clear_cache(password)
1004 elif cmd == 'get_cache':
1005 out = server.get_cache(password,sys.argv[2])
1007 out = server.address.get_history(sys.argv[2])
1009 out = server.transaction.broadcast(sys.argv[2])
1011 out = server.numblocks.subscribe()
1013 out = "Unknown command: '%s'" % cmd
1018 print "starting Electrum server"
1020 conf = DataStore.CONFIG_DEFAULTS
1021 args, argv = readconf.parse_argv( [], conf)
1022 args.dbtype= config.get('database','type')
1023 if args.dbtype == 'sqlite3':
1024 args.connect_args = { 'database' : config.get('database','database') }
1025 elif args.dbtype == 'MySQLdb':
1026 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
1027 elif args.dbtype == 'psycopg2':
1028 args.connect_args = { 'database' : config.get('database','database') }
1029 store = MyStore(args)
1031 store.mempool_keys = {}
1033 # supported protocols
1034 thread.start_new_thread(native_server_thread, ())
1035 thread.start_new_thread(tcp_server_thread, ())
1036 thread.start_new_thread(http_server_thread, (store,))
1038 thread.start_new_thread(clean_session_thread, ())
1040 if (config.get('server','irc') == 'yes' ):
1041 thread.start_new_thread(irc_thread, ())
1047 memorypool_update(store)
1049 block_number = store.get_block_number(1)
1050 if block_number != old_block_number:
1051 old_block_number = block_number
1052 for session_id in sessions_sub_numblocks.keys():
1053 send_numblocks(session_id)
1056 print "IOError: cannot reach bitcoind"
1059 traceback.print_exc(file=sys.stdout)
1067 addr = address_queue.get(False)
1070 do_update_address(addr)
1074 print "server stopped"