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
25 import time, socket, operator, thread, ast, sys,re
26 import psycopg2, binascii
29 from Abe.abe import hash_to_address, decode_check_address
30 from Abe.DataStore import DataStore as Datastore_class
31 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
35 config = ConfigParser.ConfigParser()
36 # set some defaults, which will be overwritten by the config file
37 config.add_section('server')
38 config.set('server','banner', 'Welcome to Electrum!')
39 config.set('server', 'host', 'ecdsa.org')
40 config.set('server', 'port', 50000)
41 config.set('server', 'password', '')
42 config.set('server', 'irc', 'yes')
43 config.add_section('database')
44 config.set('database', 'type', 'psycopg2')
45 config.set('database', 'database', 'abe')
48 f = open('/etc/electrum.conf','r')
52 print "Could not read electrum.conf. I will use the dafault values."
57 sessions_last_time = {}
58 dblock = thread.allocate_lock()
62 class MyStore(Datastore_class):
64 def safe_sql(self,sql, params=()):
67 ret = self.selectall(sql,params)
71 print "sql error", sql
74 def get_tx_outputs(self, tx_id):
75 return self.safe_sql("""SELECT
77 txout.txout_scriptPubKey,
84 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
85 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
86 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
87 WHERE txout.tx_id = %d
88 ORDER BY txout.txout_pos
91 def get_tx_inputs(self, tx_id):
92 return self.safe_sql(""" SELECT
96 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
98 COALESCE(txout.txout_pos, u.txout_pos),
101 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
102 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
103 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
104 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
105 WHERE txin.tx_id = %d
106 ORDER BY txin.txin_pos
109 def get_address_out_rows(self, dbhash):
110 return self.safe_sql(""" SELECT
120 FROM chain_candidate cc
121 JOIN block b ON (b.block_id = cc.block_id)
122 JOIN block_tx ON (block_tx.block_id = b.block_id)
123 JOIN tx ON (tx.tx_id = block_tx.tx_id)
124 JOIN txin ON (txin.tx_id = tx.tx_id)
125 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
126 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
127 WHERE pubkey.pubkey_hash = ?
128 AND cc.in_longest = 1""", (dbhash,))
130 def get_address_out_rows_memorypool(self, dbhash):
131 return self.safe_sql(""" SELECT
138 JOIN txin ON (txin.tx_id = tx.tx_id)
139 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
140 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
141 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
143 def get_address_in_rows(self, dbhash):
144 return self.safe_sql(""" SELECT
154 FROM chain_candidate cc
155 JOIN block b ON (b.block_id = cc.block_id)
156 JOIN block_tx ON (block_tx.block_id = b.block_id)
157 JOIN tx ON (tx.tx_id = block_tx.tx_id)
158 JOIN txout ON (txout.tx_id = tx.tx_id)
159 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
160 WHERE pubkey.pubkey_hash = ?
161 AND cc.in_longest = 1""", (dbhash,))
163 def get_address_in_rows_memorypool(self, dbhash):
164 return self.safe_sql( """ SELECT
171 JOIN txout ON (txout.tx_id = tx.tx_id)
172 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
173 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
175 def get_txpoints(self, addr):
176 version, binaddr = decode_check_address(addr)
179 dbhash = self.binin(binaddr)
181 rows += self.get_address_out_rows( dbhash )
182 rows += self.get_address_in_rows( dbhash )
189 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
191 print "cannot unpack row", row
193 tx_hash = self.hashout_hex(tx_hash)
196 #"chain_id": int(chain_id),
197 "height": int(height),
199 "blk_hash": self.hashout_hex(blk_hash),
206 txpoints.append(txpoint)
207 known_tx.append(self.hashout_hex(tx_hash))
210 # todo: sort them really...
211 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
215 rows += self.get_address_in_rows_memorypool( dbhash )
216 rows += self.get_address_out_rows_memorypool( dbhash )
218 is_in, tx_hash, tx_id, pos, value = row
219 tx_hash = self.hashout_hex(tx_hash)
220 if tx_hash in known_tx:
222 #print "mempool", tx_hash
228 "blk_hash": 'mempool',
234 txpoints.append(txpoint)
237 for txpoint in txpoints:
238 tx_id = txpoint['tx_id']
241 inrows = self.get_tx_inputs(tx_id)
243 _hash = self.binout(row[6])
244 address = hash_to_address(chr(0), _hash)
245 txinputs.append(address)
246 txpoint['inputs'] = txinputs
248 outrows = self.get_tx_outputs(tx_id)
250 _hash = self.binout(row[6])
251 address = hash_to_address(chr(0), _hash)
252 txoutputs.append(address)
253 txpoint['outputs'] = txoutputs
255 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
256 if not txpoint['is_in']:
257 # detect if already redeemed...
259 if row[6] == dbhash: break
262 #row = self.get_tx_output(tx_id,dbhash)
263 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
264 # if not redeemed, we add the script
266 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
272 def get_status(self, addr):
273 # last block for an address
274 tx_points = self.get_txpoints(addr)
278 return tx_points[-1]['blk_hash']
283 conn = bitcoinrpc.connect_to_local()
285 v = conn.importtransaction(tx)
287 v = "error: transaction rejected by memorypool"
291 def listen_thread(store):
292 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
293 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
294 s.bind((config.get('server','host'), config.getint('server','port')))
297 conn, addr = s.accept()
298 thread.start_new_thread(client_thread, (addr, conn,))
300 def random_string(N):
301 import random, string
302 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
304 def client_thread(ipaddr,conn):
305 #print "client thread", ipaddr
318 cmd, data = ast.literal_eval(msg[:-1])
320 print "syntax error", repr(msg)
325 out = "%d"%block_number
327 session_id = random_string(10)
329 addresses = ast.literal_eval(data)
335 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
337 sessions[session_id] = {}
339 sessions[session_id][a] = ''
340 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
341 sessions_last_time[session_id] = time.time()
345 addresses = sessions.get(session_id)
347 print "session not found", ipaddr
348 out = repr( (-1, {}))
350 sessions_last_time[session_id] = time.time()
352 for addr in addresses:
353 status = store.get_status( addr )
354 last_status = sessions[session_id].get( addr )
355 if last_status != status:
356 sessions[session_id][addr] = status
358 out = repr( (block_number, ret ) )
363 h = store.get_txpoints( addr )
367 if config.get('server','password') == data:
368 out = repr( len(sessions) )
370 out = 'wrong password'
377 if config.get('server','password') == data:
381 out = 'wrong password'
384 out = repr(peer_list.values())
390 #print ipaddr, cmd, len(out)
394 print "error, could not send"
400 ds = BCDataStream.BCDataStream()
403 def memorypool_update(store):
405 conn = bitcoinrpc.connect_to_local()
407 v = conn.getmemorypool()
409 print "cannot contact bitcoin daemmon"
411 v = v['transactions']
414 ds.write(hextx.decode('hex'))
415 tx = deserialize.parse_Transaction(ds)
416 tx['hash'] = util.double_sha256(tx['tx'])
418 if store.tx_find_id_and_value(tx):
421 store.import_tx(tx, False)
422 #print tx['hash'][::-1].encode('hex')
428 def clean_session_thread():
432 for k,t0 in sessions_last_time.items():
434 print "lost session",k
436 sessions_last_time.pop(k)
441 NICK = 'E_'+random_string(10)
445 s.connect(('irc.freenode.net', 6667))
446 s.send('USER electrum 0 * '+config.get('server','host')+' '+config.get('server','ircname')+'\n')
447 s.send('NICK '+NICK+'\n')
448 s.send('JOIN #electrum\n')
452 line = line.rstrip('\r\n')
455 s.send('PONG '+line[1]+'\n')
456 elif '353' in line: # answer to /names
457 k = line.index('353')
459 k2 = line.index('366')
462 for item in line[k+1:k2]:
463 if item[0:2] == 'E_':
464 s.send('WHO %s\n'%item)
465 elif '352' in line: # answer to /who
466 # warning: this is a horrible hack which apparently works
470 peer_list[name] = (ip,host)
471 elif time.time() - t > 5*60:
472 s.send('NAMES #electrum\n')
475 traceback.print_exc(file=sys.stdout)
483 if __name__ == '__main__':
488 request = "('load','%s')#"%config.get('server','password')
490 request = "('peers','')#"
492 request = "('stop','%s')#"%config.get('server','password')
494 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
495 s.connect((config.get('server','host'), config.getint('server','port')))
507 print "starting Electrum server"
508 conf = DataStore.CONFIG_DEFAULTS
509 args, argv = readconf.parse_argv( [], conf)
510 args.dbtype= config.get('database','type')
511 if args.dbtype == 'sqlite3':
512 args.connect_args = { 'database' : config.get('database','database') }
513 elif args.dbtype == 'MySQLdb':
514 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
515 elif args.dbtype == 'psycopg2':
516 args.connect_args = { 'database' : config.get('database','database') }
517 store = MyStore(args)
519 thread.start_new_thread(listen_thread, (store,))
520 thread.start_new_thread(clean_session_thread, ())
521 if (config.get('server','irc') == 'yes' ):
522 thread.start_new_thread(irc_thread, ())
528 memorypool_update(store)
529 block_number = store.get_block_number(1)
532 traceback.print_exc(file=sys.stdout)
535 print "server stopped"