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
27 This service is free. Support this node:
28 19mP9FKrXqL46Si58pHdhGKow88SUPy1V8
30 The server code is free software; you may
31 download it and operate your own Electrum
32 node. See http://ecdsa.org/electrum
37 import time, socket, operator, thread, ast, sys
39 import psycopg2, binascii
42 from Abe.abe import hash_to_address, decode_check_address
43 from Abe.DataStore import DataStore as Datastore_class
44 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
48 dblock = thread.allocate_lock()
51 class MyStore(Datastore_class):
53 def safe_sql(self,sql):
56 ret = self.selectall(sql)
60 print "sql error", sql
63 def get_tx_outputs(self, tx_id):
64 return self.safe_sql("""SELECT
66 txout.txout_scriptPubKey,
73 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
74 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
75 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
76 WHERE txout.tx_id = %d
77 ORDER BY txout.txout_pos
80 def get_tx_inputs(self, tx_id):
81 return self.safe_sql(""" SELECT
85 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
87 COALESCE(txout.txout_pos, u.txout_pos),
90 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
91 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
92 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
93 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
95 ORDER BY txin.txin_pos
98 def get_address_out_rows(self, dbhash):
99 return self.safe_sql(""" SELECT
109 FROM chain_candidate cc
110 JOIN block b ON (b.block_id = cc.block_id)
111 JOIN block_tx ON (block_tx.block_id = b.block_id)
112 JOIN tx ON (tx.tx_id = block_tx.tx_id)
113 JOIN txin ON (txin.tx_id = tx.tx_id)
114 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
115 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
116 WHERE pubkey.pubkey_hash = '%s'
117 AND cc.in_longest = 1"""%dbhash)
119 def get_address_out_rows_memorypool(self, dbhash):
120 return self.safe_sql(""" SELECT
127 JOIN txin ON (txin.tx_id = tx.tx_id)
128 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
129 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
130 WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
132 def get_address_in_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 txout ON (txout.tx_id = tx.tx_id)
148 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
149 WHERE pubkey.pubkey_hash = '%s'
150 AND cc.in_longest = 1"""%(dbhash))
152 def get_address_in_rows_memorypool(self, dbhash):
153 return self.safe_sql( """ SELECT
160 JOIN txout ON (txout.tx_id = tx.tx_id)
161 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
162 WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
164 def get_txpoints(self, addr):
165 version, binaddr = decode_check_address(addr)
168 dbhash = self.binin(binaddr)
170 rows += self.get_address_out_rows( dbhash )
171 rows += self.get_address_in_rows( dbhash )
178 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
180 print "cannot unpack row", row
182 tx_hash = self.hashout_hex(tx_hash)
185 #"chain_id": int(chain_id),
186 "height": int(height),
188 "blk_hash": self.hashout_hex(blk_hash),
195 txpoints.append(txpoint)
196 known_tx.append(self.hashout_hex(tx_hash))
199 # todo: sort them really...
200 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
204 rows += self.get_address_in_rows_memorypool( dbhash )
205 rows += self.get_address_out_rows_memorypool( dbhash )
207 is_in, tx_hash, tx_id, pos, value = row
208 tx_hash = self.hashout_hex(tx_hash)
209 if tx_hash in known_tx:
211 #print "mempool", tx_hash
217 "blk_hash": 'mempool',
223 txpoints.append(txpoint)
226 for txpoint in txpoints:
227 tx_id = txpoint['tx_id']
230 inrows = self.get_tx_inputs(tx_id)
232 _hash = self.binout(row[6])
233 address = hash_to_address(chr(0), _hash)
234 txinputs.append(address)
235 txpoint['inputs'] = txinputs
237 outrows = self.get_tx_outputs(tx_id)
239 _hash = self.binout(row[6])
240 address = hash_to_address(chr(0), _hash)
241 txoutputs.append(address)
242 txpoint['outputs'] = txoutputs
244 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
245 if not txpoint['is_in']:
246 # detect if already redeemed...
248 if row[6] == dbhash: break
251 #row = self.get_tx_output(tx_id,dbhash)
252 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
253 # if not redeemed, we add the script
255 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
261 def get_status(self, addr):
262 # last block for an address
263 tx_points = self.get_txpoints(addr)
267 return tx_points[-1]['blk_hash']
272 conn = bitcoinrpc.connect_to_local()
274 v = conn.importtransaction(tx)
276 v = "error: transaction rejected by memorypool"
280 def listen_thread(store):
282 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
283 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
284 s.bind(('ecdsa.org', 50000))
287 conn, addr = s.accept()
288 thread.start_new_thread(client_thread, (addr, conn,))
291 def client_thread(ipaddr,conn):
292 #print "client thread", ipaddr
305 cmd, data = ast.literal_eval(msg[:-1])
307 print "syntax error", repr(msg)
312 out = "%d"%store.get_block_number(1)
315 import random, string
316 session_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
317 print "new session", ipaddr, session_id, data
319 addresses = ast.literal_eval(data)
320 sessions[session_id] = {}
322 sessions[session_id][a] = ''
323 out = repr( (session_id, SERVER_MESSAGE) )
327 addresses = sessions.get(session_id)
329 print "session not found", ipaddr
330 out = repr( (-1, {}))
333 for addr in addresses:
334 status = store.get_status( addr )
335 last_status = sessions[session_id].get( addr )
336 if last_status != status:
337 sessions[session_id][addr] = status
339 out = repr( (store.get_block_number(1), ret ) )
344 h = store.get_txpoints( addr )
354 #print ipaddr, cmd, len(out)
358 print "error, could not send"
364 ds = BCDataStream.BCDataStream()
367 def memorypool_update(store):
369 conn = bitcoinrpc.connect_to_local()
371 v = conn.getmemorypool()
373 print "cannot contact bitcoin daemmon"
375 v = v['transactions']
378 ds.write(hextx.decode('hex'))
379 tx = deserialize.parse_Transaction(ds)
380 tx['hash'] = util.double_sha256(tx['tx'])
382 if store.tx_find_id_and_value(tx):
385 store.import_tx(tx, False)
386 #print tx['hash'][::-1].encode('hex')
392 if __name__ == '__main__':
394 conf = DataStore.CONFIG_DEFAULTS
395 args, argv = readconf.parse_argv( [], conf)
396 args.dbtype='psycopg2'
397 args.connect_args = {"database":"abe"}
398 store = MyStore(args)
400 thread.start_new_thread(listen_thread, (store,))
401 #listen_thread(store)
408 memorypool_update(store)
411 traceback.print_exc(file=sys.stdout)