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
24 f = open('/etc/electrum.conf','r')
25 SERVER_MESSAGE = f.read()
30 import time, socket, operator, thread, ast, sys
32 import psycopg2, binascii
35 from Abe.abe import hash_to_address, decode_check_address
36 from Abe.DataStore import DataStore as Datastore_class
37 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
41 dblock = thread.allocate_lock()
44 class MyStore(Datastore_class):
46 def safe_sql(self,sql):
49 ret = self.selectall(sql)
53 print "sql error", sql
56 def get_tx_outputs(self, tx_id):
57 return self.safe_sql("""SELECT
59 txout.txout_scriptPubKey,
66 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
67 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
68 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
69 WHERE txout.tx_id = %d
70 ORDER BY txout.txout_pos
73 def get_tx_inputs(self, tx_id):
74 return self.safe_sql(""" SELECT
78 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
80 COALESCE(txout.txout_pos, u.txout_pos),
83 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
84 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
85 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
86 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
88 ORDER BY txin.txin_pos
91 def get_address_out_rows(self, dbhash):
92 return self.safe_sql(""" SELECT
102 FROM chain_candidate cc
103 JOIN block b ON (b.block_id = cc.block_id)
104 JOIN block_tx ON (block_tx.block_id = b.block_id)
105 JOIN tx ON (tx.tx_id = block_tx.tx_id)
106 JOIN txin ON (txin.tx_id = tx.tx_id)
107 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
108 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
109 WHERE pubkey.pubkey_hash = '%s'
110 AND cc.in_longest = 1"""%dbhash)
112 def get_address_out_rows_memorypool(self, dbhash):
113 return self.safe_sql(""" SELECT
120 JOIN txin ON (txin.tx_id = tx.tx_id)
121 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
122 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
123 WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
125 def get_address_in_rows(self, dbhash):
126 return self.safe_sql(""" SELECT
136 FROM chain_candidate cc
137 JOIN block b ON (b.block_id = cc.block_id)
138 JOIN block_tx ON (block_tx.block_id = b.block_id)
139 JOIN tx ON (tx.tx_id = block_tx.tx_id)
140 JOIN txout ON (txout.tx_id = tx.tx_id)
141 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
142 WHERE pubkey.pubkey_hash = '%s'
143 AND cc.in_longest = 1"""%(dbhash))
145 def get_address_in_rows_memorypool(self, dbhash):
146 return self.safe_sql( """ SELECT
153 JOIN txout ON (txout.tx_id = tx.tx_id)
154 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
155 WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
157 def get_txpoints(self, addr):
158 version, binaddr = decode_check_address(addr)
161 dbhash = self.binin(binaddr)
163 rows += self.get_address_out_rows( dbhash )
164 rows += self.get_address_in_rows( dbhash )
171 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
173 print "cannot unpack row", row
175 tx_hash = self.hashout_hex(tx_hash)
178 #"chain_id": int(chain_id),
179 "height": int(height),
181 "blk_hash": self.hashout_hex(blk_hash),
188 txpoints.append(txpoint)
189 known_tx.append(self.hashout_hex(tx_hash))
192 # todo: sort them really...
193 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
197 rows += self.get_address_in_rows_memorypool( dbhash )
198 rows += self.get_address_out_rows_memorypool( dbhash )
200 is_in, tx_hash, tx_id, pos, value = row
201 tx_hash = self.hashout_hex(tx_hash)
202 if tx_hash in known_tx:
204 #print "mempool", tx_hash
210 "blk_hash": 'mempool',
216 txpoints.append(txpoint)
219 for txpoint in txpoints:
220 tx_id = txpoint['tx_id']
223 inrows = self.get_tx_inputs(tx_id)
225 _hash = self.binout(row[6])
226 address = hash_to_address(chr(0), _hash)
227 txinputs.append(address)
228 txpoint['inputs'] = txinputs
230 outrows = self.get_tx_outputs(tx_id)
232 _hash = self.binout(row[6])
233 address = hash_to_address(chr(0), _hash)
234 txoutputs.append(address)
235 txpoint['outputs'] = txoutputs
237 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
238 if not txpoint['is_in']:
239 # detect if already redeemed...
241 if row[6] == dbhash: break
244 #row = self.get_tx_output(tx_id,dbhash)
245 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
246 # if not redeemed, we add the script
248 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
254 def get_status(self, addr):
255 # last block for an address
256 tx_points = self.get_txpoints(addr)
260 return tx_points[-1]['blk_hash']
265 conn = bitcoinrpc.connect_to_local()
267 v = conn.importtransaction(tx)
269 v = "error: transaction rejected by memorypool"
273 def listen_thread(store):
275 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
276 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
277 s.bind(('ecdsa.org', 50000))
280 conn, addr = s.accept()
281 thread.start_new_thread(client_thread, (addr, conn,))
284 def client_thread(ipaddr,conn):
285 #print "client thread", ipaddr
298 cmd, data = ast.literal_eval(msg[:-1])
300 print "syntax error", repr(msg)
305 out = "%d"%store.get_block_number(1)
308 import random, string
309 session_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
310 print "new session", ipaddr, session_id, data
312 addresses = ast.literal_eval(data)
313 sessions[session_id] = {}
315 sessions[session_id][a] = ''
316 out = repr( (session_id, SERVER_MESSAGE) )
320 addresses = sessions.get(session_id)
322 print "session not found", ipaddr
323 out = repr( (-1, {}))
326 for addr in addresses:
327 status = store.get_status( addr )
328 last_status = sessions[session_id].get( addr )
329 if last_status != status:
330 sessions[session_id][addr] = status
332 out = repr( (store.get_block_number(1), ret ) )
337 h = store.get_txpoints( addr )
347 #print ipaddr, cmd, len(out)
351 print "error, could not send"
357 ds = BCDataStream.BCDataStream()
360 def memorypool_update(store):
362 conn = bitcoinrpc.connect_to_local()
364 v = conn.getmemorypool()
366 print "cannot contact bitcoin daemmon"
368 v = v['transactions']
371 ds.write(hextx.decode('hex'))
372 tx = deserialize.parse_Transaction(ds)
373 tx['hash'] = util.double_sha256(tx['tx'])
375 if store.tx_find_id_and_value(tx):
378 store.import_tx(tx, False)
379 #print tx['hash'][::-1].encode('hex')
385 if __name__ == '__main__':
387 conf = DataStore.CONFIG_DEFAULTS
388 args, argv = readconf.parse_argv( [], conf)
389 args.dbtype='psycopg2'
390 args.connect_args = {"database":"abe"}
391 store = MyStore(args)
393 thread.start_new_thread(listen_thread, (store,))
394 #listen_thread(store)
401 memorypool_update(store)
404 traceback.print_exc(file=sys.stdout)