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', 'cache', 'no')
54 config.set('server', 'ircname', 'Electrum server')
55 config.add_section('database')
56 config.set('database', 'type', 'psycopg2')
57 config.set('database', 'database', 'abe')
60 f = open('/etc/electrum.conf','r')
64 print "Could not read electrum.conf. I will use the default values."
67 f = open('/etc/electrum.banner','r')
68 config.set('server','banner', f.read())
73 password = config.get('server','password')
74 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
80 sessions_sub_numblocks = [] # sessions that have subscribed to the service
82 dblock = thread.allocate_lock()
85 wallets = {} # for ultra-light clients such as bccapi
87 from Queue import Queue
89 output_queue = Queue()
90 address_queue = Queue()
92 class MyStore(Datastore_class):
94 def import_tx(self, tx, is_coinbase):
95 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
96 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
98 def update_tx_cache(self, txid):
99 inrows = self.get_tx_inputs(txid, False)
101 _hash = store.binout(row[6])
102 address = hash_to_address(chr(0), _hash)
103 if self.tx_cache.has_key(address):
104 print "cache: invalidating", address
105 self.tx_cache.pop(address)
106 address_queue.put(address)
108 outrows = self.get_tx_outputs(txid, False)
110 _hash = store.binout(row[6])
111 address = hash_to_address(chr(0), _hash)
112 if self.tx_cache.has_key(address):
113 print "cache: invalidating", address
114 self.tx_cache.pop(address)
115 address_queue.put(address)
117 def safe_sql(self,sql, params=(), lock=True):
119 if lock: dblock.acquire()
120 ret = self.selectall(sql,params)
121 if lock: dblock.release()
124 print "sql error", sql
127 def get_tx_outputs(self, tx_id, lock=True):
128 return self.safe_sql("""SELECT
130 txout.txout_scriptPubKey,
137 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
138 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
139 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
140 WHERE txout.tx_id = %d
141 ORDER BY txout.txout_pos
142 """%(tx_id), (), lock)
144 def get_tx_inputs(self, tx_id, lock=True):
145 return self.safe_sql(""" SELECT
149 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
151 COALESCE(txout.txout_pos, u.txout_pos),
154 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
155 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
156 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
157 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
158 WHERE txin.tx_id = %d
159 ORDER BY txin.txin_pos
160 """%(tx_id,), (), lock)
162 def get_address_out_rows(self, dbhash):
163 return self.safe_sql(""" SELECT
173 FROM chain_candidate cc
174 JOIN block b ON (b.block_id = cc.block_id)
175 JOIN block_tx ON (block_tx.block_id = b.block_id)
176 JOIN tx ON (tx.tx_id = block_tx.tx_id)
177 JOIN txin ON (txin.tx_id = tx.tx_id)
178 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
179 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
180 WHERE pubkey.pubkey_hash = ?
181 AND cc.in_longest = 1""", (dbhash,))
183 def get_address_out_rows_memorypool(self, dbhash):
184 return self.safe_sql(""" SELECT
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 = ? """, (dbhash,))
196 def get_address_in_rows(self, dbhash):
197 return self.safe_sql(""" SELECT
207 FROM chain_candidate cc
208 JOIN block b ON (b.block_id = cc.block_id)
209 JOIN block_tx ON (block_tx.block_id = b.block_id)
210 JOIN tx ON (tx.tx_id = block_tx.tx_id)
211 JOIN txout ON (txout.tx_id = tx.tx_id)
212 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
213 WHERE pubkey.pubkey_hash = ?
214 AND cc.in_longest = 1""", (dbhash,))
216 def get_address_in_rows_memorypool(self, dbhash):
217 return self.safe_sql( """ SELECT
224 JOIN txout ON (txout.tx_id = tx.tx_id)
225 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
226 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
228 def get_history(self, addr):
230 if config.get('server','cache') == 'yes':
231 cached_version = self.tx_cache.get( addr )
232 if cached_version is not None:
233 return cached_version
235 version, binaddr = decode_check_address(addr)
239 dbhash = self.binin(binaddr)
241 rows += self.get_address_out_rows( dbhash )
242 rows += self.get_address_in_rows( dbhash )
249 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
251 print "cannot unpack row", row
253 tx_hash = self.hashout_hex(tx_hash)
256 "height": int(height),
258 "blk_hash": self.hashout_hex(blk_hash),
265 txpoints.append(txpoint)
266 known_tx.append(self.hashout_hex(tx_hash))
269 # todo: sort them really...
270 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
274 rows += self.get_address_in_rows_memorypool( dbhash )
275 rows += self.get_address_out_rows_memorypool( dbhash )
276 address_has_mempool = False
279 is_in, tx_hash, tx_id, pos, value = row
280 tx_hash = self.hashout_hex(tx_hash)
281 if tx_hash in known_tx:
284 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
285 address_has_mempool = True
287 # this means pending transactions are returned by getmemorypool
288 if tx_hash not in self.mempool_keys:
291 #print "mempool", tx_hash
296 "blk_hash": 'mempool',
302 txpoints.append(txpoint)
305 for txpoint in txpoints:
306 tx_id = txpoint['tx_id']
309 inrows = self.get_tx_inputs(tx_id)
311 _hash = self.binout(row[6])
312 address = hash_to_address(chr(0), _hash)
313 txinputs.append(address)
314 txpoint['inputs'] = txinputs
316 outrows = self.get_tx_outputs(tx_id)
318 _hash = self.binout(row[6])
319 address = hash_to_address(chr(0), _hash)
320 txoutputs.append(address)
321 txpoint['outputs'] = txoutputs
323 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
324 if not txpoint['is_in']:
325 # detect if already redeemed...
327 if row[6] == dbhash: break
330 #row = self.get_tx_output(tx_id,dbhash)
331 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
332 # if not redeemed, we add the script
334 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
337 if config.get('server','cache') == 'yes' and not address_has_mempool:
338 self.tx_cache[addr] = txpoints
344 class Direct_Interface(Interface):
348 def handler(self, method, params = ''):
349 cmds = {'session.new':new_session,
350 'session.poll':poll_session,
351 'session.update':update_session,
352 'blockchain.transaction.broadcast':send_tx,
353 'blockchain.address.get_history':store.get_history
356 return func( params )
361 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
362 respdata = urllib.urlopen(bitcoind_url, postdata).read()
364 if r['error'] != None:
365 out = "error: transaction rejected by memorypool\n"+tx
372 def random_string(N):
373 import random, string
374 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
384 return 'wrong password'
388 return repr( len(sessions) )
390 return 'wrong password'
398 return 'wrong password'
400 def get_cache(pw,addr):
402 return store.tx_cache.get(addr)
404 return 'wrong password'
407 def poll_session(session_id):
408 session = sessions.get(session_id)
410 print time.asctime(), "session not found", session_id
411 out = repr( (-1, {}))
414 addresses = session['addresses']
415 session['last_time'] = time.time()
418 for addr in addresses:
419 if store.tx_cache.get( addr ) is not None: k += 1
420 status = get_address_status( addr )
421 last_status = addresses.get( addr )
422 if last_status != status:
423 addresses[addr] = status
426 sessions[session_id]['addresses'] = addresses
427 out = repr( (block_number, ret ) )
428 t2 = time.time() - t1
430 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
435 def do_update_address(addr):
436 # an address was involved in a transaction; we check if it was subscribed to in a session
437 # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
438 for session_id in sessions.keys():
439 session = sessions[session_id]
440 if session.get('type') != 'subscribe': continue
441 addresses = session['addresses'].keys()
443 if addr in addresses:
444 print "address ", addr, "found in session", session_id
445 status = get_address_status( addr )
446 print "new_status:", status
447 last_status = session['addresses'][addr]
448 print "last_status", last_status
449 if last_status != status:
450 print "status is new", addr
451 send_status(session_id,addr,status)
452 sessions[session_id]['addresses'][addr] = status
455 def get_address_status(addr):
456 # get address status, i.e. the last block for that address.
457 tx_points = store.get_history(addr)
461 lastpoint = tx_points[-1]
462 status = lastpoint['blk_hash']
463 # this is a temporary hack; move it up once old clients have disappeared
464 if status == 'mempool': # and session['version'] != "old":
465 status = status + ':%d'% len(tx_points)
469 def send_numblocks(session_id):
470 out = json.dumps( {'method':'numblocks.subscribe', 'result':block_number} )
471 output_queue.put((session_id, out))
473 def send_status(session_id, address, status):
474 out = json.dumps( { 'method':'address.subscribe', 'address':address, 'status':status } )
475 output_queue.put((session_id, out))
477 def subscribe_to_numblocks(session_id):
478 sessions_sub_numblocks.append(session_id)
479 send_numblocks(session_id)
481 def subscribe_to_address(session_id, address):
482 status = get_address_status(address)
483 sessions[session_id]['type'] = 'subscribe'
484 sessions[session_id]['addresses'][address] = status
485 sessions[session_id]['last_time'] = time.time()
486 send_status(session_id, address, status)
488 def new_session(version, addresses):
489 session_id = random_string(10)
490 sessions[session_id] = { 'addresses':{}, 'version':version }
492 sessions[session_id]['addresses'][a] = ''
493 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
494 sessions[session_id]['last_time'] = time.time()
497 def update_session(session_id,addresses):
498 sessions[session_id]['addresses'] = {}
500 sessions[session_id]['addresses'][a] = ''
501 sessions[session_id]['last_time'] = time.time()
504 def native_server_thread():
505 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
506 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
507 s.bind((config.get('server','host'), config.getint('server','port')))
510 conn, addr = s.accept()
512 thread.start_new_thread(native_client_thread, (addr, conn,))
514 # can't start new thread if there is no memory..
515 traceback.print_exc(file=sys.stdout)
518 def native_client_thread(ipaddr,conn):
519 #print "client thread", ipaddr
529 msg = msg.split('#', 1)[0]
532 cmd, data = ast.literal_eval(msg)
534 print "syntax error", repr(msg), ipaddr
538 out = do_command(cmd, data, ipaddr)
540 #print ipaddr, cmd, len(out)
544 print "error, could not send"
551 # used by the native handler
552 def do_command(cmd, data, ipaddr):
554 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
557 out = "%d"%block_number
559 elif cmd in ['session','new_session']:
562 addresses = ast.literal_eval(data)
565 version, addresses = ast.literal_eval(data)
566 if version[0]=="0": version = "v" + version
570 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
571 out = new_session(version, addresses)
573 elif cmd=='update_session':
575 session_id, addresses = ast.literal_eval(data)
579 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
580 out = update_session(session_id,addresses)
582 elif cmd == 'bccapi_login':
585 v, k = ast.literal_eval(data)
586 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
587 print master_public_key
588 wallet_id = random_string(10)
589 w = Wallet( Direct_Interface() )
590 w.master_public_key = master_public_key.decode('hex')
592 wallets[wallet_id] = w
594 print "wallets", wallets
596 elif cmd == 'bccapi_getAccountInfo':
597 from wallet import int_to_hex
598 v, wallet_id = ast.literal_eval(data)
599 w = wallets.get(wallet_id)
601 num = len(w.addresses)
602 c, u = w.get_balance()
603 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
604 out = out.decode('hex')
609 elif cmd == 'bccapi_getAccountStatement':
610 from wallet import int_to_hex
611 v, wallet_id = ast.literal_eval(data)
612 w = wallets.get(wallet_id)
614 num = len(w.addresses)
615 c, u = w.get_balance()
616 total_records = num_records = 0
617 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 )
618 out = out.decode('hex')
623 elif cmd == 'bccapi_getSendCoinForm':
626 elif cmd == 'bccapi_submitTransaction':
630 out = poll_session(data)
635 out = repr( store.get_history( address ) )
642 print timestr, "sent tx:", ipaddr, out
648 out = repr(peer_list.values())
657 ####################################################################
659 def tcp_server_thread():
660 thread.start_new_thread(process_input_queue, ())
661 thread.start_new_thread(process_output_queue, ())
663 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
664 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
665 s.bind((config.get('server','host'), 50001))
668 conn, addr = s.accept()
670 thread.start_new_thread(tcp_client_thread, (addr, conn,))
672 # can't start new thread if there is no memory..
673 traceback.print_exc(file=sys.stdout)
676 def close_session(session_id):
677 print "lost connection", session_id
678 sessions.pop(session_id)
679 if session_id in sessions_sub_numblocks:
680 sessions_sub_numblocks.remove(session_id)
683 # one thread per client. put requests in a queue.
684 def tcp_client_thread(ipaddr,conn):
685 """ use a persistent connection. put commands in a queue."""
686 print "persistent client thread", ipaddr
689 session_id = random_string(10)
690 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown' }
699 close_session(session_id)
711 close_session(session_id)
716 print "json error", repr(c)
722 print "syntax error", repr(c), ipaddr
726 input_queue.put((session_id, cmd, data))
730 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
731 def process_input_queue():
733 session_id, cmd, data = input_queue.get()
734 if session_id not in sessions.keys():
737 if cmd == 'address.subscribe':
738 subscribe_to_address(session_id,data)
739 elif cmd == 'numblocks.subscribe':
740 subscribe_to_numblocks(session_id)
741 elif cmd == 'client.version':
742 sessions[session_id]['version'] = data
743 elif cmd == 'server.banner':
744 out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
745 elif cmd == 'server.peers':
746 out = json.dumps( { 'method':'server.peers', 'result':peer_list.values() } )
747 elif cmd == 'address.get_history':
749 out = json.dumps( { 'method':'address.get_history', 'address':address, 'result':store.get_history( address ) } )
750 elif cmd == 'transaction.broadcast':
752 print "sent tx:", txo
753 out = json.dumps( { 'method':'transaction.broadcast', 'result':txo } )
755 print "unknown command", cmd
757 output_queue.put((session_id, out))
759 # this is a separate thread
760 def process_output_queue():
762 session_id, out = output_queue.get()
763 session = sessions.get(session_id)
766 conn = session.get('conn')
769 close_session(session_id)
774 ####################################################################
777 def memorypool_update(store):
778 ds = BCDataStream.BCDataStream()
779 store.mempool_keys = []
781 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
782 respdata = urllib.urlopen(bitcoind_url, postdata).read()
784 if r['error'] != None:
787 v = r['result'].get('transactions')
790 ds.write(hextx.decode('hex'))
791 tx = deserialize.parse_Transaction(ds)
792 tx['hash'] = util.double_sha256(tx['tx'])
793 tx_hash = tx['hash'][::-1].encode('hex')
794 store.mempool_keys.append(tx_hash)
795 if store.tx_find_id_and_value(tx):
798 store.import_tx(tx, False)
804 def clean_session_thread():
808 for k,s in sessions.items():
809 if s.get('type') == 'subscribe': continue
813 print "lost session", k
818 NICK = 'E_'+random_string(10)
822 s.connect(('irc.freenode.net', 6667))
823 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
824 s.send('NICK '+NICK+'\n')
825 s.send('JOIN #electrum\n')
826 sf = s.makefile('r', 0)
830 line = line.rstrip('\r\n')
833 s.send('PONG '+line[1]+'\n')
834 elif '353' in line: # answer to /names
835 k = line.index('353')
836 for item in line[k+1:]:
837 if item[0:2] == 'E_':
838 s.send('WHO %s\n'%item)
839 elif '352' in line: # answer to /who
840 # warning: this is a horrible hack which apparently works
841 k = line.index('352')
843 ip = socket.gethostbyname(ip)
846 peer_list[name] = (ip,host)
847 if time.time() - t > 5*60:
848 s.send('NAMES #electrum\n')
852 traceback.print_exc(file=sys.stdout)
859 def http_server_thread(store):
860 # see http://code.google.com/p/jsonrpclib/
861 from SocketServer import ThreadingMixIn
862 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
863 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
864 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
865 server.register_function(lambda : peer_list.values(), 'peers')
866 server.register_function(cmd_stop, 'stop')
867 server.register_function(cmd_load, 'load')
868 server.register_function(lambda : block_number, 'blocks')
869 server.register_function(clear_cache, 'clear_cache')
870 server.register_function(get_cache, 'get_cache')
871 server.register_function(send_tx, 'blockchain.transaction.broadcast')
872 server.register_function(store.get_history, 'blockchain.address.get_history')
873 server.register_function(new_session, 'session.new')
874 server.register_function(update_session, 'session.update')
875 server.register_function(poll_session, 'session.poll')
876 server.serve_forever()
882 if __name__ == '__main__':
886 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
889 out = server.load(password)
893 out = server.stop(password)
894 elif cmd == 'clear_cache':
895 out = server.clear_cache(password)
896 elif cmd == 'get_cache':
897 out = server.get_cache(password,sys.argv[2])
899 out = server.blockchain.address.get_history(sys.argv[2])
901 out = server.blockchain.transaction.broadcast(sys.argv[2])
903 out = server.blocks()
905 out = "Unknown command: '%s'" % cmd
910 print "starting Electrum server"
911 print "cache:", config.get('server', 'cache')
913 conf = DataStore.CONFIG_DEFAULTS
914 args, argv = readconf.parse_argv( [], conf)
915 args.dbtype= config.get('database','type')
916 if args.dbtype == 'sqlite3':
917 args.connect_args = { 'database' : config.get('database','database') }
918 elif args.dbtype == 'MySQLdb':
919 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
920 elif args.dbtype == 'psycopg2':
921 args.connect_args = { 'database' : config.get('database','database') }
922 store = MyStore(args)
924 store.mempool_keys = {}
926 # supported protocols
927 thread.start_new_thread(native_server_thread, ())
928 thread.start_new_thread(tcp_server_thread, ())
929 thread.start_new_thread(http_server_thread, (store,))
931 thread.start_new_thread(clean_session_thread, ())
933 if (config.get('server','irc') == 'yes' ):
934 thread.start_new_thread(irc_thread, ())
940 memorypool_update(store)
941 block_number = store.get_block_number(1)
943 if block_number != old_block_number:
944 old_block_number = block_number
945 for session_id in sessions_sub_numblocks:
946 send_numblocks(session_id)
949 print "IOError: cannot reach bitcoind"
952 traceback.print_exc(file=sys.stdout)
960 addr = address_queue.get(False)
963 do_update_address(addr)
967 print "server stopped"