do not request merkle root for unconfirmed transactions
[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
21 from util import user_dir, print_error
22 from bitcoin import *
23
24
25
26
27 class WalletVerifier(threading.Thread):
28     """ Simple Payment Verification """
29
30     def __init__(self, interface, config):
31         threading.Thread.__init__(self)
32         self.daemon = True
33         self.config = config
34         self.interface = interface
35         self.transactions    = []                                 # monitored transactions
36         self.interface.register_channel('verifier')
37         self.verified_tx     = config.get('verified_tx',{})
38         self.merkle_roots    = config.get('merkle_roots',{})      # hashed by me
39         self.targets         = config.get('targets',{})           # compute targets
40         self.lock = threading.Lock()
41         self.pending_headers = [] # headers that have not been verified
42         self.height = 0
43         self.local_height = 0
44         self.set_local_height()
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.transactions:
50                 return (self.local_height - self.verified_tx[tx] + 1) if tx in self.verified_tx else 0
51             else:
52                 return 0
53
54     def add(self, tx):
55         """ add a transaction to the list of monitored transactions. """
56         with self.lock:
57             if tx not in self.transactions:
58                 self.transactions.append(tx)
59
60     def run(self):
61         requested_merkle = []
62         requested_chunks = []
63         requested_headers = []
64         all_chunks = False
65         
66         # subscribe to block headers
67         self.interface.send([ ('blockchain.headers.subscribe',[])], 'verifier')
68
69         while True:
70             # request missing chunks
71             if not all_chunks and self.height and not requested_chunks:
72
73                 if self.local_height + 50 < self.height:
74                     min_index = (self.local_height + 1)/2016
75                     max_index = (self.height + 1)/2016
76                     for i in range(min_index, max_index + 1):
77                         # print "requesting chunk", i
78                         self.interface.send([ ('blockchain.block.get_chunk',[i])], 'verifier')
79                         requested_chunks.append(i)
80                         break
81                 else:
82                     all_chunks = True
83                     print_error("downloaded all chunks")
84
85             # request missing tx merkle
86             for tx in self.transactions:
87                 if tx not in self.verified_tx:
88                     if tx not in requested_merkle:
89                         requested_merkle.append(tx)
90                         self.request_merkle(tx)
91                         #break
92
93
94             # process pending headers
95             if self.pending_headers and all_chunks:
96                 done = []
97                 for header in self.pending_headers:
98                     if self.verify_header(header):
99                         done.append(header)
100                     else:
101                         # request previous header
102                         i = header.get('block_height') - 1
103                         if i not in requested_headers:
104                             print_error("requesting header %d"%i)
105                             self.interface.send([ ('blockchain.block.get_header',[i])], 'verifier')
106                             requested_headers.append(i)
107                         # no point continuing
108                         break
109                 for header in done: self.pending_headers.remove(header)
110                 self.interface.trigger_callback('updated')
111
112             try:
113                 r = self.interface.get_response('verifier',timeout=1)
114             except Queue.Empty:
115                 time.sleep(1)
116                 continue
117
118             # 3. handle response
119             method = r['method']
120             params = r['params']
121             result = r['result']
122
123             if method == 'blockchain.transaction.get_merkle':
124                 tx_hash = params[0]
125                 self.verify_merkle(tx_hash, result)
126                 requested_merkle.remove(tx_hash)
127
128             elif method == 'blockchain.block.get_chunk':
129                 index = params[0]
130                 self.verify_chunk(index, result)
131                 requested_chunks.remove(index)
132
133             elif method in ['blockchain.headers.subscribe', 'blockchain.block.get_header']:
134
135                 self.pending_headers.append(result)
136                 if method == 'blockchain.block.get_header':
137                     requested_headers.remove(result.get('block_height'))
138                 else:
139                     self.height = result.get('block_height')
140                 
141                 self.pending_headers.sort(key=lambda x: x.get('block_height'))
142                 # print "pending headers", map(lambda x: x.get('block_height'), self.pending_headers)
143
144
145
146             self.interface.trigger_callback('updated')
147
148
149     def request_merkle(self, tx_hash):
150         self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash]) ], 'verifier')
151
152
153     def verify_merkle(self, tx_hash, result):
154         tx_height = result.get('block_height')
155         self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, result.get('pos'))
156         header = self.read_header(tx_height)
157         if header:
158             assert header.get('merkle_root') == self.merkle_roots[tx_hash]
159             self.verified_tx[tx_hash] = tx_height
160             print_error("verified %s"%tx_hash)
161             self.config.set_key('verified_tx', self.verified_tx, True)
162
163
164     def verify_chunk(self, index, hexdata):
165         data = hexdata.decode('hex')
166         height = index*2016
167         num = len(data)/80
168         print_error("validating headers %d"%height)
169
170         if index == 0:  
171             previous_hash = ("0"*64)
172         else:
173             prev_header = self.read_header(index*2016-1)
174             if prev_header is None: raise
175             previous_hash = self.hash_header(prev_header)
176
177         bits, target = self.get_target(index)
178
179         for i in range(num):
180             height = index*2016 + i
181             raw_header = data[i*80:(i+1)*80]
182             header = self.header_from_string(raw_header)
183             _hash = self.hash_header(header)
184             assert previous_hash == header.get('prev_block_hash')
185             assert bits == header.get('bits')
186             assert eval('0x'+_hash) < target
187
188             previous_header = header
189             previous_hash = _hash 
190
191         self.save_chunk(index, data)
192
193
194     def verify_header(self, header):
195         # add header to the blockchain file
196         # if there is a reorg, push it in a stack
197
198         height = header.get('block_height')
199
200         prev_header = self.read_header(height -1)
201         if not prev_header:
202             # return False to request previous header
203             return False
204
205         prev_hash = self.hash_header(prev_header)
206         bits, target = self.get_target(height/2016)
207         _hash = self.hash_header(header)
208         try:
209             assert prev_hash == header.get('prev_block_hash')
210             assert bits == header.get('bits')
211             assert eval('0x'+_hash) < target
212         except:
213             # this can be caused by a reorg.
214             print_error("verify header failed"+ repr(header))
215             # undo verifications
216             for tx_hash, tx_height in self.verified_tx.items():
217                 if tx_height >= height:
218                     print "redoing", tx_hash
219                     self.verified_tx.pop(tx_hash)
220                     if tx_hash in self.merkle_roots: self.merkle_roots.pop(tx_hash)
221             # return False to request previous header.
222             return False
223
224         self.save_header(header)
225         print_error("verify header:", _hash, height)
226         return True
227         
228
229             
230
231     def header_to_string(self, res):
232         s = int_to_hex(res.get('version'),4) \
233             + rev_hex(res.get('prev_block_hash')) \
234             + rev_hex(res.get('merkle_root')) \
235             + int_to_hex(int(res.get('timestamp')),4) \
236             + int_to_hex(int(res.get('bits')),4) \
237             + int_to_hex(int(res.get('nonce')),4)
238         return s
239
240
241     def header_from_string(self, s):
242         hex_to_int = lambda s: eval('0x' + s[::-1].encode('hex'))
243         h = {}
244         h['version'] = hex_to_int(s[0:4])
245         h['prev_block_hash'] = hash_encode(s[4:36])
246         h['merkle_root'] = hash_encode(s[36:68])
247         h['timestamp'] = hex_to_int(s[68:72])
248         h['bits'] = hex_to_int(s[72:76])
249         h['nonce'] = hex_to_int(s[76:80])
250         return h
251
252     def hash_header(self, header):
253         return rev_hex(Hash(self.header_to_string(header).decode('hex')).encode('hex'))
254
255     def hash_merkle_root(self, merkle_s, target_hash, pos):
256         h = hash_decode(target_hash)
257         for i in range(len(merkle_s)):
258             item = merkle_s[i]
259             h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
260         return hash_encode(h)
261
262     def path(self):
263         wdir = self.config.get('blockchain_headers_path', user_dir())
264         if not os.path.exists( wdir ): os.mkdir(wdir)
265         return os.path.join( wdir, 'blockchain_headers')
266
267     def save_chunk(self, index, chunk):
268         filename = self.path()
269         if os.path.exists(filename):
270             f = open(filename,'rb+')
271         else:
272             print "creating file", filename
273             f = open(filename,'wb+')
274         f.seek(index*2016*80)
275         h = f.write(chunk)
276         f.close()
277         self.set_local_height()
278
279     def save_header(self, header):
280         data = self.header_to_string(header).decode('hex')
281         assert len(data) == 80
282         height = header.get('block_height')
283         filename = self.path()
284         f = open(filename,'rb+')
285         f.seek(height*80)
286         h = f.write(data)
287         f.close()
288         self.set_local_height()
289
290
291     def set_local_height(self):
292         name = self.path()
293         if os.path.exists(name):
294             h = os.path.getsize(name)/80 - 1
295             if self.local_height != h:
296                 self.local_height = h
297
298
299     def read_header(self, block_height):
300         name = self.path()
301         if os.path.exists(name):
302             f = open(name,'rb')
303             f.seek(block_height*80)
304             h = f.read(80)
305             f.close()
306             if len(h) == 80:
307                 h = self.header_from_string(h)
308                 return h 
309
310
311     def get_target(self, index):
312
313         max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
314         if index == 0: return 0x1d00ffff, max_target
315
316         first = self.read_header((index-1)*2016)
317         last = self.read_header(index*2016-1)
318         
319         nActualTimespan = last.get('timestamp') - first.get('timestamp')
320         nTargetTimespan = 14*24*60*60
321         nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
322         nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
323
324         bits = last.get('bits') 
325         # convert to bignum
326         MM = 256*256*256
327         a = bits%MM
328         if a < 0x8000:
329             a *= 256
330         target = (a) * pow(2, 8 * (bits/MM - 3))
331
332         # new target
333         new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
334         
335         # convert it to bits
336         c = ("%064X"%new_target)[2:]
337         i = 31
338         while c[0:2]=="00":
339             c = c[2:]
340             i -= 1
341
342         c = eval('0x'+c[0:6])
343         if c > 0x800000: 
344             c /= 256
345             i += 1
346
347         new_bits = c + MM * i
348         return new_bits, new_target
349