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