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_block(self, b, chain_ids=frozenset()):
94 block_id = super(MyStore, self).import_block(b, chain_ids)
95 #print "block", block_id
96 for pos in xrange(len(b['transactions'])):
97 tx = b['transactions'][pos]
99 tx['hash'] = util.double_sha256(tx['tx'])
100 tx_id = store.tx_find_id_and_value(tx)
102 self.update_tx_cache(tx_id)
104 print "error: import_block: no tx_id"
108 def update_tx_cache(self, txid):
109 inrows = self.get_tx_inputs(txid, False)
111 _hash = store.binout(row[6])
112 address = hash_to_address(chr(0), _hash)
113 if self.tx_cache.has_key(address):
114 print "cache: invalidating", address
115 self.tx_cache.pop(address)
116 address_queue.put(address)
118 outrows = self.get_tx_outputs(txid, False)
120 _hash = store.binout(row[6])
121 address = hash_to_address(chr(0), _hash)
122 if self.tx_cache.has_key(address):
123 print "cache: invalidating", address
124 self.tx_cache.pop(address)
125 address_queue.put(address)
127 def safe_sql(self,sql, params=(), lock=True):
129 if lock: dblock.acquire()
130 ret = self.selectall(sql,params)
131 if lock: dblock.release()
134 print "sql error", sql
137 def get_tx_outputs(self, tx_id, lock=True):
138 return self.safe_sql("""SELECT
140 txout.txout_scriptPubKey,
147 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
148 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
149 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
150 WHERE txout.tx_id = %d
151 ORDER BY txout.txout_pos
152 """%(tx_id), (), lock)
154 def get_tx_inputs(self, tx_id, lock=True):
155 return self.safe_sql(""" SELECT
159 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
161 COALESCE(txout.txout_pos, u.txout_pos),
164 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
165 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
166 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
167 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
168 WHERE txin.tx_id = %d
169 ORDER BY txin.txin_pos
170 """%(tx_id,), (), lock)
172 def get_address_out_rows(self, dbhash):
173 return self.safe_sql(""" SELECT
183 FROM chain_candidate cc
184 JOIN block b ON (b.block_id = cc.block_id)
185 JOIN block_tx ON (block_tx.block_id = b.block_id)
186 JOIN tx ON (tx.tx_id = block_tx.tx_id)
187 JOIN txin ON (txin.tx_id = tx.tx_id)
188 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
189 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
190 WHERE pubkey.pubkey_hash = ?
191 AND cc.in_longest = 1""", (dbhash,))
193 def get_address_out_rows_memorypool(self, dbhash):
194 return self.safe_sql(""" SELECT
201 JOIN txin ON (txin.tx_id = tx.tx_id)
202 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
203 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
204 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
206 def get_address_in_rows(self, dbhash):
207 return self.safe_sql(""" SELECT
217 FROM chain_candidate cc
218 JOIN block b ON (b.block_id = cc.block_id)
219 JOIN block_tx ON (block_tx.block_id = b.block_id)
220 JOIN tx ON (tx.tx_id = block_tx.tx_id)
221 JOIN txout ON (txout.tx_id = tx.tx_id)
222 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
223 WHERE pubkey.pubkey_hash = ?
224 AND cc.in_longest = 1""", (dbhash,))
226 def get_address_in_rows_memorypool(self, dbhash):
227 return self.safe_sql( """ SELECT
234 JOIN txout ON (txout.tx_id = tx.tx_id)
235 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
236 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
238 def get_history(self, addr):
240 cached_version = self.tx_cache.get( addr )
241 if cached_version is not None:
242 return cached_version
244 version, binaddr = decode_check_address(addr)
248 dbhash = self.binin(binaddr)
250 rows += self.get_address_out_rows( dbhash )
251 rows += self.get_address_in_rows( dbhash )
258 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
260 print "cannot unpack row", row
262 tx_hash = self.hashout_hex(tx_hash)
265 "height": int(height),
267 "blk_hash": self.hashout_hex(blk_hash),
274 txpoints.append(txpoint)
275 known_tx.append(self.hashout_hex(tx_hash))
278 # todo: sort them really...
279 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
283 rows += self.get_address_in_rows_memorypool( dbhash )
284 rows += self.get_address_out_rows_memorypool( dbhash )
285 address_has_mempool = False
288 is_in, tx_hash, tx_id, pos, value = row
289 tx_hash = self.hashout_hex(tx_hash)
290 if tx_hash in known_tx:
293 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
294 address_has_mempool = True
296 # this means pending transactions are returned by getmemorypool
297 if tx_hash not in self.mempool_keys:
300 #print "mempool", tx_hash
305 "blk_hash": 'mempool',
311 txpoints.append(txpoint)
314 for txpoint in txpoints:
315 tx_id = txpoint['tx_id']
318 inrows = self.get_tx_inputs(tx_id)
320 _hash = self.binout(row[6])
321 address = hash_to_address(chr(0), _hash)
322 txinputs.append(address)
323 txpoint['inputs'] = txinputs
325 outrows = self.get_tx_outputs(tx_id)
327 _hash = self.binout(row[6])
328 address = hash_to_address(chr(0), _hash)
329 txoutputs.append(address)
330 txpoint['outputs'] = txoutputs
332 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
333 if not txpoint['is_in']:
334 # detect if already redeemed...
336 if row[6] == dbhash: break
339 #row = self.get_tx_output(tx_id,dbhash)
340 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
341 # if not redeemed, we add the script
343 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
346 if not address_has_mempool:
347 self.tx_cache[addr] = txpoints
353 class Direct_Interface(Interface):
357 def handler(self, method, params = ''):
358 cmds = {'session.new':new_session,
359 'session.poll':poll_session,
360 'session.update':update_session,
361 'transaction.broadcast':send_tx,
362 'address.get_history':store.get_history
365 return func( params )
370 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
371 respdata = urllib.urlopen(bitcoind_url, postdata).read()
373 if r['error'] != None:
374 out = "error: transaction rejected by memorypool\n"+tx
381 def random_string(N):
382 import random, string
383 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
393 return 'wrong password'
397 return repr( len(sessions) )
399 return 'wrong password'
407 return 'wrong password'
409 def get_cache(pw,addr):
411 return store.tx_cache.get(addr)
413 return 'wrong password'
416 def poll_session(session_id):
417 session = sessions.get(session_id)
419 print time.asctime(), "session not found", session_id
420 out = repr( (-1, {}))
423 addresses = session['addresses']
424 session['last_time'] = time.time()
427 for addr in addresses:
428 if store.tx_cache.get( addr ) is not None: k += 1
429 status = get_address_status( addr )
430 last_status = addresses.get( addr )
431 if last_status != status:
432 addresses[addr] = status
435 sessions[session_id]['addresses'] = addresses
436 out = repr( (block_number, ret ) )
437 t2 = time.time() - t1
439 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
444 def do_update_address(addr):
445 # an address was involved in a transaction; we check if it was subscribed to in a session
446 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
447 for session_id in sessions.keys():
448 session = sessions[session_id]
449 if session.get('type') != 'persistent': continue
450 addresses = session['addresses'].keys()
452 if addr in addresses:
453 status = get_address_status( addr )
454 message_id, last_status = session['addresses'][addr]
455 if last_status != status:
456 #print "sending new status for %s:"%addr, status
457 send_status(session_id,message_id,addr,status)
458 sessions[session_id]['addresses'][addr] = (message_id,status)
461 def get_address_status(addr):
462 # get address status, i.e. the last block for that address.
463 tx_points = store.get_history(addr)
467 lastpoint = tx_points[-1]
468 status = lastpoint['blk_hash']
469 # this is a temporary hack; move it up once old clients have disappeared
470 if status == 'mempool': # and session['version'] != "old":
471 status = status + ':%d'% len(tx_points)
475 def send_numblocks(session_id):
476 message_id = sessions_sub_numblocks[session_id]
477 out = json.dumps( {'id':message_id, 'result':block_number} )
478 output_queue.put((session_id, out))
480 def send_status(session_id, message_id, address, status):
481 out = json.dumps( { 'id':message_id, 'result':status } )
482 output_queue.put((session_id, out))
484 def subscribe_to_numblocks(session_id, message_id):
485 sessions_sub_numblocks[session_id] = message_id
486 send_numblocks(session_id)
488 def subscribe_to_address(session_id, message_id, address):
489 status = get_address_status(address)
490 sessions[session_id]['addresses'][address] = (message_id, status)
491 sessions[session_id]['last_time'] = time.time()
492 send_status(session_id, message_id, address, status)
494 def add_address_to_session(session_id, address):
495 status = get_address_status(address)
496 sessions[session_id]['addresses'][addr] = status
497 sessions[session_id]['last_time'] = time.time()
500 def new_session(version, addresses):
501 session_id = random_string(10)
502 sessions[session_id] = { 'addresses':{}, 'version':version }
504 sessions[session_id]['addresses'][a] = ''
505 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
506 sessions[session_id]['last_time'] = time.time()
509 def update_session(session_id,addresses):
510 sessions[session_id]['addresses'] = {}
512 sessions[session_id]['addresses'][a] = ''
513 sessions[session_id]['last_time'] = time.time()
516 def native_server_thread():
517 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
518 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
519 s.bind((config.get('server','host'), config.getint('server','port')))
522 conn, addr = s.accept()
524 thread.start_new_thread(native_client_thread, (addr, conn,))
526 # can't start new thread if there is no memory..
527 traceback.print_exc(file=sys.stdout)
530 def native_client_thread(ipaddr,conn):
531 #print "client thread", ipaddr
541 msg = msg.split('#', 1)[0]
544 cmd, data = ast.literal_eval(msg)
546 print "syntax error", repr(msg), ipaddr
550 out = do_command(cmd, data, ipaddr)
552 #print ipaddr, cmd, len(out)
556 print "error, could not send"
563 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
565 # used by the native handler
566 def do_command(cmd, data, ipaddr):
569 out = "%d"%block_number
571 elif cmd in ['session','new_session']:
574 addresses = ast.literal_eval(data)
577 version, addresses = ast.literal_eval(data)
578 if version[0]=="0": version = "v" + version
582 print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
583 out = new_session(version, addresses)
585 elif cmd=='address.subscribe':
587 session_id, addr = ast.literal_eval(data)
591 return add_address_to_session(session_id,addr)
593 elif cmd=='update_session':
595 session_id, addresses = ast.literal_eval(data)
599 print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
600 out = update_session(session_id,addresses)
602 elif cmd == 'bccapi_login':
605 v, k = ast.literal_eval(data)
606 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
607 print master_public_key
608 wallet_id = random_string(10)
609 w = Wallet( Direct_Interface() )
610 w.master_public_key = master_public_key.decode('hex')
612 wallets[wallet_id] = w
614 print "wallets", wallets
616 elif cmd == 'bccapi_getAccountInfo':
617 from wallet import int_to_hex
618 v, wallet_id = ast.literal_eval(data)
619 w = wallets.get(wallet_id)
621 num = len(w.addresses)
622 c, u = w.get_balance()
623 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
624 out = out.decode('hex')
629 elif cmd == 'bccapi_getAccountStatement':
630 from wallet import int_to_hex
631 v, wallet_id = ast.literal_eval(data)
632 w = wallets.get(wallet_id)
634 num = len(w.addresses)
635 c, u = w.get_balance()
636 total_records = num_records = 0
637 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 )
638 out = out.decode('hex')
643 elif cmd == 'bccapi_getSendCoinForm':
646 elif cmd == 'bccapi_submitTransaction':
650 out = poll_session(data)
655 out = repr( store.get_history( address ) )
662 print timestr(), "sent tx:", ipaddr, out
668 out = repr(peer_list.values())
677 ####################################################################
679 def tcp_server_thread():
680 thread.start_new_thread(process_input_queue, ())
681 thread.start_new_thread(process_output_queue, ())
683 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
684 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
685 s.bind((config.get('server','host'), 50001))
688 conn, addr = s.accept()
690 thread.start_new_thread(tcp_client_thread, (addr, conn,))
692 # can't start new thread if there is no memory..
693 traceback.print_exc(file=sys.stdout)
696 def close_session(session_id):
697 print "lost connection", session_id
698 sessions.pop(session_id)
699 if session_id in sessions_sub_numblocks:
700 sessions_sub_numblocks.pop(session_id)
703 # one thread per client. put requests in a queue.
704 def tcp_client_thread(ipaddr,conn):
705 """ use a persistent connection. put commands in a queue."""
707 print timestr(), "TCP session", ipaddr
710 session_id = random_string(10)
711 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
722 close_session(session_id)
735 close_session(session_id)
740 print "json error", repr(c)
743 message_id = c.get('id')
744 method = c.get('method')
745 params = c.get('params')
747 print "syntax error", repr(c), ipaddr
751 input_queue.put((session_id, message_id, method, params))
755 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
756 def process_input_queue():
758 session_id, message_id, method, data = input_queue.get()
759 if session_id not in sessions.keys():
762 if method == 'address.subscribe':
764 subscribe_to_address(session_id,message_id,address)
765 elif method == 'numblocks.subscribe':
766 subscribe_to_numblocks(session_id,message_id)
767 elif method == 'client.version':
768 sessions[session_id]['version'] = data[0]
769 elif method == 'server.banner':
770 out = { 'result':config.get('server','banner').replace('\\n','\n') }
771 elif method == 'server.peers':
772 out = { 'result':peer_list.values() }
773 elif method == 'address.get_history':
775 out = { 'result':store.get_history( address ) }
776 elif method == 'transaction.broadcast':
777 postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
778 txo = urllib.urlopen(bitcoind_url, postdata).read()
779 print "sent tx:", txo
780 out = json.loads(txo)
782 print "unknown command", method
784 out['id'] = message_id
785 out = json.dumps( out )
786 output_queue.put((session_id, out))
788 # this is a separate thread
789 def process_output_queue():
791 session_id, out = output_queue.get()
792 session = sessions.get(session_id)
795 conn = session.get('conn')
798 close_session(session_id)
803 ####################################################################
806 def memorypool_update(store):
808 ds = BCDataStream.BCDataStream()
809 previous_transactions = store.mempool_keys
810 store.mempool_keys = []
812 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
813 respdata = urllib.urlopen(bitcoind_url, postdata).read()
815 if r['error'] != None:
818 v = r['result'].get('transactions')
821 ds.write(hextx.decode('hex'))
822 tx = deserialize.parse_Transaction(ds)
823 tx['hash'] = util.double_sha256(tx['tx'])
824 tx_hash = store.hashin(tx['hash'])
826 store.mempool_keys.append(tx_hash)
827 if store.tx_find_id_and_value(tx):
830 tx_id = store.import_tx(tx, False)
831 store.update_tx_cache(tx_id)
836 def clean_session_thread():
840 for k,s in sessions.items():
841 if s.get('type') == 'persistent': continue
845 print "lost session", k
850 NICK = 'E_'+random_string(10)
854 s.connect(('irc.freenode.net', 6667))
855 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
856 s.send('NICK '+NICK+'\n')
857 s.send('JOIN #electrum\n')
858 sf = s.makefile('r', 0)
862 line = line.rstrip('\r\n')
865 s.send('PONG '+line[1]+'\n')
866 elif '353' in line: # answer to /names
867 k = line.index('353')
868 for item in line[k+1:]:
869 if item[0:2] == 'E_':
870 s.send('WHO %s\n'%item)
871 elif '352' in line: # answer to /who
872 # warning: this is a horrible hack which apparently works
873 k = line.index('352')
875 ip = socket.gethostbyname(ip)
878 peer_list[name] = (ip,host)
879 if time.time() - t > 5*60:
880 s.send('NAMES #electrum\n')
884 traceback.print_exc(file=sys.stdout)
891 def http_server_thread(store):
892 # see http://code.google.com/p/jsonrpclib/
893 from SocketServer import ThreadingMixIn
894 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
895 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
896 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
897 server.register_function(lambda : peer_list.values(), 'peers')
898 server.register_function(cmd_stop, 'stop')
899 server.register_function(cmd_load, 'load')
900 server.register_function(lambda : block_number, 'blocks')
901 server.register_function(clear_cache, 'clear_cache')
902 server.register_function(get_cache, 'get_cache')
903 server.register_function(send_tx, 'transaction.broadcast')
904 server.register_function(store.get_history, 'address.get_history')
905 server.register_function(add_address_to_session, 'address.subscribe')
906 server.register_function(new_session, 'session.new')
907 server.register_function(update_session, 'session.update')
908 server.register_function(poll_session, 'session.poll')
909 server.serve_forever()
915 if __name__ == '__main__':
919 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
922 out = server.load(password)
926 out = server.stop(password)
927 elif cmd == 'clear_cache':
928 out = server.clear_cache(password)
929 elif cmd == 'get_cache':
930 out = server.get_cache(password,sys.argv[2])
932 out = server.address.get_history(sys.argv[2])
934 out = server.transaction.broadcast(sys.argv[2])
936 out = server.blocks()
938 out = "Unknown command: '%s'" % cmd
943 print "starting Electrum server"
945 conf = DataStore.CONFIG_DEFAULTS
946 args, argv = readconf.parse_argv( [], conf)
947 args.dbtype= config.get('database','type')
948 if args.dbtype == 'sqlite3':
949 args.connect_args = { 'database' : config.get('database','database') }
950 elif args.dbtype == 'MySQLdb':
951 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
952 elif args.dbtype == 'psycopg2':
953 args.connect_args = { 'database' : config.get('database','database') }
954 store = MyStore(args)
956 store.mempool_keys = {}
958 # supported protocols
959 thread.start_new_thread(native_server_thread, ())
960 thread.start_new_thread(tcp_server_thread, ())
961 thread.start_new_thread(http_server_thread, (store,))
963 thread.start_new_thread(clean_session_thread, ())
965 if (config.get('server','irc') == 'yes' ):
966 thread.start_new_thread(irc_thread, ())
972 memorypool_update(store)
974 block_number = store.get_block_number(1)
975 if block_number != old_block_number:
976 old_block_number = block_number
977 for session_id in sessions_sub_numblocks.keys():
978 send_numblocks(session_id)
981 print "IOError: cannot reach bitcoind"
984 traceback.print_exc(file=sys.stdout)
992 addr = address_queue.get(False)
995 do_update_address(addr)
999 print "server stopped"