2 # Copyright(C) 2011 thomasv@gitorious
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.
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.
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>.
20 * server should check and return bitcoind status..
21 * improve txpoint sorting
22 * command to check cache
24 mempool transactions do not need to be added to the database; it slows it down
28 import time, socket, operator, thread, ast, sys,re
29 import psycopg2, binascii
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
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')
53 f = open('/etc/electrum.conf','r')
57 print "Could not read electrum.conf. I will use the default values."
62 dblock = thread.allocate_lock()
66 class MyStore(Datastore_class):
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)
72 def update_tx_cache(self, txid):
73 inrows = self.get_tx_inputs(txid, False)
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)
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)
88 def safe_sql(self,sql, params=(), lock=True):
90 if lock: dblock.acquire()
91 ret = self.selectall(sql,params)
92 if lock: dblock.release()
95 print "sql error", sql
98 def get_tx_outputs(self, tx_id, lock=True):
99 return self.safe_sql("""SELECT
101 txout.txout_scriptPubKey,
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)
115 def get_tx_inputs(self, tx_id, lock=True):
116 return self.safe_sql(""" SELECT
120 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
122 COALESCE(txout.txout_pos, u.txout_pos),
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)
133 def get_address_out_rows(self, dbhash):
134 return self.safe_sql(""" SELECT
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,))
154 def get_address_out_rows_memorypool(self, dbhash):
155 return self.safe_sql(""" SELECT
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,))
167 def get_address_in_rows(self, dbhash):
168 return self.safe_sql(""" SELECT
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,))
187 def get_address_in_rows_memorypool(self, dbhash):
188 return self.safe_sql( """ SELECT
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,))
199 def get_txpoints(self, addr):
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
206 version, binaddr = decode_check_address(addr)
209 dbhash = self.binin(binaddr)
211 rows += self.get_address_out_rows( dbhash )
212 rows += self.get_address_in_rows( dbhash )
219 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
221 print "cannot unpack row", row
223 tx_hash = self.hashout_hex(tx_hash)
226 #"chain_id": int(chain_id),
227 "height": int(height),
229 "blk_hash": self.hashout_hex(blk_hash),
236 txpoints.append(txpoint)
237 known_tx.append(self.hashout_hex(tx_hash))
240 # todo: sort them really...
241 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
245 rows += self.get_address_in_rows_memorypool( dbhash )
246 rows += self.get_address_out_rows_memorypool( dbhash )
247 address_has_mempool = False
250 is_in, tx_hash, tx_id, pos, value = row
251 tx_hash = self.hashout_hex(tx_hash)
252 if tx_hash in known_tx:
255 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
256 address_has_mempool = True
258 # this means pending transactions are returned by getmemorypool
259 if tx_hash not in self.mempool_keys:
262 #print "mempool", tx_hash
268 "blk_hash": 'mempool',
274 txpoints.append(txpoint)
277 for txpoint in txpoints:
278 tx_id = txpoint['tx_id']
281 inrows = self.get_tx_inputs(tx_id)
283 _hash = self.binout(row[6])
284 address = hash_to_address(chr(0), _hash)
285 txinputs.append(address)
286 txpoint['inputs'] = txinputs
288 outrows = self.get_tx_outputs(tx_id)
290 _hash = self.binout(row[6])
291 address = hash_to_address(chr(0), _hash)
292 txoutputs.append(address)
293 txpoint['outputs'] = txoutputs
295 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
296 if not txpoint['is_in']:
297 # detect if already redeemed...
299 if row[6] == dbhash: break
302 #row = self.get_tx_output(tx_id,dbhash)
303 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
304 # if not redeemed, we add the script
306 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
309 if config.get('server','cache') == 'yes' and not address_has_mempool:
310 self.tx_cache[addr] = txpoints
318 conn = bitcoinrpc.connect_to_local()
320 v = conn.importtransaction(tx)
322 v = "error: transaction rejected by memorypool"
326 def listen_thread(store):
327 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
328 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
329 s.bind((config.get('server','host'), config.getint('server','port')))
332 conn, addr = s.accept()
333 thread.start_new_thread(client_thread, (addr, conn,))
335 def random_string(N):
336 import random, string
337 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
339 def client_thread(ipaddr,conn):
340 #print "client thread", ipaddr
355 cmd, data = ast.literal_eval(msg[:-1])
357 print "syntax error", repr(msg), ipaddr
362 out = "%d"%block_number
364 elif cmd in ['session','new_session']:
365 session_id = random_string(10)
368 addresses = ast.literal_eval(data)
371 version, addresses = ast.literal_eval(data)
372 if version[0]=="0": version = "v" + version
378 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
380 sessions[session_id] = { 'addresses':{}, 'version':version, 'ip':ipaddr }
382 sessions[session_id]['addresses'][a] = ''
383 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
384 sessions[session_id]['last_time'] = time.time()
386 elif cmd=='update_session':
388 session_id, addresses = ast.literal_eval(data)
394 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
396 sessions[session_id]['addresses'] = {}
398 sessions[session_id]['addresses'][a] = ''
400 sessions[session_id]['last_time'] = time.time()
404 session = sessions.get(session_id)
406 print time.asctime(), "session not found", session_id, ipaddr
407 out = repr( (-1, {}))
410 addresses = session['addresses']
411 session['last_time'] = time.time()
414 for addr in addresses:
415 if store.tx_cache.get( addr ) is not None: k += 1
417 # get addtess status, i.e. the last block for that address.
418 tx_points = store.get_txpoints(addr)
422 lastpoint = tx_points[-1]
423 status = lastpoint['blk_hash']
424 # this is a temporary hack; move it up once old clients have disappeared
425 if status == 'mempool' and session['version'] != "old":
426 status = status + ':%s'% lastpoint['tx_hash']
428 last_status = addresses.get( addr )
429 if last_status != status:
430 addresses[addr] = status
433 sessions[session_id]['addresses'] = addresses
434 out = repr( (block_number, ret ) )
435 t2 = time.time() - t1
437 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
442 out = repr( store.get_txpoints( address ) )
445 if config.get('server','password') == data:
446 out = repr( len(sessions) )
448 out = 'wrong password'
452 print "sent tx:", out
454 elif cmd =='clear_cache':
455 if config.get('server','password') == data:
459 out = 'wrong password'
461 elif cmd =='get_cache':
467 if config.get('server','password') == pw:
468 out = store.tx_cache.get(addr)
471 out = 'wrong password'
473 out = "error: "+ repr(data)
477 if config.get('server','password') == data:
481 out = 'wrong password'
484 out = repr(peer_list.values())
490 #print ipaddr, cmd, len(out)
494 print "error, could not send"
504 def memorypool_update(store):
505 ds = BCDataStream.BCDataStream()
506 store.mempool_keys = []
507 conn = bitcoinrpc.connect_to_local()
509 v = conn.getmemorypool()
511 print "cannot contact bitcoin daemon"
513 v = v['transactions']
516 ds.write(hextx.decode('hex'))
517 tx = deserialize.parse_Transaction(ds)
518 tx['hash'] = util.double_sha256(tx['tx'])
519 tx_hash = tx['hash'][::-1].encode('hex')
520 store.mempool_keys.append(tx_hash)
521 if store.tx_find_id_and_value(tx):
524 store.import_tx(tx, False)
530 def clean_session_thread():
534 for k,s in sessions.items():
537 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "end session", s['ip']
543 NICK = 'E_'+random_string(10)
547 s.connect(('irc.freenode.net', 6667))
548 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
549 s.send('NICK '+NICK+'\n')
550 s.send('JOIN #electrum\n')
551 sf = s.makefile('r', 0)
555 line = line.rstrip('\r\n')
558 s.send('PONG '+line[1]+'\n')
559 elif '353' in line: # answer to /names
560 k = line.index('353')
561 for item in line[k+1:]:
562 if item[0:2] == 'E_':
563 s.send('WHO %s\n'%item)
564 elif '352' in line: # answer to /who
565 # warning: this is a horrible hack which apparently works
566 k = line.index('352')
568 ip = socket.gethostbyname(ip)
571 peer_list[name] = (ip,host)
572 if time.time() - t > 5*60:
573 s.send('NAMES #electrum\n')
577 traceback.print_exc(file=sys.stdout)
586 if __name__ == '__main__':
590 pw = config.get('server','password')
592 request = "('load','%s')#"%pw
594 request = "('peers','')#"
596 request = "('stop','%s')#"%pw
597 elif cmd == 'clear_cache':
598 request = "('clear_cache','%s')#"%pw
599 elif cmd == 'get_cache':
600 request = "('get_cache',('%s','%s'))#"%(pw,sys.argv[2])
602 request = "('h','%s')#"%sys.argv[2]
604 request = "('b','')#"
606 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
607 s.connect((config.get('server','host'), config.getint('server','port')))
619 print "starting Electrum server"
620 print "cache:", config.get('server', 'cache')
622 conf = DataStore.CONFIG_DEFAULTS
623 args, argv = readconf.parse_argv( [], conf)
624 args.dbtype= config.get('database','type')
625 if args.dbtype == 'sqlite3':
626 args.connect_args = { 'database' : config.get('database','database') }
627 elif args.dbtype == 'MySQLdb':
628 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
629 elif args.dbtype == 'psycopg2':
630 args.connect_args = { 'database' : config.get('database','database') }
631 store = MyStore(args)
633 store.mempool_keys = {}
635 thread.start_new_thread(listen_thread, (store,))
636 thread.start_new_thread(clean_session_thread, ())
637 if (config.get('server','irc') == 'yes' ):
638 thread.start_new_thread(irc_thread, ())
644 memorypool_update(store)
645 block_number = store.get_block_number(1)
648 traceback.print_exc(file=sys.stdout)
651 print "server stopped"