blockchain.address.get_history memory pool transactions.
[electrum-server.git] / backends / libbitcoin / history.py
1 import bitcoin
2 from bitcoin import bind, _1, _2, _3
3 import threading
4 import multimap
5 import time
6
7 class MemoryPoolBuffer:
8
9     def __init__(self, service, txpool, chain):
10         self.txpool = txpool
11         self.chain = chain
12         # prevout: inpoint
13         self.lookup_input = {}
14         # payment_address: outpoint
15         self.lookup_address = multimap.MultiMap()
16         # transaction timestamps
17         self.timestamps = {}
18
19     def recv_tx(self, tx):
20         tx_hash = bitcoin.hash_transaction(tx)
21         desc = (tx_hash, [], [])
22         for input in tx.inputs:
23             desc[1].append(input.previous_output)
24         for idx, output in enumerate(tx.outputs):
25             address = bitcoin.payment_address()
26             if address.extract(output.output_script):
27                 desc[2].append((idx, address))
28         self.txpool.store(tx,
29             bind(self.confirmed, _1, desc),
30             bind(self.mempool_stored, _1, desc))
31
32     def mempool_stored(self, ec, desc):
33         tx_hash, prevouts, addrs = desc
34         if ec:
35             print "Error storing memory pool transaction", tx_hash, ec
36             return
37         print "Accepted transaction", tx_hash
38         for idx, prevout in enumerate(prevouts):
39             inpoint = bitcoin.input_point()
40             inpoint.hash, inpoint.index = tx_hash, idx
41             self.lookup_input[str(prevout)] = inpoint
42         for idx, address in addrs:
43             outpoint = bitcoin.output_point()
44             outpoint.hash, outpoint.index = tx_hash, idx
45             self.lookup_address[str(address)] = outpoint
46         self.timestamps[str(tx_hash)] = int(time.time())
47
48     def confirmed(self, ec, desc):
49         tx_hash, prevouts, addrs = desc
50         if ec:
51             print "Problem confirming transaction", tx_hash, ec
52             return
53         print "Confirmed", tx_hash
54         for idx, prevout in enumerate(prevouts):
55             inpoint = bitcoin.input_point()
56             inpoint.hash, inpoint.index = tx_hash, idx
57             assert self.lookup_input[str(prevout)] == inpoint
58             del self.lookup_input[str(prevout)]
59         for idx, address in addrs:
60             outpoint = bitcoin.output_point()
61             outpoint.hash, outpoint.index = tx_hash, idx
62             self.lookup_address.delete(str(address), outpoint)
63         del self.timestamps[str(tx_hash)]
64
65     def check(self, output_points, address, handle):
66         class ExtendableDict(dict):
67             pass
68         result = []
69         for outpoint in output_points:
70             if self.lookup_input.has_key(str(outpoint)):
71                 point = self.lookup_input[str(outpoint)]
72                 info = ExtendableDict()
73                 info["tx_hash"] = str(point.hash)
74                 info["index"] = point.index
75                 info["is_input"] = 1
76                 info["timestamp"] = self.timestamps[info["tx_hash"]]
77                 result.append(info)
78         if self.lookup_address.has_key(str(address)):
79             point = self.lookup_address[str(address)]
80             info = ExtendableDict()
81             info["tx_hash"] = str(point.hash)
82             info["index"] = point.index
83             info["is_input"] = 0
84             info["timestamp"] = self.timestamps[info["tx_hash"]]
85             result.append(info)
86         handle(result)
87
88 class PaymentEntry:
89
90     def __init__(self, output_point):
91         self.lock = threading.Lock()
92         self.output_point = output_point
93         self.output_loaded = None
94         self.input_point = None
95         self.input_loaded = None
96         self.raw_output_script = None
97
98     def is_loaded(self):
99         with self.lock:
100             if self.output_loaded is None:
101                 return False
102             elif self.has_input() and self.input_loaded is None:
103                 return False
104         return True
105
106     def has_input(self):
107         return self.input_point is not False
108
109 class History:
110
111     def __init__(self, service, chain, txpool, membuf):
112         self.chain = chain
113         self.txpool = txpool
114         self.membuf = membuf
115         self.lock = threading.Lock()
116         self.statement = []
117         self.membuf_result = None
118         self._stopped = False
119
120     def start(self, address, handle_finish):
121         self.address = address
122         self.handle_finish = handle_finish
123
124         address = bitcoin.payment_address(address)
125         # To begin we fetch all the outputs (payments in)
126         # associated with this address
127         self.chain.fetch_outputs(address,
128             bind(self.check_membuf, _1, _2))
129
130     def stop(self):
131         with self.lock:
132             assert self._stopped == False
133             self._stopped = True
134
135     def stopped(self):
136         with self.lock:
137             return self._stopped
138
139     def stop_on_error(self, ec):
140         if ec:
141             self.handle_finish(None)
142             self.stop()
143         return self.stopped()
144
145     def check_membuf(self, ec, output_points):
146         if self.stop_on_error(ec):
147             return
148         self.membuf.check(output_points, self.address,
149             bind(self.start_loading, _1, output_points))
150
151     def start_loading(self, membuf_result, output_points):
152         # Create a bunch of entry lines which are outputs and
153         # then their corresponding input (if it exists)
154         for outpoint in output_points:
155             entry = PaymentEntry(outpoint)
156             with self.lock:
157                 self.statement.append(entry)
158             # Attempt to fetch the spend of this output
159             self.chain.fetch_spend(outpoint,
160                 bind(self.load_spend, _1, _2, entry))
161             self.load_tx_info(outpoint, entry, False)
162         # Load memory pool transactions
163         with self.lock:
164             self.membuf_result = membuf_result
165         for info in self.membuf_result:
166             self.txpool.fetch(bitcoin.hash_digest(info["tx_hash"]),
167                 bind(self.load_pool_tx, _1, _2, info))
168
169     def load_spend(self, ec, inpoint, entry):
170         # Need a custom self.stop_on_error(...) as a missing spend
171         # is not an error in this case.
172         if not self.stopped() and ec and ec != bitcoin.error.unspent_output:
173             self.handle_finish(None)
174             self.stop()
175         if self.stopped():
176             return
177         with entry.lock:
178             if ec == bitcoin.error.unspent_output:
179                 # This particular entry.output_point
180                 # has not been spent yet
181                 entry.input_point = False
182             else:
183                 entry.input_point = inpoint
184         if ec == bitcoin.error.unspent_output:
185             # Attempt to stop if all the info for the inputs and outputs
186             # has been loaded.
187             self.finish_if_done()
188         else:
189             # We still have to load at least one more payment outwards
190             self.load_tx_info(inpoint, entry, True)
191
192     def finish_if_done(self):
193         with self.lock:
194             # Still have more entries to finish loading, so return
195             if any(not entry.is_loaded() for entry in self.statement):
196                 return
197             # Memory buffer transactions finished loading?
198             if any(not info.has_key("height") for info in self.membuf_result):
199                 return
200         # Whole operation completed successfully! Finish up.
201         result = []
202         for entry in self.statement:
203             if entry.input_point:
204                 # value of the input is simply the inverse of
205                 # the corresponding output
206                 entry.input_loaded["value"] = -entry.output_loaded["value"]
207                 # output should come before the input as it's chronological
208                 result.append(entry.output_loaded)
209                 result.append(entry.input_loaded)
210             else:
211                 # Unspent outputs have a raw_output_script field
212                 assert entry.raw_output_script is not None
213                 entry.output_loaded["raw_output_script"] = \
214                     entry.raw_output_script
215                 result.append(entry.output_loaded)
216         mempool_result = []
217         for info in self.membuf_result:
218             # Lookup prevout in result
219             # Set "value" field
220             if info["is_input"] == 1:
221                 prevout_tx = None
222                 for prevout_info in result:
223                     if prevout_info["tx_hash"] == info.previous_output.hash:
224                         prevout_tx = prevout_info
225                 assert prevout_tx is not None
226                 info["value"] = -prevout_info["value"]
227             mempool_result.append(info)
228         result.extend(mempool_result)
229         self.handle_finish(result)
230         self.stop()
231
232     def load_tx_info(self, point, entry, is_input):
233         info = {}
234         info["tx_hash"] = str(point.hash)
235         info["index"] = point.index
236         info["is_input"] = 1 if is_input else 0
237         # Before loading the transaction, Stratum requires the hash
238         # of the parent block, so we load the block depth and then
239         # fetch the block header and hash it.
240         self.chain.fetch_transaction_index(point.hash,
241             bind(self.tx_index, _1, _2, _3, entry, info))
242
243     def tx_index(self, ec, block_depth, offset, entry, info):
244         if self.stop_on_error(ec):
245             return
246         info["height"] = block_depth
247         # And now for the block hash
248         self.chain.fetch_block_header_by_depth(block_depth,
249             bind(self.block_header, _1, _2, entry, info))
250
251     def block_header(self, ec, blk_head, entry, info):
252         if self.stop_on_error(ec):
253             return
254         info["timestamp"] = blk_head.timestamp
255         info["block_hash"] = str(bitcoin.hash_block_header(blk_head))
256         tx_hash = bitcoin.hash_digest(info["tx_hash"])
257         # Now load the actual main transaction for this input or output
258         self.chain.fetch_transaction(tx_hash,
259             bind(self.load_chain_tx, _1, _2, entry, info))
260
261     def load_pool_tx(self, ec, tx, info):
262         if self.stop_on_error(ec):
263             return
264         # block_hash = mempool:5
265         # inputs (load from prevtx)
266         # outputs (load from tx)
267         # raw_output_script (load from tx)
268         # height is always None
269         # value (get from finish_if_done)
270         self.load_tx(tx, info)
271         if info["is_input"] == 0:
272             our_output = tx.outputs[info["index"]]
273             info["value"] = our_output.value
274             # Save serialised output script in case this output is unspent
275             info["raw_output_script"] = \
276                 str(bitcoin.save_script(our_output.output_script))
277         else:
278             assert(info["is_input"] == 1)
279             info.previous_output = tx.inputs[info["index"]].previous_output
280         # If all the inputs are loaded
281         if self.inputs_all_loaded(info["inputs"]):
282             # We are the sole input
283             assert(info["is_input"] == 1)
284             self.finish_if_done()
285         create_handler = lambda prevout_index, input_index: \
286             bind(self.load_input_pool_tx, _1, _2,
287                 prevout_index, info, input_index)
288         self.fetch_input_txs(tx, info, create_handler)
289
290     def load_tx(self, tx, info):
291         # List of output addresses
292         outputs = []
293         for tx_out in tx.outputs:
294             address = bitcoin.payment_address()
295             # Attempt to extract address from output script
296             if address.extract(tx_out.output_script):
297                 outputs.append(address.encoded())
298             else:
299                 # ... otherwise append "Unknown"
300                 outputs.append("Unknown")
301         info["outputs"] = outputs
302         # For the inputs, we need the originator address which has to
303         # be looked up in the blockchain.
304         # Create list of Nones and then populate it.
305         # Loading has finished when list is no longer all None.
306         info["inputs"] = [None for i in tx.inputs]
307         # If this transaction was loaded for an input, then we already
308         # have a source address for at least one input.
309         if info["is_input"] == 1:
310             info["inputs"][info["index"]] = self.address
311
312     def fetch_input_txs(self, tx, info, create_handler):
313         # Load the previous_output for every input so we can get
314         # the output address
315         for input_index, tx_input in enumerate(tx.inputs):
316             if info["is_input"] == 1 and info["index"] == input_index:
317                 continue
318             prevout = tx_input.previous_output
319             handler = create_handler(prevout.index, input_index)
320             self.chain.fetch_transaction(prevout.hash, handler)
321
322     def load_chain_tx(self, ec, tx, entry, info):
323         if self.stop_on_error(ec):
324             return
325         self.load_tx(tx, info)
326         if info["is_input"] == 0:
327             our_output = tx.outputs[info["index"]]
328             info["value"] = our_output.value
329             # Save serialised output script in case this output is unspent
330             with entry.lock:
331                 entry.raw_output_script = \
332                     str(bitcoin.save_script(our_output.output_script))
333         # If all the inputs are loaded
334         if self.inputs_all_loaded(info["inputs"]):
335             # We are the sole input
336             assert(info["is_input"] == 1)
337             with entry.lock:
338                 entry.input_loaded = info
339             self.finish_if_done()
340         create_handler = lambda prevout_index, input_index: \
341             bind(self.load_input_chain_tx, _1, _2,
342                 prevout_index, entry, info, input_index)
343         self.fetch_input_txs(tx, info, create_handler)
344
345     def inputs_all_loaded(self, info_inputs):
346         return not [empty_in for empty_in in info_inputs if empty_in is None]
347
348     def load_input_tx(self, tx, output_index, info, input_index):
349         # For our input, we load the previous tx so we can get the
350         # corresponding output.
351         # We need the output to extract the address.
352         script = tx.outputs[output_index].output_script
353         address = bitcoin.payment_address()
354         if address.extract(script):
355             info["inputs"][input_index] = address.encoded()
356         else:
357             info["inputs"][input_index] = "Unknown"
358
359     def load_input_chain_tx(self, ec, tx, output_index,
360                             entry, info, input_index):
361         if self.stop_on_error(ec):
362             return
363         self.load_input_tx(tx, output_index, info, input_index)
364         # If all the inputs are loaded, then we have finished loading
365         # the info for this input-output entry pair
366         if self.inputs_all_loaded(info["inputs"]):
367             with entry.lock:
368                 if info["is_input"] == 1:
369                     entry.input_loaded = info
370                 else:
371                     entry.output_loaded = info
372         self.finish_if_done()
373
374     def load_input_pool_tx(self, ec, tx, output_index, info, input_index):
375         if self.stop_on_error(ec):
376             return
377         self.load_input_tx(tx, output_index, info, input_index)
378         if not [inp for inp in info["inputs"] if inp is None]:
379             # No more inputs left to load
380             # This info has finished loading
381             info["height"] = None
382         self.finish_if_done()
383
384 if __name__ == "__main__":
385     ex = bitcoin.satoshi_exporter()
386     tx_a = bitcoin.data_chunk("0100000003d0406a31f628e18f5d894b2eaf4af719906dc61be4fb433a484ed870f6112d15000000008b48304502210089c11db8c1524d8839243803ac71e536f3d876e8265bbb3bc4a722a5d0bd40aa022058c3e59a7842ef1504b1c2ce048f9af2d69bbf303401dced1f68b38d672098a10141046060f6c8e355b94375eec2cc1d231f8044e811552d54a7c4b36fe8ee564861d07545c6c9d5b9f60d16e67d683b93486c01d3bd3b64d142f48af70bb7867d0ffbffffffff6152ed1552b1f2635317cea7be06615a077fc0f4aa62795872836c4182ca0f25000000008b48304502205f75a468ddb08070d235f76cb94c3f3e2a75e537bc55d087cc3e2a1559b7ac9b022100b17e4c958aaaf9b93359f5476aa5ed438422167e294e7207d5cfc105e897ed91014104a7108ec63464d6735302085124f3b7a06aa8f9363eab1f85f49a21689b286eb80fbabda7f838d9b6bff8550b377ad790b41512622518801c5230463dbbff6001ffffffff01c52914dcb0f3d8822e5a9e3374e5893a7b6033c9cfce5a8e5e6a1b3222a5cb010000008c4930460221009561f7206cc98f40f3eab5f3308b12846d76523bd07b5f058463f387694452b2022100b2684ec201760fa80b02954e588f071e46d0ff16562c1ab393888416bf8fcc44014104a7108ec63464d6735302085124f3b7a06aa8f9363eab1f85f49a21689b286eb80fbabda7f838d9b6bff8550b377ad790b41512622518801c5230463dbbff6001ffffffff02407e0f00000000001976a914c3b98829108923c41b3c1ba6740ecb678752fd5e88ac40420f00000000001976a914424648ea6548cc1c4ea707c7ca58e6131791785188ac00000000")
387     tx_a = ex.load_transaction(tx_a)
388     assert bitcoin.hash_transaction(tx_a) == "e72e4f025695446cfd5c5349d1720beb38801f329a00281f350cb7e847153397"
389     tx_b = bitcoin.data_chunk("0100000001e269f0d74b8e6849233953715bc0be3ba6727afe0bc5000d015758f9e67dde34000000008c4930460221008e305e3fdf4420203a8cced5be20b73738a3b51186dfda7c6294ee6bebe331b7022100c812ded044196132f5e796dbf4b566b6ee3246cc4915eca3cf07047bcdf24a9301410493b6ce24182a58fc3bd0cbee0ddf5c282e00c0c10b1293c7a3567e95bfaaf6c9a431114c493ba50398ad0a82df06254605d963d6c226db615646fadd083ddfd9ffffffff020f9c1208000000001976a91492fffb2cb978d539b6bcd12c968b263896c6aacf88ac8e3f7600000000001976a914654dc745e9237f86b5fcdfd7e01165af2d72909588ac00000000")
390     tx_b = ex.load_transaction(tx_b)
391     assert bitcoin.hash_transaction(tx_b) == "acfda6dbf4ae1b102326bfb7c9541702d5ebb0339bc57bd74d36746855be8eac"
392
393     def blockchain_started(ec, chain):
394         print "Blockchain initialisation:", ec
395     def finish(result):
396         print "Finish"
397         if result is None:
398             return
399         for line in result:
400             for k, v in line.iteritems():
401                 begin = k + ":"
402                 print begin, " " * (12 - len(begin)), v
403             print
404
405     service = bitcoin.async_service(1)
406     prefix = "/home/genjix/libbitcoin/database.old"
407     chain = bitcoin.bdb_blockchain(service, prefix, blockchain_started)
408     txpool = bitcoin.transaction_pool(service, chain)
409     local_service = bitcoin.AsyncService()
410     membuf = MemoryPoolBuffer(local_service, txpool, chain)
411     membuf.recv_tx(tx_a)
412     membuf.recv_tx(tx_b)
413     raw_input()
414     #address = bitcoin.payment_address("1Jqu2PVGDvNv4La113hgCJsvRUCDb3W65D")
415     address = "1EMnecJFwihf2pf4nE2m8fUNFKVRMWKqhR"
416     #address = "1Pbn3DLXfjqF1fFV9YPdvpvyzejZwkHhZE"
417     print "Looking up", address
418     h = History(local_service, chain, txpool, membuf)
419     h.start(address, finish)
420     raw_input()
421     print "Stopping..."
422