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()
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 if config.get('server', 'cache') == 'yes': 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 outrows = self.get_tx_outputs(txid, False)
107 _hash = store.binout(row[6])
108 address = hash_to_address(chr(0), _hash)
109 if self.tx_cache.has_key(address):
110 print "cache: invalidating", address
111 self.tx_cache.pop(address)
113 def safe_sql(self,sql, params=(), lock=True):
115 if lock: dblock.acquire()
116 ret = self.selectall(sql,params)
117 if lock: dblock.release()
120 print "sql error", sql
123 def get_tx_outputs(self, tx_id, lock=True):
124 return self.safe_sql("""SELECT
126 txout.txout_scriptPubKey,
133 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
134 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
135 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
136 WHERE txout.tx_id = %d
137 ORDER BY txout.txout_pos
138 """%(tx_id), (), lock)
140 def get_tx_inputs(self, tx_id, lock=True):
141 return self.safe_sql(""" SELECT
145 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
147 COALESCE(txout.txout_pos, u.txout_pos),
150 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
151 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
152 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
153 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
154 WHERE txin.tx_id = %d
155 ORDER BY txin.txin_pos
156 """%(tx_id,), (), lock)
158 def get_address_out_rows(self, dbhash):
159 return self.safe_sql(""" SELECT
169 FROM chain_candidate cc
170 JOIN block b ON (b.block_id = cc.block_id)
171 JOIN block_tx ON (block_tx.block_id = b.block_id)
172 JOIN tx ON (tx.tx_id = block_tx.tx_id)
173 JOIN txin ON (txin.tx_id = tx.tx_id)
174 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
175 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
176 WHERE pubkey.pubkey_hash = ?
177 AND cc.in_longest = 1""", (dbhash,))
179 def get_address_out_rows_memorypool(self, dbhash):
180 return self.safe_sql(""" SELECT
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 = ? """, (dbhash,))
192 def get_address_in_rows(self, dbhash):
193 return self.safe_sql(""" SELECT
203 FROM chain_candidate cc
204 JOIN block b ON (b.block_id = cc.block_id)
205 JOIN block_tx ON (block_tx.block_id = b.block_id)
206 JOIN tx ON (tx.tx_id = block_tx.tx_id)
207 JOIN txout ON (txout.tx_id = tx.tx_id)
208 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
209 WHERE pubkey.pubkey_hash = ?
210 AND cc.in_longest = 1""", (dbhash,))
212 def get_address_in_rows_memorypool(self, dbhash):
213 return self.safe_sql( """ SELECT
220 JOIN txout ON (txout.tx_id = tx.tx_id)
221 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
222 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
224 def get_history(self, addr):
226 if config.get('server','cache') == 'yes':
227 cached_version = self.tx_cache.get( addr )
228 if cached_version is not None:
229 return cached_version
231 version, binaddr = decode_check_address(addr)
235 dbhash = self.binin(binaddr)
237 rows += self.get_address_out_rows( dbhash )
238 rows += self.get_address_in_rows( dbhash )
245 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
247 print "cannot unpack row", row
249 tx_hash = self.hashout_hex(tx_hash)
252 #"chain_id": int(chain_id),
253 "height": int(height),
255 "blk_hash": self.hashout_hex(blk_hash),
262 txpoints.append(txpoint)
263 known_tx.append(self.hashout_hex(tx_hash))
266 # todo: sort them really...
267 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
271 rows += self.get_address_in_rows_memorypool( dbhash )
272 rows += self.get_address_out_rows_memorypool( dbhash )
273 address_has_mempool = False
276 is_in, tx_hash, tx_id, pos, value = row
277 tx_hash = self.hashout_hex(tx_hash)
278 if tx_hash in known_tx:
281 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
282 address_has_mempool = True
284 # this means pending transactions are returned by getmemorypool
285 if tx_hash not in self.mempool_keys:
288 #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 config.get('server','cache') == 'yes' and 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
432 def get_address_status(addr):
433 # get addtess status, i.e. the last block for that address.
434 tx_points = store.get_history(addr)
438 lastpoint = tx_points[-1]
439 status = lastpoint['blk_hash']
440 # this is a temporary hack; move it up once old clients have disappeared
441 if status == 'mempool': # and session['version'] != "old":
442 status = status + ':%d'% len(tx_points)
446 def send_numblocks(session_id):
447 out = json.dumps( {'method':'numblocks.subscribe', 'result':block_number} )
448 output_queue.put((session_id, out))
450 def subscribe_to_numblocks(session_id):
451 sessions_sub_numblocks.append(session_id)
452 send_numblocks(session_id)
454 def subscribe_to_address(session_id, address):
455 #print "%s subscribing to %s"%(session_id,address)
456 status = get_address_status(address)
457 sessions[session_id]['type'] = 'subscribe'
458 sessions[session_id]['addresses'][address] = status
459 sessions[session_id]['last_time'] = time.time()
460 out = json.dumps( { 'method':'address.subscribe', 'address':address, 'status':status } )
461 output_queue.put((session_id, out))
463 def new_session(version, addresses):
464 session_id = random_string(10)
465 sessions[session_id] = { 'addresses':{}, 'version':version }
467 sessions[session_id]['addresses'][a] = ''
468 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
469 sessions[session_id]['last_time'] = time.time()
472 def update_session(session_id,addresses):
473 sessions[session_id]['addresses'] = {}
475 sessions[session_id]['addresses'][a] = ''
476 sessions[session_id]['last_time'] = time.time()
479 def native_server_thread():
480 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
481 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
482 s.bind((config.get('server','host'), config.getint('server','port')))
485 conn, addr = s.accept()
487 thread.start_new_thread(native_client_thread, (addr, conn,))
489 # can't start new thread if there is no memory..
490 traceback.print_exc(file=sys.stdout)
493 def native_client_thread(ipaddr,conn):
494 #print "client thread", ipaddr
504 msg = msg.split('#', 1)[0]
507 cmd, data = ast.literal_eval(msg)
509 print "syntax error", repr(msg), ipaddr
513 out = do_command(cmd, data, ipaddr)
515 #print ipaddr, cmd, len(out)
519 print "error, could not send"
526 # used by the native handler
527 def do_command(cmd, data, ipaddr):
529 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
532 out = "%d"%block_number
534 elif cmd in ['session','new_session']:
537 addresses = ast.literal_eval(data)
540 version, addresses = ast.literal_eval(data)
541 if version[0]=="0": version = "v" + version
545 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
546 out = new_session(version, addresses)
548 elif cmd=='update_session':
550 session_id, addresses = ast.literal_eval(data)
554 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
555 out = update_session(session_id,addresses)
557 elif cmd == 'bccapi_login':
560 v, k = ast.literal_eval(data)
561 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
562 print master_public_key
563 wallet_id = random_string(10)
564 w = Wallet( Direct_Interface() )
565 w.master_public_key = master_public_key.decode('hex')
567 wallets[wallet_id] = w
569 print "wallets", wallets
571 elif cmd == 'bccapi_getAccountInfo':
572 from wallet import int_to_hex
573 v, wallet_id = ast.literal_eval(data)
574 w = wallets.get(wallet_id)
576 num = len(w.addresses)
577 c, u = w.get_balance()
578 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
579 out = out.decode('hex')
584 elif cmd == 'bccapi_getAccountStatement':
585 from wallet import int_to_hex
586 v, wallet_id = ast.literal_eval(data)
587 w = wallets.get(wallet_id)
589 num = len(w.addresses)
590 c, u = w.get_balance()
591 total_records = num_records = 0
592 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 )
593 out = out.decode('hex')
598 elif cmd == 'bccapi_getSendCoinForm':
601 elif cmd == 'bccapi_submitTransaction':
605 out = poll_session(data)
610 out = repr( store.get_history( address ) )
617 print timestr, "sent tx:", ipaddr, out
623 out = repr(peer_list.values())
632 ####################################################################
634 def tcp_server_thread():
635 thread.start_new_thread(process_input_queue, ())
636 thread.start_new_thread(process_output_queue, ())
638 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
639 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
640 s.bind((config.get('server','host'), 50001))
643 conn, addr = s.accept()
645 thread.start_new_thread(tcp_client_thread, (addr, conn,))
647 # can't start new thread if there is no memory..
648 traceback.print_exc(file=sys.stdout)
651 # one thread per client. put requests in a queue.
652 def tcp_client_thread(ipaddr,conn):
653 """ use a persistent connection. put commands in a queue."""
654 print "persistent client thread", ipaddr
657 session_id = random_string(10)
658 sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown' }
679 print "syntax error", repr(c), ipaddr
683 input_queue.put((session_id, cmd, data))
686 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
687 def process_input_queue():
689 session_id, cmd, data = input_queue.get()
691 if cmd == 'address.subscribe':
692 subscribe_to_address(session_id,data)
693 elif cmd == 'numblocks.subscribe':
694 subscribe_to_numblocks(session_id)
695 elif cmd == 'client.version':
696 sessions[session_id]['version'] = data
697 elif cmd == 'server.banner':
698 out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
699 elif cmd == 'address.get_history':
701 out = json.dumps( { 'method':'address.get_history', 'address':address, 'result':store.get_history( address ) } )
702 elif cmd == 'transaction.broadcast':
703 out = json.dumps( { 'method':'transaction.broadcast', 'result':send_tx(data) } )
705 print "unknown command", cmd
707 output_queue.put((session_id, out))
709 # this is a separate thread
710 def process_output_queue():
712 session_id, out = output_queue.get()
713 session = sessions.get(session_id)
715 conn = session.get('conn')
720 ####################################################################
723 def memorypool_update(store):
724 ds = BCDataStream.BCDataStream()
725 store.mempool_keys = []
727 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
728 respdata = urllib.urlopen(bitcoind_url, postdata).read()
730 if r['error'] != None:
733 v = r['result'].get('transactions')
736 ds.write(hextx.decode('hex'))
737 tx = deserialize.parse_Transaction(ds)
738 tx['hash'] = util.double_sha256(tx['tx'])
739 tx_hash = tx['hash'][::-1].encode('hex')
740 store.mempool_keys.append(tx_hash)
741 if store.tx_find_id_and_value(tx):
744 store.import_tx(tx, False)
750 def clean_session_thread():
754 for k,s in sessions.items():
762 NICK = 'E_'+random_string(10)
766 s.connect(('irc.freenode.net', 6667))
767 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
768 s.send('NICK '+NICK+'\n')
769 s.send('JOIN #electrum\n')
770 sf = s.makefile('r', 0)
774 line = line.rstrip('\r\n')
777 s.send('PONG '+line[1]+'\n')
778 elif '353' in line: # answer to /names
779 k = line.index('353')
780 for item in line[k+1:]:
781 if item[0:2] == 'E_':
782 s.send('WHO %s\n'%item)
783 elif '352' in line: # answer to /who
784 # warning: this is a horrible hack which apparently works
785 k = line.index('352')
787 ip = socket.gethostbyname(ip)
790 peer_list[name] = (ip,host)
791 if time.time() - t > 5*60:
792 s.send('NAMES #electrum\n')
796 traceback.print_exc(file=sys.stdout)
803 def http_server_thread(store):
804 # see http://code.google.com/p/jsonrpclib/
805 from SocketServer import ThreadingMixIn
806 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
807 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
808 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
809 server.register_function(lambda : peer_list.values(), 'peers')
810 server.register_function(cmd_stop, 'stop')
811 server.register_function(cmd_load, 'load')
812 server.register_function(lambda : block_number, 'blocks')
813 server.register_function(clear_cache, 'clear_cache')
814 server.register_function(get_cache, 'get_cache')
815 server.register_function(send_tx, 'blockchain.transaction.broadcast')
816 server.register_function(store.get_history, 'blockchain.address.get_history')
817 server.register_function(new_session, 'session.new')
818 server.register_function(update_session, 'session.update')
819 server.register_function(poll_session, 'session.poll')
820 server.serve_forever()
826 if __name__ == '__main__':
830 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
833 out = server.load(password)
837 out = server.stop(password)
838 elif cmd == 'clear_cache':
839 out = server.clear_cache(password)
840 elif cmd == 'get_cache':
841 out = server.get_cache(password,sys.argv[2])
843 out = server.blockchain.address.get_history(sys.argv[2])
845 out = server.blockchain.transaction.broadcast(sys.argv[2])
847 out = server.blocks()
849 out = "Unknown command: '%s'" % cmd
854 print "starting Electrum server"
855 print "cache:", config.get('server', 'cache')
857 conf = DataStore.CONFIG_DEFAULTS
858 args, argv = readconf.parse_argv( [], conf)
859 args.dbtype= config.get('database','type')
860 if args.dbtype == 'sqlite3':
861 args.connect_args = { 'database' : config.get('database','database') }
862 elif args.dbtype == 'MySQLdb':
863 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
864 elif args.dbtype == 'psycopg2':
865 args.connect_args = { 'database' : config.get('database','database') }
866 store = MyStore(args)
868 store.mempool_keys = {}
870 # supported protocols
871 thread.start_new_thread(native_server_thread, ())
872 thread.start_new_thread(tcp_server_thread, ())
873 thread.start_new_thread(http_server_thread, (store,))
875 thread.start_new_thread(clean_session_thread, ())
876 if (config.get('server','irc') == 'yes' ):
877 thread.start_new_thread(irc_thread, ())
883 memorypool_update(store)
884 block_number = store.get_block_number(1)
886 if block_number != old_block_number:
887 old_block_number = block_number
888 for session_id in sessions_sub_numblocks:
889 send_numblocks(session_id)
892 print "IOError: cannot reach bitcoind"
895 traceback.print_exc(file=sys.stdout)
901 print "server stopped"