version 0.40a
[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 try:
67     f = open('/etc/electrum.banner','r')
68     config.set('server','banner', f.read())
69     f.close()
70 except:
71     pass
72
73 password = config.get('server','password')
74 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
75
76 stopping = False
77 block_number = -1
78 sessions = {}
79 dblock = thread.allocate_lock()
80 peer_list = {}
81
82 wallets = {} # for ultra-light clients such as bccapi
83
84 class MyStore(Datastore_class):
85
86     def import_tx(self, tx, is_coinbase):
87         tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
88         if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
89
90     def update_tx_cache(self, txid):
91         inrows = self.get_tx_inputs(txid, False)
92         for row in inrows:
93             _hash = store.binout(row[6])
94             address = hash_to_address(chr(0), _hash)
95             if self.tx_cache.has_key(address):
96                 print "cache: invalidating", address
97                 self.tx_cache.pop(address)
98         outrows = self.get_tx_outputs(txid, False)
99         for row in outrows:
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
106     def safe_sql(self,sql, params=(), lock=True):
107         try:
108             if lock: dblock.acquire()
109             ret = self.selectall(sql,params)
110             if lock: dblock.release()
111             return ret
112         except:
113             print "sql error", sql
114             return []
115
116     def get_tx_outputs(self, tx_id, lock=True):
117         return self.safe_sql("""SELECT
118                 txout.txout_pos,
119                 txout.txout_scriptPubKey,
120                 txout.txout_value,
121                 nexttx.tx_hash,
122                 nexttx.tx_id,
123                 txin.txin_pos,
124                 pubkey.pubkey_hash
125               FROM txout
126               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
127               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
129              WHERE txout.tx_id = %d 
130              ORDER BY txout.txout_pos
131         """%(tx_id), (), lock)
132
133     def get_tx_inputs(self, tx_id, lock=True):
134         return self.safe_sql(""" SELECT
135                 txin.txin_pos,
136                 txin.txin_scriptSig,
137                 txout.txout_value,
138                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
139                 prevtx.tx_id,
140                 COALESCE(txout.txout_pos, u.txout_pos),
141                 pubkey.pubkey_hash
142               FROM txin
143               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
144               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
145               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
146               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
147              WHERE txin.tx_id = %d
148              ORDER BY txin.txin_pos
149              """%(tx_id,), (), lock)
150
151     def get_address_out_rows(self, dbhash):
152         return self.safe_sql(""" SELECT
153                 b.block_nTime,
154                 cc.chain_id,
155                 b.block_height,
156                 1,
157                 b.block_hash,
158                 tx.tx_hash,
159                 tx.tx_id,
160                 txin.txin_pos,
161                 -prevout.txout_value
162               FROM chain_candidate cc
163               JOIN block b ON (b.block_id = cc.block_id)
164               JOIN block_tx ON (block_tx.block_id = b.block_id)
165               JOIN tx ON (tx.tx_id = block_tx.tx_id)
166               JOIN txin ON (txin.tx_id = tx.tx_id)
167               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
168               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
169              WHERE pubkey.pubkey_hash = ?
170                AND cc.in_longest = 1""", (dbhash,))
171
172     def get_address_out_rows_memorypool(self, dbhash):
173         return self.safe_sql(""" SELECT
174                 1,
175                 tx.tx_hash,
176                 tx.tx_id,
177                 txin.txin_pos,
178                 -prevout.txout_value
179               FROM tx 
180               JOIN txin ON (txin.tx_id = tx.tx_id)
181               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
182               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
183              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
184
185     def get_address_in_rows(self, dbhash):
186         return self.safe_sql(""" SELECT
187                 b.block_nTime,
188                 cc.chain_id,
189                 b.block_height,
190                 0,
191                 b.block_hash,
192                 tx.tx_hash,
193                 tx.tx_id,
194                 txout.txout_pos,
195                 txout.txout_value
196               FROM chain_candidate cc
197               JOIN block b ON (b.block_id = cc.block_id)
198               JOIN block_tx ON (block_tx.block_id = b.block_id)
199               JOIN tx ON (tx.tx_id = block_tx.tx_id)
200               JOIN txout ON (txout.tx_id = tx.tx_id)
201               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
202              WHERE pubkey.pubkey_hash = ?
203                AND cc.in_longest = 1""", (dbhash,))
204
205     def get_address_in_rows_memorypool(self, dbhash):
206         return self.safe_sql( """ SELECT
207                 0,
208                 tx.tx_hash,
209                 tx.tx_id,
210                 txout.txout_pos,
211                 txout.txout_value
212               FROM tx
213               JOIN txout ON (txout.tx_id = tx.tx_id)
214               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
215              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
216
217     def get_history(self, addr):
218         
219         if config.get('server','cache') == 'yes':
220             cached_version = self.tx_cache.get( addr ) 
221             if cached_version is not None: 
222                 return cached_version
223
224         version, binaddr = decode_check_address(addr)
225         if binaddr is None:
226             return None
227
228         dbhash = self.binin(binaddr)
229         rows = []
230         rows += self.get_address_out_rows( dbhash )
231         rows += self.get_address_in_rows( dbhash )
232
233         txpoints = []
234         known_tx = []
235
236         for row in rows:
237             try:
238                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
239             except:
240                 print "cannot unpack row", row
241                 break
242             tx_hash = self.hashout_hex(tx_hash)
243             txpoint = {
244                     "nTime":    int(nTime),
245                     #"chain_id": int(chain_id),
246                     "height":   int(height),
247                     "is_in":    int(is_in),
248                     "blk_hash": self.hashout_hex(blk_hash),
249                     "tx_hash":  tx_hash,
250                     "tx_id":    int(tx_id),
251                     "pos":      int(pos),
252                     "value":    int(value),
253                     }
254
255             txpoints.append(txpoint)
256             known_tx.append(self.hashout_hex(tx_hash))
257
258
259         # todo: sort them really...
260         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
261
262         # read memory pool
263         rows = []
264         rows += self.get_address_in_rows_memorypool( dbhash )
265         rows += self.get_address_out_rows_memorypool( dbhash )
266         address_has_mempool = False
267
268         for row in rows:
269             is_in, tx_hash, tx_id, pos, value = row
270             tx_hash = self.hashout_hex(tx_hash)
271             if tx_hash in known_tx:
272                 continue
273
274             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
275             address_has_mempool = True
276
277             # this means pending transactions are returned by getmemorypool
278             if tx_hash not in self.mempool_keys:
279                 continue
280
281             #print "mempool", tx_hash
282             txpoint = {
283                     "nTime":    0,
284                     #"chain_id": 1,
285                     "height":   0,
286                     "is_in":    int(is_in),
287                     "blk_hash": 'mempool', 
288                     "tx_hash":  tx_hash,
289                     "tx_id":    int(tx_id),
290                     "pos":      int(pos),
291                     "value":    int(value),
292                     }
293             txpoints.append(txpoint)
294
295
296         for txpoint in txpoints:
297             tx_id = txpoint['tx_id']
298             
299             txinputs = []
300             inrows = self.get_tx_inputs(tx_id)
301             for row in inrows:
302                 _hash = self.binout(row[6])
303                 address = hash_to_address(chr(0), _hash)
304                 txinputs.append(address)
305             txpoint['inputs'] = txinputs
306             txoutputs = []
307             outrows = self.get_tx_outputs(tx_id)
308             for row in outrows:
309                 _hash = self.binout(row[6])
310                 address = hash_to_address(chr(0), _hash)
311                 txoutputs.append(address)
312             txpoint['outputs'] = txoutputs
313
314             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
315             if not txpoint['is_in']:
316                 # detect if already redeemed...
317                 for row in outrows:
318                     if row[6] == dbhash: break
319                 else:
320                     raise
321                 #row = self.get_tx_output(tx_id,dbhash)
322                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
323                 # if not redeemed, we add the script
324                 if row:
325                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
326
327         # cache result
328         if config.get('server','cache') == 'yes' and not address_has_mempool:
329             self.tx_cache[addr] = txpoints
330         
331         return txpoints
332
333
334
335 class Direct_Interface(Interface):
336     def __init__(self):
337         pass
338
339     def handler(self, method, params = ''):
340         cmds = {'session.new':new_session,
341                 'session.poll':poll_session,
342                 'session.update':update_session,
343                 'blockchain.transaction.broadcast':send_tx,
344                 'blockchain.address.get_history':store.get_history
345                 }
346         func = cmds[method]
347         return func( params )
348
349
350
351 def send_tx(tx):
352     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
353     respdata = urllib.urlopen(bitcoind_url, postdata).read()
354     r = loads(respdata)
355     if r['error'] != None:
356         out = "error: transaction rejected by memorypool"
357     else:
358         out = r['result']
359     return out
360
361
362
363 def random_string(N):
364     import random, string
365     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
366
367     
368
369 def cmd_stop(data):
370     global stopping
371     if password == data:
372         stopping = True
373         return 'ok'
374     else:
375         return 'wrong password'
376
377 def cmd_load(pw):
378     if password == pw:
379         return repr( len(sessions) )
380     else:
381         return 'wrong password'
382
383
384 def clear_cache(pw):
385     if password == pw:
386         store.tx_cache = {}
387         return 'ok'
388     else:
389         return 'wrong password'
390
391 def get_cache(pw,addr):
392     if password == pw:
393         return store.tx_cache.get(addr)
394     else:
395         return 'wrong password'
396
397
398 def poll_session(session_id):
399     session = sessions.get(session_id)
400     if session is None:
401         print time.asctime(), "session not found", session_id
402         out = repr( (-1, {}))
403     else:
404         t1 = time.time()
405         addresses = session['addresses']
406         session['last_time'] = time.time()
407         ret = {}
408         k = 0
409         for addr in addresses:
410             if store.tx_cache.get( addr ) is not None: k += 1
411
412             # get addtess status, i.e. the last block for that address.
413             tx_points = store.get_history(addr)
414             if not tx_points:
415                 status = None
416             else:
417                 lastpoint = tx_points[-1]
418                 status = lastpoint['blk_hash']
419                 # this is a temporary hack; move it up once old clients have disappeared
420                 if status == 'mempool' and session['version'] != "old":
421                     status = status + ':%d'% len(tx_points)
422
423             last_status = addresses.get( addr )
424             if last_status != status:
425                 addresses[addr] = status
426                 ret[addr] = status
427         if ret:
428             sessions[session_id]['addresses'] = addresses
429         out = repr( (block_number, ret ) )
430         t2 = time.time() - t1 
431         if t2 > 10:
432             print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
433
434         return out
435
436
437 def new_session(version, addresses):
438     session_id = random_string(10)
439     sessions[session_id] = { 'addresses':{}, 'version':version }
440     for a in addresses:
441         sessions[session_id]['addresses'][a] = ''
442     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
443     sessions[session_id]['last_time'] = time.time()
444     return out
445
446 def update_session(session_id,addresses):
447     sessions[session_id]['addresses'] = {}
448     for a in addresses:
449         sessions[session_id]['addresses'][a] = ''
450     sessions[session_id]['last_time'] = time.time()
451     return 'ok'
452
453 def listen_thread(store):
454     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
455     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
456     s.bind((config.get('server','host'), config.getint('server','port')))
457     s.listen(1)
458     while not stopping:
459         conn, addr = s.accept()
460         try:
461             thread.start_new_thread(client_thread, (addr, conn,))
462         except:
463             # can't start new thread if there is no memory..
464             traceback.print_exc(file=sys.stdout)
465
466
467
468 def client_thread(ipaddr,conn):
469     #print "client thread", ipaddr
470     try:
471         ipaddr = ipaddr[0]
472         msg = ''
473         while 1:
474             d = conn.recv(1024)
475             msg += d
476             if not d: 
477                 break
478             if '#' in msg:
479                 msg = msg.split('#', 1)[0]
480                 break
481         try:
482             cmd, data = ast.literal_eval(msg)
483         except:
484             print "syntax error", repr(msg), ipaddr
485             conn.close()
486             return
487
488         out = do_command(cmd, data, ipaddr)
489         if out:
490             #print ipaddr, cmd, len(out)
491             try:
492                 conn.send(out)
493             except:
494                 print "error, could not send"
495
496     finally:
497         conn.close()
498
499
500 def do_command(cmd, data, ipaddr):
501
502     timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
503
504     if cmd=='b':
505         out = "%d"%block_number
506
507     elif cmd in ['session','new_session']:
508         try:
509             if cmd == 'session':
510                 addresses = ast.literal_eval(data)
511                 version = "old"
512             else:
513                 version, addresses = ast.literal_eval(data)
514                 if version[0]=="0": version = "v" + version
515         except:
516             print "error", data
517             return None
518         print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
519         out = new_session(version, addresses)
520
521     elif cmd=='update_session':
522         try:
523             session_id, addresses = ast.literal_eval(data)
524         except:
525             print "error"
526             return None
527         print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
528         out = update_session(session_id,addresses)
529
530     elif cmd == 'bccapi_login':
531         import electrum
532         print "data",data
533         v, k = ast.literal_eval(data)
534         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
535         print master_public_key
536         wallet_id = random_string(10)
537         w = Wallet( Direct_Interface() )
538         w.master_public_key = master_public_key.decode('hex')
539         w.synchronize()
540         wallets[wallet_id] = w
541         out = wallet_id
542         print "wallets", wallets
543
544     elif cmd == 'bccapi_getAccountInfo':
545         from wallet import int_to_hex
546         v, wallet_id = ast.literal_eval(data)
547         w = wallets.get(wallet_id)
548         if w is not None:
549             num = len(w.addresses)
550             c, u = w.get_balance()
551             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
552             out = out.decode('hex')
553         else:
554             print "error",data
555             out = "error"
556
557     elif cmd == 'bccapi_getAccountStatement':
558         from wallet import int_to_hex
559         v, wallet_id = ast.literal_eval(data)
560         w = wallets.get(wallet_id)
561         if w is not None:
562             num = len(w.addresses)
563             c, u = w.get_balance()
564             total_records = num_records = 0
565             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 )
566             out = out.decode('hex')
567         else:
568             print "error",data
569             out = "error"
570
571     elif cmd == 'bccapi_getSendCoinForm':
572         out = ''
573
574     elif cmd == 'bccapi_submitTransaction':
575         out = ''
576             
577     elif cmd=='poll': 
578         out = poll_session(data)
579
580     elif cmd == 'h': 
581         # history
582         address = data
583         out = repr( store.get_history( address ) )
584
585     elif cmd == 'load': 
586         out = cmd_load(data)
587
588     elif cmd =='tx':
589         out = send_tx(data)
590         print timestr, "sent tx:", ipaddr, out
591
592     elif cmd == 'stop':
593         out = cmd_stop(data)
594
595     elif cmd == 'peers':
596         out = repr(peer_list.values())
597
598     else:
599         out = None
600
601     return out
602
603
604
605
606 def memorypool_update(store):
607     ds = BCDataStream.BCDataStream()
608     store.mempool_keys = []
609
610     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
611     respdata = urllib.urlopen(bitcoind_url, postdata).read()
612     r = loads(respdata)
613     if r['error'] != None:
614         return
615
616     v = r['result'].get('transactions')
617     for hextx in v:
618         ds.clear()
619         ds.write(hextx.decode('hex'))
620         tx = deserialize.parse_Transaction(ds)
621         tx['hash'] = util.double_sha256(tx['tx'])
622         tx_hash = tx['hash'][::-1].encode('hex')
623         store.mempool_keys.append(tx_hash)
624         if store.tx_find_id_and_value(tx):
625             pass
626         else:
627             store.import_tx(tx, False)
628
629     store.commit()
630
631
632
633 def clean_session_thread():
634     while not stopping:
635         time.sleep(30)
636         t = time.time()
637         for k,s in sessions.items():
638             t0 = s['last_time']
639             if t - t0 > 5*60:
640                 sessions.pop(k)
641             
642
643 def irc_thread():
644     global peer_list
645     NICK = 'E_'+random_string(10)
646     while not stopping:
647         try:
648             s = socket.socket()
649             s.connect(('irc.freenode.net', 6667))
650             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
651             s.send('NICK '+NICK+'\n')
652             s.send('JOIN #electrum\n')
653             sf = s.makefile('r', 0)
654             t = 0
655             while not stopping:
656                 line = sf.readline()
657                 line = line.rstrip('\r\n')
658                 line = line.split()
659                 if line[0]=='PING': 
660                     s.send('PONG '+line[1]+'\n')
661                 elif '353' in line: # answer to /names
662                     k = line.index('353')
663                     for item in line[k+1:]:
664                         if item[0:2] == 'E_':
665                             s.send('WHO %s\n'%item)
666                 elif '352' in line: # answer to /who
667                     # warning: this is a horrible hack which apparently works
668                     k = line.index('352')
669                     ip = line[k+4]
670                     ip = socket.gethostbyname(ip)
671                     name = line[k+6]
672                     host = line[k+9]
673                     peer_list[name] = (ip,host)
674                 if time.time() - t > 5*60:
675                     s.send('NAMES #electrum\n')
676                     t = time.time()
677                     peer_list = {}
678         except:
679             traceback.print_exc(file=sys.stdout)
680         finally:
681             sf.close()
682             s.close()
683
684
685
686 def jsonrpc_thread(store):
687     # see http://code.google.com/p/jsonrpclib/
688     from SocketServer import ThreadingMixIn
689     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
690     class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
691     server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
692     server.register_function(lambda : peer_list.values(), 'peers')
693     server.register_function(cmd_stop, 'stop')
694     server.register_function(cmd_load, 'load')
695     server.register_function(lambda : block_number, 'blocks')
696     server.register_function(clear_cache, 'clear_cache')
697     server.register_function(get_cache, 'get_cache')
698     server.register_function(send_tx, 'blockchain.transaction.broadcast')
699     server.register_function(store.get_history, 'blockchain.address.get_history')
700     server.register_function(new_session, 'session.new')
701     server.register_function(update_session, 'session.update')
702     server.register_function(poll_session, 'session.poll')
703     server.serve_forever()
704
705
706 import traceback
707
708
709 if __name__ == '__main__':
710
711     if len(sys.argv)>1:
712         import jsonrpclib
713         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
714         cmd = sys.argv[1]
715         if cmd == 'load':
716             out = server.load(password)
717         elif cmd == 'peers':
718             out = server.peers()
719         elif cmd == 'stop':
720             out = server.stop(password)
721         elif cmd == 'clear_cache':
722             out = server.clear_cache(password)
723         elif cmd == 'get_cache':
724             out = server.get_cache(password,sys.argv[2])
725         elif cmd == 'h':
726             out = server.blockchain.address.get_history(sys.argv[2])
727         elif cmd == 'tx':
728             out = server.blockchain.transaction.broadcast(sys.argv[2])
729         elif cmd == 'b':
730             out = server.blocks()
731         else:
732             out = "Unknown command: '%s'" % cmd
733         print out
734         sys.exit(0)
735
736
737     print "starting Electrum server"
738     print "cache:", config.get('server', 'cache')
739
740     conf = DataStore.CONFIG_DEFAULTS
741     args, argv = readconf.parse_argv( [], conf)
742     args.dbtype= config.get('database','type')
743     if args.dbtype == 'sqlite3':
744         args.connect_args = { 'database' : config.get('database','database') }
745     elif args.dbtype == 'MySQLdb':
746         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
747     elif args.dbtype == 'psycopg2':
748         args.connect_args = { 'database' : config.get('database','database') }
749     store = MyStore(args)
750     store.tx_cache = {}
751     store.mempool_keys = {}
752
753     thread.start_new_thread(listen_thread, (store,))
754     thread.start_new_thread(jsonrpc_thread, (store,))
755     thread.start_new_thread(clean_session_thread, ())
756     if (config.get('server','irc') == 'yes' ):
757         thread.start_new_thread(irc_thread, ())
758
759     while not stopping:
760         try:
761             dblock.acquire()
762             store.catch_up()
763             memorypool_update(store)
764             block_number = store.get_block_number(1)
765         except IOError:
766             print "IOError: cannot reach bitcoind"
767             block_number = 0
768         except:
769             traceback.print_exc(file=sys.stdout)
770             block_number = 0
771         finally:
772             dblock.release()
773         time.sleep(10)
774
775     print "server stopped"
776