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