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, 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 config = ConfigParser.ConfigParser()
40 # set some defaults, which will be overwritten by the config file
41 config.add_section('server')
42 config.set('server','banner', 'Welcome to Electrum!')
43 config.set('server', 'host', 'localhost')
44 config.set('server', 'port', 50000)
45 config.set('server', 'password', '')
46 config.set('server', 'irc', 'yes')
47 config.set('server', 'cache', 'no')
48 config.set('server', 'ircname', 'Electrum server')
49 config.add_section('database')
50 config.set('database', 'type', 'psycopg2')
51 config.set('database', 'database', 'abe')
54 f = open('/etc/electrum.conf','r')
58 print "Could not read electrum.conf. I will use the default values."
60 password = config.get('server','password')
61 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
66 dblock = thread.allocate_lock()
69 wallets = {} # for ultra-light clients such as bccapi
71 class MyStore(Datastore_class):
73 def import_tx(self, tx, is_coinbase):
74 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
75 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
77 def update_tx_cache(self, txid):
78 inrows = self.get_tx_inputs(txid, False)
80 _hash = store.binout(row[6])
81 address = hash_to_address(chr(0), _hash)
82 if self.tx_cache.has_key(address):
83 print "cache: invalidating", address
84 self.tx_cache.pop(address)
85 outrows = self.get_tx_outputs(txid, False)
87 _hash = store.binout(row[6])
88 address = hash_to_address(chr(0), _hash)
89 if self.tx_cache.has_key(address):
90 print "cache: invalidating", address
91 self.tx_cache.pop(address)
93 def safe_sql(self,sql, params=(), lock=True):
95 if lock: dblock.acquire()
96 ret = self.selectall(sql,params)
97 if lock: dblock.release()
100 print "sql error", sql
103 def get_tx_outputs(self, tx_id, lock=True):
104 return self.safe_sql("""SELECT
106 txout.txout_scriptPubKey,
113 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
114 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
115 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
116 WHERE txout.tx_id = %d
117 ORDER BY txout.txout_pos
118 """%(tx_id), (), lock)
120 def get_tx_inputs(self, tx_id, lock=True):
121 return self.safe_sql(""" SELECT
125 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
127 COALESCE(txout.txout_pos, u.txout_pos),
130 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
131 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
132 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
133 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
134 WHERE txin.tx_id = %d
135 ORDER BY txin.txin_pos
136 """%(tx_id,), (), lock)
138 def get_address_out_rows(self, dbhash):
139 return self.safe_sql(""" SELECT
149 FROM chain_candidate cc
150 JOIN block b ON (b.block_id = cc.block_id)
151 JOIN block_tx ON (block_tx.block_id = b.block_id)
152 JOIN tx ON (tx.tx_id = block_tx.tx_id)
153 JOIN txin ON (txin.tx_id = tx.tx_id)
154 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
155 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
156 WHERE pubkey.pubkey_hash = ?
157 AND cc.in_longest = 1""", (dbhash,))
159 def get_address_out_rows_memorypool(self, dbhash):
160 return self.safe_sql(""" SELECT
167 JOIN txin ON (txin.tx_id = tx.tx_id)
168 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
169 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
170 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
172 def get_address_in_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 txout ON (txout.tx_id = tx.tx_id)
188 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
189 WHERE pubkey.pubkey_hash = ?
190 AND cc.in_longest = 1""", (dbhash,))
192 def get_address_in_rows_memorypool(self, dbhash):
193 return self.safe_sql( """ SELECT
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 = ? """, (dbhash,))
204 def get_history(self, addr):
206 if config.get('server','cache') == 'yes':
207 cached_version = self.tx_cache.get( addr )
208 if cached_version is not None:
209 return cached_version
211 version, binaddr = decode_check_address(addr)
215 dbhash = self.binin(binaddr)
217 rows += self.get_address_out_rows( dbhash )
218 rows += self.get_address_in_rows( dbhash )
225 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
227 print "cannot unpack row", row
229 tx_hash = self.hashout_hex(tx_hash)
232 #"chain_id": int(chain_id),
233 "height": int(height),
235 "blk_hash": self.hashout_hex(blk_hash),
242 txpoints.append(txpoint)
243 known_tx.append(self.hashout_hex(tx_hash))
246 # todo: sort them really...
247 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
251 rows += self.get_address_in_rows_memorypool( dbhash )
252 rows += self.get_address_out_rows_memorypool( dbhash )
253 address_has_mempool = False
256 is_in, tx_hash, tx_id, pos, value = row
257 tx_hash = self.hashout_hex(tx_hash)
258 if tx_hash in known_tx:
261 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
262 address_has_mempool = True
264 # this means pending transactions are returned by getmemorypool
265 if tx_hash not in self.mempool_keys:
268 #print "mempool", tx_hash
274 "blk_hash": 'mempool',
280 txpoints.append(txpoint)
283 for txpoint in txpoints:
284 tx_id = txpoint['tx_id']
287 inrows = self.get_tx_inputs(tx_id)
289 _hash = self.binout(row[6])
290 address = hash_to_address(chr(0), _hash)
291 txinputs.append(address)
292 txpoint['inputs'] = txinputs
294 outrows = self.get_tx_outputs(tx_id)
296 _hash = self.binout(row[6])
297 address = hash_to_address(chr(0), _hash)
298 txoutputs.append(address)
299 txpoint['outputs'] = txoutputs
301 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
302 if not txpoint['is_in']:
303 # detect if already redeemed...
305 if row[6] == dbhash: break
308 #row = self.get_tx_output(tx_id,dbhash)
309 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
310 # if not redeemed, we add the script
312 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
315 if config.get('server','cache') == 'yes' and not address_has_mempool:
316 self.tx_cache[addr] = txpoints
324 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
325 respdata = urllib.urlopen(bitcoind_url, postdata).read()
327 if r['error'] != None:
328 out = "error: transaction rejected by memorypool"
335 def random_string(N):
336 import random, string
337 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
347 return 'wrong password'
351 return repr( len(sessions) )
353 return 'wrong password'
361 return 'wrong password'
363 def get_cache(pw,addr):
365 return store.tx_cache.get(addr)
367 return 'wrong password'
370 def poll_session(session_id):
371 session = sessions.get(session_id)
373 print time.asctime(), "session not found", session_id
374 out = repr( (-1, {}))
377 addresses = session['addresses']
378 session['last_time'] = time.time()
381 for addr in addresses:
382 if store.tx_cache.get( addr ) is not None: k += 1
384 # get addtess status, i.e. the last block for that address.
385 tx_points = store.get_history(addr)
389 lastpoint = tx_points[-1]
390 status = lastpoint['blk_hash']
391 # this is a temporary hack; move it up once old clients have disappeared
392 if status == 'mempool' and session['version'] != "old":
393 status = status + ':%d'% len(tx_points)
395 last_status = addresses.get( addr )
396 if last_status != status:
397 addresses[addr] = status
400 sessions[session_id]['addresses'] = addresses
401 out = repr( (block_number, ret ) )
402 t2 = time.time() - t1
404 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
409 def new_session(version, addresses):
410 session_id = random_string(10)
411 sessions[session_id] = { 'addresses':{}, 'version':version }
413 sessions[session_id]['addresses'][a] = ''
414 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
415 sessions[session_id]['last_time'] = time.time()
418 def update_session(session_id,addresses):
419 sessions[session_id]['addresses'] = {}
421 sessions[session_id]['addresses'][a] = ''
422 sessions[session_id]['last_time'] = time.time()
425 def listen_thread(store):
426 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
427 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
428 s.bind((config.get('server','host'), config.getint('server','port')))
431 conn, addr = s.accept()
432 thread.start_new_thread(client_thread, (addr, conn,))
436 def client_thread(ipaddr,conn):
437 #print "client thread", ipaddr
447 msg = msg.split('#', 1)[0]
450 cmd, data = ast.literal_eval(msg)
452 print "syntax error", repr(msg), ipaddr
456 out = do_command(cmd, data, ipaddr)
458 #print ipaddr, cmd, len(out)
462 print "error, could not send"
468 def do_command(cmd, data, ipaddr):
471 out = "%d"%block_number
473 elif cmd in ['session','new_session']:
476 addresses = ast.literal_eval(data)
479 version, addresses = ast.literal_eval(data)
480 if version[0]=="0": version = "v" + version
484 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
485 out = new_session(version, addresses)
487 elif cmd=='update_session':
489 session_id, addresses = ast.literal_eval(data)
493 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
494 out = update_session(session_id,addresses)
496 elif cmd == 'bccapi_login':
499 v, k = ast.literal_eval(data)
500 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
501 print master_public_key
502 wallet_id = random_string(10)
503 w = electrum.Wallet()
504 w.master_public_key = master_public_key.decode('hex')
506 wallets[wallet_id] = w
508 print "wallets", wallets
510 elif cmd == 'bccapi_getAccountInfo':
511 from electrum import int_to_hex
512 v, wallet_id = ast.literal_eval(data)
513 w = wallets.get(wallet_id)
515 num = len(w.addresses)
516 c, u = w.get_balance()
517 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
518 out = out.decode('hex')
523 elif cmd == 'bccapi_getAccountStatement':
524 from electrum import int_to_hex
525 v, wallet_id = ast.literal_eval(data)
526 w = wallets.get(wallet_id)
528 num = len(w.addresses)
529 c, u = w.get_balance()
530 total_records = num_records = 0
531 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 )
532 out = out.decode('hex')
537 elif cmd == 'bccapi_getSendCoinForm':
540 elif cmd == 'bccapi_submitTransaction':
544 out = poll_session(data)
549 out = repr( store.get_history( address ) )
556 print "sent tx:", out
562 out = repr(peer_list.values())
572 def memorypool_update(store):
573 ds = BCDataStream.BCDataStream()
574 store.mempool_keys = []
576 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
577 respdata = urllib.urlopen(bitcoind_url, postdata).read()
579 if r['error'] != None:
582 v = r['result'].get('transactions')
585 ds.write(hextx.decode('hex'))
586 tx = deserialize.parse_Transaction(ds)
587 tx['hash'] = util.double_sha256(tx['tx'])
588 tx_hash = tx['hash'][::-1].encode('hex')
589 store.mempool_keys.append(tx_hash)
590 if store.tx_find_id_and_value(tx):
593 store.import_tx(tx, False)
599 def clean_session_thread():
603 for k,s in sessions.items():
611 NICK = 'E_'+random_string(10)
615 s.connect(('irc.freenode.net', 6667))
616 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
617 s.send('NICK '+NICK+'\n')
618 s.send('JOIN #electrum\n')
619 sf = s.makefile('r', 0)
623 line = line.rstrip('\r\n')
626 s.send('PONG '+line[1]+'\n')
627 elif '353' in line: # answer to /names
628 k = line.index('353')
629 for item in line[k+1:]:
630 if item[0:2] == 'E_':
631 s.send('WHO %s\n'%item)
632 elif '352' in line: # answer to /who
633 # warning: this is a horrible hack which apparently works
634 k = line.index('352')
636 ip = socket.gethostbyname(ip)
639 peer_list[name] = (ip,host)
640 if time.time() - t > 5*60:
641 s.send('NAMES #electrum\n')
645 traceback.print_exc(file=sys.stdout)
652 def jsonrpc_thread(store):
653 # see http://code.google.com/p/jsonrpclib/
654 from SocketServer import ThreadingMixIn
655 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
656 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
657 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
658 server.register_function(lambda : peer_list.values(), 'peers')
659 server.register_function(cmd_stop, 'stop')
660 server.register_function(cmd_load, 'load')
661 server.register_function(lambda : block_number, 'blocks')
662 server.register_function(clear_cache, 'clear_cache')
663 server.register_function(get_cache, 'get_cache')
664 server.register_function(send_tx, 'blockchain.transaction.broadcast')
665 server.register_function(store.get_history, 'blockchain.address.get_history')
666 server.register_function(new_session, 'session.new')
667 server.register_function(update_session, 'session.update')
668 server.register_function(poll_session, 'session.poll')
669 server.serve_forever()
675 if __name__ == '__main__':
679 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
682 out = server.load(password)
686 out = server.stop(password)
687 elif cmd == 'clear_cache':
688 out = server.clear_cache(password)
689 elif cmd == 'get_cache':
690 out = server.get_cache(password,sys.argv[2])
692 out = server.blockchain.address.get_history(sys.argv[2])
694 out = server.blockchain.transaction.broadcast(sys.argv[2])
696 out = server.blocks()
701 print "starting Electrum server"
702 print "cache:", config.get('server', 'cache')
704 conf = DataStore.CONFIG_DEFAULTS
705 args, argv = readconf.parse_argv( [], conf)
706 args.dbtype= config.get('database','type')
707 if args.dbtype == 'sqlite3':
708 args.connect_args = { 'database' : config.get('database','database') }
709 elif args.dbtype == 'MySQLdb':
710 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
711 elif args.dbtype == 'psycopg2':
712 args.connect_args = { 'database' : config.get('database','database') }
713 store = MyStore(args)
715 store.mempool_keys = {}
717 thread.start_new_thread(listen_thread, (store,))
718 thread.start_new_thread(jsonrpc_thread, (store,))
719 thread.start_new_thread(clean_session_thread, ())
720 if (config.get('server','irc') == 'yes' ):
721 thread.start_new_thread(irc_thread, ())
727 memorypool_update(store)
728 block_number = store.get_block_number(1)
731 traceback.print_exc(file=sys.stdout)
734 print "server stopped"