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
26 import time, socket, operator, thread, ast, sys,re
27 import psycopg2, binascii
30 from Abe.abe import hash_to_address, decode_check_address
31 from Abe.DataStore import DataStore as Datastore_class
32 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
36 config = ConfigParser.ConfigParser()
37 # set some defaults, which will be overwritten by the config file
38 config.add_section('server')
39 config.set('server','banner', 'Welcome to Electrum!')
40 config.set('server', 'host', 'localhost')
41 config.set('server', 'port', 50000)
42 config.set('server', 'password', '')
43 config.set('server', 'irc', 'yes')
44 config.set('server', 'cache', 'no')
45 config.set('server', 'ircname', 'Electrum server')
46 config.add_section('database')
47 config.set('database', 'type', 'psycopg2')
48 config.set('database', 'database', 'abe')
51 f = open('/etc/electrum.conf','r')
55 print "Could not read electrum.conf. I will use the default values."
60 dblock = thread.allocate_lock()
64 class MyStore(Datastore_class):
66 def import_tx(self, tx, is_coinbase):
67 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
68 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
70 def update_tx_cache(self, txid):
71 inrows = self.get_tx_inputs(txid, False)
73 _hash = store.binout(row[6])
74 address = hash_to_address(chr(0), _hash)
75 if self.tx_cache.has_key(address):
76 print "cache: invalidating", address, self.ismempool
77 self.tx_cache.pop(address)
78 outrows = self.get_tx_outputs(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, self.ismempool
84 self.tx_cache.pop(address)
86 def safe_sql(self,sql, params=(), lock=True):
88 if lock: dblock.acquire()
89 ret = self.selectall(sql,params)
90 if lock: dblock.release()
93 print "sql error", sql
96 def get_tx_outputs(self, tx_id, lock=True):
97 return self.safe_sql("""SELECT
99 txout.txout_scriptPubKey,
106 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
107 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
108 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
109 WHERE txout.tx_id = %d
110 ORDER BY txout.txout_pos
111 """%(tx_id), (), lock)
113 def get_tx_inputs(self, tx_id, lock=True):
114 return self.safe_sql(""" SELECT
118 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
120 COALESCE(txout.txout_pos, u.txout_pos),
123 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
124 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
125 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
126 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
127 WHERE txin.tx_id = %d
128 ORDER BY txin.txin_pos
129 """%(tx_id,), (), lock)
131 def get_address_out_rows(self, dbhash):
132 return self.safe_sql(""" SELECT
142 FROM chain_candidate cc
143 JOIN block b ON (b.block_id = cc.block_id)
144 JOIN block_tx ON (block_tx.block_id = b.block_id)
145 JOIN tx ON (tx.tx_id = block_tx.tx_id)
146 JOIN txin ON (txin.tx_id = tx.tx_id)
147 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
148 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
149 WHERE pubkey.pubkey_hash = ?
150 AND cc.in_longest = 1""", (dbhash,))
152 def get_address_out_rows_memorypool(self, dbhash):
153 return self.safe_sql(""" SELECT
160 JOIN txin ON (txin.tx_id = tx.tx_id)
161 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
162 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
163 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
165 def get_address_in_rows(self, dbhash):
166 return self.safe_sql(""" SELECT
176 FROM chain_candidate cc
177 JOIN block b ON (b.block_id = cc.block_id)
178 JOIN block_tx ON (block_tx.block_id = b.block_id)
179 JOIN tx ON (tx.tx_id = block_tx.tx_id)
180 JOIN txout ON (txout.tx_id = tx.tx_id)
181 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
182 WHERE pubkey.pubkey_hash = ?
183 AND cc.in_longest = 1""", (dbhash,))
185 def get_address_in_rows_memorypool(self, dbhash):
186 return self.safe_sql( """ SELECT
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 = ? """, (dbhash,))
197 def get_txpoints(self, addr):
199 if config.get('server','cache') == 'yes':
200 cached_version = self.tx_cache.get( addr )
201 if cached_version is not None:
202 return cached_version
204 version, binaddr = decode_check_address(addr)
207 dbhash = self.binin(binaddr)
209 rows += self.get_address_out_rows( dbhash )
210 rows += self.get_address_in_rows( dbhash )
217 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
219 print "cannot unpack row", row
221 tx_hash = self.hashout_hex(tx_hash)
224 #"chain_id": int(chain_id),
225 "height": int(height),
227 "blk_hash": self.hashout_hex(blk_hash),
234 txpoints.append(txpoint)
235 known_tx.append(self.hashout_hex(tx_hash))
238 # todo: sort them really...
239 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
243 rows += self.get_address_in_rows_memorypool( dbhash )
244 rows += self.get_address_out_rows_memorypool( dbhash )
245 address_has_mempool = False
248 is_in, tx_hash, tx_id, pos, value = row
249 tx_hash = self.hashout_hex(tx_hash)
250 if tx_hash in known_tx:
252 if tx_hash not in self.mempool_keys:
255 address_has_mempool = True
256 #print "mempool", tx_hash
262 "blk_hash": 'mempool',
268 txpoints.append(txpoint)
271 for txpoint in txpoints:
272 tx_id = txpoint['tx_id']
275 inrows = self.get_tx_inputs(tx_id)
277 _hash = self.binout(row[6])
278 address = hash_to_address(chr(0), _hash)
279 txinputs.append(address)
280 txpoint['inputs'] = txinputs
282 outrows = self.get_tx_outputs(tx_id)
284 _hash = self.binout(row[6])
285 address = hash_to_address(chr(0), _hash)
286 txoutputs.append(address)
287 txpoint['outputs'] = txoutputs
289 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
290 if not txpoint['is_in']:
291 # detect if already redeemed...
293 if row[6] == dbhash: break
296 #row = self.get_tx_output(tx_id,dbhash)
297 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
298 # if not redeemed, we add the script
300 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
303 if config.get('server','cache') == 'yes' and not address_has_mempool:
304 self.tx_cache[addr] = txpoints
313 conn = bitcoinrpc.connect_to_local()
315 v = conn.importtransaction(tx)
317 v = "error: transaction rejected by memorypool"
321 def listen_thread(store):
322 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
323 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
324 s.bind((config.get('server','host'), config.getint('server','port')))
327 conn, addr = s.accept()
328 thread.start_new_thread(client_thread, (addr, conn,))
330 def random_string(N):
331 import random, string
332 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
334 def client_thread(ipaddr,conn):
335 #print "client thread", ipaddr
350 cmd, data = ast.literal_eval(msg[:-1])
352 print "syntax error", repr(msg)
357 out = "%d"%block_number
359 elif cmd in ['session','new_session']:
360 session_id = random_string(10)
363 addresses = ast.literal_eval(data)
366 version, addresses = ast.literal_eval(data)
367 version = "v"+version
373 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
375 sessions[session_id] = { 'addresses':{}, 'version':version, 'ip':ipaddr }
377 sessions[session_id]['addresses'][a] = ''
378 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
379 sessions[session_id]['last_time'] = time.time()
381 elif cmd=='update_session':
383 session_id, addresses = ast.literal_eval(data)
389 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
391 sessions[session_id]['addresses'] = {}
393 sessions[session_id]['addresses'][a] = ''
395 sessions[session_id]['last_time'] = time.time()
399 session = sessions.get(session_id)
401 print time.asctime(), "session not found", session_id, ipaddr
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_txpoints(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 + ':%s'% lastpoint['tx_hash']
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 out = repr( store.get_txpoints( address ) )
440 if config.get('server','password') == data:
441 out = repr( len(sessions) )
443 out = 'wrong password'
447 print "sent tx:", out
449 elif cmd =='clear_cache':
450 if config.get('server','password') == data:
454 out = 'wrong password'
456 elif cmd =='get_cache':
462 if config.get('server','password') == pw:
463 out = store.tx_cache.get(addr)
466 out = 'wrong password'
468 out = "error: "+ repr(data)
472 if config.get('server','password') == data:
476 out = 'wrong password'
479 out = repr(peer_list.values())
485 #print ipaddr, cmd, len(out)
489 print "error, could not send"
495 ds = BCDataStream.BCDataStream()
500 def memorypool_update(store):
501 store.mempool_keys = []
502 conn = bitcoinrpc.connect_to_local()
504 v = conn.getmemorypool()
506 print "cannot contact bitcoin daemon"
508 v = v['transactions']
511 ds.write(hextx.decode('hex'))
512 tx = deserialize.parse_Transaction(ds)
513 tx['hash'] = util.double_sha256(tx['tx'])
514 store.mempool_keys.append(tx['hash'][::-1].encode('hex'))
515 if store.tx_find_id_and_value(tx):
518 store.import_tx(tx, False)
524 def clean_session_thread():
528 for k,s in sessions.items():
531 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "end session", s['ip']
537 NICK = 'E_'+random_string(10)
541 s.connect(('irc.freenode.net', 6667))
542 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
543 s.send('NICK '+NICK+'\n')
544 s.send('JOIN #electrum\n')
545 sf = s.makefile('r', 0)
549 line = line.rstrip('\r\n')
552 s.send('PONG '+line[1]+'\n')
553 elif '353' in line: # answer to /names
554 k = line.index('353')
555 for item in line[k+1:]:
556 if item[0:2] == 'E_':
557 s.send('WHO %s\n'%item)
558 elif '352' in line: # answer to /who
559 # warning: this is a horrible hack which apparently works
560 k = line.index('352')
562 ip = socket.gethostbyname(ip)
565 peer_list[name] = (ip,host)
566 if time.time() - t > 5*60:
567 s.send('NAMES #electrum\n')
571 traceback.print_exc(file=sys.stdout)
580 if __name__ == '__main__':
585 request = "('load','%s')#"%config.get('server','password')
587 request = "('peers','')#"
589 request = "('stop','%s')#"%config.get('server','password')
590 elif cmd == 'clear_cache':
591 request = "('clear_cache','%s')#"%config.get('server','password')
592 elif cmd == 'get_cache':
593 request = "('get_cache',('%s','%s'))#"%(config.get('server','password'),sys.argv[2])
595 request = "('h','%s')#"%sys.argv[2]
597 request = "('b','')#"
599 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
600 s.connect((config.get('server','host'), config.getint('server','port')))
612 print "starting Electrum server"
613 print "cache:", config.get('server', 'cache')
615 conf = DataStore.CONFIG_DEFAULTS
616 args, argv = readconf.parse_argv( [], conf)
617 args.dbtype= config.get('database','type')
618 if args.dbtype == 'sqlite3':
619 args.connect_args = { 'database' : config.get('database','database') }
620 elif args.dbtype == 'MySQLdb':
621 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
622 elif args.dbtype == 'psycopg2':
623 args.connect_args = { 'database' : config.get('database','database') }
624 store = MyStore(args)
626 store.ismempool = False
627 store.mempool_keys = {}
629 thread.start_new_thread(listen_thread, (store,))
630 thread.start_new_thread(clean_session_thread, ())
631 if (config.get('server','irc') == 'yes' ):
632 thread.start_new_thread(irc_thread, ())
638 store.ismempool = True
639 memorypool_update(store)
640 store.ismempool = False
641 block_number = store.get_block_number(1)
644 traceback.print_exc(file=sys.stdout)
647 print "server stopped"