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'))
79 dblock = thread.allocate_lock()
82 wallets = {} # for ultra-light clients such as bccapi
84 class MyStore(Datastore_class):
86 def import_tx(self, tx, is_coinbase):
87 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
88 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
90 def update_tx_cache(self, txid):
91 inrows = self.get_tx_inputs(txid, False)
93 _hash = store.binout(row[6])
94 address = hash_to_address(chr(0), _hash)
95 if self.tx_cache.has_key(address):
96 print "cache: invalidating", address
97 self.tx_cache.pop(address)
98 outrows = self.get_tx_outputs(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)
106 def safe_sql(self,sql, params=(), lock=True):
108 if lock: dblock.acquire()
109 ret = self.selectall(sql,params)
110 if lock: dblock.release()
113 print "sql error", sql
116 def get_tx_outputs(self, tx_id, lock=True):
117 return self.safe_sql("""SELECT
119 txout.txout_scriptPubKey,
126 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
127 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
129 WHERE txout.tx_id = %d
130 ORDER BY txout.txout_pos
131 """%(tx_id), (), lock)
133 def get_tx_inputs(self, tx_id, lock=True):
134 return self.safe_sql(""" SELECT
138 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
140 COALESCE(txout.txout_pos, u.txout_pos),
143 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
144 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
145 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
146 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
147 WHERE txin.tx_id = %d
148 ORDER BY txin.txin_pos
149 """%(tx_id,), (), lock)
151 def get_address_out_rows(self, dbhash):
152 return self.safe_sql(""" SELECT
162 FROM chain_candidate cc
163 JOIN block b ON (b.block_id = cc.block_id)
164 JOIN block_tx ON (block_tx.block_id = b.block_id)
165 JOIN tx ON (tx.tx_id = block_tx.tx_id)
166 JOIN txin ON (txin.tx_id = tx.tx_id)
167 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
168 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
169 WHERE pubkey.pubkey_hash = ?
170 AND cc.in_longest = 1""", (dbhash,))
172 def get_address_out_rows_memorypool(self, dbhash):
173 return self.safe_sql(""" SELECT
180 JOIN txin ON (txin.tx_id = tx.tx_id)
181 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
182 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
183 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
185 def get_address_in_rows(self, dbhash):
186 return self.safe_sql(""" SELECT
196 FROM chain_candidate cc
197 JOIN block b ON (b.block_id = cc.block_id)
198 JOIN block_tx ON (block_tx.block_id = b.block_id)
199 JOIN tx ON (tx.tx_id = block_tx.tx_id)
200 JOIN txout ON (txout.tx_id = tx.tx_id)
201 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
202 WHERE pubkey.pubkey_hash = ?
203 AND cc.in_longest = 1""", (dbhash,))
205 def get_address_in_rows_memorypool(self, dbhash):
206 return self.safe_sql( """ SELECT
213 JOIN txout ON (txout.tx_id = tx.tx_id)
214 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
215 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
217 def get_history(self, addr):
219 if config.get('server','cache') == 'yes':
220 cached_version = self.tx_cache.get( addr )
221 if cached_version is not None:
222 return cached_version
224 version, binaddr = decode_check_address(addr)
228 dbhash = self.binin(binaddr)
230 rows += self.get_address_out_rows( dbhash )
231 rows += self.get_address_in_rows( dbhash )
238 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
240 print "cannot unpack row", row
242 tx_hash = self.hashout_hex(tx_hash)
245 #"chain_id": int(chain_id),
246 "height": int(height),
248 "blk_hash": self.hashout_hex(blk_hash),
255 txpoints.append(txpoint)
256 known_tx.append(self.hashout_hex(tx_hash))
259 # todo: sort them really...
260 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
264 rows += self.get_address_in_rows_memorypool( dbhash )
265 rows += self.get_address_out_rows_memorypool( dbhash )
266 address_has_mempool = False
269 is_in, tx_hash, tx_id, pos, value = row
270 tx_hash = self.hashout_hex(tx_hash)
271 if tx_hash in known_tx:
274 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
275 address_has_mempool = True
277 # this means pending transactions are returned by getmemorypool
278 if tx_hash not in self.mempool_keys:
281 #print "mempool", tx_hash
287 "blk_hash": 'mempool',
293 txpoints.append(txpoint)
296 for txpoint in txpoints:
297 tx_id = txpoint['tx_id']
300 inrows = self.get_tx_inputs(tx_id)
302 _hash = self.binout(row[6])
303 address = hash_to_address(chr(0), _hash)
304 txinputs.append(address)
305 txpoint['inputs'] = txinputs
307 outrows = self.get_tx_outputs(tx_id)
309 _hash = self.binout(row[6])
310 address = hash_to_address(chr(0), _hash)
311 txoutputs.append(address)
312 txpoint['outputs'] = txoutputs
314 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
315 if not txpoint['is_in']:
316 # detect if already redeemed...
318 if row[6] == dbhash: break
321 #row = self.get_tx_output(tx_id,dbhash)
322 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
323 # if not redeemed, we add the script
325 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
328 if config.get('server','cache') == 'yes' and not address_has_mempool:
329 self.tx_cache[addr] = txpoints
335 class Direct_Interface(Interface):
339 def handler(self, method, params = ''):
340 cmds = {'session.new':new_session,
341 'session.poll':poll_session,
342 'session.update':update_session,
343 'blockchain.transaction.broadcast':send_tx,
344 'blockchain.address.get_history':store.get_history
347 return func( params )
352 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
353 respdata = urllib.urlopen(bitcoind_url, postdata).read()
355 if r['error'] != None:
356 out = "error: transaction rejected by memorypool\n"+tx
363 def random_string(N):
364 import random, string
365 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
375 return 'wrong password'
379 return repr( len(sessions) )
381 return 'wrong password'
389 return 'wrong password'
391 def get_cache(pw,addr):
393 return store.tx_cache.get(addr)
395 return 'wrong password'
398 def poll_session(session_id):
399 session = sessions.get(session_id)
401 print time.asctime(), "session not found", session_id
402 out = repr( (-1, {}))
405 addresses = session['addresses']
406 session['last_time'] = time.time()
409 for addr in addresses:
410 if store.tx_cache.get( addr ) is not None: k += 1
412 # get addtess status, i.e. the last block for that address.
413 tx_points = store.get_history(addr)
417 lastpoint = tx_points[-1]
418 status = lastpoint['blk_hash']
419 # this is a temporary hack; move it up once old clients have disappeared
420 if status == 'mempool' and session['version'] != "old":
421 status = status + ':%d'% len(tx_points)
423 last_status = addresses.get( addr )
424 if last_status != status:
425 addresses[addr] = status
428 sessions[session_id]['addresses'] = addresses
429 out = repr( (block_number, ret ) )
430 t2 = time.time() - t1
432 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
437 def new_session(version, addresses):
438 session_id = random_string(10)
439 sessions[session_id] = { 'addresses':{}, 'version':version }
441 sessions[session_id]['addresses'][a] = ''
442 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
443 sessions[session_id]['last_time'] = time.time()
446 def subscribe_to_address(session_id, address):
447 sessions[session_id]['addresses'][address] = ''
448 sessions[session_id]['last_time'] = time.time()
451 def update_session(session_id,addresses):
452 sessions[session_id]['addresses'] = {}
454 sessions[session_id]['addresses'][a] = ''
455 sessions[session_id]['last_time'] = time.time()
458 def native_server_thread():
459 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
460 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
461 s.bind((config.get('server','host'), config.getint('server','port')))
464 conn, addr = s.accept()
466 thread.start_new_thread(native_client_thread, (addr, conn,))
468 # can't start new thread if there is no memory..
469 traceback.print_exc(file=sys.stdout)
472 def native_client_thread(ipaddr,conn):
473 #print "client thread", ipaddr
483 msg = msg.split('#', 1)[0]
486 cmd, data = ast.literal_eval(msg)
488 print "syntax error", repr(msg), ipaddr
492 out = do_command(cmd, data, ipaddr)
494 #print ipaddr, cmd, len(out)
498 print "error, could not send"
505 # used by the native handler
506 def do_command(cmd, data, ipaddr):
508 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
511 out = "%d"%block_number
513 elif cmd in ['session','new_session']:
516 addresses = ast.literal_eval(data)
519 version, addresses = ast.literal_eval(data)
520 if version[0]=="0": version = "v" + version
524 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
525 out = new_session(version, addresses)
527 elif cmd=='update_session':
529 session_id, addresses = ast.literal_eval(data)
533 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
534 out = update_session(session_id,addresses)
536 elif cmd == 'bccapi_login':
539 v, k = ast.literal_eval(data)
540 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
541 print master_public_key
542 wallet_id = random_string(10)
543 w = Wallet( Direct_Interface() )
544 w.master_public_key = master_public_key.decode('hex')
546 wallets[wallet_id] = w
548 print "wallets", wallets
550 elif cmd == 'bccapi_getAccountInfo':
551 from wallet import int_to_hex
552 v, wallet_id = ast.literal_eval(data)
553 w = wallets.get(wallet_id)
555 num = len(w.addresses)
556 c, u = w.get_balance()
557 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
558 out = out.decode('hex')
563 elif cmd == 'bccapi_getAccountStatement':
564 from wallet import int_to_hex
565 v, wallet_id = ast.literal_eval(data)
566 w = wallets.get(wallet_id)
568 num = len(w.addresses)
569 c, u = w.get_balance()
570 total_records = num_records = 0
571 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 )
572 out = out.decode('hex')
577 elif cmd == 'bccapi_getSendCoinForm':
580 elif cmd == 'bccapi_submitTransaction':
584 out = poll_session(data)
589 out = repr( store.get_history( address ) )
596 print timestr, "sent tx:", ipaddr, out
602 out = repr(peer_list.values())
611 ####################################################################
613 def tcp_server_thread():
614 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
615 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
616 s.bind((config.get('server','host'), 50001))
619 conn, addr = s.accept()
621 thread.start_new_thread(tcp_client_thread, (addr, conn,))
623 # can't start new thread if there is no memory..
624 traceback.print_exc(file=sys.stdout)
628 def tcp_client_thread(ipaddr,conn):
629 """ use a persistent connection. put commands in a queue."""
630 print "persistent client thread", ipaddr
633 session_id = random_string(10)
634 sessions[session_id] = { 'addresses':{}, 'version':'unknown' }
655 print "syntax error", repr(c), ipaddr
659 if cmd == 'blockchain.address.subscribe':
660 subscribe_to_address(session_id,data)
661 elif cmd == 'client.version':
662 sessions[session_id]['version'] = data
663 elif cmd == 'server.banner':
664 out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
666 print "unknown command", cmd
673 ####################################################################
676 def memorypool_update(store):
677 ds = BCDataStream.BCDataStream()
678 store.mempool_keys = []
680 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
681 respdata = urllib.urlopen(bitcoind_url, postdata).read()
683 if r['error'] != None:
686 v = r['result'].get('transactions')
689 ds.write(hextx.decode('hex'))
690 tx = deserialize.parse_Transaction(ds)
691 tx['hash'] = util.double_sha256(tx['tx'])
692 tx_hash = tx['hash'][::-1].encode('hex')
693 store.mempool_keys.append(tx_hash)
694 if store.tx_find_id_and_value(tx):
697 store.import_tx(tx, False)
703 def clean_session_thread():
707 for k,s in sessions.items():
715 NICK = 'E_'+random_string(10)
719 s.connect(('irc.freenode.net', 6667))
720 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
721 s.send('NICK '+NICK+'\n')
722 s.send('JOIN #electrum\n')
723 sf = s.makefile('r', 0)
727 line = line.rstrip('\r\n')
730 s.send('PONG '+line[1]+'\n')
731 elif '353' in line: # answer to /names
732 k = line.index('353')
733 for item in line[k+1:]:
734 if item[0:2] == 'E_':
735 s.send('WHO %s\n'%item)
736 elif '352' in line: # answer to /who
737 # warning: this is a horrible hack which apparently works
738 k = line.index('352')
740 ip = socket.gethostbyname(ip)
743 peer_list[name] = (ip,host)
744 if time.time() - t > 5*60:
745 s.send('NAMES #electrum\n')
749 traceback.print_exc(file=sys.stdout)
756 def http_server_thread(store):
757 # see http://code.google.com/p/jsonrpclib/
758 from SocketServer import ThreadingMixIn
759 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
760 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
761 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
762 server.register_function(lambda : peer_list.values(), 'peers')
763 server.register_function(cmd_stop, 'stop')
764 server.register_function(cmd_load, 'load')
765 server.register_function(lambda : block_number, 'blocks')
766 server.register_function(clear_cache, 'clear_cache')
767 server.register_function(get_cache, 'get_cache')
768 server.register_function(send_tx, 'blockchain.transaction.broadcast')
769 server.register_function(store.get_history, 'blockchain.address.get_history')
770 server.register_function(new_session, 'session.new')
771 server.register_function(update_session, 'session.update')
772 server.register_function(poll_session, 'session.poll')
773 server.serve_forever()
779 if __name__ == '__main__':
783 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
786 out = server.load(password)
790 out = server.stop(password)
791 elif cmd == 'clear_cache':
792 out = server.clear_cache(password)
793 elif cmd == 'get_cache':
794 out = server.get_cache(password,sys.argv[2])
796 out = server.blockchain.address.get_history(sys.argv[2])
798 out = server.blockchain.transaction.broadcast(sys.argv[2])
800 out = server.blocks()
802 out = "Unknown command: '%s'" % cmd
807 print "starting Electrum server"
808 print "cache:", config.get('server', 'cache')
810 conf = DataStore.CONFIG_DEFAULTS
811 args, argv = readconf.parse_argv( [], conf)
812 args.dbtype= config.get('database','type')
813 if args.dbtype == 'sqlite3':
814 args.connect_args = { 'database' : config.get('database','database') }
815 elif args.dbtype == 'MySQLdb':
816 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
817 elif args.dbtype == 'psycopg2':
818 args.connect_args = { 'database' : config.get('database','database') }
819 store = MyStore(args)
821 store.mempool_keys = {}
823 # supported protocols
824 thread.start_new_thread(native_server_thread, ())
825 thread.start_new_thread(tcp_server_thread, ())
826 thread.start_new_thread(http_server_thread, (store,))
828 thread.start_new_thread(clean_session_thread, ())
829 if (config.get('server','irc') == 'yes' ):
830 thread.start_new_thread(irc_thread, ())
836 memorypool_update(store)
837 block_number = store.get_block_number(1)
839 print "IOError: cannot reach bitcoind"
842 traceback.print_exc(file=sys.stdout)
848 print "server stopped"