jsonrpc
[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, json, 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', '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 try:
66     f = open('/etc/electrum.banner','r')
67     config.set('server','banner', f.read())
68     f.close()
69 except:
70     pass
71
72 password = config.get('server','password')
73 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
74
75 stopping = False
76 block_number = -1
77 old_block_number = -1
78 sessions = {}
79 sessions_sub_numblocks = {} # sessions that have subscribed to the service
80
81 dblock = thread.allocate_lock()
82 peer_list = {}
83
84 wallets = {} # for ultra-light clients such as bccapi
85
86 from Queue import Queue
87 input_queue = Queue()
88 output_queue = Queue()
89 address_queue = Queue()
90
91 class MyStore(Datastore_class):
92
93     def import_block(self, b, chain_ids=frozenset()):
94         block_id = super(MyStore, self).import_block(b, chain_ids)
95         #print "block", block_id
96         for pos in xrange(len(b['transactions'])):
97             tx = b['transactions'][pos]
98             if 'hash' not in tx:
99                 tx['hash'] = util.double_sha256(tx['tx'])
100             tx_id = store.tx_find_id_and_value(tx)
101             if tx_id:
102                 self.update_tx_cache(tx_id)
103             else:
104                 print "error: import_block: no tx_id"
105         return block_id
106
107
108     def update_tx_cache(self, txid):
109         inrows = self.get_tx_inputs(txid, False)
110         for row in inrows:
111             _hash = store.binout(row[6])
112             address = hash_to_address(chr(0), _hash)
113             if self.tx_cache.has_key(address):
114                 print "cache: invalidating", address
115                 self.tx_cache.pop(address)
116             address_queue.put(address)
117
118         outrows = self.get_tx_outputs(txid, False)
119         for row in outrows:
120             _hash = store.binout(row[6])
121             address = hash_to_address(chr(0), _hash)
122             if self.tx_cache.has_key(address):
123                 print "cache: invalidating", address
124                 self.tx_cache.pop(address)
125             address_queue.put(address)
126
127     def safe_sql(self,sql, params=(), lock=True):
128         try:
129             if lock: dblock.acquire()
130             ret = self.selectall(sql,params)
131             if lock: dblock.release()
132             return ret
133         except:
134             print "sql error", sql
135             return []
136
137     def get_tx_outputs(self, tx_id, lock=True):
138         return self.safe_sql("""SELECT
139                 txout.txout_pos,
140                 txout.txout_scriptPubKey,
141                 txout.txout_value,
142                 nexttx.tx_hash,
143                 nexttx.tx_id,
144                 txin.txin_pos,
145                 pubkey.pubkey_hash
146               FROM txout
147               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
148               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
149               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
150              WHERE txout.tx_id = %d 
151              ORDER BY txout.txout_pos
152         """%(tx_id), (), lock)
153
154     def get_tx_inputs(self, tx_id, lock=True):
155         return self.safe_sql(""" SELECT
156                 txin.txin_pos,
157                 txin.txin_scriptSig,
158                 txout.txout_value,
159                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
160                 prevtx.tx_id,
161                 COALESCE(txout.txout_pos, u.txout_pos),
162                 pubkey.pubkey_hash
163               FROM txin
164               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
165               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
166               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
167               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
168              WHERE txin.tx_id = %d
169              ORDER BY txin.txin_pos
170              """%(tx_id,), (), lock)
171
172     def get_address_out_rows(self, dbhash):
173         return self.safe_sql(""" SELECT
174                 b.block_nTime,
175                 cc.chain_id,
176                 b.block_height,
177                 1,
178                 b.block_hash,
179                 tx.tx_hash,
180                 tx.tx_id,
181                 txin.txin_pos,
182                 -prevout.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 txin ON (txin.tx_id = tx.tx_id)
188               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
189               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
190              WHERE pubkey.pubkey_hash = ?
191                AND cc.in_longest = 1""", (dbhash,))
192
193     def get_address_out_rows_memorypool(self, dbhash):
194         return self.safe_sql(""" SELECT
195                 1,
196                 tx.tx_hash,
197                 tx.tx_id,
198                 txin.txin_pos,
199                 -prevout.txout_value
200               FROM tx 
201               JOIN txin ON (txin.tx_id = tx.tx_id)
202               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
203               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
204              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
205
206     def get_address_in_rows(self, dbhash):
207         return self.safe_sql(""" SELECT
208                 b.block_nTime,
209                 cc.chain_id,
210                 b.block_height,
211                 0,
212                 b.block_hash,
213                 tx.tx_hash,
214                 tx.tx_id,
215                 txout.txout_pos,
216                 txout.txout_value
217               FROM chain_candidate cc
218               JOIN block b ON (b.block_id = cc.block_id)
219               JOIN block_tx ON (block_tx.block_id = b.block_id)
220               JOIN tx ON (tx.tx_id = block_tx.tx_id)
221               JOIN txout ON (txout.tx_id = tx.tx_id)
222               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
223              WHERE pubkey.pubkey_hash = ?
224                AND cc.in_longest = 1""", (dbhash,))
225
226     def get_address_in_rows_memorypool(self, dbhash):
227         return self.safe_sql( """ SELECT
228                 0,
229                 tx.tx_hash,
230                 tx.tx_id,
231                 txout.txout_pos,
232                 txout.txout_value
233               FROM tx
234               JOIN txout ON (txout.tx_id = tx.tx_id)
235               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
236              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
237
238     def get_history(self, addr):
239         
240         cached_version = self.tx_cache.get( addr )
241         if cached_version is not None:
242             return cached_version
243
244         version, binaddr = decode_check_address(addr)
245         if binaddr is None:
246             return None
247
248         dbhash = self.binin(binaddr)
249         rows = []
250         rows += self.get_address_out_rows( dbhash )
251         rows += self.get_address_in_rows( dbhash )
252
253         txpoints = []
254         known_tx = []
255
256         for row in rows:
257             try:
258                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
259             except:
260                 print "cannot unpack row", row
261                 break
262             tx_hash = self.hashout_hex(tx_hash)
263             txpoint = {
264                     "nTime":    int(nTime),
265                     "height":   int(height),
266                     "is_in":    int(is_in),
267                     "blk_hash": self.hashout_hex(blk_hash),
268                     "tx_hash":  tx_hash,
269                     "tx_id":    int(tx_id),
270                     "pos":      int(pos),
271                     "value":    int(value),
272                     }
273
274             txpoints.append(txpoint)
275             known_tx.append(self.hashout_hex(tx_hash))
276
277
278         # todo: sort them really...
279         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
280
281         # read memory pool
282         rows = []
283         rows += self.get_address_in_rows_memorypool( dbhash )
284         rows += self.get_address_out_rows_memorypool( dbhash )
285         address_has_mempool = False
286
287         for row in rows:
288             is_in, tx_hash, tx_id, pos, value = row
289             tx_hash = self.hashout_hex(tx_hash)
290             if tx_hash in known_tx:
291                 continue
292
293             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
294             address_has_mempool = True
295
296             # this means pending transactions are returned by getmemorypool
297             if tx_hash not in self.mempool_keys:
298                 continue
299
300             #print "mempool", tx_hash
301             txpoint = {
302                     "nTime":    0,
303                     "height":   0,
304                     "is_in":    int(is_in),
305                     "blk_hash": 'mempool', 
306                     "tx_hash":  tx_hash,
307                     "tx_id":    int(tx_id),
308                     "pos":      int(pos),
309                     "value":    int(value),
310                     }
311             txpoints.append(txpoint)
312
313
314         for txpoint in txpoints:
315             tx_id = txpoint['tx_id']
316             
317             txinputs = []
318             inrows = self.get_tx_inputs(tx_id)
319             for row in inrows:
320                 _hash = self.binout(row[6])
321                 address = hash_to_address(chr(0), _hash)
322                 txinputs.append(address)
323             txpoint['inputs'] = txinputs
324             txoutputs = []
325             outrows = self.get_tx_outputs(tx_id)
326             for row in outrows:
327                 _hash = self.binout(row[6])
328                 address = hash_to_address(chr(0), _hash)
329                 txoutputs.append(address)
330             txpoint['outputs'] = txoutputs
331
332             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
333             if not txpoint['is_in']:
334                 # detect if already redeemed...
335                 for row in outrows:
336                     if row[6] == dbhash: break
337                 else:
338                     raise
339                 #row = self.get_tx_output(tx_id,dbhash)
340                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
341                 # if not redeemed, we add the script
342                 if row:
343                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
344
345         # cache result
346         if not address_has_mempool:
347             self.tx_cache[addr] = txpoints
348         
349         return txpoints
350
351
352
353 class Direct_Interface(Interface):
354     def __init__(self):
355         pass
356
357     def handler(self, method, params = ''):
358         cmds = {'session.new':new_session,
359                 'session.poll':poll_session,
360                 'session.update':update_session,
361                 'transaction.broadcast':send_tx,
362                 'address.get_history':store.get_history
363                 }
364         func = cmds[method]
365         return func( params )
366
367
368
369 def send_tx(tx):
370     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
371     respdata = urllib.urlopen(bitcoind_url, postdata).read()
372     r = loads(respdata)
373     if r['error'] != None:
374         out = "error: transaction rejected by memorypool\n"+tx
375     else:
376         out = r['result']
377     return out
378
379
380
381 def random_string(N):
382     import random, string
383     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
384
385     
386
387 def cmd_stop(data):
388     global stopping
389     if password == data:
390         stopping = True
391         return 'ok'
392     else:
393         return 'wrong password'
394
395 def cmd_load(pw):
396     if password == pw:
397         return repr( len(sessions) )
398     else:
399         return 'wrong password'
400
401
402 def clear_cache(pw):
403     if password == pw:
404         store.tx_cache = {}
405         return 'ok'
406     else:
407         return 'wrong password'
408
409 def get_cache(pw,addr):
410     if password == pw:
411         return store.tx_cache.get(addr)
412     else:
413         return 'wrong password'
414
415
416 def poll_session(session_id):
417     session = sessions.get(session_id)
418     if session is None:
419         print time.asctime(), "session not found", session_id
420         out = repr( (-1, {}))
421     else:
422         t1 = time.time()
423         addresses = session['addresses']
424         session['last_time'] = time.time()
425         ret = {}
426         k = 0
427         for addr in addresses:
428             if store.tx_cache.get( addr ) is not None: k += 1
429             status = get_address_status( addr )
430             last_status = addresses.get( addr )
431             if last_status != status:
432                 addresses[addr] = status
433                 ret[addr] = status
434         if ret:
435             sessions[session_id]['addresses'] = addresses
436         out = repr( (block_number, ret ) )
437         t2 = time.time() - t1 
438         if t2 > 10:
439             print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
440
441         return out
442
443
444 def do_update_address(addr):
445     # an address was involved in a transaction; we check if it was subscribed to in a session
446     # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
447     for session_id in sessions.keys():
448         session = sessions[session_id]
449         if session.get('type') != 'persistent': continue
450         addresses = session['addresses'].keys()
451
452         if addr in addresses:
453             status = get_address_status( addr )
454             message_id, last_status = session['addresses'][addr]
455             if last_status != status:
456                 #print "sending new status for %s:"%addr, status
457                 send_status(session_id,message_id,addr,status)
458                 sessions[session_id]['addresses'][addr] = (message_id,status)
459
460
461 def get_address_status(addr):
462     # get address status, i.e. the last block for that address.
463     tx_points = store.get_history(addr)
464     if not tx_points:
465         status = None
466     else:
467         lastpoint = tx_points[-1]
468         status = lastpoint['blk_hash']
469         # this is a temporary hack; move it up once old clients have disappeared
470         if status == 'mempool': # and session['version'] != "old":
471             status = status + ':%d'% len(tx_points)
472     return status
473
474
475 def send_numblocks(session_id):
476     message_id = sessions_sub_numblocks[session_id]
477     out = json.dumps( {'id':message_id, 'result':block_number} )
478     output_queue.put((session_id, out))
479
480 def send_status(session_id, message_id, address, status):
481     out = json.dumps( { 'id':message_id, 'result':status } )
482     output_queue.put((session_id, out))
483
484 def subscribe_to_numblocks(session_id, message_id):
485     sessions_sub_numblocks[session_id] = message_id
486     send_numblocks(session_id)
487
488 def subscribe_to_address(session_id, message_id, address):
489     status = get_address_status(address)
490     sessions[session_id]['addresses'][address] = (message_id, status)
491     sessions[session_id]['last_time'] = time.time()
492     send_status(session_id, message_id, address, status)
493
494 def add_address_to_session(session_id, address):
495     status = get_address_status(address)
496     sessions[session_id]['addresses'][addr] = status
497     sessions[session_id]['last_time'] = time.time()
498     return status
499
500 def new_session(version, addresses):
501     session_id = random_string(10)
502     sessions[session_id] = { 'addresses':{}, 'version':version }
503     for a in addresses:
504         sessions[session_id]['addresses'][a] = ''
505     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
506     sessions[session_id]['last_time'] = time.time()
507     return out
508
509 def get_banner():
510     print "get banner"
511     return config.get('server','banner').replace('\\n','\n')
512
513 def update_session(session_id,addresses):
514     """deprecated in 0.42"""
515     sessions[session_id]['addresses'] = {}
516     for a in addresses:
517         sessions[session_id]['addresses'][a] = ''
518     sessions[session_id]['last_time'] = time.time()
519     return 'ok'
520
521 def native_server_thread():
522     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
523     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
524     s.bind((config.get('server','host'), config.getint('server','port')))
525     s.listen(1)
526     while not stopping:
527         conn, addr = s.accept()
528         try:
529             thread.start_new_thread(native_client_thread, (addr, conn,))
530         except:
531             # can't start new thread if there is no memory..
532             traceback.print_exc(file=sys.stdout)
533
534
535 def native_client_thread(ipaddr,conn):
536     #print "client thread", ipaddr
537     try:
538         ipaddr = ipaddr[0]
539         msg = ''
540         while 1:
541             d = conn.recv(1024)
542             msg += d
543             if not d: 
544                 break
545             if '#' in msg:
546                 msg = msg.split('#', 1)[0]
547                 break
548         try:
549             cmd, data = ast.literal_eval(msg)
550         except:
551             print "syntax error", repr(msg), ipaddr
552             conn.close()
553             return
554
555         out = do_command(cmd, data, ipaddr)
556         if out:
557             #print ipaddr, cmd, len(out)
558             try:
559                 conn.send(out)
560             except:
561                 print "error, could not send"
562
563     finally:
564         conn.close()
565
566
567 def timestr():
568     return time.strftime("[%d/%m/%Y-%H:%M:%S]")
569
570 # used by the native handler
571 def do_command(cmd, data, ipaddr):
572
573     if cmd=='b':
574         out = "%d"%block_number
575
576     elif cmd in ['session','new_session']:
577         try:
578             if cmd == 'session':
579                 addresses = ast.literal_eval(data)
580                 version = "old"
581             else:
582                 version, addresses = ast.literal_eval(data)
583                 if version[0]=="0": version = "v" + version
584         except:
585             print "error", data
586             return None
587         print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
588         out = new_session(version, addresses)
589
590     elif cmd=='address.subscribe':
591         try:
592             session_id, addr = ast.literal_eval(data)
593         except:
594             print "error"
595             return None
596         out = add_address_to_session(session_id,addr)
597
598     elif cmd=='update_session':
599         try:
600             session_id, addresses = ast.literal_eval(data)
601         except:
602             print "error"
603             return None
604         print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
605         out = update_session(session_id,addresses)
606
607     elif cmd == 'bccapi_login':
608         import electrum
609         print "data",data
610         v, k = ast.literal_eval(data)
611         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
612         print master_public_key
613         wallet_id = random_string(10)
614         w = Wallet( Direct_Interface() )
615         w.master_public_key = master_public_key.decode('hex')
616         w.synchronize()
617         wallets[wallet_id] = w
618         out = wallet_id
619         print "wallets", wallets
620
621     elif cmd == 'bccapi_getAccountInfo':
622         from wallet import int_to_hex
623         v, wallet_id = ast.literal_eval(data)
624         w = wallets.get(wallet_id)
625         if w is not None:
626             num = len(w.addresses)
627             c, u = w.get_balance()
628             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
629             out = out.decode('hex')
630         else:
631             print "error",data
632             out = "error"
633
634     elif cmd == 'bccapi_getAccountStatement':
635         from wallet import int_to_hex
636         v, wallet_id = ast.literal_eval(data)
637         w = wallets.get(wallet_id)
638         if w is not None:
639             num = len(w.addresses)
640             c, u = w.get_balance()
641             total_records = num_records = 0
642             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 )
643             out = out.decode('hex')
644         else:
645             print "error",data
646             out = "error"
647
648     elif cmd == 'bccapi_getSendCoinForm':
649         out = ''
650
651     elif cmd == 'bccapi_submitTransaction':
652         out = ''
653             
654     elif cmd=='poll': 
655         out = poll_session(data)
656
657     elif cmd == 'h': 
658         # history
659         address = data
660         out = repr( store.get_history( address ) )
661
662     elif cmd == 'load': 
663         out = cmd_load(data)
664
665     elif cmd =='tx':
666         out = send_tx(data)
667         print timestr(), "sent tx:", ipaddr, out
668
669     elif cmd == 'stop':
670         out = cmd_stop(data)
671
672     elif cmd == 'peers':
673         out = repr(peer_list.values())
674
675     else:
676         out = None
677
678     return out
679
680
681
682 ####################################################################
683
684 def tcp_server_thread():
685     thread.start_new_thread(process_input_queue, ())
686     thread.start_new_thread(process_output_queue, ())
687
688     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
689     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
690     s.bind((config.get('server','host'), 50001))
691     s.listen(1)
692     while not stopping:
693         conn, addr = s.accept()
694         try:
695             thread.start_new_thread(tcp_client_thread, (addr, conn,))
696         except:
697             # can't start new thread if there is no memory..
698             traceback.print_exc(file=sys.stdout)
699
700
701 def close_session(session_id):
702     #print "lost connection", session_id
703     sessions.pop(session_id)
704     if session_id in sessions_sub_numblocks:
705         sessions_sub_numblocks.pop(session_id)
706
707
708 # one thread per client. put requests in a queue.
709 def tcp_client_thread(ipaddr,conn):
710     """ use a persistent connection. put commands in a queue."""
711
712     print timestr(), "TCP session", ipaddr
713     global sessions
714
715     session_id = random_string(10)
716     sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
717
718     ipaddr = ipaddr[0]
719     msg = ''
720
721     while not stopping:
722         try:
723             d = conn.recv(1024)
724         except socket.error:
725             d = ''
726         if not d:
727             close_session(session_id)
728             break
729
730         msg += d
731         while True:
732             s = msg.find('\n')
733             if s ==-1:
734                 break
735             else:
736                 c = msg[0:s].strip()
737                 msg = msg[s+1:]
738                 if c == 'quit': 
739                     conn.close()
740                     close_session(session_id)
741                     return
742                 try:
743                     c = json.loads(c)
744                 except:
745                     print "json error", repr(c)
746                     continue
747                 try:
748                     message_id = c.get('id')
749                     method = c.get('method')
750                     params = c.get('params')
751                 except:
752                     print "syntax error", repr(c), ipaddr
753                     continue
754
755                 # add to queue
756                 input_queue.put((session_id, message_id, method, params))
757
758
759
760 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
761 def process_input_queue():
762     while not stopping:
763         session_id, message_id, method, data = input_queue.get()
764         if session_id not in sessions.keys():
765             continue
766         out = None
767         if method == 'address.subscribe':
768             address = data[0]
769             subscribe_to_address(session_id,message_id,address)
770         elif method == 'numblocks.subscribe':
771             subscribe_to_numblocks(session_id,message_id)
772         elif method == 'client.version':
773             sessions[session_id]['version'] = data[0]
774         elif method == 'server.banner':
775             out = { 'result':config.get('server','banner').replace('\\n','\n') } 
776         elif method == 'server.peers':
777             out = { 'result':peer_list.values() } 
778         elif method == 'address.get_history':
779             address = data[0]
780             out = { 'result':store.get_history( address ) } 
781         elif method == 'transaction.broadcast':
782             postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
783             txo = urllib.urlopen(bitcoind_url, postdata).read()
784             print "sent tx:", txo
785             out = json.loads(txo)
786         else:
787             print "unknown command", method
788         if out:
789             out['id'] = message_id
790             out = json.dumps( out )
791             output_queue.put((session_id, out))
792
793 # this is a separate thread
794 def process_output_queue():
795     while not stopping:
796         session_id, out = output_queue.get()
797         session = sessions.get(session_id)
798         if session: 
799             try:
800                 conn = session.get('conn')
801                 conn.send(out+'\n')
802             except:
803                 close_session(session_id)
804                 
805
806
807
808 ####################################################################
809
810
811 def memorypool_update(store):
812
813     ds = BCDataStream.BCDataStream()
814     previous_transactions = store.mempool_keys
815     store.mempool_keys = []
816
817     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
818     respdata = urllib.urlopen(bitcoind_url, postdata).read()
819     r = loads(respdata)
820     if r['error'] != None:
821         return
822
823     v = r['result'].get('transactions')
824     for hextx in v:
825         ds.clear()
826         ds.write(hextx.decode('hex'))
827         tx = deserialize.parse_Transaction(ds)
828         tx['hash'] = util.double_sha256(tx['tx'])
829         tx_hash = store.hashin(tx['hash'])
830
831         store.mempool_keys.append(tx_hash)
832         if store.tx_find_id_and_value(tx):
833             pass
834         else:
835             tx_id = store.import_tx(tx, False)
836             store.update_tx_cache(tx_id)
837
838     store.commit()
839
840
841 def clean_session_thread():
842     while not stopping:
843         time.sleep(30)
844         t = time.time()
845         for k,s in sessions.items():
846             if s.get('type') == 'persistent': continue
847             t0 = s['last_time']
848             if t - t0 > 5*60:
849                 sessions.pop(k)
850                 print "lost session", k
851             
852
853 def irc_thread():
854     global peer_list
855     NICK = 'E_'+random_string(10)
856     while not stopping:
857         try:
858             s = socket.socket()
859             s.connect(('irc.freenode.net', 6667))
860             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
861             s.send('NICK '+NICK+'\n')
862             s.send('JOIN #electrum\n')
863             sf = s.makefile('r', 0)
864             t = 0
865             while not stopping:
866                 line = sf.readline()
867                 line = line.rstrip('\r\n')
868                 line = line.split()
869                 if line[0]=='PING': 
870                     s.send('PONG '+line[1]+'\n')
871                 elif '353' in line: # answer to /names
872                     k = line.index('353')
873                     for item in line[k+1:]:
874                         if item[0:2] == 'E_':
875                             s.send('WHO %s\n'%item)
876                 elif '352' in line: # answer to /who
877                     # warning: this is a horrible hack which apparently works
878                     k = line.index('352')
879                     ip = line[k+4]
880                     ip = socket.gethostbyname(ip)
881                     name = line[k+6]
882                     host = line[k+9]
883                     peer_list[name] = (ip,host)
884                 if time.time() - t > 5*60:
885                     s.send('NAMES #electrum\n')
886                     t = time.time()
887                     peer_list = {}
888         except:
889             traceback.print_exc(file=sys.stdout)
890         finally:
891             sf.close()
892             s.close()
893
894
895
896 def http_server_thread(store):
897     # see http://code.google.com/p/jsonrpclib/
898     from SocketServer import ThreadingMixIn
899     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
900     class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
901     server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
902     server.register_function(lambda : peer_list.values(), 'server.peers')
903     server.register_function(cmd_stop, 'stop')
904     server.register_function(cmd_load, 'load')
905     server.register_function(lambda : block_number, 'blocks')
906     server.register_function(clear_cache, 'clear_cache')
907     server.register_function(get_cache, 'get_cache')
908     server.register_function(get_banner, 'server.banner')
909     server.register_function(send_tx, 'transaction.broadcast')
910     server.register_function(store.get_history, 'address.get_history')
911     server.register_function(add_address_to_session, 'address.subscribe')
912     server.register_function(new_session, 'session.new')
913     server.register_function(update_session, 'session.update')
914     server.register_function(poll_session, 'session.poll')
915     server.serve_forever()
916
917
918 import traceback
919
920
921 if __name__ == '__main__':
922
923     if len(sys.argv)>1:
924         import jsonrpclib
925         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
926         cmd = sys.argv[1]
927         if cmd == 'load':
928             out = server.load(password)
929         elif cmd == 'peers':
930             out = server.peers()
931         elif cmd == 'stop':
932             out = server.stop(password)
933         elif cmd == 'clear_cache':
934             out = server.clear_cache(password)
935         elif cmd == 'get_cache':
936             out = server.get_cache(password,sys.argv[2])
937         elif cmd == 'h':
938             out = server.address.get_history(sys.argv[2])
939         elif cmd == 'tx':
940             out = server.transaction.broadcast(sys.argv[2])
941         elif cmd == 'b':
942             out = server.blocks()
943         else:
944             out = "Unknown command: '%s'" % cmd
945         print out
946         sys.exit(0)
947
948
949     print "starting Electrum server"
950
951     conf = DataStore.CONFIG_DEFAULTS
952     args, argv = readconf.parse_argv( [], conf)
953     args.dbtype= config.get('database','type')
954     if args.dbtype == 'sqlite3':
955         args.connect_args = { 'database' : config.get('database','database') }
956     elif args.dbtype == 'MySQLdb':
957         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
958     elif args.dbtype == 'psycopg2':
959         args.connect_args = { 'database' : config.get('database','database') }
960     store = MyStore(args)
961     store.tx_cache = {}
962     store.mempool_keys = {}
963
964     # supported protocols
965     thread.start_new_thread(native_server_thread, ())
966     thread.start_new_thread(tcp_server_thread, ())
967     thread.start_new_thread(http_server_thread, (store,))
968
969     thread.start_new_thread(clean_session_thread, ())
970
971     if (config.get('server','irc') == 'yes' ):
972         thread.start_new_thread(irc_thread, ())
973
974     while not stopping:
975         try:
976             dblock.acquire()
977             store.catch_up()
978             memorypool_update(store)
979
980             block_number = store.get_block_number(1)
981             if block_number != old_block_number:
982                 old_block_number = block_number
983                 for session_id in sessions_sub_numblocks.keys():
984                     send_numblocks(session_id)
985
986         except IOError:
987             print "IOError: cannot reach bitcoind"
988             block_number = 0
989         except:
990             traceback.print_exc(file=sys.stdout)
991             block_number = 0
992         finally:
993             dblock.release()
994
995         # do addresses
996         while True:
997             try:
998                 addr = address_queue.get(False)
999             except:
1000                 break
1001             do_update_address(addr)
1002
1003         time.sleep(10)
1004
1005     print "server stopped"
1006