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