address.get_history
[electrum-server.git] / composed.py
1 import bitcoin
2 import threading
3 import time
4
5 class ExpiryQueue(threading.Thread):
6
7     def __init__(self):
8         self.lock = threading.Lock()
9         self.items = []
10         threading.Thread.__init__(self)
11         self.daemon = True
12
13     def run(self):
14         # Garbage collection
15         while True:
16             with self.lock:
17                 self.items = [i for i in self.items if not i.stopped()]
18             time.sleep(0.1)
19
20     def add(self, item):
21         with self.lock:
22             self.items.append(item)
23
24 expiry_queue = ExpiryQueue()
25
26 class StatementLine:
27
28     def __init__(self, output_point):
29         self.lock = threading.Lock()
30         self.output_point = output_point
31         self.output_loaded = None
32         self.input_point = None
33         self.input_loaded = None
34
35     def is_loaded(self):
36         with self.lock:
37             if self.output_loaded is None:
38                 return False
39             elif (self.input_point is not False and
40                   self.input_loaded is None):
41                 return False
42         return True
43
44 class PaymentHistory:
45
46     def __init__(self, chain):
47         self.chain = chain
48         self.lock = threading.Lock()
49         self.statement = []
50         self._stopped = False
51
52     def run(self, address, handle_finish):
53         self.address = address
54         self.handle_finish = handle_finish
55
56         pubkey_hash = bitcoin.address_to_short_hash(address)
57         self.chain.fetch_outputs(pubkey_hash, self.start_loading)
58
59     def start_loading(self, ec, output_points):
60         with self.lock:
61             for outpoint in output_points:
62                 statement_line = StatementLine(outpoint)
63                 self.statement.append(statement_line)
64                 self.chain.fetch_spend(outpoint,
65                     bitcoin.bind(self.load_spend,
66                         bitcoin._1, bitcoin._2, statement_line))
67                 self.load_tx_info(outpoint, statement_line, False)
68
69     def load_spend(self, ec, inpoint, statement_line):
70         with statement_line.lock:
71             if ec:
72                 statement_line.input_point = False
73             else:
74                 statement_line.input_point = inpoint
75         self.finish_if_done()
76         self.load_tx_info(inpoint, statement_line, True)
77
78     def finish_if_done(self):
79         with self.lock:
80             if any(not line.is_loaded() for line in self.statement):
81                 return
82         result = []
83         for line in self.statement:
84             line.input_loaded["value"] = -line.output_loaded["value"]
85             result.append(line.input_loaded)
86             result.append(line.output_loaded)
87         self.handle_finish(result)
88         self.stop()
89
90     def stop(self):
91         with self.lock:
92             self._stopped = True
93
94     def stopped(self):
95         with self.lock:
96             return self._stopped
97
98     def load_tx_info(self, point, statement_line, is_input):
99         info = {}
100         info["tx_hash"] = str(point.hash)
101         info["pos"] = point.index
102         info["is_in"] = 1 if is_input else 0
103         self.chain.fetch_transaction_index(point.hash,
104             bitcoin.bind(self.tx_index, bitcoin._1, bitcoin._2, bitcoin._3,
105                 statement_line, info))
106
107     def tx_index(self, ec, block_depth, offset, statement_line, info):
108         info["height"] = block_depth
109         self.chain.fetch_block_header_by_depth(block_depth,
110             bitcoin.bind(self.block_header, bitcoin._1, bitcoin._2,
111                 statement_line, info))
112
113     def block_header(self, ec, blk_head, statement_line, info):
114         info["time"] = blk_head.timestamp
115         info["blk_hash"] = str(bitcoin.hash_block_header(blk_head))
116         tx_hash = bitcoin.hash_digest(info["tx_hash"])
117         self.chain.fetch_transaction(tx_hash,
118             bitcoin.bind(self.load_tx, bitcoin._1, bitcoin._2,
119                 statement_line, info))
120
121     def load_tx(self, ec, tx, statement_line, info):
122         outputs = []
123         for tx_out in tx.outputs:
124             script = tx_out.output_script
125             if script.type() == bitcoin.payment_type.pubkey_hash:
126                 pkh = bitcoin.short_hash(str(script.operations()[2].data))
127                 outputs.append(bitcoin.public_key_hash_to_address(pkh))
128             else:
129                 outputs.append("Unknown")
130         info["outputs"] = outputs
131         info["inputs"] = [None for i in range(len(tx.inputs))]
132         if info["is_in"] == 1:
133             info["inputs"][info["pos"]] = self.address
134         else:
135             info["value"] = tx.outputs[info["pos"]].value
136         if not [empty_in for empty_in in info["inputs"] if empty_in is None]:
137             # We have the sole input
138             assert(info["is_in"] == 1)
139             with statement_line.lock:
140                 statement_line.input_loaded = info
141             self.finish_if_done()
142         for tx_idx, tx_in in enumerate(tx.inputs):
143             if info["is_in"] == 1 and info["pos"] == tx_idx:
144                 continue
145             self.chain.fetch_transaction(tx_in.previous_output.hash,
146                 bitcoin.bind(self.load_input, bitcoin._1, bitcoin._2,
147                     tx_in.previous_output.index, statement_line, info, tx_idx))
148
149     def load_input(self, ec, tx, index, statement_line, info, inputs_index):
150         script = tx.outputs[index].output_script
151         if script.type() == bitcoin.payment_type.pubkey_hash:
152             pkh = bitcoin.short_hash(str(script.operations()[2].data))
153             info["inputs"][inputs_index] = \
154                 bitcoin.public_key_hash_to_address(pkh)
155         else:
156             info["inputs"][inputs_index] = "Unknown"
157         if not [empty_in for empty_in in info["inputs"] if empty_in is None]:
158             with statement_line.lock:
159                 if info["is_in"] == 1:
160                     statement_line.input_loaded = info
161                 else:
162                     statement_line.output_loaded = info
163         self.finish_if_done()
164
165 def payment_history(chain, address, handle_finish):
166     ph = PaymentHistory(chain)
167     expiry_queue.add(ph)
168     ph.run(address, handle_finish)
169
170 if __name__ == "__main__":
171     def finish(result):
172         print result
173
174     service = bitcoin.async_service(1)
175     prefix = "/home/genjix/libbitcoin/database"
176     chain = bitcoin.bdb_blockchain(service, prefix)
177     address = "1FpES68UNcxnXeoaFciqvUSGiKGZ33gbfQ"
178     print "Looking up", address
179     payment_history(chain, address, finish)
180     raw_input()
181