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, SERVER_MESSAGE = ast.literal_eval(data)
39 print "could not read /etc/electrum.conf"
40 SERVER_MESSAGE = "Welcome to Electrum"
47 dblock = thread.allocate_lock()
50 class MyStore(Datastore_class):
52 def safe_sql(self,sql):
55 ret = self.selectall(sql)
59 print "sql error", sql
62 def get_tx_outputs(self, tx_id):
63 return self.safe_sql("""SELECT
65 txout.txout_scriptPubKey,
72 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
73 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
74 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
75 WHERE txout.tx_id = %d
76 ORDER BY txout.txout_pos
79 def get_tx_inputs(self, tx_id):
80 return self.safe_sql(""" SELECT
84 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
86 COALESCE(txout.txout_pos, u.txout_pos),
89 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
90 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
91 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
92 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
94 ORDER BY txin.txin_pos
97 def get_address_out_rows(self, dbhash):
98 return self.safe_sql(""" SELECT
108 FROM chain_candidate cc
109 JOIN block b ON (b.block_id = cc.block_id)
110 JOIN block_tx ON (block_tx.block_id = b.block_id)
111 JOIN tx ON (tx.tx_id = block_tx.tx_id)
112 JOIN txin ON (txin.tx_id = tx.tx_id)
113 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
114 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
115 WHERE pubkey.pubkey_hash = '%s'
116 AND cc.in_longest = 1"""%dbhash)
118 def get_address_out_rows_memorypool(self, dbhash):
119 return self.safe_sql(""" SELECT
126 JOIN txin ON (txin.tx_id = tx.tx_id)
127 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
128 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
129 WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
131 def get_address_in_rows(self, dbhash):
132 return self.safe_sql(""" SELECT
142 FROM chain_candidate cc
143 JOIN block b ON (b.block_id = cc.block_id)
144 JOIN block_tx ON (block_tx.block_id = b.block_id)
145 JOIN tx ON (tx.tx_id = block_tx.tx_id)
146 JOIN txout ON (txout.tx_id = tx.tx_id)
147 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
148 WHERE pubkey.pubkey_hash = '%s'
149 AND cc.in_longest = 1"""%(dbhash))
151 def get_address_in_rows_memorypool(self, dbhash):
152 return self.safe_sql( """ SELECT
159 JOIN txout ON (txout.tx_id = tx.tx_id)
160 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
161 WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
163 def get_txpoints(self, addr):
164 version, binaddr = decode_check_address(addr)
167 dbhash = self.binin(binaddr)
169 rows += self.get_address_out_rows( dbhash )
170 rows += self.get_address_in_rows( dbhash )
177 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
179 print "cannot unpack row", row
181 tx_hash = self.hashout_hex(tx_hash)
184 #"chain_id": int(chain_id),
185 "height": int(height),
187 "blk_hash": self.hashout_hex(blk_hash),
194 txpoints.append(txpoint)
195 known_tx.append(self.hashout_hex(tx_hash))
198 # todo: sort them really...
199 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
203 rows += self.get_address_in_rows_memorypool( dbhash )
204 rows += self.get_address_out_rows_memorypool( dbhash )
206 is_in, tx_hash, tx_id, pos, value = row
207 tx_hash = self.hashout_hex(tx_hash)
208 if tx_hash in known_tx:
210 #print "mempool", tx_hash
216 "blk_hash": 'mempool',
222 txpoints.append(txpoint)
225 for txpoint in txpoints:
226 tx_id = txpoint['tx_id']
229 inrows = self.get_tx_inputs(tx_id)
231 _hash = self.binout(row[6])
232 address = hash_to_address(chr(0), _hash)
233 txinputs.append(address)
234 txpoint['inputs'] = txinputs
236 outrows = self.get_tx_outputs(tx_id)
238 _hash = self.binout(row[6])
239 address = hash_to_address(chr(0), _hash)
240 txoutputs.append(address)
241 txpoint['outputs'] = txoutputs
243 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
244 if not txpoint['is_in']:
245 # detect if already redeemed...
247 if row[6] == dbhash: break
250 #row = self.get_tx_output(tx_id,dbhash)
251 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
252 # if not redeemed, we add the script
254 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
260 def get_status(self, addr):
261 # last block for an address
262 tx_points = self.get_txpoints(addr)
266 return tx_points[-1]['blk_hash']
271 conn = bitcoinrpc.connect_to_local()
273 v = conn.importtransaction(tx)
275 v = "error: transaction rejected by memorypool"
279 def listen_thread(store):
281 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
282 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
286 conn, addr = s.accept()
287 thread.start_new_thread(client_thread, (addr, conn,))
290 def client_thread(ipaddr,conn):
291 #print "client thread", ipaddr
304 cmd, data = ast.literal_eval(msg[:-1])
306 print "syntax error", repr(msg)
311 out = "%d"%store.get_block_number(1)
314 import random, string
315 session_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
317 addresses = ast.literal_eval(data)
323 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
325 sessions[session_id] = {}
327 sessions[session_id][a] = ''
328 out = repr( (session_id, SERVER_MESSAGE) )
332 addresses = sessions.get(session_id)
334 print "session not found", ipaddr
335 out = repr( (-1, {}))
338 for addr in addresses:
339 status = store.get_status( addr )
340 last_status = sessions[session_id].get( addr )
341 if last_status != status:
342 sessions[session_id][addr] = status
344 out = repr( (store.get_block_number(1), ret ) )
349 h = store.get_txpoints( addr )
359 #print ipaddr, cmd, len(out)
363 print "error, could not send"
369 ds = BCDataStream.BCDataStream()
372 def memorypool_update(store):
374 conn = bitcoinrpc.connect_to_local()
376 v = conn.getmemorypool()
378 print "cannot contact bitcoin daemmon"
380 v = v['transactions']
383 ds.write(hextx.decode('hex'))
384 tx = deserialize.parse_Transaction(ds)
385 tx['hash'] = util.double_sha256(tx['tx'])
387 if store.tx_find_id_and_value(tx):
390 store.import_tx(tx, False)
391 #print tx['hash'][::-1].encode('hex')
397 if __name__ == '__main__':
399 print "starting Electrum server"
400 conf = DataStore.CONFIG_DEFAULTS
401 args, argv = readconf.parse_argv( [], conf)
402 args.dbtype='psycopg2'
403 args.connect_args = {"database":"abe"}
404 store = MyStore(args)
406 thread.start_new_thread(listen_thread, (store,))
407 #listen_thread(store)
414 memorypool_update(store)
417 traceback.print_exc(file=sys.stdout)
418 print "continuing..."