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
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
34 f = open('/etc/electrum.conf','r')
37 HOST, PORT, PASSWORD, SERVER_MESSAGE = ast.literal_eval(data)
39 print "could not read /etc/electrum.conf"
40 SERVER_MESSAGE = "Welcome to Electrum"
49 sessions_last_time = {}
50 dblock = thread.allocate_lock()
54 class MyStore(Datastore_class):
56 def safe_sql(self,sql):
59 ret = self.selectall(sql)
63 print "sql error", sql
66 def get_tx_outputs(self, tx_id):
67 return self.safe_sql("""SELECT
69 txout.txout_scriptPubKey,
76 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
77 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
78 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
79 WHERE txout.tx_id = %d
80 ORDER BY txout.txout_pos
83 def get_tx_inputs(self, tx_id):
84 return self.safe_sql(""" SELECT
88 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
90 COALESCE(txout.txout_pos, u.txout_pos),
93 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
94 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
95 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
96 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
98 ORDER BY txin.txin_pos
101 def get_address_out_rows(self, dbhash):
102 return self.safe_sql(""" SELECT
112 FROM chain_candidate cc
113 JOIN block b ON (b.block_id = cc.block_id)
114 JOIN block_tx ON (block_tx.block_id = b.block_id)
115 JOIN tx ON (tx.tx_id = block_tx.tx_id)
116 JOIN txin ON (txin.tx_id = tx.tx_id)
117 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
118 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
119 WHERE pubkey.pubkey_hash = '%s'
120 AND cc.in_longest = 1"""%dbhash)
122 def get_address_out_rows_memorypool(self, dbhash):
123 return self.safe_sql(""" SELECT
130 JOIN txin ON (txin.tx_id = tx.tx_id)
131 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
132 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
133 WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
135 def get_address_in_rows(self, dbhash):
136 return self.safe_sql(""" SELECT
146 FROM chain_candidate cc
147 JOIN block b ON (b.block_id = cc.block_id)
148 JOIN block_tx ON (block_tx.block_id = b.block_id)
149 JOIN tx ON (tx.tx_id = block_tx.tx_id)
150 JOIN txout ON (txout.tx_id = tx.tx_id)
151 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
152 WHERE pubkey.pubkey_hash = '%s'
153 AND cc.in_longest = 1"""%(dbhash))
155 def get_address_in_rows_memorypool(self, dbhash):
156 return self.safe_sql( """ SELECT
163 JOIN txout ON (txout.tx_id = tx.tx_id)
164 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
165 WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
167 def get_txpoints(self, addr):
168 version, binaddr = decode_check_address(addr)
171 dbhash = self.binin(binaddr)
173 rows += self.get_address_out_rows( dbhash )
174 rows += self.get_address_in_rows( dbhash )
181 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
183 print "cannot unpack row", row
185 tx_hash = self.hashout_hex(tx_hash)
188 #"chain_id": int(chain_id),
189 "height": int(height),
191 "blk_hash": self.hashout_hex(blk_hash),
198 txpoints.append(txpoint)
199 known_tx.append(self.hashout_hex(tx_hash))
202 # todo: sort them really...
203 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
207 rows += self.get_address_in_rows_memorypool( dbhash )
208 rows += self.get_address_out_rows_memorypool( dbhash )
210 is_in, tx_hash, tx_id, pos, value = row
211 tx_hash = self.hashout_hex(tx_hash)
212 if tx_hash in known_tx:
214 #print "mempool", tx_hash
220 "blk_hash": 'mempool',
226 txpoints.append(txpoint)
229 for txpoint in txpoints:
230 tx_id = txpoint['tx_id']
233 inrows = self.get_tx_inputs(tx_id)
235 _hash = self.binout(row[6])
236 address = hash_to_address(chr(0), _hash)
237 txinputs.append(address)
238 txpoint['inputs'] = txinputs
240 outrows = self.get_tx_outputs(tx_id)
242 _hash = self.binout(row[6])
243 address = hash_to_address(chr(0), _hash)
244 txoutputs.append(address)
245 txpoint['outputs'] = txoutputs
247 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
248 if not txpoint['is_in']:
249 # detect if already redeemed...
251 if row[6] == dbhash: break
254 #row = self.get_tx_output(tx_id,dbhash)
255 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
256 # if not redeemed, we add the script
258 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
264 def get_status(self, addr):
265 # last block for an address
266 tx_points = self.get_txpoints(addr)
270 return tx_points[-1]['blk_hash']
275 conn = bitcoinrpc.connect_to_local()
277 v = conn.importtransaction(tx)
279 v = "error: transaction rejected by memorypool"
283 def listen_thread(store):
284 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
285 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
289 conn, addr = s.accept()
290 thread.start_new_thread(client_thread, (addr, conn,))
292 def random_string(N):
293 import random, string
294 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
296 def client_thread(ipaddr,conn):
297 #print "client thread", ipaddr
310 cmd, data = ast.literal_eval(msg[:-1])
312 print "syntax error", repr(msg)
317 out = "%d"%block_number
319 session_id = random_string(10)
321 addresses = ast.literal_eval(data)
327 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
329 sessions[session_id] = {}
331 sessions[session_id][a] = ''
332 out = repr( (session_id, SERVER_MESSAGE) )
333 sessions_last_time[session_id] = time.time()
337 addresses = sessions.get(session_id)
339 print "session not found", ipaddr
340 out = repr( (-1, {}))
342 sessions_last_time[session_id] = time.time()
344 for addr in addresses:
345 status = store.get_status( addr )
346 last_status = sessions[session_id].get( addr )
347 if last_status != status:
348 sessions[session_id][addr] = status
350 out = repr( (block_number, ret ) )
355 h = store.get_txpoints( addr )
360 out = repr( len(sessions) )
362 out = 'wrong password'
373 out = 'wrong password'
376 out = repr(peer_list.values())
382 #print ipaddr, cmd, len(out)
386 print "error, could not send"
392 ds = BCDataStream.BCDataStream()
395 def memorypool_update(store):
397 conn = bitcoinrpc.connect_to_local()
399 v = conn.getmemorypool()
401 print "cannot contact bitcoin daemmon"
403 v = v['transactions']
406 ds.write(hextx.decode('hex'))
407 tx = deserialize.parse_Transaction(ds)
408 tx['hash'] = util.double_sha256(tx['tx'])
410 if store.tx_find_id_and_value(tx):
413 store.import_tx(tx, False)
414 #print tx['hash'][::-1].encode('hex')
420 def clean_session_thread():
424 for k,t0 in sessions_last_time.items():
426 print "lost session",k
428 sessions_last_time.pop(k)
433 NICK = 'E_'+random_string(10)
437 s.connect(('irc.freenode.net', 6667))
438 s.send('USER '+NICK+' '+NICK+' bla :'+NICK+'\n')
439 s.send('NICK '+NICK+'\n')
440 s.send('JOIN #electrum\n')
444 line = line.rstrip('\r\n')
447 s.send('PONG '+line[1]+'\n')
448 elif '353' in line: # answer to /names
449 k = line.index('353')
450 k2 = line.index('366')
451 for item in line[k+1:k2]:
452 if item[0:2] == 'E_':
453 s.send('USERHOST %s\n'%item)
454 elif '302' in line: # answer to /userhost
455 k = line.index('302')
457 host = line[k+2].split('@')[1]
458 peer_list[name] = host
459 elif time.time() - t > 5*60:
460 s.send('NAMES #electrum\n')
463 traceback.print_exc(file=sys.stdout)
471 if __name__ == '__main__':
476 request = "('load','%s')#"%PASSWORD
478 request = "('peers','')#"
480 request = "('stop','%s')#"%PASSWORD
482 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
483 s.connect(( HOST, PORT))
495 print "starting Electrum server"
496 conf = DataStore.CONFIG_DEFAULTS
497 args, argv = readconf.parse_argv( [], conf)
498 args.dbtype='psycopg2'
499 args.connect_args = {"database":"abe"}
500 store = MyStore(args)
502 thread.start_new_thread(listen_thread, (store,))
503 thread.start_new_thread(clean_session_thread, ())
504 thread.start_new_thread(irc_thread, ())
510 memorypool_update(store)
511 block_number = store.get_block_number(1)
514 traceback.print_exc(file=sys.stdout)
517 print "server stopped"