simplify interface: use callbacks
[electrum-nvc.git] / lib / verifier.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2012 thomasv@ecdsa.org
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19
20 import threading, time, Queue, os, sys, shutil
21 from util import user_dir, appdata_dir, print_error
22 from bitcoin import *
23
24
25
26
27 class TxVerifier(threading.Thread):
28     """ Simple Payment Verification """
29
30     def __init__(self, network, storage):
31         threading.Thread.__init__(self)
32         self.daemon = True
33         self.storage = storage
34         self.network = network
35         self.blockchain = network.blockchain
36         self.interface = network.interface
37         self.transactions    = {}                                 # requested verifications (with height sent by the requestor)
38         #self.interface.register_channel('txverifier')
39         self.verified_tx     = storage.get('verified_tx3',{})      # height, timestamp of verified transactions
40         self.merkle_roots    = storage.get('merkle_roots',{})      # hashed by me
41         self.lock = threading.Lock()
42         self.running = False
43         self.queue = Queue.Queue()
44
45
46     def get_confirmations(self, tx):
47         """ return the number of confirmations of a monitored transaction. """
48         with self.lock:
49             if tx in self.verified_tx:
50                 height, timestamp, pos = self.verified_tx[tx]
51                 conf = (self.blockchain.local_height - height + 1)
52                 if conf <= 0: timestamp = None
53
54             elif tx in self.transactions:
55                 conf = -1
56                 timestamp = None
57
58             else:
59                 conf = 0
60                 timestamp = None
61
62         return conf, timestamp
63
64
65     def get_txpos(self, tx_hash):
66         "return position, even if the tx is unverified"
67         with self.lock:
68             x = self.verified_tx.get(tx_hash)
69             y = self.transactions.get(tx_hash)
70         if x:
71             height, timestamp, pos = x
72             return height, pos
73         elif y:
74             return y, 0
75         else:
76             return 1e12, 0
77
78
79     def get_height(self, tx_hash):
80         with self.lock:
81             v = self.verified_tx.get(tx_hash)
82         height = v[0] if v else None
83         return height
84
85
86     def add(self, tx_hash, tx_height):
87         """ add a transaction to the list of monitored transactions. """
88         assert tx_height > 0
89         with self.lock:
90             if tx_hash not in self.transactions.keys():
91                 self.transactions[tx_hash] = tx_height
92
93     def stop(self):
94         with self.lock: self.running = False
95         #self.interface.poke('verifier')
96
97     def is_running(self):
98         with self.lock: return self.running
99
100     def run(self):
101         with self.lock:
102             self.running = True
103         requested_merkle = []
104
105         while self.is_running():
106             # request missing tx
107             for tx_hash, tx_height in self.transactions.items():
108                 if tx_hash not in self.verified_tx:
109                     if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
110                         print_error('requesting merkle', tx_hash)
111                         self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r))
112                         requested_merkle.append(tx_hash)
113
114             try:
115                 r = self.queue.get(timeout=1)
116             except Queue.Empty:
117                 continue
118
119             if not r: continue
120
121             if r.get('error'):
122                 print_error('Verifier received an error:', r)
123                 continue
124
125             # 3. handle response
126             method = r['method']
127             params = r['params']
128             result = r['result']
129
130             if method == 'blockchain.transaction.get_merkle':
131                 tx_hash = params[0]
132                 self.verify_merkle(tx_hash, result)
133                 requested_merkle.remove(tx_hash)
134
135
136     def verify_merkle(self, tx_hash, result):
137         tx_height = result.get('block_height')
138         pos = result.get('pos')
139         self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, pos)
140         header = self.blockchain.read_header(tx_height)
141         if not header: return
142         assert header.get('merkle_root') == self.merkle_roots[tx_hash]
143         # we passed all the tests
144         timestamp = header.get('timestamp')
145         with self.lock:
146             self.verified_tx[tx_hash] = (tx_height, timestamp, pos)
147         print_error("verified %s"%tx_hash)
148         self.storage.put('verified_tx3', self.verified_tx, True)
149         self.network.trigger_callback('updated')
150
151
152     def hash_merkle_root(self, merkle_s, target_hash, pos):
153         h = hash_decode(target_hash)
154         for i in range(len(merkle_s)):
155             item = merkle_s[i]
156             h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
157         return hash_encode(h)
158
159
160
161     def undo_verifications(self, height):
162         with self.lock:
163             items = self.verified_tx.items()[:]
164         for tx_hash, item in items:
165             tx_height, timestamp, pos = item
166             if tx_height >= height:
167                 print_error("redoing", tx_hash)
168                 with self.lock:
169                     self.verified_tx.pop(tx_hash)
170                     if tx_hash in self.merkle_roots:
171                         self.merkle_roots.pop(tx_hash)