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/')
44 config = ConfigParser.ConfigParser()
45 # set some defaults, which will be overwritten by the config file
46 config.add_section('server')
47 config.set('server','banner', 'Welcome to Electrum!')
48 config.set('server', 'host', 'localhost')
49 config.set('server', 'port', 50000)
50 config.set('server', 'password', '')
51 config.set('server', 'irc', 'yes')
52 config.set('server', 'cache', 'no')
53 config.set('server', 'ircname', 'Electrum server')
54 config.add_section('database')
55 config.set('database', 'type', 'psycopg2')
56 config.set('database', 'database', 'abe')
59 f = open('/etc/electrum.conf','r')
63 print "Could not read electrum.conf. I will use the default values."
65 password = config.get('server','password')
66 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
71 dblock = thread.allocate_lock()
74 wallets = {} # for ultra-light clients such as bccapi
76 class MyStore(Datastore_class):
78 def import_tx(self, tx, is_coinbase):
79 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
80 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
82 def update_tx_cache(self, txid):
83 inrows = self.get_tx_inputs(txid, False)
85 _hash = store.binout(row[6])
86 address = hash_to_address(chr(0), _hash)
87 if self.tx_cache.has_key(address):
88 print "cache: invalidating", address
89 self.tx_cache.pop(address)
90 outrows = self.get_tx_outputs(txid, False)
92 _hash = store.binout(row[6])
93 address = hash_to_address(chr(0), _hash)
94 if self.tx_cache.has_key(address):
95 print "cache: invalidating", address
96 self.tx_cache.pop(address)
98 def safe_sql(self,sql, params=(), lock=True):
100 if lock: dblock.acquire()
101 ret = self.selectall(sql,params)
102 if lock: dblock.release()
105 print "sql error", sql
108 def get_tx_outputs(self, tx_id, lock=True):
109 return self.safe_sql("""SELECT
111 txout.txout_scriptPubKey,
118 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
119 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
120 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
121 WHERE txout.tx_id = %d
122 ORDER BY txout.txout_pos
123 """%(tx_id), (), lock)
125 def get_tx_inputs(self, tx_id, lock=True):
126 return self.safe_sql(""" SELECT
130 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
132 COALESCE(txout.txout_pos, u.txout_pos),
135 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
136 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
137 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
138 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
139 WHERE txin.tx_id = %d
140 ORDER BY txin.txin_pos
141 """%(tx_id,), (), lock)
143 def get_address_out_rows(self, dbhash):
144 return self.safe_sql(""" SELECT
154 FROM chain_candidate cc
155 JOIN block b ON (b.block_id = cc.block_id)
156 JOIN block_tx ON (block_tx.block_id = b.block_id)
157 JOIN tx ON (tx.tx_id = block_tx.tx_id)
158 JOIN txin ON (txin.tx_id = tx.tx_id)
159 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
160 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
161 WHERE pubkey.pubkey_hash = ?
162 AND cc.in_longest = 1""", (dbhash,))
164 def get_address_out_rows_memorypool(self, dbhash):
165 return self.safe_sql(""" SELECT
172 JOIN txin ON (txin.tx_id = tx.tx_id)
173 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
174 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
175 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
177 def get_address_in_rows(self, dbhash):
178 return self.safe_sql(""" SELECT
188 FROM chain_candidate cc
189 JOIN block b ON (b.block_id = cc.block_id)
190 JOIN block_tx ON (block_tx.block_id = b.block_id)
191 JOIN tx ON (tx.tx_id = block_tx.tx_id)
192 JOIN txout ON (txout.tx_id = tx.tx_id)
193 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
194 WHERE pubkey.pubkey_hash = ?
195 AND cc.in_longest = 1""", (dbhash,))
197 def get_address_in_rows_memorypool(self, dbhash):
198 return self.safe_sql( """ SELECT
205 JOIN txout ON (txout.tx_id = tx.tx_id)
206 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
207 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
209 def get_history(self, addr):
211 if config.get('server','cache') == 'yes':
212 cached_version = self.tx_cache.get( addr )
213 if cached_version is not None:
214 return cached_version
216 version, binaddr = decode_check_address(addr)
220 dbhash = self.binin(binaddr)
222 rows += self.get_address_out_rows( dbhash )
223 rows += self.get_address_in_rows( dbhash )
230 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
232 print "cannot unpack row", row
234 tx_hash = self.hashout_hex(tx_hash)
237 #"chain_id": int(chain_id),
238 "height": int(height),
240 "blk_hash": self.hashout_hex(blk_hash),
247 txpoints.append(txpoint)
248 known_tx.append(self.hashout_hex(tx_hash))
251 # todo: sort them really...
252 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
256 rows += self.get_address_in_rows_memorypool( dbhash )
257 rows += self.get_address_out_rows_memorypool( dbhash )
258 address_has_mempool = False
261 is_in, tx_hash, tx_id, pos, value = row
262 tx_hash = self.hashout_hex(tx_hash)
263 if tx_hash in known_tx:
266 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
267 address_has_mempool = True
269 # this means pending transactions are returned by getmemorypool
270 if tx_hash not in self.mempool_keys:
273 #print "mempool", tx_hash
279 "blk_hash": 'mempool',
285 txpoints.append(txpoint)
288 for txpoint in txpoints:
289 tx_id = txpoint['tx_id']
292 inrows = self.get_tx_inputs(tx_id)
294 _hash = self.binout(row[6])
295 address = hash_to_address(chr(0), _hash)
296 txinputs.append(address)
297 txpoint['inputs'] = txinputs
299 outrows = self.get_tx_outputs(tx_id)
301 _hash = self.binout(row[6])
302 address = hash_to_address(chr(0), _hash)
303 txoutputs.append(address)
304 txpoint['outputs'] = txoutputs
306 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
307 if not txpoint['is_in']:
308 # detect if already redeemed...
310 if row[6] == dbhash: break
313 #row = self.get_tx_output(tx_id,dbhash)
314 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
315 # if not redeemed, we add the script
317 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
320 if config.get('server','cache') == 'yes' and not address_has_mempool:
321 self.tx_cache[addr] = txpoints
327 class Direct_Interface(electrum.Interface):
331 def handler(self, method, params = ''):
332 cmds = {'session.new':new_session,
333 'session.poll':poll_session,
334 'session.update':update_session,
335 'blockchain.transaction.broadcast':send_tx,
336 'blockchain.address.get_history':store.get_history
339 return func( params )
344 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
345 respdata = urllib.urlopen(bitcoind_url, postdata).read()
347 if r['error'] != None:
348 out = "error: transaction rejected by memorypool"
355 def random_string(N):
356 import random, string
357 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
367 return 'wrong password'
371 return repr( len(sessions) )
373 return 'wrong password'
381 return 'wrong password'
383 def get_cache(pw,addr):
385 return store.tx_cache.get(addr)
387 return 'wrong password'
390 def poll_session(session_id):
391 session = sessions.get(session_id)
393 print time.asctime(), "session not found", session_id
394 out = repr( (-1, {}))
397 addresses = session['addresses']
398 session['last_time'] = time.time()
401 for addr in addresses:
402 if store.tx_cache.get( addr ) is not None: k += 1
404 # get addtess status, i.e. the last block for that address.
405 tx_points = store.get_history(addr)
409 lastpoint = tx_points[-1]
410 status = lastpoint['blk_hash']
411 # this is a temporary hack; move it up once old clients have disappeared
412 if status == 'mempool' and session['version'] != "old":
413 status = status + ':%d'% len(tx_points)
415 last_status = addresses.get( addr )
416 if last_status != status:
417 addresses[addr] = status
420 sessions[session_id]['addresses'] = addresses
421 out = repr( (block_number, ret ) )
422 t2 = time.time() - t1
424 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
429 def new_session(version, addresses):
430 session_id = random_string(10)
431 sessions[session_id] = { 'addresses':{}, 'version':version }
433 sessions[session_id]['addresses'][a] = ''
434 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
435 sessions[session_id]['last_time'] = time.time()
438 def update_session(session_id,addresses):
439 sessions[session_id]['addresses'] = {}
441 sessions[session_id]['addresses'][a] = ''
442 sessions[session_id]['last_time'] = time.time()
445 def listen_thread(store):
446 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
447 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
448 s.bind((config.get('server','host'), config.getint('server','port')))
451 conn, addr = s.accept()
452 thread.start_new_thread(client_thread, (addr, conn,))
456 def client_thread(ipaddr,conn):
457 #print "client thread", ipaddr
467 msg = msg.split('#', 1)[0]
470 cmd, data = ast.literal_eval(msg)
472 print "syntax error", repr(msg), ipaddr
476 out = do_command(cmd, data, ipaddr)
478 #print ipaddr, cmd, len(out)
482 print "error, could not send"
488 def do_command(cmd, data, ipaddr):
490 timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
493 out = "%d"%block_number
495 elif cmd in ['session','new_session']:
498 addresses = ast.literal_eval(data)
501 version, addresses = ast.literal_eval(data)
502 if version[0]=="0": version = "v" + version
506 print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
507 out = new_session(version, addresses)
509 elif cmd=='update_session':
511 session_id, addresses = ast.literal_eval(data)
515 print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
516 out = update_session(session_id,addresses)
518 elif cmd == 'bccapi_login':
521 v, k = ast.literal_eval(data)
522 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
523 print master_public_key
524 wallet_id = random_string(10)
525 w = electrum.Wallet( Direct_Interface() )
526 w.master_public_key = master_public_key.decode('hex')
528 wallets[wallet_id] = w
530 print "wallets", wallets
532 elif cmd == 'bccapi_getAccountInfo':
533 from electrum import int_to_hex
534 v, wallet_id = ast.literal_eval(data)
535 w = wallets.get(wallet_id)
537 num = len(w.addresses)
538 c, u = w.get_balance()
539 out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
540 out = out.decode('hex')
545 elif cmd == 'bccapi_getAccountStatement':
546 from electrum import int_to_hex
547 v, wallet_id = ast.literal_eval(data)
548 w = wallets.get(wallet_id)
550 num = len(w.addresses)
551 c, u = w.get_balance()
552 total_records = num_records = 0
553 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 )
554 out = out.decode('hex')
559 elif cmd == 'bccapi_getSendCoinForm':
562 elif cmd == 'bccapi_submitTransaction':
566 out = poll_session(data)
571 out = repr( store.get_history( address ) )
578 print timestr, "sent tx:", ipaddr, out
584 out = repr(peer_list.values())
594 def memorypool_update(store):
595 ds = BCDataStream.BCDataStream()
596 store.mempool_keys = []
598 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
599 respdata = urllib.urlopen(bitcoind_url, postdata).read()
601 if r['error'] != None:
604 v = r['result'].get('transactions')
607 ds.write(hextx.decode('hex'))
608 tx = deserialize.parse_Transaction(ds)
609 tx['hash'] = util.double_sha256(tx['tx'])
610 tx_hash = tx['hash'][::-1].encode('hex')
611 store.mempool_keys.append(tx_hash)
612 if store.tx_find_id_and_value(tx):
615 store.import_tx(tx, False)
621 def clean_session_thread():
625 for k,s in sessions.items():
633 NICK = 'E_'+random_string(10)
637 s.connect(('irc.freenode.net', 6667))
638 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
639 s.send('NICK '+NICK+'\n')
640 s.send('JOIN #electrum\n')
641 sf = s.makefile('r', 0)
645 line = line.rstrip('\r\n')
648 s.send('PONG '+line[1]+'\n')
649 elif '353' in line: # answer to /names
650 k = line.index('353')
651 for item in line[k+1:]:
652 if item[0:2] == 'E_':
653 s.send('WHO %s\n'%item)
654 elif '352' in line: # answer to /who
655 # warning: this is a horrible hack which apparently works
656 k = line.index('352')
658 ip = socket.gethostbyname(ip)
661 peer_list[name] = (ip,host)
662 if time.time() - t > 5*60:
663 s.send('NAMES #electrum\n')
667 traceback.print_exc(file=sys.stdout)
674 def jsonrpc_thread(store):
675 # see http://code.google.com/p/jsonrpclib/
676 from SocketServer import ThreadingMixIn
677 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
678 class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
679 server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
680 server.register_function(lambda : peer_list.values(), 'peers')
681 server.register_function(cmd_stop, 'stop')
682 server.register_function(cmd_load, 'load')
683 server.register_function(lambda : block_number, 'blocks')
684 server.register_function(clear_cache, 'clear_cache')
685 server.register_function(get_cache, 'get_cache')
686 server.register_function(send_tx, 'blockchain.transaction.broadcast')
687 server.register_function(store.get_history, 'blockchain.address.get_history')
688 server.register_function(new_session, 'session.new')
689 server.register_function(update_session, 'session.update')
690 server.register_function(poll_session, 'session.poll')
691 server.serve_forever()
697 if __name__ == '__main__':
701 server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
704 out = server.load(password)
708 out = server.stop(password)
709 elif cmd == 'clear_cache':
710 out = server.clear_cache(password)
711 elif cmd == 'get_cache':
712 out = server.get_cache(password,sys.argv[2])
714 out = server.blockchain.address.get_history(sys.argv[2])
716 out = server.blockchain.transaction.broadcast(sys.argv[2])
718 out = server.blocks()
723 print "starting Electrum server"
724 print "cache:", config.get('server', 'cache')
726 conf = DataStore.CONFIG_DEFAULTS
727 args, argv = readconf.parse_argv( [], conf)
728 args.dbtype= config.get('database','type')
729 if args.dbtype == 'sqlite3':
730 args.connect_args = { 'database' : config.get('database','database') }
731 elif args.dbtype == 'MySQLdb':
732 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
733 elif args.dbtype == 'psycopg2':
734 args.connect_args = { 'database' : config.get('database','database') }
735 store = MyStore(args)
737 store.mempool_keys = {}
739 thread.start_new_thread(listen_thread, (store,))
740 thread.start_new_thread(jsonrpc_thread, (store,))
741 thread.start_new_thread(clean_session_thread, ())
742 if (config.get('server','irc') == 'yes' ):
743 thread.start_new_thread(irc_thread, ())
749 memorypool_update(store)
750 block_number = store.get_block_number(1)
753 traceback.print_exc(file=sys.stdout)
756 print "server stopped"