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