mempool fix, cache
[electrum-server.git] / server.py
1 #!/usr/bin/env python
2 # Copyright(C) 2011 thomasv@gitorious
3
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.
8 #
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.
13 #
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>.
17
18 """
19 Todo:
20    * server should check and return bitcoind status..
21    * improve txpoint sorting
22    * command to check cache
23
24  mempool transactions do not need to be added to the database; it slows it down
25 """
26
27
28 import time, json, socket, operator, thread, ast, sys,re
29 import psycopg2, binascii
30
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
34
35 import ConfigParser
36 from json import dumps, loads
37 import urllib
38
39 # we need to import electrum
40 sys.path.append('../client/')
41 from wallet import Wallet
42 from interface import Interface
43
44
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', 'ircname', 'Electrum server')
54 config.add_section('database')
55 config.set('database', 'type', 'psycopg2')
56 config.set('database', 'database', 'abe')
57
58 try:
59     f = open('/etc/electrum.conf','r')
60     config.readfp(f)
61     f.close()
62 except:
63     print "Could not read electrum.conf. I will use the default values."
64
65 try:
66     f = open('/etc/electrum.banner','r')
67     config.set('server','banner', f.read())
68     f.close()
69 except:
70     pass
71
72 password = config.get('server','password')
73 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
74
75 stopping = False
76 block_number = -1
77 old_block_number = -1
78 sessions = {}
79 sessions_sub_numblocks = [] # sessions that have subscribed to the service
80
81 dblock = thread.allocate_lock()
82 peer_list = {}
83
84 wallets = {} # for ultra-light clients such as bccapi
85
86 from Queue import Queue
87 input_queue = Queue()
88 output_queue = Queue()
89 address_queue = Queue()
90
91 class MyStore(Datastore_class):
92
93     def import_tx(self, tx, is_coinbase):
94         tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
95         self.update_tx_cache(tx_id)
96
97     def update_tx_cache(self, txid):
98         inrows = self.get_tx_inputs(txid, False)
99         for row in inrows:
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)
105             address_queue.put(address)
106
107         outrows = self.get_tx_outputs(txid, False)
108         for row in outrows:
109             _hash = store.binout(row[6])
110             address = hash_to_address(chr(0), _hash)
111             if self.tx_cache.has_key(address):
112                 print "cache: invalidating", address
113                 self.tx_cache.pop(address)
114             address_queue.put(address)
115
116     def safe_sql(self,sql, params=(), lock=True):
117         try:
118             if lock: dblock.acquire()
119             ret = self.selectall(sql,params)
120             if lock: dblock.release()
121             return ret
122         except:
123             print "sql error", sql
124             return []
125
126     def get_tx_outputs(self, tx_id, lock=True):
127         return self.safe_sql("""SELECT
128                 txout.txout_pos,
129                 txout.txout_scriptPubKey,
130                 txout.txout_value,
131                 nexttx.tx_hash,
132                 nexttx.tx_id,
133                 txin.txin_pos,
134                 pubkey.pubkey_hash
135               FROM txout
136               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
137               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
138               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
139              WHERE txout.tx_id = %d 
140              ORDER BY txout.txout_pos
141         """%(tx_id), (), lock)
142
143     def get_tx_inputs(self, tx_id, lock=True):
144         return self.safe_sql(""" SELECT
145                 txin.txin_pos,
146                 txin.txin_scriptSig,
147                 txout.txout_value,
148                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
149                 prevtx.tx_id,
150                 COALESCE(txout.txout_pos, u.txout_pos),
151                 pubkey.pubkey_hash
152               FROM txin
153               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
154               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
155               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
156               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
157              WHERE txin.tx_id = %d
158              ORDER BY txin.txin_pos
159              """%(tx_id,), (), lock)
160
161     def get_address_out_rows(self, dbhash):
162         return self.safe_sql(""" SELECT
163                 b.block_nTime,
164                 cc.chain_id,
165                 b.block_height,
166                 1,
167                 b.block_hash,
168                 tx.tx_hash,
169                 tx.tx_id,
170                 txin.txin_pos,
171                 -prevout.txout_value
172               FROM chain_candidate cc
173               JOIN block b ON (b.block_id = cc.block_id)
174               JOIN block_tx ON (block_tx.block_id = b.block_id)
175               JOIN tx ON (tx.tx_id = block_tx.tx_id)
176               JOIN txin ON (txin.tx_id = tx.tx_id)
177               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
178               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
179              WHERE pubkey.pubkey_hash = ?
180                AND cc.in_longest = 1""", (dbhash,))
181
182     def get_address_out_rows_memorypool(self, dbhash):
183         return self.safe_sql(""" SELECT
184                 1,
185                 tx.tx_hash,
186                 tx.tx_id,
187                 txin.txin_pos,
188                 -prevout.txout_value
189               FROM tx 
190               JOIN txin ON (txin.tx_id = tx.tx_id)
191               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
192               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
193              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
194
195     def get_address_in_rows(self, dbhash):
196         return self.safe_sql(""" SELECT
197                 b.block_nTime,
198                 cc.chain_id,
199                 b.block_height,
200                 0,
201                 b.block_hash,
202                 tx.tx_hash,
203                 tx.tx_id,
204                 txout.txout_pos,
205                 txout.txout_value
206               FROM chain_candidate cc
207               JOIN block b ON (b.block_id = cc.block_id)
208               JOIN block_tx ON (block_tx.block_id = b.block_id)
209               JOIN tx ON (tx.tx_id = block_tx.tx_id)
210               JOIN txout ON (txout.tx_id = tx.tx_id)
211               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
212              WHERE pubkey.pubkey_hash = ?
213                AND cc.in_longest = 1""", (dbhash,))
214
215     def get_address_in_rows_memorypool(self, dbhash):
216         return self.safe_sql( """ SELECT
217                 0,
218                 tx.tx_hash,
219                 tx.tx_id,
220                 txout.txout_pos,
221                 txout.txout_value
222               FROM tx
223               JOIN txout ON (txout.tx_id = tx.tx_id)
224               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
225              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
226
227     def get_history(self, addr):
228         
229         cached_version = self.tx_cache.get( addr )
230         if cached_version is not None:
231             return cached_version
232
233         version, binaddr = decode_check_address(addr)
234         if binaddr is None:
235             return None
236
237         dbhash = self.binin(binaddr)
238         rows = []
239         rows += self.get_address_out_rows( dbhash )
240         rows += self.get_address_in_rows( dbhash )
241
242         txpoints = []
243         known_tx = []
244
245         for row in rows:
246             try:
247                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
248             except:
249                 print "cannot unpack row", row
250                 break
251             tx_hash = self.hashout_hex(tx_hash)
252             txpoint = {
253                     "nTime":    int(nTime),
254                     "height":   int(height),
255                     "is_in":    int(is_in),
256                     "blk_hash": self.hashout_hex(blk_hash),
257                     "tx_hash":  tx_hash,
258                     "tx_id":    int(tx_id),
259                     "pos":      int(pos),
260                     "value":    int(value),
261                     }
262
263             txpoints.append(txpoint)
264             known_tx.append(self.hashout_hex(tx_hash))
265
266
267         # todo: sort them really...
268         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
269
270         # read memory pool
271         rows = []
272         rows += self.get_address_in_rows_memorypool( dbhash )
273         rows += self.get_address_out_rows_memorypool( dbhash )
274         address_has_mempool = False
275
276         for row in rows:
277             is_in, tx_hash, tx_id, pos, value = row
278             tx_hash = self.hashout_hex(tx_hash)
279             if tx_hash in known_tx:
280                 continue
281
282             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
283             address_has_mempool = True
284
285             # this means pending transactions are returned by getmemorypool
286             if tx_hash not in self.mempool_keys:
287                 continue
288
289             #print "mempool", tx_hash
290             txpoint = {
291                     "nTime":    0,
292                     "height":   0,
293                     "is_in":    int(is_in),
294                     "blk_hash": 'mempool', 
295                     "tx_hash":  tx_hash,
296                     "tx_id":    int(tx_id),
297                     "pos":      int(pos),
298                     "value":    int(value),
299                     }
300             txpoints.append(txpoint)
301
302
303         for txpoint in txpoints:
304             tx_id = txpoint['tx_id']
305             
306             txinputs = []
307             inrows = self.get_tx_inputs(tx_id)
308             for row in inrows:
309                 _hash = self.binout(row[6])
310                 address = hash_to_address(chr(0), _hash)
311                 txinputs.append(address)
312             txpoint['inputs'] = txinputs
313             txoutputs = []
314             outrows = self.get_tx_outputs(tx_id)
315             for row in outrows:
316                 _hash = self.binout(row[6])
317                 address = hash_to_address(chr(0), _hash)
318                 txoutputs.append(address)
319             txpoint['outputs'] = txoutputs
320
321             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
322             if not txpoint['is_in']:
323                 # detect if already redeemed...
324                 for row in outrows:
325                     if row[6] == dbhash: break
326                 else:
327                     raise
328                 #row = self.get_tx_output(tx_id,dbhash)
329                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
330                 # if not redeemed, we add the script
331                 if row:
332                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
333
334         # cache result
335         if not address_has_mempool:
336             self.tx_cache[addr] = txpoints
337         
338         return txpoints
339
340
341
342 class Direct_Interface(Interface):
343     def __init__(self):
344         pass
345
346     def handler(self, method, params = ''):
347         cmds = {'session.new':new_session,
348                 'session.poll':poll_session,
349                 'session.update':update_session,
350                 'blockchain.transaction.broadcast':send_tx,
351                 'blockchain.address.get_history':store.get_history
352                 }
353         func = cmds[method]
354         return func( params )
355
356
357
358 def send_tx(tx):
359     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
360     respdata = urllib.urlopen(bitcoind_url, postdata).read()
361     r = loads(respdata)
362     if r['error'] != None:
363         out = "error: transaction rejected by memorypool\n"+tx
364     else:
365         out = r['result']
366     return out
367
368
369
370 def random_string(N):
371     import random, string
372     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
373
374     
375
376 def cmd_stop(data):
377     global stopping
378     if password == data:
379         stopping = True
380         return 'ok'
381     else:
382         return 'wrong password'
383
384 def cmd_load(pw):
385     if password == pw:
386         return repr( len(sessions) )
387     else:
388         return 'wrong password'
389
390
391 def clear_cache(pw):
392     if password == pw:
393         store.tx_cache = {}
394         return 'ok'
395     else:
396         return 'wrong password'
397
398 def get_cache(pw,addr):
399     if password == pw:
400         return store.tx_cache.get(addr)
401     else:
402         return 'wrong password'
403
404
405 def poll_session(session_id):
406     session = sessions.get(session_id)
407     if session is None:
408         print time.asctime(), "session not found", session_id
409         out = repr( (-1, {}))
410     else:
411         t1 = time.time()
412         addresses = session['addresses']
413         session['last_time'] = time.time()
414         ret = {}
415         k = 0
416         for addr in addresses:
417             if store.tx_cache.get( addr ) is not None: k += 1
418             status = get_address_status( addr )
419             last_status = addresses.get( addr )
420             if last_status != status:
421                 addresses[addr] = status
422                 ret[addr] = status
423         if ret:
424             sessions[session_id]['addresses'] = addresses
425         out = repr( (block_number, ret ) )
426         t2 = time.time() - t1 
427         if t2 > 10:
428             print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
429
430         return out
431
432
433 def do_update_address(addr):
434     # an address was involved in a transaction; we check if it was subscribed to in a session
435     # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
436     for session_id in sessions.keys():
437         session = sessions[session_id]
438         if session.get('type') != 'subscribe': continue
439         addresses = session['addresses'].keys()
440
441         if addr in addresses:
442             print "address ", addr, "is watched by", session_id
443             status = get_address_status( addr )
444             last_status = session['addresses'][addr]
445             if last_status != status:
446                 print "sending new status for %s:"%addr, status
447                 send_status(session_id,addr,status)
448                 sessions[session_id]['addresses'][addr] = status
449
450
451 def get_address_status(addr):
452     # get address status, i.e. the last block for that address.
453     tx_points = store.get_history(addr)
454     if not tx_points:
455         status = None
456     else:
457         lastpoint = tx_points[-1]
458         status = lastpoint['blk_hash']
459         # this is a temporary hack; move it up once old clients have disappeared
460         if status == 'mempool': # and session['version'] != "old":
461             status = status + ':%d'% len(tx_points)
462     return status
463
464
465 def send_numblocks(session_id):
466     out = json.dumps( {'method':'numblocks.subscribe', 'result':block_number} )
467     output_queue.put((session_id, out))
468
469 def send_status(session_id, address, status):
470     out = json.dumps( { 'method':'address.subscribe', 'address':address, 'status':status } )
471     output_queue.put((session_id, out))
472
473 def subscribe_to_numblocks(session_id):
474     sessions_sub_numblocks.append(session_id)
475     send_numblocks(session_id)
476
477 def subscribe_to_address(session_id, address):
478     status = get_address_status(address)
479     sessions[session_id]['type'] = 'subscribe'
480     sessions[session_id]['addresses'][address] = status
481     sessions[session_id]['last_time'] = time.time()
482     send_status(session_id, address, status)
483
484 def new_session(version, addresses):
485     session_id = random_string(10)
486     sessions[session_id] = { 'addresses':{}, 'version':version }
487     for a in addresses:
488         sessions[session_id]['addresses'][a] = ''
489     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
490     sessions[session_id]['last_time'] = time.time()
491     return out
492
493 def update_session(session_id,addresses):
494     sessions[session_id]['addresses'] = {}
495     for a in addresses:
496         sessions[session_id]['addresses'][a] = ''
497     sessions[session_id]['last_time'] = time.time()
498     return 'ok'
499
500 def native_server_thread():
501     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
502     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
503     s.bind((config.get('server','host'), config.getint('server','port')))
504     s.listen(1)
505     while not stopping:
506         conn, addr = s.accept()
507         try:
508             thread.start_new_thread(native_client_thread, (addr, conn,))
509         except:
510             # can't start new thread if there is no memory..
511             traceback.print_exc(file=sys.stdout)
512
513
514 def native_client_thread(ipaddr,conn):
515     #print "client thread", ipaddr
516     try:
517         ipaddr = ipaddr[0]
518         msg = ''
519         while 1:
520             d = conn.recv(1024)
521             msg += d
522             if not d: 
523                 break
524             if '#' in msg:
525                 msg = msg.split('#', 1)[0]
526                 break
527         try:
528             cmd, data = ast.literal_eval(msg)
529         except:
530             print "syntax error", repr(msg), ipaddr
531             conn.close()
532             return
533
534         out = do_command(cmd, data, ipaddr)
535         if out:
536             #print ipaddr, cmd, len(out)
537             try:
538                 conn.send(out)
539             except:
540                 print "error, could not send"
541
542     finally:
543         conn.close()
544
545
546
547 # used by the native handler
548 def do_command(cmd, data, ipaddr):
549
550     timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
551
552     if cmd=='b':
553         out = "%d"%block_number
554
555     elif cmd in ['session','new_session']:
556         try:
557             if cmd == 'session':
558                 addresses = ast.literal_eval(data)
559                 version = "old"
560             else:
561                 version, addresses = ast.literal_eval(data)
562                 if version[0]=="0": version = "v" + version
563         except:
564             print "error", data
565             return None
566         print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
567         out = new_session(version, addresses)
568
569     elif cmd=='update_session':
570         try:
571             session_id, addresses = ast.literal_eval(data)
572         except:
573             print "error"
574             return None
575         print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
576         out = update_session(session_id,addresses)
577
578     elif cmd == 'bccapi_login':
579         import electrum
580         print "data",data
581         v, k = ast.literal_eval(data)
582         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
583         print master_public_key
584         wallet_id = random_string(10)
585         w = Wallet( Direct_Interface() )
586         w.master_public_key = master_public_key.decode('hex')
587         w.synchronize()
588         wallets[wallet_id] = w
589         out = wallet_id
590         print "wallets", wallets
591
592     elif cmd == 'bccapi_getAccountInfo':
593         from wallet import int_to_hex
594         v, wallet_id = ast.literal_eval(data)
595         w = wallets.get(wallet_id)
596         if w is not None:
597             num = len(w.addresses)
598             c, u = w.get_balance()
599             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
600             out = out.decode('hex')
601         else:
602             print "error",data
603             out = "error"
604
605     elif cmd == 'bccapi_getAccountStatement':
606         from wallet import int_to_hex
607         v, wallet_id = ast.literal_eval(data)
608         w = wallets.get(wallet_id)
609         if w is not None:
610             num = len(w.addresses)
611             c, u = w.get_balance()
612             total_records = num_records = 0
613             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 )
614             out = out.decode('hex')
615         else:
616             print "error",data
617             out = "error"
618
619     elif cmd == 'bccapi_getSendCoinForm':
620         out = ''
621
622     elif cmd == 'bccapi_submitTransaction':
623         out = ''
624             
625     elif cmd=='poll': 
626         out = poll_session(data)
627
628     elif cmd == 'h': 
629         # history
630         address = data
631         out = repr( store.get_history( address ) )
632
633     elif cmd == 'load': 
634         out = cmd_load(data)
635
636     elif cmd =='tx':
637         out = send_tx(data)
638         print timestr, "sent tx:", ipaddr, out
639
640     elif cmd == 'stop':
641         out = cmd_stop(data)
642
643     elif cmd == 'peers':
644         out = repr(peer_list.values())
645
646     else:
647         out = None
648
649     return out
650
651
652
653 ####################################################################
654
655 def tcp_server_thread():
656     thread.start_new_thread(process_input_queue, ())
657     thread.start_new_thread(process_output_queue, ())
658
659     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
660     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
661     s.bind((config.get('server','host'), 50001))
662     s.listen(1)
663     while not stopping:
664         conn, addr = s.accept()
665         try:
666             thread.start_new_thread(tcp_client_thread, (addr, conn,))
667         except:
668             # can't start new thread if there is no memory..
669             traceback.print_exc(file=sys.stdout)
670
671
672 def close_session(session_id):
673     print "lost connection", session_id
674     sessions.pop(session_id)
675     if session_id in sessions_sub_numblocks:
676         sessions_sub_numblocks.remove(session_id)
677
678
679 # one thread per client. put requests in a queue.
680 def tcp_client_thread(ipaddr,conn):
681     """ use a persistent connection. put commands in a queue."""
682     print "persistent client thread", ipaddr
683     global sessions
684
685     session_id = random_string(10)
686     sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown' }
687
688     ipaddr = ipaddr[0]
689     msg = ''
690
691     while not stopping:
692         try:
693             d = conn.recv(1024)
694         except socket.error:
695             d = ''
696         if not d:
697             close_session(session_id)
698             break
699
700         msg += d
701         while True:
702             s = msg.find('\n')
703             if s ==-1:
704                 break
705             else:
706                 c = msg[0:s].strip()
707                 msg = msg[s+1:]
708                 if c == 'quit': 
709                     conn.close()
710                     close_session(session_id)
711                     return
712                 try:
713                     c = json.loads(c)
714                 except:
715                     print "json error", repr(c)
716                     continue
717                 try:
718                     cmd = c['method']
719                     data = c['params']
720                 except:
721                     print "syntax error", repr(c), ipaddr
722                     continue
723
724                 # add to queue
725                 input_queue.put((session_id, cmd, data))
726
727
728
729 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
730 def process_input_queue():
731     while not stopping:
732         session_id, cmd, data = input_queue.get()
733         if session_id not in sessions.keys():
734             continue
735         out = None
736         if cmd == 'address.subscribe':
737             subscribe_to_address(session_id,data)
738         elif cmd == 'numblocks.subscribe':
739             subscribe_to_numblocks(session_id)
740         elif cmd == 'client.version':
741             sessions[session_id]['version'] = data
742         elif cmd == 'server.banner':
743             out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
744         elif cmd == 'server.peers':
745             out = json.dumps( { 'method':'server.peers', 'result':peer_list.values() } )
746         elif cmd == 'address.get_history':
747             address = data
748             out = json.dumps( { 'method':'address.get_history', 'address':address, 'result':store.get_history( address ) } )
749         elif cmd == 'transaction.broadcast':
750             txo = send_tx(data)
751             print "sent tx:", txo
752             out = json.dumps( { 'method':'transaction.broadcast', 'result':txo } )
753         else:
754             print "unknown command", cmd
755         if out:
756             output_queue.put((session_id, out))
757
758 # this is a separate thread
759 def process_output_queue():
760     while not stopping:
761         session_id, out = output_queue.get()
762         session = sessions.get(session_id)
763         if session: 
764             try:
765                 conn = session.get('conn')
766                 conn.send(out+'\n')
767             except:
768                 close_session(session_id)
769                 
770
771
772
773 ####################################################################
774
775
776 def memorypool_update(store):
777     """ when a tx is removed from memory pool, I need to notify subscribers"""
778
779     ds = BCDataStream.BCDataStream()
780     previous_transactions = store.mempool_keys
781     store.mempool_keys = []
782
783     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
784     respdata = urllib.urlopen(bitcoind_url, postdata).read()
785     r = loads(respdata)
786     if r['error'] != None:
787         return
788
789     v = r['result'].get('transactions')
790     for hextx in v:
791         ds.clear()
792         ds.write(hextx.decode('hex'))
793         tx = deserialize.parse_Transaction(ds)
794         tx['hash'] = util.double_sha256(tx['tx'])
795         tx_hash = store.hashin(tx['hash'])
796
797         store.mempool_keys.append(tx_hash)
798         if store.tx_find_id_and_value(tx):
799             pass
800         else:
801             store.import_tx(tx, False)
802     store.commit()
803
804     for tx_hash in previous_transactions:
805         if tx_hash not in store.mempool_keys:
806             tx = { 'hash':store.hashout(tx_hash) }
807             tx_id = store.tx_find_id_and_value(tx)
808             if tx_id:
809                 store.update_tx_cache(tx_id)
810
811
812 def clean_session_thread():
813     while not stopping:
814         time.sleep(30)
815         t = time.time()
816         for k,s in sessions.items():
817             if s.get('type') == 'subscribe': continue
818             t0 = s['last_time']
819             if t - t0 > 5*60:
820                 sessions.pop(k)
821                 print "lost session", k
822             
823
824 def irc_thread():
825     global peer_list
826     NICK = 'E_'+random_string(10)
827     while not stopping:
828         try:
829             s = socket.socket()
830             s.connect(('irc.freenode.net', 6667))
831             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
832             s.send('NICK '+NICK+'\n')
833             s.send('JOIN #electrum\n')
834             sf = s.makefile('r', 0)
835             t = 0
836             while not stopping:
837                 line = sf.readline()
838                 line = line.rstrip('\r\n')
839                 line = line.split()
840                 if line[0]=='PING': 
841                     s.send('PONG '+line[1]+'\n')
842                 elif '353' in line: # answer to /names
843                     k = line.index('353')
844                     for item in line[k+1:]:
845                         if item[0:2] == 'E_':
846                             s.send('WHO %s\n'%item)
847                 elif '352' in line: # answer to /who
848                     # warning: this is a horrible hack which apparently works
849                     k = line.index('352')
850                     ip = line[k+4]
851                     ip = socket.gethostbyname(ip)
852                     name = line[k+6]
853                     host = line[k+9]
854                     peer_list[name] = (ip,host)
855                 if time.time() - t > 5*60:
856                     s.send('NAMES #electrum\n')
857                     t = time.time()
858                     peer_list = {}
859         except:
860             traceback.print_exc(file=sys.stdout)
861         finally:
862             sf.close()
863             s.close()
864
865
866
867 def http_server_thread(store):
868     # see http://code.google.com/p/jsonrpclib/
869     from SocketServer import ThreadingMixIn
870     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
871     class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
872     server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
873     server.register_function(lambda : peer_list.values(), 'peers')
874     server.register_function(cmd_stop, 'stop')
875     server.register_function(cmd_load, 'load')
876     server.register_function(lambda : block_number, 'blocks')
877     server.register_function(clear_cache, 'clear_cache')
878     server.register_function(get_cache, 'get_cache')
879     server.register_function(send_tx, 'blockchain.transaction.broadcast')
880     server.register_function(store.get_history, 'blockchain.address.get_history')
881     server.register_function(new_session, 'session.new')
882     server.register_function(update_session, 'session.update')
883     server.register_function(poll_session, 'session.poll')
884     server.serve_forever()
885
886
887 import traceback
888
889
890 if __name__ == '__main__':
891
892     if len(sys.argv)>1:
893         import jsonrpclib
894         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
895         cmd = sys.argv[1]
896         if cmd == 'load':
897             out = server.load(password)
898         elif cmd == 'peers':
899             out = server.peers()
900         elif cmd == 'stop':
901             out = server.stop(password)
902         elif cmd == 'clear_cache':
903             out = server.clear_cache(password)
904         elif cmd == 'get_cache':
905             out = server.get_cache(password,sys.argv[2])
906         elif cmd == 'h':
907             out = server.blockchain.address.get_history(sys.argv[2])
908         elif cmd == 'tx':
909             out = server.blockchain.transaction.broadcast(sys.argv[2])
910         elif cmd == 'b':
911             out = server.blocks()
912         else:
913             out = "Unknown command: '%s'" % cmd
914         print out
915         sys.exit(0)
916
917
918     print "starting Electrum server"
919
920     conf = DataStore.CONFIG_DEFAULTS
921     args, argv = readconf.parse_argv( [], conf)
922     args.dbtype= config.get('database','type')
923     if args.dbtype == 'sqlite3':
924         args.connect_args = { 'database' : config.get('database','database') }
925     elif args.dbtype == 'MySQLdb':
926         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
927     elif args.dbtype == 'psycopg2':
928         args.connect_args = { 'database' : config.get('database','database') }
929     store = MyStore(args)
930     store.tx_cache = {}
931     store.mempool_keys = {}
932
933     # supported protocols
934     thread.start_new_thread(native_server_thread, ())
935     thread.start_new_thread(tcp_server_thread, ())
936     thread.start_new_thread(http_server_thread, (store,))
937
938     thread.start_new_thread(clean_session_thread, ())
939
940     if (config.get('server','irc') == 'yes' ):
941         thread.start_new_thread(irc_thread, ())
942
943     while not stopping:
944         try:
945             dblock.acquire()
946             store.catch_up()
947             memorypool_update(store)
948             block_number = store.get_block_number(1)
949
950             if block_number != old_block_number:
951                 old_block_number = block_number
952                 for session_id in sessions_sub_numblocks:
953                     send_numblocks(session_id)
954
955         except IOError:
956             print "IOError: cannot reach bitcoind"
957             block_number = 0
958         except:
959             traceback.print_exc(file=sys.stdout)
960             block_number = 0
961         finally:
962             dblock.release()
963
964         # do addresses
965         while True:
966             try:
967                 addr = address_queue.get(False)
968             except:
969                 break
970             do_update_address(addr)
971
972         time.sleep(10)
973
974     print "server stopped"
975