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