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."
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"
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 update_session(session_id,addresses):
447 sessions[session_id]['addresses'] = {}
449 sessions[session_id]['addresses'][a] = ''
450 sessions[session_id]['last_time'] = time.time()
453 def listen_thread(store):
454 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
455 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
456 s.bind((config.get('server','host'), config.getint('server','port')))
459 conn, addr = s.accept()
460 thread.start_new_thread(client_thread, (addr, conn,))
464 def client_thread(ipaddr,conn):
465 #print "client thread", ipaddr
475 msg = msg.split('#', 1)[0]
478 cmd, data = ast.literal_eval(msg)
480 print "syntax error", repr(msg), ipaddr
484 out = do_command(cmd, data, ipaddr)
486 #print ipaddr, cmd, len(out)
490 print "error, could not send"
496 def do_command(cmd, data, ipaddr):
498 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
501 out = "%d"%block_number
503 elif cmd in ['session','new_session']:
506 addresses = ast.literal_eval(data)
509 version, addresses = ast.literal_eval(data)
510 if version[0]=="0": version = "v" + version
514 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
515 out = new_session(version, addresses)
517 elif cmd=='update_session':
519 session_id, addresses = ast.literal_eval(data)
523 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
524 out = update_session(session_id,addresses)
526 elif cmd == 'bccapi_login':
529 v, k = ast.literal_eval(data)
530 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
531 print master_public_key
532 wallet_id = random_string(10)
533 w = Wallet( Direct_Interface() )
534 w.master_public_key = master_public_key.decode('hex')
536 wallets[wallet_id] = w
538 print "wallets", wallets
540 elif cmd == 'bccapi_getAccountInfo':
541 from wallet import int_to_hex
542 v, wallet_id = ast.literal_eval(data)
543 w = wallets.get(wallet_id)
545 num = len(w.addresses)
546 c, u = w.get_balance()
547 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
548 out = out.decode('hex')
553 elif cmd == 'bccapi_getAccountStatement':
554 from wallet import int_to_hex
555 v, wallet_id = ast.literal_eval(data)
556 w = wallets.get(wallet_id)
558 num = len(w.addresses)
559 c, u = w.get_balance()
560 total_records = num_records = 0
561 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 )
562 out = out.decode('hex')
567 elif cmd == 'bccapi_getSendCoinForm':
570 elif cmd == 'bccapi_submitTransaction':
574 out = poll_session(data)
579 out = repr( store.get_history( address ) )
586 print timestr, "sent tx:", ipaddr, out
592 out = repr(peer_list.values())
602 def memorypool_update(store):
603 ds = BCDataStream.BCDataStream()
604 store.mempool_keys = []
606 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
607 respdata = urllib.urlopen(bitcoind_url, postdata).read()
609 if r['error'] != None:
612 v = r['result'].get('transactions')
615 ds.write(hextx.decode('hex'))
616 tx = deserialize.parse_Transaction(ds)
617 tx['hash'] = util.double_sha256(tx['tx'])
618 tx_hash = tx['hash'][::-1].encode('hex')
619 store.mempool_keys.append(tx_hash)
620 if store.tx_find_id_and_value(tx):
623 store.import_tx(tx, False)
629 def clean_session_thread():
633 for k,s in sessions.items():
641 NICK = 'E_'+random_string(10)
645 s.connect(('irc.freenode.net', 6667))
646 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
647 s.send('NICK '+NICK+'\n')
648 s.send('JOIN #electrum\n')
649 sf = s.makefile('r', 0)
653 line = line.rstrip('\r\n')
656 s.send('PONG '+line[1]+'\n')
657 elif '353' in line: # answer to /names
658 k = line.index('353')
659 for item in line[k+1:]:
660 if item[0:2] == 'E_':
661 s.send('WHO %s\n'%item)
662 elif '352' in line: # answer to /who
663 # warning: this is a horrible hack which apparently works
664 k = line.index('352')
666 ip = socket.gethostbyname(ip)
669 peer_list[name] = (ip,host)
670 if time.time() - t > 5*60:
671 s.send('NAMES #electrum\n')
675 traceback.print_exc(file=sys.stdout)
682 def jsonrpc_thread(store):
683 # see http://code.google.com/p/jsonrpclib/
684 from SocketServer import ThreadingMixIn
685 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
686 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
687 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
688 server.register_function(lambda : peer_list.values(), 'peers')
689 server.register_function(cmd_stop, 'stop')
690 server.register_function(cmd_load, 'load')
691 server.register_function(lambda : block_number, 'blocks')
692 server.register_function(clear_cache, 'clear_cache')
693 server.register_function(get_cache, 'get_cache')
694 server.register_function(send_tx, 'blockchain.transaction.broadcast')
695 server.register_function(store.get_history, 'blockchain.address.get_history')
696 server.register_function(new_session, 'session.new')
697 server.register_function(update_session, 'session.update')
698 server.register_function(poll_session, 'session.poll')
699 server.serve_forever()
705 if __name__ == '__main__':
709 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
712 out = server.load(password)
716 out = server.stop(password)
717 elif cmd == 'clear_cache':
718 out = server.clear_cache(password)
719 elif cmd == 'get_cache':
720 out = server.get_cache(password,sys.argv[2])
722 out = server.blockchain.address.get_history(sys.argv[2])
724 out = server.blockchain.transaction.broadcast(sys.argv[2])
726 out = server.blocks()
728 out = "Unknown command: '%s'" % cmd
733 print "starting Electrum server"
734 print "cache:", config.get('server', 'cache')
736 conf = DataStore.CONFIG_DEFAULTS
737 args, argv = readconf.parse_argv( [], conf)
738 args.dbtype= config.get('database','type')
739 if args.dbtype == 'sqlite3':
740 args.connect_args = { 'database' : config.get('database','database') }
741 elif args.dbtype == 'MySQLdb':
742 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
743 elif args.dbtype == 'psycopg2':
744 args.connect_args = { 'database' : config.get('database','database') }
745 store = MyStore(args)
747 store.mempool_keys = {}
749 thread.start_new_thread(listen_thread, (store,))
750 thread.start_new_thread(jsonrpc_thread, (store,))
751 thread.start_new_thread(clean_session_thread, ())
752 if (config.get('server','irc') == 'yes' ):
753 thread.start_new_thread(irc_thread, ())
759 memorypool_update(store)
760 block_number = store.get_block_number(1)
762 print "IOError: cannot reach bitcoind"
765 traceback.print_exc(file=sys.stdout)
771 print "server stopped"