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
26 import time, socket, operator, thread, ast, sys,re
27 import psycopg2, binascii
30 from Abe.abe import hash_to_address, decode_check_address
31 from Abe.DataStore import DataStore as Datastore_class
32 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
36 config = ConfigParser.ConfigParser()
37 # set some defaults, which will be overwritten by the config file
38 config.add_section('server')
39 config.set('server','banner', 'Welcome to Electrum!')
40 config.set('server', 'host', 'localhost')
41 config.set('server', 'port', 50000)
42 config.set('server', 'password', '')
43 config.set('server', 'irc', 'yes')
44 config.set('server', 'cache', 'no')
45 config.set('server', 'ircname', 'Electrum server')
46 config.add_section('database')
47 config.set('database', 'type', 'psycopg2')
48 config.set('database', 'database', 'abe')
51 f = open('/etc/electrum.conf','r')
55 print "Could not read electrum.conf. I will use the default values."
60 sessions_last_time = {}
61 dblock = thread.allocate_lock()
65 class MyStore(Datastore_class):
67 def import_tx(self, tx, is_coinbase):
68 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
69 if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
71 def update_tx_cache(self, txid):
72 inrows = self.get_tx_inputs(txid, False)
74 _hash = store.binout(row[6])
75 address = hash_to_address(chr(0), _hash)
76 if self.tx_cache.has_key(address):
77 print "cache: invalidating", address, self.ismempool
78 self.tx_cache.pop(address)
79 outrows = self.get_tx_outputs(txid, False)
81 _hash = store.binout(row[6])
82 address = hash_to_address(chr(0), _hash)
83 if self.tx_cache.has_key(address):
84 print "cache: invalidating", address, self.ismempool
85 self.tx_cache.pop(address)
87 def safe_sql(self,sql, params=(), lock=True):
89 if lock: dblock.acquire()
90 ret = self.selectall(sql,params)
91 if lock: dblock.release()
94 print "sql error", sql
97 def get_tx_outputs(self, tx_id, lock=True):
98 return self.safe_sql("""SELECT
100 txout.txout_scriptPubKey,
107 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
108 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
109 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
110 WHERE txout.tx_id = %d
111 ORDER BY txout.txout_pos
112 """%(tx_id), (), lock)
114 def get_tx_inputs(self, tx_id, lock=True):
115 return self.safe_sql(""" SELECT
119 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
121 COALESCE(txout.txout_pos, u.txout_pos),
124 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
125 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
126 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
127 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
128 WHERE txin.tx_id = %d
129 ORDER BY txin.txin_pos
130 """%(tx_id,), (), lock)
132 def get_address_out_rows(self, dbhash):
133 return self.safe_sql(""" SELECT
143 FROM chain_candidate cc
144 JOIN block b ON (b.block_id = cc.block_id)
145 JOIN block_tx ON (block_tx.block_id = b.block_id)
146 JOIN tx ON (tx.tx_id = block_tx.tx_id)
147 JOIN txin ON (txin.tx_id = tx.tx_id)
148 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
149 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
150 WHERE pubkey.pubkey_hash = ?
151 AND cc.in_longest = 1""", (dbhash,))
153 def get_address_out_rows_memorypool(self, dbhash):
154 return self.safe_sql(""" SELECT
161 JOIN txin ON (txin.tx_id = tx.tx_id)
162 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
163 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
164 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
166 def get_address_in_rows(self, dbhash):
167 return self.safe_sql(""" SELECT
177 FROM chain_candidate cc
178 JOIN block b ON (b.block_id = cc.block_id)
179 JOIN block_tx ON (block_tx.block_id = b.block_id)
180 JOIN tx ON (tx.tx_id = block_tx.tx_id)
181 JOIN txout ON (txout.tx_id = tx.tx_id)
182 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
183 WHERE pubkey.pubkey_hash = ?
184 AND cc.in_longest = 1""", (dbhash,))
186 def get_address_in_rows_memorypool(self, dbhash):
187 return self.safe_sql( """ SELECT
194 JOIN txout ON (txout.tx_id = tx.tx_id)
195 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
196 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
198 def get_txpoints(self, addr):
200 if config.get('server','cache') == 'yes':
201 cached_version = self.tx_cache.get( addr )
202 if cached_version is not None:
203 return cached_version
205 version, binaddr = decode_check_address(addr)
208 dbhash = self.binin(binaddr)
210 rows += self.get_address_out_rows( dbhash )
211 rows += self.get_address_in_rows( dbhash )
218 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
220 print "cannot unpack row", row
222 tx_hash = self.hashout_hex(tx_hash)
225 #"chain_id": int(chain_id),
226 "height": int(height),
228 "blk_hash": self.hashout_hex(blk_hash),
235 txpoints.append(txpoint)
236 known_tx.append(self.hashout_hex(tx_hash))
239 # todo: sort them really...
240 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
244 rows += self.get_address_in_rows_memorypool( dbhash )
245 rows += self.get_address_out_rows_memorypool( dbhash )
246 address_has_mempool = False
249 is_in, tx_hash, tx_id, pos, value = row
250 tx_hash = self.hashout_hex(tx_hash)
251 if tx_hash in known_tx:
254 address_has_mempool = True
255 #print "mempool", tx_hash
261 "blk_hash": 'mempool',
267 txpoints.append(txpoint)
270 for txpoint in txpoints:
271 tx_id = txpoint['tx_id']
274 inrows = self.get_tx_inputs(tx_id)
276 _hash = self.binout(row[6])
277 address = hash_to_address(chr(0), _hash)
278 txinputs.append(address)
279 txpoint['inputs'] = txinputs
281 outrows = self.get_tx_outputs(tx_id)
283 _hash = self.binout(row[6])
284 address = hash_to_address(chr(0), _hash)
285 txoutputs.append(address)
286 txpoint['outputs'] = txoutputs
288 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
289 if not txpoint['is_in']:
290 # detect if already redeemed...
292 if row[6] == dbhash: break
295 #row = self.get_tx_output(tx_id,dbhash)
296 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
297 # if not redeemed, we add the script
299 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
302 if config.get('server','cache') == 'yes' and not address_has_mempool:
303 self.tx_cache[addr] = txpoints
308 def get_status(self, addr):
309 # last block for an address.
310 tx_points = self.get_txpoints(addr)
314 return tx_points[-1]['blk_hash']
319 conn = bitcoinrpc.connect_to_local()
321 v = conn.importtransaction(tx)
323 v = "error: transaction rejected by memorypool"
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')))
333 conn, addr = s.accept()
334 thread.start_new_thread(client_thread, (addr, conn,))
336 def random_string(N):
337 import random, string
338 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
340 def client_thread(ipaddr,conn):
341 #print "client thread", ipaddr
356 cmd, data = ast.literal_eval(msg[:-1])
358 print "syntax error", repr(msg)
363 out = "%d"%block_number
365 session_id = random_string(10)
367 addresses = ast.literal_eval(data)
373 print time.asctime(), "session", ipaddr, session_id, addresses[0] if addresses else addresses, len(addresses)
375 sessions[session_id] = {}
377 sessions[session_id][a] = ''
378 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
379 sessions_last_time[session_id] = time.time()
383 addresses = sessions.get(session_id)
384 if addresses is None:
385 print time.asctime(), " Session not found", session_id, ipaddr
386 out = repr( (-1, {}))
389 sessions_last_time[session_id] = time.time()
392 for addr in addresses:
393 if store.tx_cache.get( addr ) is not None: k += 1
394 status = store.get_status( addr )
395 last_status = addresses.get( addr )
396 if last_status != status:
397 addresses[addr] = status
400 sessions[session_id] = addresses
401 out = repr( (block_number, ret ) )
402 t2 = time.time() - t1
404 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
409 out = repr( store.get_txpoints( address ) )
412 if config.get('server','password') == data:
413 out = repr( len(sessions) )
415 out = 'wrong password'
420 elif cmd =='clear_cache':
421 if config.get('server','password') == data:
425 out = 'wrong password'
427 elif cmd =='get_cache':
433 if config.get('server','password') == pw:
434 out = store.tx_cache.get(addr)
437 out = 'wrong password'
439 out = "error: "+ repr(data)
443 if config.get('server','password') == data:
447 out = 'wrong password'
450 out = repr(peer_list.values())
456 #print ipaddr, cmd, len(out)
460 print "error, could not send"
466 ds = BCDataStream.BCDataStream()
471 def memorypool_update(store):
472 conn = bitcoinrpc.connect_to_local()
474 v = conn.getmemorypool()
476 print "cannot contact bitcoin daemon"
478 v = v['transactions']
481 ds.write(hextx.decode('hex'))
482 tx = deserialize.parse_Transaction(ds)
485 tx['hash'] = util.double_sha256(tx['tx'])
487 if store.tx_find_id_and_value(tx):
490 store.import_tx(tx, False)
497 def clean_session_thread():
501 for k,t0 in sessions_last_time.items():
503 print time.asctime(), "lost session",k
505 sessions_last_time.pop(k)
510 NICK = 'E_'+random_string(10)
514 s.connect(('irc.freenode.net', 6667))
515 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
516 s.send('NICK '+NICK+'\n')
517 s.send('JOIN #electrum\n')
518 sf = s.makefile('r', 0)
522 line = line.rstrip('\r\n')
525 s.send('PONG '+line[1]+'\n')
526 elif '353' in line: # answer to /names
527 k = line.index('353')
528 for item in line[k+1:]:
529 if item[0:2] == 'E_':
530 s.send('WHO %s\n'%item)
531 elif '352' in line: # answer to /who
532 # warning: this is a horrible hack which apparently works
533 k = line.index('352')
535 ip = socket.gethostbyname(ip)
538 peer_list[name] = (ip,host)
539 if time.time() - t > 5*60:
540 s.send('NAMES #electrum\n')
544 traceback.print_exc(file=sys.stdout)
553 if __name__ == '__main__':
558 request = "('load','%s')#"%config.get('server','password')
560 request = "('peers','')#"
562 request = "('stop','%s')#"%config.get('server','password')
563 elif cmd == 'clear_cache':
564 request = "('clear_cache','%s')#"%config.get('server','password')
565 elif cmd == 'get_cache':
566 request = "('get_cache',('%s','%s'))#"%(config.get('server','password'),sys.argv[2])
568 request = "('h','%s')#"%sys.argv[2]
570 request = "('b','')#"
572 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
573 s.connect((config.get('server','host'), config.getint('server','port')))
585 print "starting Electrum server"
586 print "cache:", config.get('server', 'cache')
588 conf = DataStore.CONFIG_DEFAULTS
589 args, argv = readconf.parse_argv( [], conf)
590 args.dbtype= config.get('database','type')
591 if args.dbtype == 'sqlite3':
592 args.connect_args = { 'database' : config.get('database','database') }
593 elif args.dbtype == 'MySQLdb':
594 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
595 elif args.dbtype == 'psycopg2':
596 args.connect_args = { 'database' : config.get('database','database') }
597 store = MyStore(args)
599 store.ismempool = False
601 thread.start_new_thread(listen_thread, (store,))
602 thread.start_new_thread(clean_session_thread, ())
603 if (config.get('server','irc') == 'yes' ):
604 thread.start_new_thread(irc_thread, ())
610 store.ismempool = True
611 memorypool_update(store)
612 store.ismempool = False
613 block_number = store.get_block_number(1)
616 traceback.print_exc(file=sys.stdout)
619 print "server stopped"