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 dblock = thread.allocate_lock()
84 wallets = {} # for ultra-light clients such as bccapi
86 from Queue import Queue
88 output_queue = Queue()
89 address_queue = Queue()
91 class MyStore(Datastore_class):
93 def import_tx(self, tx, is_coinbase):
94 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
95 self.update_tx_cache(tx_id)
97 def update_tx_cache(self, txid):
98 inrows = self.get_tx_inputs(txid, False)
100 _hash = store.binout(row[6])
101 address = hash_to_address(chr(0), _hash)
102 if self.tx_cache.has_key(address):
103 print "cache: invalidating", address
104 self.tx_cache.pop(address)
105 address_queue.put(address)
107 outrows = self.get_tx_outputs(txid, False)
109 _hash = store.binout(row[6])
110 address = hash_to_address(chr(0), _hash)
111 if self.tx_cache.has_key(address):
112 print "cache: invalidating", address
113 self.tx_cache.pop(address)
114 address_queue.put(address)
116 def safe_sql(self,sql, params=(), lock=True):
118 if lock: dblock.acquire()
119 ret = self.selectall(sql,params)
120 if lock: dblock.release()
123 print "sql error", sql
126 def get_tx_outputs(self, tx_id, lock=True):
127 return self.safe_sql("""SELECT
129 txout.txout_scriptPubKey,
136 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
137 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
138 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
139 WHERE txout.tx_id = %d
140 ORDER BY txout.txout_pos
141 """%(tx_id), (), lock)
143 def get_tx_inputs(self, tx_id, lock=True):
144 return self.safe_sql(""" SELECT
148 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
150 COALESCE(txout.txout_pos, u.txout_pos),
153 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
154 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
155 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
156 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
157 WHERE txin.tx_id = %d
158 ORDER BY txin.txin_pos
159 """%(tx_id,), (), lock)
161 def get_address_out_rows(self, dbhash):
162 return self.safe_sql(""" SELECT
172 FROM chain_candidate cc
173 JOIN block b ON (b.block_id = cc.block_id)
174 JOIN block_tx ON (block_tx.block_id = b.block_id)
175 JOIN tx ON (tx.tx_id = block_tx.tx_id)
176 JOIN txin ON (txin.tx_id = tx.tx_id)
177 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
178 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
179 WHERE pubkey.pubkey_hash = ?
180 AND cc.in_longest = 1""", (dbhash,))
182 def get_address_out_rows_memorypool(self, dbhash):
183 return self.safe_sql(""" SELECT
190 JOIN txin ON (txin.tx_id = tx.tx_id)
191 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
192 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
193 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
195 def get_address_in_rows(self, dbhash):
196 return self.safe_sql(""" SELECT
206 FROM chain_candidate cc
207 JOIN block b ON (b.block_id = cc.block_id)
208 JOIN block_tx ON (block_tx.block_id = b.block_id)
209 JOIN tx ON (tx.tx_id = block_tx.tx_id)
210 JOIN txout ON (txout.tx_id = tx.tx_id)
211 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
212 WHERE pubkey.pubkey_hash = ?
213 AND cc.in_longest = 1""", (dbhash,))
215 def get_address_in_rows_memorypool(self, dbhash):
216 return self.safe_sql( """ SELECT
223 JOIN txout ON (txout.tx_id = tx.tx_id)
224 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
225 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
227 def get_history(self, addr):
229 cached_version = self.tx_cache.get( addr )
230 if cached_version is not None:
231 return cached_version
233 version, binaddr = decode_check_address(addr)
237 dbhash = self.binin(binaddr)
239 rows += self.get_address_out_rows( dbhash )
240 rows += self.get_address_in_rows( dbhash )
247 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
249 print "cannot unpack row", row
251 tx_hash = self.hashout_hex(tx_hash)
254 "height": int(height),
256 "blk_hash": self.hashout_hex(blk_hash),
263 txpoints.append(txpoint)
264 known_tx.append(self.hashout_hex(tx_hash))
267 # todo: sort them really...
268 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
272 rows += self.get_address_in_rows_memorypool( dbhash )
273 rows += self.get_address_out_rows_memorypool( dbhash )
274 address_has_mempool = False
277 is_in, tx_hash, tx_id, pos, value = row
278 tx_hash = self.hashout_hex(tx_hash)
279 if tx_hash in known_tx:
282 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
283 address_has_mempool = True
285 # this means pending transactions are returned by getmemorypool
286 if tx_hash not in self.mempool_keys:
289 #print "mempool", tx_hash
294 "blk_hash": 'mempool',
300 txpoints.append(txpoint)
303 for txpoint in txpoints:
304 tx_id = txpoint['tx_id']
307 inrows = self.get_tx_inputs(tx_id)
309 _hash = self.binout(row[6])
310 address = hash_to_address(chr(0), _hash)
311 txinputs.append(address)
312 txpoint['inputs'] = txinputs
314 outrows = self.get_tx_outputs(tx_id)
316 _hash = self.binout(row[6])
317 address = hash_to_address(chr(0), _hash)
318 txoutputs.append(address)
319 txpoint['outputs'] = txoutputs
321 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
322 if not txpoint['is_in']:
323 # detect if already redeemed...
325 if row[6] == dbhash: break
328 #row = self.get_tx_output(tx_id,dbhash)
329 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
330 # if not redeemed, we add the script
332 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
335 if not address_has_mempool:
336 self.tx_cache[addr] = txpoints
342 class Direct_Interface(Interface):
346 def handler(self, method, params = ''):
347 cmds = {'session.new':new_session,
348 'session.poll':poll_session,
349 'session.update':update_session,
350 'blockchain.transaction.broadcast':send_tx,
351 'blockchain.address.get_history':store.get_history
354 return func( params )
359 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
360 respdata = urllib.urlopen(bitcoind_url, postdata).read()
362 if r['error'] != None:
363 out = "error: transaction rejected by memorypool\n"+tx
370 def random_string(N):
371 import random, string
372 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
382 return 'wrong password'
386 return repr( len(sessions) )
388 return 'wrong password'
396 return 'wrong password'
398 def get_cache(pw,addr):
400 return store.tx_cache.get(addr)
402 return 'wrong password'
405 def poll_session(session_id):
406 session = sessions.get(session_id)
408 print time.asctime(), "session not found", session_id
409 out = repr( (-1, {}))
412 addresses = session['addresses']
413 session['last_time'] = time.time()
416 for addr in addresses:
417 if store.tx_cache.get( addr ) is not None: k += 1
418 status = get_address_status( addr )
419 last_status = addresses.get( addr )
420 if last_status != status:
421 addresses[addr] = status
424 sessions[session_id]['addresses'] = addresses
425 out = repr( (block_number, ret ) )
426 t2 = time.time() - t1
428 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
433 def do_update_address(addr):
434 # an address was involved in a transaction; we check if it was subscribed to in a session
435 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
436 for session_id in sessions.keys():
437 session = sessions[session_id]
438 if session.get('type') != 'subscribe': continue
439 addresses = session['addresses'].keys()
441 if addr in addresses:
442 print "address ", addr, "is watched by", session_id
443 status = get_address_status( addr )
444 last_status = session['addresses'][addr]
445 if last_status != status:
446 print "sending new status for %s:"%addr, status
447 send_status(session_id,addr,status)
448 sessions[session_id]['addresses'][addr] = status
451 def get_address_status(addr):
452 # get address status, i.e. the last block for that address.
453 tx_points = store.get_history(addr)
457 lastpoint = tx_points[-1]
458 status = lastpoint['blk_hash']
459 # this is a temporary hack; move it up once old clients have disappeared
460 if status == 'mempool': # and session['version'] != "old":
461 status = status + ':%d'% len(tx_points)
465 def send_numblocks(session_id):
466 out = json.dumps( {'method':'numblocks.subscribe', 'result':block_number} )
467 output_queue.put((session_id, out))
469 def send_status(session_id, address, status):
470 out = json.dumps( { 'method':'address.subscribe', 'address':address, 'status':status } )
471 output_queue.put((session_id, out))
473 def subscribe_to_numblocks(session_id):
474 sessions_sub_numblocks.append(session_id)
475 send_numblocks(session_id)
477 def subscribe_to_address(session_id, address):
478 status = get_address_status(address)
479 sessions[session_id]['type'] = 'subscribe'
480 sessions[session_id]['addresses'][address] = status
481 sessions[session_id]['last_time'] = time.time()
482 send_status(session_id, address, status)
484 def new_session(version, addresses):
485 session_id = random_string(10)
486 sessions[session_id] = { 'addresses':{}, 'version':version }
488 sessions[session_id]['addresses'][a] = ''
489 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
490 sessions[session_id]['last_time'] = time.time()
493 def update_session(session_id,addresses):
494 sessions[session_id]['addresses'] = {}
496 sessions[session_id]['addresses'][a] = ''
497 sessions[session_id]['last_time'] = time.time()
500 def native_server_thread():
501 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
502 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
503 s.bind((config.get('server','host'), config.getint('server','port')))
506 conn, addr = s.accept()
508 thread.start_new_thread(native_client_thread, (addr, conn,))
510 # can't start new thread if there is no memory..
511 traceback.print_exc(file=sys.stdout)
514 def native_client_thread(ipaddr,conn):
515 #print "client thread", ipaddr
525 msg = msg.split('#', 1)[0]
528 cmd, data = ast.literal_eval(msg)
530 print "syntax error", repr(msg), ipaddr
534 out = do_command(cmd, data, ipaddr)
536 #print ipaddr, cmd, len(out)
540 print "error, could not send"
547 # used by the native handler
548 def do_command(cmd, data, ipaddr):
550 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
553 out = "%d"%block_number
555 elif cmd in ['session','new_session']:
558 addresses = ast.literal_eval(data)
561 version, addresses = ast.literal_eval(data)
562 if version[0]=="0": version = "v" + version
566 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
567 out = new_session(version, addresses)
569 elif cmd=='update_session':
571 session_id, addresses = ast.literal_eval(data)
575 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
576 out = update_session(session_id,addresses)
578 elif cmd == 'bccapi_login':
581 v, k = ast.literal_eval(data)
582 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
583 print master_public_key
584 wallet_id = random_string(10)
585 w = Wallet( Direct_Interface() )
586 w.master_public_key = master_public_key.decode('hex')
588 wallets[wallet_id] = w
590 print "wallets", wallets
592 elif cmd == 'bccapi_getAccountInfo':
593 from wallet import int_to_hex
594 v, wallet_id = ast.literal_eval(data)
595 w = wallets.get(wallet_id)
597 num = len(w.addresses)
598 c, u = w.get_balance()
599 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
600 out = out.decode('hex')
605 elif cmd == 'bccapi_getAccountStatement':
606 from wallet import int_to_hex
607 v, wallet_id = ast.literal_eval(data)
608 w = wallets.get(wallet_id)
610 num = len(w.addresses)
611 c, u = w.get_balance()
612 total_records = num_records = 0
613 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 )
614 out = out.decode('hex')
619 elif cmd == 'bccapi_getSendCoinForm':
622 elif cmd == 'bccapi_submitTransaction':
626 out = poll_session(data)
631 out = repr( store.get_history( address ) )
638 print timestr, "sent tx:", ipaddr, out
644 out = repr(peer_list.values())
653 ####################################################################
655 def tcp_server_thread():
656 thread.start_new_thread(process_input_queue, ())
657 thread.start_new_thread(process_output_queue, ())
659 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
660 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
661 s.bind((config.get('server','host'), 50001))
664 conn, addr = s.accept()
666 thread.start_new_thread(tcp_client_thread, (addr, conn,))
668 # can't start new thread if there is no memory..
669 traceback.print_exc(file=sys.stdout)
672 def close_session(session_id):
673 print "lost connection", session_id
674 sessions.pop(session_id)
675 if session_id in sessions_sub_numblocks:
676 sessions_sub_numblocks.remove(session_id)
679 # one thread per client. put requests in a queue.
680 def tcp_client_thread(ipaddr,conn):
681 """ use a persistent connection. put commands in a queue."""
682 print "persistent client thread", ipaddr
685 session_id = random_string(10)
686 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown' }
697 close_session(session_id)
710 close_session(session_id)
715 print "json error", repr(c)
721 print "syntax error", repr(c), ipaddr
725 input_queue.put((session_id, cmd, data))
729 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
730 def process_input_queue():
732 session_id, cmd, data = input_queue.get()
733 if session_id not in sessions.keys():
736 if cmd == 'address.subscribe':
737 subscribe_to_address(session_id,data)
738 elif cmd == 'numblocks.subscribe':
739 subscribe_to_numblocks(session_id)
740 elif cmd == 'client.version':
741 sessions[session_id]['version'] = data
742 elif cmd == 'server.banner':
743 out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
744 elif cmd == 'server.peers':
745 out = json.dumps( { 'method':'server.peers', 'result':peer_list.values() } )
746 elif cmd == 'address.get_history':
748 out = json.dumps( { 'method':'address.get_history', 'address':address, 'result':store.get_history( address ) } )
749 elif cmd == 'transaction.broadcast':
751 print "sent tx:", txo
752 out = json.dumps( { 'method':'transaction.broadcast', 'result':txo } )
754 print "unknown command", cmd
756 output_queue.put((session_id, out))
758 # this is a separate thread
759 def process_output_queue():
761 session_id, out = output_queue.get()
762 session = sessions.get(session_id)
765 conn = session.get('conn')
768 close_session(session_id)
773 ####################################################################
776 def memorypool_update(store):
777 """ when a tx is removed from memory pool, I need to notify subscribers"""
779 ds = BCDataStream.BCDataStream()
780 previous_transactions = store.mempool_keys
781 store.mempool_keys = []
783 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
784 respdata = urllib.urlopen(bitcoind_url, postdata).read()
786 if r['error'] != None:
789 v = r['result'].get('transactions')
792 ds.write(hextx.decode('hex'))
793 tx = deserialize.parse_Transaction(ds)
794 tx['hash'] = util.double_sha256(tx['tx'])
795 tx_hash = store.hashin(tx['hash'])
797 store.mempool_keys.append(tx_hash)
798 if store.tx_find_id_and_value(tx):
801 store.import_tx(tx, False)
804 for tx_hash in previous_transactions:
805 if tx_hash not in store.mempool_keys:
806 tx = { 'hash':store.hashout(tx_hash) }
807 tx_id = store.tx_find_id_and_value(tx)
809 store.update_tx_cache(tx_id)
812 def clean_session_thread():
816 for k,s in sessions.items():
817 if s.get('type') == 'subscribe': continue
821 print "lost session", k
826 NICK = 'E_'+random_string(10)
830 s.connect(('irc.freenode.net', 6667))
831 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
832 s.send('NICK '+NICK+'\n')
833 s.send('JOIN #electrum\n')
834 sf = s.makefile('r', 0)
838 line = line.rstrip('\r\n')
841 s.send('PONG '+line[1]+'\n')
842 elif '353' in line: # answer to /names
843 k = line.index('353')
844 for item in line[k+1:]:
845 if item[0:2] == 'E_':
846 s.send('WHO %s\n'%item)
847 elif '352' in line: # answer to /who
848 # warning: this is a horrible hack which apparently works
849 k = line.index('352')
851 ip = socket.gethostbyname(ip)
854 peer_list[name] = (ip,host)
855 if time.time() - t > 5*60:
856 s.send('NAMES #electrum\n')
860 traceback.print_exc(file=sys.stdout)
867 def http_server_thread(store):
868 # see http://code.google.com/p/jsonrpclib/
869 from SocketServer import ThreadingMixIn
870 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
871 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
872 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
873 server.register_function(lambda : peer_list.values(), 'peers')
874 server.register_function(cmd_stop, 'stop')
875 server.register_function(cmd_load, 'load')
876 server.register_function(lambda : block_number, 'blocks')
877 server.register_function(clear_cache, 'clear_cache')
878 server.register_function(get_cache, 'get_cache')
879 server.register_function(send_tx, 'blockchain.transaction.broadcast')
880 server.register_function(store.get_history, 'blockchain.address.get_history')
881 server.register_function(new_session, 'session.new')
882 server.register_function(update_session, 'session.update')
883 server.register_function(poll_session, 'session.poll')
884 server.serve_forever()
890 if __name__ == '__main__':
894 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
897 out = server.load(password)
901 out = server.stop(password)
902 elif cmd == 'clear_cache':
903 out = server.clear_cache(password)
904 elif cmd == 'get_cache':
905 out = server.get_cache(password,sys.argv[2])
907 out = server.blockchain.address.get_history(sys.argv[2])
909 out = server.blockchain.transaction.broadcast(sys.argv[2])
911 out = server.blocks()
913 out = "Unknown command: '%s'" % cmd
918 print "starting Electrum server"
920 conf = DataStore.CONFIG_DEFAULTS
921 args, argv = readconf.parse_argv( [], conf)
922 args.dbtype= config.get('database','type')
923 if args.dbtype == 'sqlite3':
924 args.connect_args = { 'database' : config.get('database','database') }
925 elif args.dbtype == 'MySQLdb':
926 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
927 elif args.dbtype == 'psycopg2':
928 args.connect_args = { 'database' : config.get('database','database') }
929 store = MyStore(args)
931 store.mempool_keys = {}
933 # supported protocols
934 thread.start_new_thread(native_server_thread, ())
935 thread.start_new_thread(tcp_server_thread, ())
936 thread.start_new_thread(http_server_thread, (store,))
938 thread.start_new_thread(clean_session_thread, ())
940 if (config.get('server','irc') == 'yes' ):
941 thread.start_new_thread(irc_thread, ())
947 memorypool_update(store)
948 block_number = store.get_block_number(1)
950 if block_number != old_block_number:
951 old_block_number = block_number
952 for session_id in sessions_sub_numblocks:
953 send_numblocks(session_id)
956 print "IOError: cannot reach bitcoind"
959 traceback.print_exc(file=sys.stdout)
967 addr = address_queue.get(False)
970 do_update_address(addr)
974 print "server stopped"