a1346ebe8f3f13835a29ca6e7c46279a0995895f
[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         thread.start_new_thread(client_thread, (addr, conn,))
461
462
463
464 def client_thread(ipaddr,conn):
465     #print "client thread", ipaddr
466     try:
467         ipaddr = ipaddr[0]
468         msg = ''
469         while 1:
470             d = conn.recv(1024)
471             msg += d
472             if not d: 
473                 break
474             if '#' in msg:
475                 msg = msg.split('#', 1)[0]
476                 break
477         try:
478             cmd, data = ast.literal_eval(msg)
479         except:
480             print "syntax error", repr(msg), ipaddr
481             conn.close()
482             return
483
484         out = do_command(cmd, data, ipaddr)
485         if out:
486             #print ipaddr, cmd, len(out)
487             try:
488                 conn.send(out)
489             except:
490                 print "error, could not send"
491
492     finally:
493         conn.close()
494
495
496 def do_command(cmd, data, ipaddr):
497
498     timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
499
500     if cmd=='b':
501         out = "%d"%block_number
502
503     elif cmd in ['session','new_session']:
504         try:
505             if cmd == 'session':
506                 addresses = ast.literal_eval(data)
507                 version = "old"
508             else:
509                 version, addresses = ast.literal_eval(data)
510                 if version[0]=="0": version = "v" + version
511         except:
512             print "error", data
513             return None
514         print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
515         out = new_session(version, addresses)
516
517     elif cmd=='update_session':
518         try:
519             session_id, addresses = ast.literal_eval(data)
520         except:
521             print "error"
522             return None
523         print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
524         out = update_session(session_id,addresses)
525
526     elif cmd == 'bccapi_login':
527         import electrum
528         print "data",data
529         v, k = ast.literal_eval(data)
530         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
531         print master_public_key
532         wallet_id = random_string(10)
533         w = Wallet( Direct_Interface() )
534         w.master_public_key = master_public_key.decode('hex')
535         w.synchronize()
536         wallets[wallet_id] = w
537         out = wallet_id
538         print "wallets", wallets
539
540     elif cmd == 'bccapi_getAccountInfo':
541         from wallet import int_to_hex
542         v, wallet_id = ast.literal_eval(data)
543         w = wallets.get(wallet_id)
544         if w is not None:
545             num = len(w.addresses)
546             c, u = w.get_balance()
547             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
548             out = out.decode('hex')
549         else:
550             print "error",data
551             out = "error"
552
553     elif cmd == 'bccapi_getAccountStatement':
554         from wallet import int_to_hex
555         v, wallet_id = ast.literal_eval(data)
556         w = wallets.get(wallet_id)
557         if w is not None:
558             num = len(w.addresses)
559             c, u = w.get_balance()
560             total_records = num_records = 0
561             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 )
562             out = out.decode('hex')
563         else:
564             print "error",data
565             out = "error"
566
567     elif cmd == 'bccapi_getSendCoinForm':
568         out = ''
569
570     elif cmd == 'bccapi_submitTransaction':
571         out = ''
572             
573     elif cmd=='poll': 
574         out = poll_session(data)
575
576     elif cmd == 'h': 
577         # history
578         address = data
579         out = repr( store.get_history( address ) )
580
581     elif cmd == 'load': 
582         out = cmd_load(data)
583
584     elif cmd =='tx':
585         out = send_tx(data)
586         print timestr, "sent tx:", ipaddr, out
587
588     elif cmd == 'stop':
589         out = cmd_stop(data)
590
591     elif cmd == 'peers':
592         out = repr(peer_list.values())
593
594     else:
595         out = None
596
597     return out
598
599
600
601
602 def memorypool_update(store):
603     ds = BCDataStream.BCDataStream()
604     store.mempool_keys = []
605
606     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
607     respdata = urllib.urlopen(bitcoind_url, postdata).read()
608     r = loads(respdata)
609     if r['error'] != None:
610         return
611
612     v = r['result'].get('transactions')
613     for hextx in v:
614         ds.clear()
615         ds.write(hextx.decode('hex'))
616         tx = deserialize.parse_Transaction(ds)
617         tx['hash'] = util.double_sha256(tx['tx'])
618         tx_hash = tx['hash'][::-1].encode('hex')
619         store.mempool_keys.append(tx_hash)
620         if store.tx_find_id_and_value(tx):
621             pass
622         else:
623             store.import_tx(tx, False)
624
625     store.commit()
626
627
628
629 def clean_session_thread():
630     while not stopping:
631         time.sleep(30)
632         t = time.time()
633         for k,s in sessions.items():
634             t0 = s['last_time']
635             if t - t0 > 5*60:
636                 sessions.pop(k)
637             
638
639 def irc_thread():
640     global peer_list
641     NICK = 'E_'+random_string(10)
642     while not stopping:
643         try:
644             s = socket.socket()
645             s.connect(('irc.freenode.net', 6667))
646             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
647             s.send('NICK '+NICK+'\n')
648             s.send('JOIN #electrum\n')
649             sf = s.makefile('r', 0)
650             t = 0
651             while not stopping:
652                 line = sf.readline()
653                 line = line.rstrip('\r\n')
654                 line = line.split()
655                 if line[0]=='PING': 
656                     s.send('PONG '+line[1]+'\n')
657                 elif '353' in line: # answer to /names
658                     k = line.index('353')
659                     for item in line[k+1:]:
660                         if item[0:2] == 'E_':
661                             s.send('WHO %s\n'%item)
662                 elif '352' in line: # answer to /who
663                     # warning: this is a horrible hack which apparently works
664                     k = line.index('352')
665                     ip = line[k+4]
666                     ip = socket.gethostbyname(ip)
667                     name = line[k+6]
668                     host = line[k+9]
669                     peer_list[name] = (ip,host)
670                 if time.time() - t > 5*60:
671                     s.send('NAMES #electrum\n')
672                     t = time.time()
673                     peer_list = {}
674         except:
675             traceback.print_exc(file=sys.stdout)
676         finally:
677             sf.close()
678             s.close()
679
680
681
682 def jsonrpc_thread(store):
683     # see http://code.google.com/p/jsonrpclib/
684     from SocketServer import ThreadingMixIn
685     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
686     class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
687     server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
688     server.register_function(lambda : peer_list.values(), 'peers')
689     server.register_function(cmd_stop, 'stop')
690     server.register_function(cmd_load, 'load')
691     server.register_function(lambda : block_number, 'blocks')
692     server.register_function(clear_cache, 'clear_cache')
693     server.register_function(get_cache, 'get_cache')
694     server.register_function(send_tx, 'blockchain.transaction.broadcast')
695     server.register_function(store.get_history, 'blockchain.address.get_history')
696     server.register_function(new_session, 'session.new')
697     server.register_function(update_session, 'session.update')
698     server.register_function(poll_session, 'session.poll')
699     server.serve_forever()
700
701
702 import traceback
703
704
705 if __name__ == '__main__':
706
707     if len(sys.argv)>1:
708         import jsonrpclib
709         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
710         cmd = sys.argv[1]
711         if cmd == 'load':
712             out = server.load(password)
713         elif cmd == 'peers':
714             out = server.peers()
715         elif cmd == 'stop':
716             out = server.stop(password)
717         elif cmd == 'clear_cache':
718             out = server.clear_cache(password)
719         elif cmd == 'get_cache':
720             out = server.get_cache(password,sys.argv[2])
721         elif cmd == 'h':
722             out = server.blockchain.address.get_history(sys.argv[2])
723         elif cmd == 'tx':
724             out = server.blockchain.transaction.broadcast(sys.argv[2])
725         elif cmd == 'b':
726             out = server.blocks()
727         else:
728             out = "Unknown command: '%s'" % cmd
729         print out
730         sys.exit(0)
731
732
733     print "starting Electrum server"
734     print "cache:", config.get('server', 'cache')
735
736     conf = DataStore.CONFIG_DEFAULTS
737     args, argv = readconf.parse_argv( [], conf)
738     args.dbtype= config.get('database','type')
739     if args.dbtype == 'sqlite3':
740         args.connect_args = { 'database' : config.get('database','database') }
741     elif args.dbtype == 'MySQLdb':
742         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
743     elif args.dbtype == 'psycopg2':
744         args.connect_args = { 'database' : config.get('database','database') }
745     store = MyStore(args)
746     store.tx_cache = {}
747     store.mempool_keys = {}
748
749     thread.start_new_thread(listen_thread, (store,))
750     thread.start_new_thread(jsonrpc_thread, (store,))
751     thread.start_new_thread(clean_session_thread, ())
752     if (config.get('server','irc') == 'yes' ):
753         thread.start_new_thread(irc_thread, ())
754
755     while not stopping:
756         try:
757             dblock.acquire()
758             store.catch_up()
759             memorypool_update(store)
760             block_number = store.get_block_number(1)
761         except IOError:
762             print "IOError: cannot reach bitcoind"
763             block_number = 0
764         except:
765             traceback.print_exc(file=sys.stdout)
766             block_number = 0
767         finally:
768             dblock.release()
769         time.sleep(10)
770
771     print "server stopped"
772