use block_number=0 for no server; -1 means unknown session
[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, 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', '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')
58
59 try:
60     f = open('/etc/electrum.conf','r')
61     config.readfp(f)
62     f.close()
63 except:
64     print "Could not read electrum.conf. I will use the default values."
65
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'))
68
69 stopping = False
70 block_number = -1
71 sessions = {}
72 dblock = thread.allocate_lock()
73 peer_list = {}
74
75 wallets = {} # for ultra-light clients such as bccapi
76
77 class MyStore(Datastore_class):
78
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)
82
83     def update_tx_cache(self, txid):
84         inrows = self.get_tx_inputs(txid, False)
85         for row in inrows:
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)
92         for row in outrows:
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
99     def safe_sql(self,sql, params=(), lock=True):
100         try:
101             if lock: dblock.acquire()
102             ret = self.selectall(sql,params)
103             if lock: dblock.release()
104             return ret
105         except:
106             print "sql error", sql
107             return []
108
109     def get_tx_outputs(self, tx_id, lock=True):
110         return self.safe_sql("""SELECT
111                 txout.txout_pos,
112                 txout.txout_scriptPubKey,
113                 txout.txout_value,
114                 nexttx.tx_hash,
115                 nexttx.tx_id,
116                 txin.txin_pos,
117                 pubkey.pubkey_hash
118               FROM txout
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)
125
126     def get_tx_inputs(self, tx_id, lock=True):
127         return self.safe_sql(""" SELECT
128                 txin.txin_pos,
129                 txin.txin_scriptSig,
130                 txout.txout_value,
131                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
132                 prevtx.tx_id,
133                 COALESCE(txout.txout_pos, u.txout_pos),
134                 pubkey.pubkey_hash
135               FROM txin
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)
143
144     def get_address_out_rows(self, dbhash):
145         return self.safe_sql(""" SELECT
146                 b.block_nTime,
147                 cc.chain_id,
148                 b.block_height,
149                 1,
150                 b.block_hash,
151                 tx.tx_hash,
152                 tx.tx_id,
153                 txin.txin_pos,
154                 -prevout.txout_value
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,))
164
165     def get_address_out_rows_memorypool(self, dbhash):
166         return self.safe_sql(""" SELECT
167                 1,
168                 tx.tx_hash,
169                 tx.tx_id,
170                 txin.txin_pos,
171                 -prevout.txout_value
172               FROM tx 
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,))
177
178     def get_address_in_rows(self, dbhash):
179         return self.safe_sql(""" SELECT
180                 b.block_nTime,
181                 cc.chain_id,
182                 b.block_height,
183                 0,
184                 b.block_hash,
185                 tx.tx_hash,
186                 tx.tx_id,
187                 txout.txout_pos,
188                 txout.txout_value
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,))
197
198     def get_address_in_rows_memorypool(self, dbhash):
199         return self.safe_sql( """ SELECT
200                 0,
201                 tx.tx_hash,
202                 tx.tx_id,
203                 txout.txout_pos,
204                 txout.txout_value
205               FROM tx
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,))
209
210     def get_history(self, addr):
211         
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
216
217         version, binaddr = decode_check_address(addr)
218         if binaddr is None:
219             return None
220
221         dbhash = self.binin(binaddr)
222         rows = []
223         rows += self.get_address_out_rows( dbhash )
224         rows += self.get_address_in_rows( dbhash )
225
226         txpoints = []
227         known_tx = []
228
229         for row in rows:
230             try:
231                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
232             except:
233                 print "cannot unpack row", row
234                 break
235             tx_hash = self.hashout_hex(tx_hash)
236             txpoint = {
237                     "nTime":    int(nTime),
238                     #"chain_id": int(chain_id),
239                     "height":   int(height),
240                     "is_in":    int(is_in),
241                     "blk_hash": self.hashout_hex(blk_hash),
242                     "tx_hash":  tx_hash,
243                     "tx_id":    int(tx_id),
244                     "pos":      int(pos),
245                     "value":    int(value),
246                     }
247
248             txpoints.append(txpoint)
249             known_tx.append(self.hashout_hex(tx_hash))
250
251
252         # todo: sort them really...
253         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
254
255         # read memory pool
256         rows = []
257         rows += self.get_address_in_rows_memorypool( dbhash )
258         rows += self.get_address_out_rows_memorypool( dbhash )
259         address_has_mempool = False
260
261         for row in rows:
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:
265                 continue
266
267             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
268             address_has_mempool = True
269
270             # this means pending transactions are returned by getmemorypool
271             if tx_hash not in self.mempool_keys:
272                 continue
273
274             #print "mempool", tx_hash
275             txpoint = {
276                     "nTime":    0,
277                     #"chain_id": 1,
278                     "height":   0,
279                     "is_in":    int(is_in),
280                     "blk_hash": 'mempool', 
281                     "tx_hash":  tx_hash,
282                     "tx_id":    int(tx_id),
283                     "pos":      int(pos),
284                     "value":    int(value),
285                     }
286             txpoints.append(txpoint)
287
288
289         for txpoint in txpoints:
290             tx_id = txpoint['tx_id']
291             
292             txinputs = []
293             inrows = self.get_tx_inputs(tx_id)
294             for row in inrows:
295                 _hash = self.binout(row[6])
296                 address = hash_to_address(chr(0), _hash)
297                 txinputs.append(address)
298             txpoint['inputs'] = txinputs
299             txoutputs = []
300             outrows = self.get_tx_outputs(tx_id)
301             for row in outrows:
302                 _hash = self.binout(row[6])
303                 address = hash_to_address(chr(0), _hash)
304                 txoutputs.append(address)
305             txpoint['outputs'] = txoutputs
306
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...
310                 for row in outrows:
311                     if row[6] == dbhash: break
312                 else:
313                     raise
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
317                 if row:
318                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
319
320         # cache result
321         if config.get('server','cache') == 'yes' and not address_has_mempool:
322             self.tx_cache[addr] = txpoints
323         
324         return txpoints
325
326
327
328 class Direct_Interface(Interface):
329     def __init__(self):
330         pass
331
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
338                 }
339         func = cmds[method]
340         return func( params )
341
342
343
344 def send_tx(tx):
345     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
346     respdata = urllib.urlopen(bitcoind_url, postdata).read()
347     r = loads(respdata)
348     if r['error'] != None:
349         out = "error: transaction rejected by memorypool"
350     else:
351         out = r['result']
352     return out
353
354
355
356 def random_string(N):
357     import random, string
358     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
359
360     
361
362 def cmd_stop(data):
363     global stopping
364     if password == data:
365         stopping = True
366         return 'ok'
367     else:
368         return 'wrong password'
369
370 def cmd_load(pw):
371     if password == pw:
372         return repr( len(sessions) )
373     else:
374         return 'wrong password'
375
376
377 def clear_cache(pw):
378     if password == pw:
379         store.tx_cache = {}
380         return 'ok'
381     else:
382         return 'wrong password'
383
384 def get_cache(pw,addr):
385     if password == pw:
386         return store.tx_cache.get(addr)
387     else:
388         return 'wrong password'
389
390
391 def poll_session(session_id):
392     session = sessions.get(session_id)
393     if session is None:
394         print time.asctime(), "session not found", session_id
395         out = repr( (-1, {}))
396     else:
397         t1 = time.time()
398         addresses = session['addresses']
399         session['last_time'] = time.time()
400         ret = {}
401         k = 0
402         for addr in addresses:
403             if store.tx_cache.get( addr ) is not None: k += 1
404
405             # get addtess status, i.e. the last block for that address.
406             tx_points = store.get_history(addr)
407             if not tx_points:
408                 status = None
409             else:
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)
415
416             last_status = addresses.get( addr )
417             if last_status != status:
418                 addresses[addr] = status
419                 ret[addr] = status
420         if ret:
421             sessions[session_id]['addresses'] = addresses
422         out = repr( (block_number, ret ) )
423         t2 = time.time() - t1 
424         if t2 > 10:
425             print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
426
427         return out
428
429
430 def new_session(version, addresses):
431     session_id = random_string(10)
432     sessions[session_id] = { 'addresses':{}, 'version':version }
433     for a in addresses:
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()
437     return out
438
439 def update_session(session_id,addresses):
440     sessions[session_id]['addresses'] = {}
441     for a in addresses:
442         sessions[session_id]['addresses'][a] = ''
443     sessions[session_id]['last_time'] = time.time()
444     return 'ok'
445
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')))
450     s.listen(1)
451     while not stopping:
452         conn, addr = s.accept()
453         thread.start_new_thread(client_thread, (addr, conn,))
454
455
456
457 def client_thread(ipaddr,conn):
458     #print "client thread", ipaddr
459     try:
460         ipaddr = ipaddr[0]
461         msg = ''
462         while 1:
463             d = conn.recv(1024)
464             msg += d
465             if not d: 
466                 break
467             if '#' in msg:
468                 msg = msg.split('#', 1)[0]
469                 break
470         try:
471             cmd, data = ast.literal_eval(msg)
472         except:
473             print "syntax error", repr(msg), ipaddr
474             conn.close()
475             return
476
477         out = do_command(cmd, data, ipaddr)
478         if out:
479             #print ipaddr, cmd, len(out)
480             try:
481                 conn.send(out)
482             except:
483                 print "error, could not send"
484
485     finally:
486         conn.close()
487
488
489 def do_command(cmd, data, ipaddr):
490
491     timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
492
493     if cmd=='b':
494         out = "%d"%block_number
495
496     elif cmd in ['session','new_session']:
497         try:
498             if cmd == 'session':
499                 addresses = ast.literal_eval(data)
500                 version = "old"
501             else:
502                 version, addresses = ast.literal_eval(data)
503                 if version[0]=="0": version = "v" + version
504         except:
505             print "error", data
506             return None
507         print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
508         out = new_session(version, addresses)
509
510     elif cmd=='update_session':
511         try:
512             session_id, addresses = ast.literal_eval(data)
513         except:
514             print "error"
515             return None
516         print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
517         out = update_session(session_id,addresses)
518
519     elif cmd == 'bccapi_login':
520         import electrum
521         print "data",data
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')
528         w.synchronize()
529         wallets[wallet_id] = w
530         out = wallet_id
531         print "wallets", wallets
532
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)
537         if w is not None:
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')
542         else:
543             print "error",data
544             out = "error"
545
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)
550         if w is not None:
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')
556         else:
557             print "error",data
558             out = "error"
559
560     elif cmd == 'bccapi_getSendCoinForm':
561         out = ''
562
563     elif cmd == 'bccapi_submitTransaction':
564         out = ''
565             
566     elif cmd=='poll': 
567         out = poll_session(data)
568
569     elif cmd == 'h': 
570         # history
571         address = data
572         out = repr( store.get_history( address ) )
573
574     elif cmd == 'load': 
575         out = cmd_load(data)
576
577     elif cmd =='tx':
578         out = send_tx(data)
579         print timestr, "sent tx:", ipaddr, out
580
581     elif cmd == 'stop':
582         out = cmd_stop(data)
583
584     elif cmd == 'peers':
585         out = repr(peer_list.values())
586
587     else:
588         out = None
589
590     return out
591
592
593
594
595 def memorypool_update(store):
596     ds = BCDataStream.BCDataStream()
597     store.mempool_keys = []
598
599     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
600     respdata = urllib.urlopen(bitcoind_url, postdata).read()
601     r = loads(respdata)
602     if r['error'] != None:
603         return
604
605     v = r['result'].get('transactions')
606     for hextx in v:
607         ds.clear()
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):
614             pass
615         else:
616             store.import_tx(tx, False)
617
618     store.commit()
619
620
621
622 def clean_session_thread():
623     while not stopping:
624         time.sleep(30)
625         t = time.time()
626         for k,s in sessions.items():
627             t0 = s['last_time']
628             if t - t0 > 5*60:
629                 sessions.pop(k)
630             
631
632 def irc_thread():
633     global peer_list
634     NICK = 'E_'+random_string(10)
635     while not stopping:
636         try:
637             s = socket.socket()
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)
643             t = 0
644             while not stopping:
645                 line = sf.readline()
646                 line = line.rstrip('\r\n')
647                 line = line.split()
648                 if line[0]=='PING': 
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')
658                     ip = line[k+4]
659                     ip = socket.gethostbyname(ip)
660                     name = line[k+6]
661                     host = line[k+9]
662                     peer_list[name] = (ip,host)
663                 if time.time() - t > 5*60:
664                     s.send('NAMES #electrum\n')
665                     t = time.time()
666                     peer_list = {}
667         except:
668             traceback.print_exc(file=sys.stdout)
669         finally:
670             sf.close()
671             s.close()
672
673
674
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()
693
694
695 import traceback
696
697
698 if __name__ == '__main__':
699
700     if len(sys.argv)>1:
701         import jsonrpclib
702         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
703         cmd = sys.argv[1]
704         if cmd == 'load':
705             out = server.load(password)
706         elif cmd == 'peers':
707             out = server.peers()
708         elif cmd == 'stop':
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])
714         elif cmd == 'h':
715             out = server.blockchain.address.get_history(sys.argv[2])
716         elif cmd == 'tx':
717             out = server.blockchain.transaction.broadcast(sys.argv[2])
718         elif cmd == 'b':
719             out = server.blocks()
720         else:
721             out = "Unknown command: '%s'" % cmd
722         print out
723         sys.exit(0)
724
725
726     print "starting Electrum server"
727     print "cache:", config.get('server', 'cache')
728
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)
739     store.tx_cache = {}
740     store.mempool_keys = {}
741
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, ())
747
748     while not stopping:
749         try:
750             dblock.acquire()
751             store.catch_up()
752             memorypool_update(store)
753             block_number = store.get_block_number(1)
754         except IOError:
755             print "IOError: cannot reach bitcoind"
756             block_number = 0
757         except:
758             traceback.print_exc(file=sys.stdout)
759             block_number = 0
760         finally:
761             dblock.release()
762         time.sleep(10)
763
764     print "server stopped"
765