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 # 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."
66 password = config.get('server','password')
67 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
72 dblock = thread.allocate_lock()
75 wallets = {} # for ultra-light clients such as bccapi
77 class MyStore(Datastore_class):
79 def import_tx(self, tx, is_coinbase):
80 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
81 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
83 def update_tx_cache(self, txid):
84 inrows = self.get_tx_inputs(txid, False)
86 _hash = store.binout(row[6])
87 address = hash_to_address(chr(0), _hash)
88 if self.tx_cache.has_key(address):
89 print "cache: invalidating", address
90 self.tx_cache.pop(address)
91 outrows = self.get_tx_outputs(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)
99 def safe_sql(self,sql, params=(), lock=True):
101 if lock: dblock.acquire()
102 ret = self.selectall(sql,params)
103 if lock: dblock.release()
106 print "sql error", sql
109 def get_tx_outputs(self, tx_id, lock=True):
110 return self.safe_sql("""SELECT
112 txout.txout_scriptPubKey,
119 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
120 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
121 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
122 WHERE txout.tx_id = %d
123 ORDER BY txout.txout_pos
124 """%(tx_id), (), lock)
126 def get_tx_inputs(self, tx_id, lock=True):
127 return self.safe_sql(""" SELECT
131 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
133 COALESCE(txout.txout_pos, u.txout_pos),
136 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
137 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
138 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
139 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
140 WHERE txin.tx_id = %d
141 ORDER BY txin.txin_pos
142 """%(tx_id,), (), lock)
144 def get_address_out_rows(self, dbhash):
145 return self.safe_sql(""" SELECT
155 FROM chain_candidate cc
156 JOIN block b ON (b.block_id = cc.block_id)
157 JOIN block_tx ON (block_tx.block_id = b.block_id)
158 JOIN tx ON (tx.tx_id = block_tx.tx_id)
159 JOIN txin ON (txin.tx_id = tx.tx_id)
160 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
161 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
162 WHERE pubkey.pubkey_hash = ?
163 AND cc.in_longest = 1""", (dbhash,))
165 def get_address_out_rows_memorypool(self, dbhash):
166 return self.safe_sql(""" SELECT
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 = ? """, (dbhash,))
178 def get_address_in_rows(self, dbhash):
179 return self.safe_sql(""" SELECT
189 FROM chain_candidate cc
190 JOIN block b ON (b.block_id = cc.block_id)
191 JOIN block_tx ON (block_tx.block_id = b.block_id)
192 JOIN tx ON (tx.tx_id = block_tx.tx_id)
193 JOIN txout ON (txout.tx_id = tx.tx_id)
194 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
195 WHERE pubkey.pubkey_hash = ?
196 AND cc.in_longest = 1""", (dbhash,))
198 def get_address_in_rows_memorypool(self, dbhash):
199 return self.safe_sql( """ SELECT
206 JOIN txout ON (txout.tx_id = tx.tx_id)
207 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
208 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
210 def get_history(self, addr):
212 if config.get('server','cache') == 'yes':
213 cached_version = self.tx_cache.get( addr )
214 if cached_version is not None:
215 return cached_version
217 version, binaddr = decode_check_address(addr)
221 dbhash = self.binin(binaddr)
223 rows += self.get_address_out_rows( dbhash )
224 rows += self.get_address_in_rows( dbhash )
231 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
233 print "cannot unpack row", row
235 tx_hash = self.hashout_hex(tx_hash)
238 #"chain_id": int(chain_id),
239 "height": int(height),
241 "blk_hash": self.hashout_hex(blk_hash),
248 txpoints.append(txpoint)
249 known_tx.append(self.hashout_hex(tx_hash))
252 # todo: sort them really...
253 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
257 rows += self.get_address_in_rows_memorypool( dbhash )
258 rows += self.get_address_out_rows_memorypool( dbhash )
259 address_has_mempool = False
262 is_in, tx_hash, tx_id, pos, value = row
263 tx_hash = self.hashout_hex(tx_hash)
264 if tx_hash in known_tx:
267 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
268 address_has_mempool = True
270 # this means pending transactions are returned by getmemorypool
271 if tx_hash not in self.mempool_keys:
274 #print "mempool", tx_hash
280 "blk_hash": 'mempool',
286 txpoints.append(txpoint)
289 for txpoint in txpoints:
290 tx_id = txpoint['tx_id']
293 inrows = self.get_tx_inputs(tx_id)
295 _hash = self.binout(row[6])
296 address = hash_to_address(chr(0), _hash)
297 txinputs.append(address)
298 txpoint['inputs'] = txinputs
300 outrows = self.get_tx_outputs(tx_id)
302 _hash = self.binout(row[6])
303 address = hash_to_address(chr(0), _hash)
304 txoutputs.append(address)
305 txpoint['outputs'] = txoutputs
307 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
308 if not txpoint['is_in']:
309 # detect if already redeemed...
311 if row[6] == dbhash: break
314 #row = self.get_tx_output(tx_id,dbhash)
315 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
316 # if not redeemed, we add the script
318 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
321 if config.get('server','cache') == 'yes' and not address_has_mempool:
322 self.tx_cache[addr] = txpoints
328 class Direct_Interface(Interface):
332 def handler(self, method, params = ''):
333 cmds = {'session.new':new_session,
334 'session.poll':poll_session,
335 'session.update':update_session,
336 'blockchain.transaction.broadcast':send_tx,
337 'blockchain.address.get_history':store.get_history
340 return func( params )
345 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
346 respdata = urllib.urlopen(bitcoind_url, postdata).read()
348 if r['error'] != None:
349 out = "error: transaction rejected by memorypool"
356 def random_string(N):
357 import random, string
358 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
368 return 'wrong password'
372 return repr( len(sessions) )
374 return 'wrong password'
382 return 'wrong password'
384 def get_cache(pw,addr):
386 return store.tx_cache.get(addr)
388 return 'wrong password'
391 def poll_session(session_id):
392 session = sessions.get(session_id)
394 print time.asctime(), "session not found", session_id
395 out = repr( (-1, {}))
398 addresses = session['addresses']
399 session['last_time'] = time.time()
402 for addr in addresses:
403 if store.tx_cache.get( addr ) is not None: k += 1
405 # get addtess status, i.e. the last block for that address.
406 tx_points = store.get_history(addr)
410 lastpoint = tx_points[-1]
411 status = lastpoint['blk_hash']
412 # this is a temporary hack; move it up once old clients have disappeared
413 if status == 'mempool' and session['version'] != "old":
414 status = status + ':%d'% len(tx_points)
416 last_status = addresses.get( addr )
417 if last_status != status:
418 addresses[addr] = status
421 sessions[session_id]['addresses'] = addresses
422 out = repr( (block_number, ret ) )
423 t2 = time.time() - t1
425 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
430 def new_session(version, addresses):
431 session_id = random_string(10)
432 sessions[session_id] = { 'addresses':{}, 'version':version }
434 sessions[session_id]['addresses'][a] = ''
435 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
436 sessions[session_id]['last_time'] = time.time()
439 def update_session(session_id,addresses):
440 sessions[session_id]['addresses'] = {}
442 sessions[session_id]['addresses'][a] = ''
443 sessions[session_id]['last_time'] = time.time()
446 def listen_thread(store):
447 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
448 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
449 s.bind((config.get('server','host'), config.getint('server','port')))
452 conn, addr = s.accept()
453 thread.start_new_thread(client_thread, (addr, conn,))
457 def client_thread(ipaddr,conn):
458 #print "client thread", ipaddr
468 msg = msg.split('#', 1)[0]
471 cmd, data = ast.literal_eval(msg)
473 print "syntax error", repr(msg), ipaddr
477 out = do_command(cmd, data, ipaddr)
479 #print ipaddr, cmd, len(out)
483 print "error, could not send"
489 def do_command(cmd, data, ipaddr):
491 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
494 out = "%d"%block_number
496 elif cmd in ['session','new_session']:
499 addresses = ast.literal_eval(data)
502 version, addresses = ast.literal_eval(data)
503 if version[0]=="0": version = "v" + version
507 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
508 out = new_session(version, addresses)
510 elif cmd=='update_session':
512 session_id, addresses = ast.literal_eval(data)
516 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
517 out = update_session(session_id,addresses)
519 elif cmd == 'bccapi_login':
522 v, k = ast.literal_eval(data)
523 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
524 print master_public_key
525 wallet_id = random_string(10)
526 w = Wallet( Direct_Interface() )
527 w.master_public_key = master_public_key.decode('hex')
529 wallets[wallet_id] = w
531 print "wallets", wallets
533 elif cmd == 'bccapi_getAccountInfo':
534 from wallet import int_to_hex
535 v, wallet_id = ast.literal_eval(data)
536 w = wallets.get(wallet_id)
538 num = len(w.addresses)
539 c, u = w.get_balance()
540 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
541 out = out.decode('hex')
546 elif cmd == 'bccapi_getAccountStatement':
547 from wallet import int_to_hex
548 v, wallet_id = ast.literal_eval(data)
549 w = wallets.get(wallet_id)
551 num = len(w.addresses)
552 c, u = w.get_balance()
553 total_records = num_records = 0
554 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 )
555 out = out.decode('hex')
560 elif cmd == 'bccapi_getSendCoinForm':
563 elif cmd == 'bccapi_submitTransaction':
567 out = poll_session(data)
572 out = repr( store.get_history( address ) )
579 print timestr, "sent tx:", ipaddr, out
585 out = repr(peer_list.values())
595 def memorypool_update(store):
596 ds = BCDataStream.BCDataStream()
597 store.mempool_keys = []
599 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
600 respdata = urllib.urlopen(bitcoind_url, postdata).read()
602 if r['error'] != None:
605 v = r['result'].get('transactions')
608 ds.write(hextx.decode('hex'))
609 tx = deserialize.parse_Transaction(ds)
610 tx['hash'] = util.double_sha256(tx['tx'])
611 tx_hash = tx['hash'][::-1].encode('hex')
612 store.mempool_keys.append(tx_hash)
613 if store.tx_find_id_and_value(tx):
616 store.import_tx(tx, False)
622 def clean_session_thread():
626 for k,s in sessions.items():
634 NICK = 'E_'+random_string(10)
638 s.connect(('irc.freenode.net', 6667))
639 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
640 s.send('NICK '+NICK+'\n')
641 s.send('JOIN #electrum\n')
642 sf = s.makefile('r', 0)
646 line = line.rstrip('\r\n')
649 s.send('PONG '+line[1]+'\n')
650 elif '353' in line: # answer to /names
651 k = line.index('353')
652 for item in line[k+1:]:
653 if item[0:2] == 'E_':
654 s.send('WHO %s\n'%item)
655 elif '352' in line: # answer to /who
656 # warning: this is a horrible hack which apparently works
657 k = line.index('352')
659 ip = socket.gethostbyname(ip)
662 peer_list[name] = (ip,host)
663 if time.time() - t > 5*60:
664 s.send('NAMES #electrum\n')
668 traceback.print_exc(file=sys.stdout)
675 def jsonrpc_thread(store):
676 # see http://code.google.com/p/jsonrpclib/
677 from SocketServer import ThreadingMixIn
678 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
679 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
680 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
681 server.register_function(lambda : peer_list.values(), 'peers')
682 server.register_function(cmd_stop, 'stop')
683 server.register_function(cmd_load, 'load')
684 server.register_function(lambda : block_number, 'blocks')
685 server.register_function(clear_cache, 'clear_cache')
686 server.register_function(get_cache, 'get_cache')
687 server.register_function(send_tx, 'blockchain.transaction.broadcast')
688 server.register_function(store.get_history, 'blockchain.address.get_history')
689 server.register_function(new_session, 'session.new')
690 server.register_function(update_session, 'session.update')
691 server.register_function(poll_session, 'session.poll')
692 server.serve_forever()
698 if __name__ == '__main__':
702 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
705 out = server.load(password)
709 out = server.stop(password)
710 elif cmd == 'clear_cache':
711 out = server.clear_cache(password)
712 elif cmd == 'get_cache':
713 out = server.get_cache(password,sys.argv[2])
715 out = server.blockchain.address.get_history(sys.argv[2])
717 out = server.blockchain.transaction.broadcast(sys.argv[2])
719 out = server.blocks()
721 out = "Unknown command: '%s'" % cmd
726 print "starting Electrum server"
727 print "cache:", config.get('server', 'cache')
729 conf = DataStore.CONFIG_DEFAULTS
730 args, argv = readconf.parse_argv( [], conf)
731 args.dbtype= config.get('database','type')
732 if args.dbtype == 'sqlite3':
733 args.connect_args = { 'database' : config.get('database','database') }
734 elif args.dbtype == 'MySQLdb':
735 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
736 elif args.dbtype == 'psycopg2':
737 args.connect_args = { 'database' : config.get('database','database') }
738 store = MyStore(args)
740 store.mempool_keys = {}
742 thread.start_new_thread(listen_thread, (store,))
743 thread.start_new_thread(jsonrpc_thread, (store,))
744 thread.start_new_thread(clean_session_thread, ())
745 if (config.get('server','irc') == 'yes' ):
746 thread.start_new_thread(irc_thread, ())
752 memorypool_update(store)
753 block_number = store.get_block_number(1)
755 print "IOError: cannot reach bitcoind"
758 traceback.print_exc(file=sys.stdout)
764 print "server stopped"